/// GLOBAL JS | requires JQuery and all plugins
$(document).ready(function() {
    SetupNotificationMessages();
    SetupHelpButtons();
    SetupTableZebraStripes();
    SetupMaxLengthValidation();
    SetupDropDownMenus();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
    if($get('body'))
	{$get('body').style.cursor = 'wait';}
}
function EndRequest(sender, args) {
    if($get('body'))
	{$get('body').style.cursor = 'auto';
    SetupTableZebraStripes();
	}
}
////////// AJAX ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var spinID;
var spinSrc;
var spinnerImg = "http://static.propertylinkonline.com/images/spinner.gif";
var strAjaxError = "Sorry, there was a problem with your request. Please try again in a few minutes or contact customer service if you continue to have problems. We apologize for any inconvenience.";
function AjaxFailed(error, userContext, methodName) { alert(strAjaxError); };
////////// IMAGE ROLLOVER FUNCTIONS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function MM_swapImgRestore() { //v3.0
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}
function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; }
    }
}
function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}
////////// UTILITY ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getForm() {
    var theForm = document.forms['aspnetForm'];
    if (!theForm) { theForm = document.aspnetForm; }
    return theForm;
}
function submitPage() { getForm().submit(); }
function resetPage() { getForm().reset(); }
function goUrl(url) { parent.location = url; }
function goPopup(url) { window.open(url); }
function goPopupSlim(url) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open('" + url + "', '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,left = 0,top = 0');");
}
function runAfter(secs, callback) { window.setTimeout(callback, (secs * 1000)); }
function CleanPhone(input) {
    var output = "";
    var numbersArray = input.match(/\d+/g);
    if (numbersArray != null) {
        for (i = 0; i < numbersArray.length; i++) {
            output = output + "" + numbersArray[i];
        }
    }
    return output;
}
function StandardizePhone(input) {
    return input.substring(0, 3) + "-" + input.substring(3, 6) + "-" + input.substring(6, 10);
}
function spinnerOn(ID, src) {
    spinID = ID;
    spinSrc = src;
}
function spinnerOff() {
    $(spinID).attr("src", spinSrc);
}
////////// SETUP ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function SetupNotificationMessages() {
    $("div[class*='notification-']").bind("click", function() { $(this).slideUp("fast"); });
    var timer = setTimeout(function() { $("div[class*='notification-']").slideUp("fast"); }, 10000);
}
function SetupHelpButtons() {
    $("#btnHelpSupport").bind('click', function() { $('#divHelp').slideToggle('slow'); });
    $("#divHelp .closeBtn").bind('click', function() { $('#divHelp').slideUp('slow'); });
}
function SetupTableZebraStripes() {
    $("table.zebraStripe tbody tr:nth-child(odd)").addClass("odd");
    $("table.zebraStripe tbody tr:nth-child(even)").addClass("even");
    $("table.zebraStripeHover tbody tr.odd")
        .bind("mouseover", function() { $(this).addClass("hover"); })
        .bind("mouseout", function() { $(this).removeClass("hover"); });
    $("table.zebraStripeHover tbody tr.even")
        .bind("mouseover", function() { $(this).addClass("hover"); })
        .bind("mouseout", function() { $(this).removeClass("hover"); });
}
function SetupMaxLengthValidation() {
    //$("textarea[class*='maxLength-']").enforceMaxTextLengths();
    $("textarea.maxLength").MaxLengths();
}
function SetupDropDownMenus() {
    var m1 = document.getElementById("menu-main-anchor1");
    if (m1 != null) at_attach("menu-main-anchor1", "menu-main-child1", "hover", "y", "pointer");
    var m2 = document.getElementById("menu-main-anchor2");
    if (m2 != null) at_attach("menu-main-anchor2", "menu-main-child2", "hover", "y", "pointer");
}
function SetupAccordians() {
    $('.accordian').accordion({
        autoHeight: false,
        header: '.accordian-header'
    });
}
function SetupDateInputs() {
    $(".dateinput").date_input();
}
////////// VALIDATION ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function ValidateFloorplanValues(minValueId, maxValueId, compareType) {
    var minValue = $("#" + minValueId).val();
    var maxValue = $("#" + maxValueId).val();

    if (compareType == "area") {
        var re = new RegExp("^[0-9]+$");
        if (minValue.match(re) && maxValue.match(re)) {
            return CompareNumericRangeValues(parseInt(minValue), parseInt(maxValue));
        }
    } else if (compareType == "rents" || compareType == "bathrooms") {
        var re = new RegExp("^\\d+(\\.\\d+)?$");
        if (minValue.match(re) && maxValue.match(re)) {
            return CompareNumericRangeValues(parseFloat(minValue), parseFloat(maxValue));
        }
    }
    return false;
}
function CompareNumericRangeValues(minValue, maxValue) {
    if (isNaN(minValue) || isNaN(maxValue))
        return false;
    else
        return (minValue > 0 && maxValue > 0) && (minValue <= maxValue);
}
////////// SITE SEARCH ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function DoSearch(a) {
    var searchBox = $("#searchbox");
    var searchInput = searchBox.val();
    var userKey = $("#upk input:hidden").val();
    var sr = $("#search-results");
    var src = $("#search-results-content");

    if (searchInput == "" || searchInput == null || window.event.keyCode == 27) { CloseSearch();return; }

    PropertyLink.Services.SearchService.GetSearchResults(searchInput, userKey, GetSearchResultsComplete);
    searchBox.css("background", "#ffffff url(http://static.propertylinkonline.com/images/input_text_candy.gif) bottom right");

    function GetSearchResultsComplete(response) {
        searchInput = response[0];
        var results = response[1];
        var title = "";
        if (searchInput == null || searchInput == "") {
            title = "<h2>Nothing to search for</h2>The search terms you've entered are not valid, please search again with different keywords or <a href=\"Portfolio.aspx\">view your entire portfolio</a><br/><br/>";
        } else {
            if (results == null || results == "") {
                title = "<h2>No results</h2>Sorry, we could not find anything for \"" + searchInput + "\"<br/>Please search again with different keywords or <a href=\"Portfolio.aspx\">view your entire portfolio</a><br/><br/>";
            } else if (results != null) {
                title = "<h2>Search results</h2>Searched for \"" + searchInput + "\"<br/><br/>";
            }
        }
        src.html(title + results);
        sr.show();
        sr.css("display:block");
        searchBox.css("background", "#ffffff");
    }
}

function CloseSearch() {
    event.returnValue = false;
    event.cancel = true;
    
    var searchBox = $("#searchbox");
    var sr = $("#search-results");
    var src = $("#search-results-content");

    sr.hide();
    searchBox.css("background", "#ffffff");
    searchBox.val("");
}
////////// PLUGINS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////
////////// Dropdown menus
//////////
function at_show_aux(parent, child) {
    var p = document.getElementById(parent);
    var c = document.getElementById(child);

    var top = (c["at_position"] == "y") ? p.offsetHeight + 2 : 0;
    var left = (c["at_position"] == "x") ? p.offsetWidth + 2 : 0;

    for (; p; p = p.offsetParent) {
        top += p.offsetTop;
        left += p.offsetLeft;
    }

    c.style.position = "absolute";
    c.style.top = top + 'px';
    c.style.left = left + 'px';
    c.style.visibility = "visible";
}
function at_show() {
    var p = document.getElementById(this["at_parent"]);
    var c = document.getElementById(this["at_child"]);

    //  $('#' + this["at_parent"]).attr("class","hover");
    at_show_aux(p.id, c.id);
    clearTimeout(c["at_timeout"]);
}
function at_hide() {
    var p = document.getElementById(this["at_parent"]);
    var c = document.getElementById(this["at_child"]);

    //  $('#' + this["at_parent"]).attr("class","");
    //  document.getElementById(c.id).style.visibility = 'hidden';
    c["at_timeout"] = setTimeout("document.getElementById('" + c.id + "').style.visibility = 'hidden'", 333);
}
function at_click() {
    var p = document.getElementById(this["at_parent"]);
    var c = document.getElementById(this["at_child"]);

    if (c.style.visibility != "visible") at_show_aux(p.id, c.id); else c.style.visibility = "hidden";
    return false;
}
function at_attach(parent, child, showtype, position, cursor) {
    var p = document.getElementById(parent);
    var c = document.getElementById(child);

    p["at_parent"] = p.id;
    c["at_parent"] = p.id;
    p["at_child"] = c.id;
    c["at_child"] = c.id;
    p["at_position"] = position;
    c["at_position"] = position;

    c.style.position = "absolute";
    c.style.visibility = "hidden";

    if (cursor != undefined) p.style.cursor = cursor;

    switch (showtype) {
        case "click":
            p.onclick = at_click;
            p.onmouseout = at_hide;
            c.onmouseover = at_show;
            c.onmouseout = at_hide;
            break;
        case "hover":
            p.onmouseover = at_show;
            p.onmouseout = at_hide;
            c.onmouseover = at_show;
            c.onmouseout = at_hide;
            break;
    }
}
////////// CONTENT SPECIFIC ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////
////////// PAGE|Portfolio-MarketingStatus
//////////
var anchor;
function TSS(a, propertyId, subscriberId) {
    anchor = $(a);
    anchor.children("img").attr("src", "http://static.propertylinkonline.com/images/spinner.gif");
    $get('body').style.cursor = 'wait';
    PageMethods.ToggleCheck(propertyId, subscriberId, onResult, onFail);

    function onResult(result, userContext, methodName) {
        var status = result[0];
        var flag = result[1];
        var statusText = result[2];
        var subscriberName = result[3];

        var newCheckSrc = "http://static.propertylinkonline.com/images/checkboxes/" + status + ".png";
        anchor.children("img").attr("src", newCheckSrc);

        var newFlagSrc = "http://static.propertylinkonline.com/images/flags/" + flag + ".png";
        anchor.parent().parent().children("td").children("img.imgFlag").attr("src", newFlagSrc);

        var msgNotification = subscriberName + " has been <strong>" + statusText + "</strong>";
        $("#divNotification").html(msgNotification).slideDown('fast');

        $get('body').style.cursor = 'auto';
    }

    function onFail(error, userContext, methodName) {
        alert(strAjaxError);
        $get('body').style.cursor = 'auto';
    }
}
//////////
////////// PAGE|Property-Edit-Summary
//////////
function CheckOfficeHours(ddl, order) {
    var time = $(ddl).val();
    if (order == 1) {
        var otherTime = $(ddl).parent().parent().children("td.time-close").children("select").val();
        if (time > otherTime) {
            window.alert("Please select an opening time before your closing time");
            $(ddl).val(otherTime);
        }
    }
    else if (order == 2) {
        var otherTime = $(ddl).parent().parent().children("td.time-open").children("select").val();
        if (time < otherTime) {
            window.alert("Please select a closing time after your opening time");
            $(ddl).val(otherTime);
        }
    }
}
function CheckPhoneField(textfield) {
    textfield = $(textfield);
    textfield.css("background", "url(http://static.propertylinkonline.com/images/input_text_candy.gif) bottom right");
    var cleanedPhone = CleanPhone(textfield.val());
    if (cleanedPhone.length < 10) {
        textfield.val(cleanedPhone);
        textfield.css("background", "");
    }
    //    else if (cleanedPhone.length == 7) {
    //        PageMethods.GetLocalAreaCodeFromZipCode(GetCurrentZipCode(), textfield.attr("id"), GetLocalAreaCodeFromZipCodeComplete);
    //        textfield.val(cleanedPhone);
    //        textfield.css("background", "");
    //    }
    else if (cleanedPhone.length == 10) {
        textfield.val(StandardizePhone(cleanedPhone));
        textfield.css("background", "");
    }
    else if (cleanedPhone.length == 11 && cleanedPhone.substring(0, 1) == "1") {
        cleanedPhone = cleanedPhone.substring(1);
        textfield.val(StandardizePhone(cleanedPhone));
        textfield.css("background", "");
    }
    else if (cleanedPhone.length > 10) {
        var extension = cleanedPhone.substring(10);
        cleanedPhone = cleanedPhone.substring(0, 10);
        textfield.val(StandardizePhone(cleanedPhone));
        textfield.siblings("~ input").val(extension + textfield.siblings("~ input").val());
        textfield.css("background", "");
    }
}
function GetLocalAreaCodeFromZipCodeComplete(result) {
    var textfield = $("#" + result[1]);
    textfield.css("background", "");
    if (result[0] != "0") {
        var cleanedPhone = CleanPhone(textfield.val());
        if (cleanedPhone.length == 7) {
            cleanedPhone = result[0] + "" + cleanedPhone;
            textfield.val(StandardizePhone(cleanedPhone));
        }
    }
}
function GetCurrentZipCode() {
    return $("#page-property-summary-address-zipcode input").val();
}
//////////
////////// PAGE|Property-Edit-Amenities
//////////
function CancelPetModal() {
    $("#ctl00_ctl00_MainContent_EditingContent_txtPetTypeNew").val("");
    $("#ctl00_ctl00_MainContent_EditingContent_txtPetCommentNew").val("");
    $("#ctl00_ctl00_MainContent_EditingContent_txtPetRestrictionsNew").val("");
    tb_remove();
}
function CancelParkingModal() {
    $("#ctl00_ctl00_MainContent_EditingContent_ddlParkingTypeNew").val("Surface Lot");
    $("#ctl00_ctl00_MainContent_EditingContent_ddlParkingSpacesNew").val("0");
    $("#ctl00_ctl00_MainContent_EditingContent_txtParkingCommentNew").val("");
    tb_remove();
}
//////////
////////// PAGE|Property-Edit-Marketing
//////////
function CancelServiceModal() {
    $("#ctl00_ctl00_MainContent_EditingContent_ddlServiceNameNew").val("0");
    $("#ctl00_ctl00_MainContent_EditingContent_txtServiceDescriptionNew").val("");
    $("#ctl00_ctl00_MainContent_EditingContent_txtServiceDistanceNew").val("");
    $("#ctl00_ctl00_MainContent_EditingContent_txtServiceCommentNew").val("");
    tb_remove();
}
//////////
////////// PAGE|Property-Edit-Specials
//////////
function CancelSpecialModal() {
    $("#ctl00_ctl00_MainContent_EditingContent_ddlServiceNameNew").val("0");
    $("#ctl00_ctl00_MainContent_EditingContent_txtServiceDescriptionNew").val("");
    $("#ctl00_ctl00_MainContent_EditingContent_txtServiceDistanceNew").val("");
    $("#ctl00_ctl00_MainContent_EditingContent_txtServiceCommentNew").val("");
    tb_remove();
}
function ValidateConcessionDateEndIsCurrent(sender, args) {
    var calendarID = $(sender).attr("id").replace("vldDateEndCurrent", "dateControlEndDate_Calendar");

    var calendar = eval(calendarID);
    var selectedDate = calendar.getSelectedDate();

    var todayDate = new Date();
    todayDate.setTime(Date.parse(todayDate.toDateString()));

    args.IsValid = (selectedDate >= todayDate);
}
function ValidateConcessionDateEndIsWithinSixtyDays(sender, args) {
    var calendarID = $(sender).attr("id").replace("vldDateEndFuture", "dateControlEndDate_Calendar");

    var calendar = eval(calendarID);
    var selectedDate = calendar.getSelectedDate();

    var futureDate = new Date();
    futureDate.setTime(Date.parse(futureDate.toDateString()));
    futureDate.setDate(futureDate.getDate() + 60);

    args.IsValid = (selectedDate <= futureDate);
}
function ValidateRentDescriptionRequired(sender, args) {
    var src = $("#ctl00_ctl00_MainContent_ucContentDistributionPanel_ltvChannelGroups_ctrl0_ltvCheckControl_ctrl5_lnkChannelToggle").children("img").attr("src");

    if (src.substring((src.length - 5)) == "4.png") {
        var titleID = $(sender).attr("id").replace("vldRentDescRequired", "txtTitle");
        var value = $("#" + titleID).val();
        if (value == "" || value == null)
            args.IsValid = false;
        else
            args.IsValid = true;
    }
}
//////////
////////// PAGE|Property-Distribution-AvailabilityLinks
//////////
function CheckAvailabilityUrls(isPageLoad) {
    $("div.channel").each(function() {
        var providerID = $(this).find("select.provider").val();
        var urls = $(this).find("table.urls");
	//	alert(providerID);
        if (providerID == 0) {
            urls.find("input.url").val("").attr("readonly", "readonly").css("background", "#e6e6e6");
        }
        else if (providerID == 1) {
            var channelID = $(this).find("span.channelID").find("input").val();
            urls.find("input.url").val("").attr("readonly", "readonly").css("background", "#e6e6e6");
            urls.find("input.url").each(function(ref) {
                var rollupID = $(this).parent().children("input").val();
                if (rollupID.substr(0, 1) == 4) {
                    rollupID = rollupID.substr(2);
                } else rollupID = 0;
                $(this).val(GetPLAvailabilityUrl(channelID, PropertyID, rollupID));
            });
        }
        else {
            if (isPageLoad == false && urls.find("input.url").val().indexOf("www.propertylinkonline.com") >= 0 )
			{
                urls.find("input.url").val("").attr("readonly", "").css("background", "");
            }
        }
    });
}
function CheckAvailabilityUrlsPageLoad() {
    CheckAvailabilityUrls(true);
}
function CheckAvailabilityUrlsClick() {
    CheckAvailabilityUrls(false);
}
function GetPLAvailabilityUrl(channelID, propertyID, rollupID) {
    return "http://www.propertylinkonline.com/Availability/Availability.aspx?c=" + channelID + "&p=" + propertyID + "&r=" + rollupID;
}
//////////
////////// PAGE|Property-Availability-Units
//////////
// Set new units avail displayed count
function nUAD(a, f, n) {
    PageMethods.SetNewUAD(f, n, nUAD_Complete, AjaxFailed);
    function nUAD_Complete(result, userContext, methodName) {
        __doPostBack($(a).parent().parent().parent().parent().parent().attr("id").replace(/_/gi, "$").replace(/divRollups/gi, "auxPanelUpdateHook"), '')
    }
}
// Change unit rank with stars
function rS(a, u, r) {
    PageMethods.ChangeUnitRank(u, r, rS_Complete, AjaxFailed);
    function rS_Complete(result, userContext, methodName) {
        __doPostBack($(a).parent().parent().parent().parent().parent().parent().parent().parent().attr("id").replace(/_/gi, "$").replace(/udpUnits/gi, "auxPanelUpdateHook"), '')
    }
}
// Change unit rank with buttons
function rB(a, u, r) {
    PageMethods.ChangeUnitRank(u, r, rB_Complete, AjaxFailed);

    function rB_Complete(result, userContext, methodName) {
        __doPostBack($(a).parent().parent().parent().parent().parent().parent().attr("id").replace(/_/gi, "$").replace(/udpUnits/gi, "auxPanelUpdateHook"), '')
    }
}
//////////
////////// USERCONTROL|PropertyTickets
//////////
function eSR(ticketId) {
    $("#logs" + ticketId).slideToggle('fast');
    $("#logs" + ticketId).children("div").children("input").attr("id");
}
function tct(textbox) {
    if ($(textbox).val() == "add note here")
        $(textbox).val("");
}
//////////
////////// USERCONTROL|PickerAndCalendar
//////////
function picker_onSelectionChanged(sender, eventArgs) {
    sender.AssociatedCalendar.setSelectedDate(sender.getSelectedDate());
}
function calendar_onSelectionChanged(sender, eventArgs) {
    sender.AssociatedPicker.setSelectedDate(sender.getSelectedDate());
}
function calendarBtn_OnClick(alignElement, calendar) {
    if (calendar.get_popUpShowing()) {
        calendar.hide();
    }
    else {
        calendar.setSelectedDate(calendar.AssociatedPicker.getSelectedDate());
        calendar.show(alignElement);
    }
}
function calendarBtn_OnMouseUp(calendar, event) {
    if (calendar.get_popUpShowing()) {
        event.cancelBubble = true;
        event.returnValue = false;
        return false;
    }
    else {
        return true;
    }
}


function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    //MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
			+ myValue
			+ myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}