﻿
var SR_MaxListings = 1000;
var SR_GalleryStartWidth = null;

var SR_SetPageLayoutTimeout = 0
var SR_SetLastResizeWidth = 0;
var SR_SetLastResizeHeight = 0;
var SR_Submitted = false;
var __SearchPage = null;

var SE_PreLoadTest_SearchResults = 1;
$aa.SearchResults = {};
$aa.SearchResults.Format_Table = "table";
$aa.SearchResults.Format_List = "list";
$aa.SearchResults.Format_Map = "map";
$aa.SearchResults.Format_Gallery = "gallery";

function SR_SearchPage() {

    this.pageSetup_Delayed_SoFar = 0;
    this.attachEvents_Delayed_SoFar = 0;    
    
    this.$sr_results_container = $(".sr_results_container");
    this.$sr_results = this.$sr_results_container.find(".sr_results");
    this.$pnlResultsList = this.$sr_results.find(".pnlResultsList");  
    this.$sr_results_list = $("#sr_results_list");
    this.itemFormat = $("#hdnItemFormat").val();
    this.$sr_table = [];
    this.$sr_gallery_container = [];
    this.dropDownsLoadedByServer = SE_IsSlowClient;
    this.autoSubmitSearches = $("[id $= 'chkAutoSubmitSearches']").is(":checked");
    this.$sr_list_item = [];
    
    switch (this.itemFormat) {
        case "Table":
           this.$sr_table = this.$sr_results.find(".sr_table");
            $("[ id $= 'btnTable']").attr("href", "javascript:SE_NOP()");
            break;
        case "Gallery":
            this.$sr_gallery_container = this.$sr_results.find(".gallery-view");            
             $("[ id $= 'btnGallery']").attr("href", "javascript:SE_NOP()");
             break;
        case "List":
            this.$sr_list_item = this.$sr_results.find(".sr_list_item");
            $("[ id $= 'btnList']").attr("href", "javascript:SE_NOP()");
            break;
        case "Map":
            $("[ id $= 'btnMap']").attr("href", "javascript:SE_NOP()");
            break;
    }       
   
    this.$results = this.$sr_results_list.contents().detach();
    
    this.$sr_map_container =[];
    this.hasMap = $("#hdnHasMap").val() == "1";
    if (this.hasMap)
        this.$sr_map_container = $(".sr_map_container");

    
    this.mapLocation = $("#hdnMapLocation").val();
    this.$sr_map_container_right = [];
    switch (this.mapLocation) {
        case "Right":
            this.$sr_map_container_right = $(".sr_map_container_right");
            break;
    }
    $("#chkFilterOnMap").live("click", function(){SB_MapFilterClick(this);});
    
    this.searchBarLocation = $("#hdnSearchBarLocation").val();
    this.$sr_search_container_vertical = [];
    switch (this.searchBarLocation) {
        case "Top":
            break;
        default:
            this.$sr_search_container_vertical = $(".sr_search_container_vertical");
            break;
    }

    $(".sb_container").keypress(function (event) {
        if (event.which == '13') {
            SB_SubmitSearchForce(event);
        }
    });
   
}

function SR_PageSetup() {

    __SearchPage = new SR_SearchPage();
    SR_Submitted = false;
    SR_SetPageLayoutTimeout = 0;
    
    __SearchPage.pageSetup_Delayable();
    var $divActionPicker = $("#divActionPicker");

    if ($divActionPicker.length > 0 && __SearchPage.$results.find(".sr_checkbox_label, .sr_checkbox").length > 0) {
         $divActionPicker.appendTo($("#divAAActionsContainer"));
   }

   $("[id $= 'btnPrev'], [id $= 'btnNext'], .sr_view_button, .sr_map_position_control_a ").not(":disabled").not(".active").bind("click", SB_ShowResultsLoading);
    $(".sr_sort_list").bind("change", SB_ShowResultsLoading);
    SE_LoadDropDownWithIntegers($("[ id$='ddlCurrentPage']"), 1, $("[ id $= 'hdnPageCount']").val(), $("[ id $= 'hdnCurrentPage']").val());
    SR_LoadFriendlyURLs();
    __SearchPage.setPageLayoutSizes();
    SR_SetupCheckboxes();
    
    var pager = __SearchPage.$sr_results.find("[ id $='divPager']");
    var pagerWidth = pager.find(".pager_count").outerWidth(true) + pager.find(".pager_nav").outerWidth(true);
    if (pagerWidth > pager.width())
        pager.width(pagerWidth + 2);

    SR_GalleryViewSetup();
    
    if ($aa.pageSettings) {
        $aa.pageSettings.pageTitle = $("[ id $='hdnPageTitle']", __SearchPage.$sr_results_container.parent()).val();
        //$("title").html($aa.pageSettings.pageTitle)
    }
 
}

SR_SearchPage.prototype.pageSetup_Delayable = function () {
    var maxDelay = 3000;
    var thisDelay = 250;
    
    if (SE_IsSlowClient
        && (this.map == null || !this.map.tilesLoaded)
        && this.pageSetup_Delayed_SoFar < maxDelay) {
        var thisSearchPage = this;
        this.pageSetup_Delayable_timeout = setTimeout(function () { thisSearchPage.pageSetup_Delayable(); }, thisDelay);
        this.pageSetup_Delayed_SoFar += thisDelay;
    }
    else {
        $(window).bind("resize", SR_DelayedSetPageLayoutSizes);
        this.hoverState();
        $hdnPageTitle = $("[id $= 'hdnPageTitle']");
        if ($hdnPageTitle.val() != "")
            $(".pagetitle, .PageTitle").html($hdnPageTitle.val());
        var $pagerNav = $(".pager_nav input[disabled=disabled]");
        $pagerNav.parents("li").fadeTo(0, 0.5);
        $pagerNav.parents("span").css("cursor", "default");
        SR_SetActiveViewButtons();
    
    }
}

function SR_LoadFriendlyURLs() {
    if ($("#divFriendlyURLs").length > 0 && $("#divFriendlyURLs").html().length > 0 && SR_FriendlyURL != null) {
        SR_FriendlyURL = new Array();
        var friendlyUrls = $("#divFriendlyURLs").html();
        friendlyUrls = friendlyUrls.replace("<!--", '').replace("-->", '');
        eval(friendlyUrls);
    }
}

function SR_DelayedSetPageLayoutSizes() {

    if (Math.abs(SR_SetLastResizeWidth - $(window).width()) < 50
        && Math.abs(SR_SetLastResizeHeight - $(window).height()) < 50)
        return;
    if (SR_SetPageLayoutTimeout != 0)
        clearTimeout(SR_SetPageLayoutTimeout);

    if (SE_IsSlowClient)
        SR_SetPageLayoutTimeout = setTimeout(function () { __SearchPage.setPageLayoutSizes(); }, 10);
    else
        __SearchPage.setPageLayoutSizes();
}

SR_SearchPage.prototype.setPageLayoutSizes = function () {

    if (this.itemFormat == "Table")
        this.$sr_table.hide();
    SR_SetLastResizeWidth = $(window).width();
    SR_SetLastResizeHeight = $(window).height();

    SR_SetContentSize();
    SR_SetSearchAreaSizes();
    // add the stuff that we removed for performance reasons
    this.$sr_results_list.append(__SearchPage.$results);

    this.setup_AddThis();

    SR_SetMapSize();

    SR_SetGallerySizes();
    SR_SetListSizes();
    SR_SetTableSizes();

    if (SR_ShowLoadingCover)
        SR_ShowLoadingCover(false);
    if (this.map) {
        //alert('update map')
    }
    else {
        if (this.hasMap && SR_MapInit)
            SR_MapInit();
        if (this.hasMap || SR_MapWidget_Id)
            this.setMap();
    }

}

SR_SearchPage.prototype.setup_AddThis = function () {
    if (typeof (addthis) != 'undefined') {
        addthis_config = {
            ui_delay: "500",
            services_exclude: "email,print,printfriendly,favorites",
            ui_click: "true",
            data_ga_tracker: (typeof (pageTracker) != 'undefined' ? pageTracker : null),
            ui_offset_top: 0,
            ui_offset_left: 0
        }
        addthis_close();
        addthis.button('.lnk_addthis', window.addthis_config);
    }
}

function SR_SetContentSize() {

    if (typeof (aws_HasMasterTable) != 'undefined'
        && aws_HasMasterTable == true
        && typeof (SetMasterTableWidth) == 'function')
        SetMasterTableWidth();
            
    __SearchPage.$sr_results_list.css("width", "auto");
    __SearchPage.$sr_results_container.css("width", "auto");
    
    __SearchPage.$sr_results_container.resizeToFillContainerWidth(__SearchPage.$sr_search_container_vertical);

    if (__SearchPage.$sr_map_container_right.length > 0
        && __SearchPage.$sr_results_container.width() < 2 * __SearchPage.$sr_map_container_right.width())
        __SearchPage.$sr_map_container_right.width(__SearchPage.$sr_results_container.width() / 2);

    __SearchPage.$sr_results.resizeToFillContainerWidth(__SearchPage.$sr_map_container_right);
    __SearchPage.$sr_results_list.resizeToFillContainerWidth();

}

function SR_SetButtons() {
    alert(ctl.id)
    return false;
}

function SR_SetMapSize() {
    if (__SearchPage.hasMap) {
        var $mapContainer = __SearchPage.$sr_map_container
        if ($mapContainer.is(":hidden")) {
            $mapContainer.show();
        }
        if (__SearchPage.$sr_search_container_vertical.length > 0 
            && $mapContainer.hasClass("sr_map_container_right")) {
            var maxChildWidth = 0;
            __SearchPage.$pnlResultsList.children().each(function () {
                if ($(this).width() > maxChildWidth)
                    maxChildWidth = $(this).width();
            })
            if (maxChildWidth > __SearchPage.$sr_results.width()) {
                $mapContainer.width(__SearchPage.$sr_results.outerWidth() - maxChildWidth);
            }
        }
        else {
            var $container = $(".sr_map_container_top,.sr_map_container_mapformat ");
            if ($container.length > 0) {
                $container.resizeToFillContainerWidth();
            }           
        }
    }
}

function SR_ToggleMap(ctlID, show) {
    if (show)
        $("#" + ctlID).show();
    else
        $("#" + ctlID).hide();
}

function SR_SetGallerySizes() {

    if (__SearchPage.$sr_gallery_container.length > 0) {

        var maxCols = 1;
        var currentCol = 1;
        __SearchPage.$sr_gallery_container.css("padding-left", "");
        __SearchPage.$sr_gallery_container.css("padding-right", "");
        if (!SR_GalleryStartWidth)
            SR_GalleryStartWidth = __SearchPage.$sr_gallery_container.width();
        else
            __SearchPage.$sr_gallery_container.width(SR_GalleryStartWidth);

        var extraSpace = __SearchPage.$sr_gallery_container.outerWidth(true) - __SearchPage.$sr_gallery_container.width();
        var origWidth = __SearchPage.$sr_gallery_container.outerWidth(true);
        var availableWidth =__SearchPage.$sr_results_list.availableWidth();

        maxCols = Math.max(1, Math.floor(availableWidth / origWidth));

        var totalWidthIncrease = Math.max(0, (availableWidth / maxCols) - origWidth);

        var increasedPaddingPerSide = parseInt((totalWidthIncrease) / 2 / 2);
        var increasedInnerWidth = parseInt(totalWidthIncrease / 3);

        var origPaddingLeft = parseInt((__SearchPage.$sr_gallery_container.css("padding-left") || __SearchPage.$sr_gallery_container.css("padding")).replace("px", ""));
        var origPaddingRight = parseInt((__SearchPage.$sr_gallery_container.css("padding-right") || __SearchPage.$sr_gallery_container.css("padding")).replace("px", ""));
        var origWidth = parseInt((__SearchPage.$sr_gallery_container.css("width") || __SearchPage.$sr_gallery_container.css("width")).replace("px", ""));
        
        if (maxCols > 1) {
            var maxHeightsByRow = new Array();
            var row = 0;
            currentCol = 0;
            var rowByIndex = [];

            __SearchPage.$sr_gallery_container.each(function (index) {

                if (maxHeightsByRow[row])
                    maxHeightsByRow[row] = Math.max(maxHeightsByRow[row], $(this).height());
                else
                    maxHeightsByRow[row] = $(this).height();
                rowByIndex[index] = row;
                if ($(this).offset().left < 50)
                    currentCol = 0;
                if ((currentCol + 1) % maxCols == 0) {
                    $(this).after("<div class=\"clearfix\"></div>");
                    row++;
                }
                currentCol++;
            })

            row = 0;

            __SearchPage.$sr_gallery_container.each(function (index) {
                $(this).height(maxHeightsByRow[rowByIndex[index]]);
            })
        }

        if (maxCols > 1 && __SearchPage.$sr_gallery_container.length > 1) {
            if (__SearchPage.$sr_gallery_container.outerWidth(true) * maxCols <__SearchPage.$sr_results_list.availableWidth()) {

                __SearchPage.$sr_gallery_container.each(function () {
                    $(this).width($(this).width() + increasedInnerWidth);
                    $(this).css("padding-left", (origPaddingLeft + increasedPaddingPerSide) + "px");
                    $(this).css("padding-right", (origPaddingRight + increasedPaddingPerSide) + "px");

                });
            }
        }
        else if (__SearchPage.$sr_gallery_container.length > 0 && totalWidthIncrease > 0) {
            var forcedMaximumSingleGalleryColumnWidth = 475;
            var expansionSpace = 0;

            if (availableWidth > forcedMaximumSingleGalleryColumnWidth) {
                expansionSpace = forcedMaximumSingleGalleryColumnWidth - origWidth;
                increasedPaddingPerSide = parseInt(expansionSpace / 2 / 2);
                increasedInnerWidth = parseInt(expansionSpace / 3);

                __SearchPage.$sr_gallery_container.each(function () {

                    $(this).width($(this).width() + increasedInnerWidth);
                    $(this).css({ "padding-left": (origPaddingLeft + increasedPaddingPerSide) + "px",
                        "padding-right": (origPaddingRight + increasedPaddingPerSide) + "px"
                    });
                });
            }
            else {
                var increasedPaddingPerSide = parseInt((totalWidthIncrease) / 2 / 2);
                var increasedInnerWidth = parseInt(totalWidthIncrease / 3);
                __SearchPage.$sr_gallery_container.each(function () {

                    $(this).width($(this).width() + increasedInnerWidth);
                    $(this).css({"padding-left": (origPaddingLeft + increasedPaddingPerSide) + "px", 
                        "padding-right": (origPaddingRight + increasedPaddingPerSide) + "px"});
                });
            }
        }
        else if (__SearchPage.$sr_gallery_container.length > 0 && totalWidthIncrease == 0) {
            $galleryPhotoImage = $(".sr_gallery_photo img");
            var reducedOperatingWidth = parseInt(availableWidth) - parseInt(extraSpace);
            var origImgWidth = $galleryPhotoImage.width();
            var origImgHeight = $galleryPhotoImage.width();
            var imgReductionPercentage = reducedOperatingWidth / origImgWidth;

            __SearchPage.$sr_gallery_container.each(function () {
                $(this).width(reducedOperatingWidth);
            });

            $(".sr_gallery_photo").each(function () {
                if ($(this).width() != reducedOperatingWidth)
                    $(this).width(reducedOperatingWidth);
            });

            var newWidth = Math.floor(origImgWidth * imgReductionPercentage);
            var newHeight = Math.floor(origImgHeight * imgReductionPercentage);
            $galleryPhotoImage.each(function () {
                if ($(this).width() != newWidth)
                    $(this).width(newWidth);
                if ($(this).height() != newHeight)
                    $(this).height(newHeight);
            });

        }
    }
}

function SR_SetListSizes() {

    if (__SearchPage.$sr_list_item.length > 0) {

        var $sr_list_photo = $(".sr_list_photo");
        var $sr_list_address = $(".sr_list_address");
        var origWidth = __SearchPage.$sr_list_item.outerWidth(true);
        var imgWidth = $sr_list_photo.outerWidth(true);
        var remainingWidth = $sr_list_address.availableWidth() - parseInt(imgWidth);        
        var forcedMinimumListViewAddressModifyWorthyWidth = 122;
        if (remainingWidth >= forcedMinimumListViewAddressModifyWorthyWidth)
            $sr_list_address.width(remainingWidth);
        else 
            $sr_list_address.width(forcedMinimumListViewAddressModifyWorthyWidth);
    }
}

function SR_SetTableSizes() {
   
    if (__SearchPage.$sr_table.length > 0) {
    
        var minimumTableFullWidth = 673;
        var minimumTableMediumWidth = 425;
        var $fullRow = $(".sr_table_row_full");
        var $medRow = $(".sr_table_row_medium");
        var $shortRow = $(".sr_table_row_short");
        var $veryShortRow = $(".sr_table_veryshort");
        var availableWidth = __SearchPage.$sr_table.availableWidth();
        $veryShortRow.hide();
        $(".sr_table_veryshort_hide").show();
        switch (true) {
            case availableWidth > minimumTableFullWidth:
                $fullRow.show();
                $medRow.hide()
                $shortRow.hide();
                break;
            case availableWidth < minimumTableMediumWidth:
                $fullRow.hide();
                $medRow.hide()
                $shortRow.show();
                break;
            default:
                $fullRow.hide();
                $medRow.show();
                $shortRow.hide();
        }

        __SearchPage.$sr_table.width(100);
        __SearchPage.$sr_table.show();
        
        if ($fullRow.is(":visible") && __SearchPage.$sr_table.width() > availableWidth) {
            $fullRow.hide();
            $medRow.show();
        }
        if ($medRow.is(":visible") && __SearchPage.$sr_table.width() > availableWidth) {
            $medRow.hide();
            $shortRow.show();
        }

        if ($shortRow.is(":visible") && __SearchPage.$sr_table.width() > availableWidth) {
            $veryShortRow.show();
            $(".sr_table_veryshort_hide").hide();
        }
        __SearchPage.$sr_table.width(availableWidth);
        __SearchPage.$sr_table.show();

        var $ddlActiveSold = $("[id$='ddlActiveSold']");
        if ($ddlActiveSold.length > 0) {
            var typeoflisting = $ddlActiveSold.find(':selected').text();
            if (typeoflisting != 'Active Listings')
                $("#trListDate").html('Close&#160;Date');
        }       
    }
}

function SR_SetSearchAreaSizes() {
    if (__SearchPage.$sr_search_container_vertical.length > 0) {
        __SearchPage.$sr_search_container_vertical.height(
            Math.max(__SearchPage.$sr_search_container_vertical.height(), __SearchPage.$sr_results.height()));
    }
}

var SR_Map = null;
var SR_Map_Id = "";
var SR_MapInit = null;
var SR_MapWidget_Id = "";

SR_SearchPage.prototype.setMap = function () {

    if (SR_Map_Id != "" && this.hasMap)
        this.map = eval(SR_Map_Id);
    else if (SR_MapWidget_Id) {
        this.map = eval(SR_MapWidget_Id);     
    }
    else
        this.map = null;
}

var SR_LoadingTimeout = null;
function SR_ShowLoadingCover(show) {

    SR_LoadingTimeout = MLX_LoadingDialog(show, "", "", SR_LoadingTimeout);
}

SR_SearchPage.prototype.hoverState = function() {
    //hover states
    $('.pager_no_button, .sr_view_button').not(":disabled").hover(
    function () {
        if ( $(this).parents('li').length > 0)
            $(this).parents('li').removeClass('ui-state-default').addClass('ui-state-hover'); 
        else
            $(this).removeClass('ui-state-default').addClass('ui-state-hover'); 
        },
	function () {
		if ( $(this).parents('li').length > 0)
			$(this).parents('li').removeClass('ui-state-hover').addClass('ui-state-default');
		else
            $(this).removeClass('ui-state-hover').addClass('ui-state-default'); 
        }
	);
    this.setMapHover();
}

SR_SearchPage.prototype.setMapHover = function () {

    if (this.hasMap || SR_MapWidget_Id) {
        var thisSearchPage = this;
        var hoverItems = this.$sr_list_item.length > 0 ? this.$sr_list_item.find('.sr_list_row_content') : this.$sr_gallery_container;
        if (hoverItems.hover)
        {
            hoverItems.hover(
            function () {
                thisSearchPage.mapTooltip($(this).attr("mapMarkerOrdinal"), true);
            },
            function () {
                thisSearchPage.mapTooltip($(this).attr("mapMarkerOrdinal"), false);
            }
            );
        }
    }
}

SR_SearchPage.prototype.mapTooltip = function (ordinal, isHighlight) {

    this.setMap();
    if (this.map != null)
        this.map.highlightAndTooltip(ordinal, isHighlight);
}

var SR_IsOpeningDialog = false;
function SR_VL(listingID) {

    if (!SR_IsOpeningDialog) {
        SE_VL(listingID);
    }
}

function SR_ListingImageDialog(listingID, listingTitle, imageCount, showMap, isMappable, isOpenHomesPage, event) {

    if (imageCount > 0 || showMap) {
        SR_IsOpeningDialog = true;
        setTimeout(function () { SR_IsOpeningDialog = false; }, 2000);
        //prevent the browser from following the link
        SE_CancelEvent(event);
        if (typeof (SEMap.ClosePopups) == 'function') {
            SEMap.ClosePopups();
        }

        var url = SE_SR_MediaPopupUrl + "?listingid=" + listingID
            + "&action=" + (showMap ? "viewmap" : "")
            + "&hidemap=" + (isMappable ? "0" : "1")
            + "&isopenhomespage=" + (isOpenHomesPage ? "0" : "1")
            + "&" + MLX_UniqueString();
           //url = "/search/mediapopup.htm?" + MLX_UniqueString()
        $(".sr_listing_image_popup").remove();
        var dialogDiv = $('<div style="display:hidden;" class="sr_listing_image_popup"></div>').appendTo('body');
        dialogDiv.html("<div style='text-align:center;'>--</div>");
        dialogDiv.load("/common/loading.htm");
        var dialogWidth = 600;
        dialogDiv.dialog({
            width: dialogWidth,
            width: 600,
            minHeight: 400,
            modal: true,
            title: listingTitle,
            beforeclose: function () {
                if (typeof (media) != 'undefined' && media.map) {
                    media.map.killMe();
                    media.map = null;
                }
                if (typeof (media) != 'undefined'
                        && media
                        && media.Photos_StopSlideShow) {
                    media.Photos_StopSlideShow()
                }
                if (typeof (SEMap.ClosePopups) == 'function')
                    SEMap.ClosePopups(true);
            }
        });
        $(".ui-dialog").cl_shadow();
        
        // load remote content
        dialogDiv.load(
        url,
        null,
        function (responseText, textStatus, XMLHttpRequest) {
            
            if (typeof (media) != 'undefined' && media.map)
                media.map.isloading = true;
            SR_IsOpeningDialog = false;
            if (textStatus == 'error') {
                dialogDiv.html("<div style='text-align:center;'>We had a problem retrieving the information you requested."
                    + "<br/>An error was returned.<br/>Please try again.</div>");
            }
            else if (!responseText || responseText == '') {
                dialogDiv.html("<div style='text-align:center;'>We had a problem retrieving the information you requested."
                    + "<br/>No content was returned.<br/>Please try again.</div>");
            }
            dialogDiv.dialog("option", "position", "center");
        });

    }
    return false;
}

function SR_ViewSummary(url) {
    SE_OpenWin(url, 300, 300, 'SearchSummary');
}

function SR_ClickSaveSearch() {
    $("[id $= 'btnSaveSearch']").click();
}

function SR_SetActiveViewButtons() {

    var objListActive = $("a.btn-list span.bg-list").find('span.ui-icon-check');
    if (objListActive.is(":visible")) {
        $("a.btn-list").addClass("active");
    }

    var objGalleryActive = $("a.btn-gallery span.bg-gallery").find('span.ui-icon-check');
    if (objGalleryActive.is(":visible")) {
        $("a.btn-gallery").addClass("active");
    }

    var objMapActive = $("a.btn-map span.bg-map").find('span.ui-icon-check');
    if (objMapActive.is(":visible")) {
        $("a.btn-map").addClass("active");
    }

    var objTableActive = $("a.btn-table span.bg-table").find('span.ui-icon-check');
    if (objTableActive.is(":visible")) {
        $("a.btn-table").addClass("active");
    }
}

function SR_GalleryViewSetup() {

    $(".gallery-view").each(function () {

        var front = $(this).children("div.switch-box-cover");
        var back = $(this).children("div.switch-box-details");
        front.click(function () {
            $(this).addClass("invisible");
            back.removeClass("invisible");
        });
        back.click(function () {
            $(this).addClass("invisible");
            front.removeClass("invisible");
        });
    });
}

// searchbar methods
function SB_SubmitSearch(event) {

    if (__SearchPage.autoSubmitSearches)
    {
        SB_SubmitSearchForce(event);
    }
}

function SB_SubmitSearchForce(event) {
    if (!SR_Submitted && ((MLX_SysPageRequestManagerExists() && !Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) || !MLX_SysPageRequestManagerExists())) {
        SR_Submitted = true; ;
        SE_CancelEnterKey(event);
        SB_ShowResultsLoading();
        $("[id $= 'btnSearchBarSearch']").click();
    }
}

function SB_ShowResultsLoading() {
    if (SR_ShowLoadingCover) {
        SR_ShowLoadingCover(true);
    }
}
var SB_PreventSubmit = false;
var SB_SchoolDistricts = null;

function SB_AttachEvents() {
    __SearchPage.attachEvents_Delayable();

    SB_LoadPrices();
    SB_LoadSqFt();
    if (__SearchPage.autoSubmitSearches)
    {
        $(".sb_criteria").change(SB_SubmitSearch);
        $(".sb_criteria_check").click(SB_SubmitSearch);
    }
    if ($("#" + SB_ctlLocationSuggestorID + "_hidSearch").length > 0) {
        var suggestor = eval(SB_ctlLocationSuggestorID + '_suggestor');
        suggestor.afterSelect = SB_AddLocation;
        suggestor.clearTextBox();
        suggestor.clearCache = true;
    }

    SR_ScrollToResults();
    SB_SetLocationBoxFocus();
}

SR_SearchPage.prototype.attachEvents_Delayable = function () {
    var maxDelay = 3000;
    var thisDelay = 250;

    if (SE_IsSlowClient
        && (this.map == null || !this.map.tilesLoaded)
        && this.attachEvents_Delayed_SoFar < maxDelay) {
        var thisSearchPage = this;
        this.attachEvents_Delayable_timeout = setTimeout(function () { thisSearchPage.attachEvents_Delayable(); }, thisDelay);
        this.attachEvents_Delayed_SoFar += thisDelay;
    }
    else {
        $("[id $= 'divSearchBar']").live("keydown", function (e) {
            // keep the enter key local
            if (!e)
                e = window.event;

            if (e.keyCode == 13) {
                SB_PreventSubmit = true;
                setTimeout(function () { SB_PreventSubmit = false; }, 100);
            }
        });
        this.loadMLSAreas();
        this.loadSchoolDistricts();
        $(".note_expand").click(function () {
            $('a .ui-icon', this).toggleClass('ui-icon-carat-1-s');
            $(this).next().slideToggle();
        });
        var thisSearchPage = this;
        $("[id $= 'chkAutoSubmitSearches']").click(function () { thisSearchPage.SB_SaveAutoSubmit(); });
    }
}

function SB_SetLocationBoxFocus() {
    if (!SB_IsMapSearch() && !SR_IsPostBack)
    {
        var $locSuggestor = $("#" + SB_ctlLocationSuggestorID + "_txtSearch");
        if ($locSuggestor.is(":visible")) 
            $locSuggestor.focus();
    }
}
function SR_ScrollToResults() {

    var hdnScrollToResults = document.getElementById(SR_ClientID + "_hdnScrollToResults");
    
    if (hdnScrollToResults.value != "") {
        $(document).scrollTop(__SearchPage.$sr_results_container.offset().top);
        hdnScrollToResults.value = "";
    }
}

function SB_IsMapSearch() {
    if (__SearchPage.isMapSearch == null)
        __SearchPage.isMapSearch = $("[id $= 'chkMapSearch']").attr("checked");
    return __SearchPage.isMapSearch;
}
function SB_SetMapSearch(isMapSearch) {
    __SearchPage.isMapSearch = isMapSearch;
    if (isMapSearch)
        $("[id $= 'chkMapSearch']").attr("checked", "checked");
    else
        $("[id $= 'chkMapSearch']").removeAttr("checked");
}

function SB_SubmitMapChange() {
    $(".sr_map_chk_filter").attr("checked", "checked");
    SB_SubmitSearchForce();
}

SR_SearchPage.prototype.SB_SaveAutoSubmit = function () {
    this.autoSubmitSearches = $("[id $= 'chkAutoSubmitSearches']").is(":checked");
    if (this.autoSubmitSearches) {
        $(".sb_criteria").change(SB_SubmitSearch);
        $(".sb_criteria_check").click(SB_SubmitSearch);
    }
    else {
        $(".sb_criteria").unbind('change', SB_SubmitSearch);
        $(".sb_criteria_check").unbind('click', SB_SubmitSearch);
    }
    var url = SE_PrepURL(location.href) + "AutoSubmitSearch=" + (this.autoSubmitSearches ? "1" : "0") + "&" + MLX_UniqueString();
    $.get(url);
}

function SB_MapFilterClick(chk) {

    var isMapSearchRequest = $(chk).is(":checked");
    var isChange = SB_IsMapSearch() != isMapSearchRequest;
    if (isChange) {
        $("[id $= 'chkMapSearch']").attr("checked", isMapSearchRequest);
        SB_SubmitSearch();
    }
}

var SB_MLSAreas = null;
var SB_MLSAreasBasedOnCountyItems = null
var SB_MLSAreasAutocompleteSource = function (request, response) {

    if (SB_IsMapSearch() || $("[id $= 'hidCountyItemIDs']").val() == '') {
        response(["Please narrow your search location before searching on MLS Area"]);
    }

    else if (SB_MLSAreas == null
        || $("[id $= 'hidCountyItemIDs']").val() != SB_MLSAreasBasedOnCountyItems) {

        SB_MLSAreasBasedOnCountyItems = $("[id $= 'hidCountyItemIDs']").val();
        var mlsAreaUrl = "/common/publicpropsearch/actionhandler.aspx?"
            + "&searchtype=mlsareaautocomplete&publicsearchid=" + $("[id $= 'hidPublicSearchID']").val()
            + "&" + MLX_UniqueString();
        $.getJSON(
	        mlsAreaUrl,
            function (data) {
                $.ajaxSetup({ cache: false });
                if (data && data.length > 0) {
                    SB_MLSAreas = data;
                    response(data);
                }
                else
                    response(["No mls areas found"]);
            });
    }
    else if (SB_MLSAreas)
        response(SB_MLSAreas);
}

SR_SearchPage.prototype.loadMLSAreas = function() {
    var txtMLSAreas = $("[id $= 'txtMLSAreas']").autocomplete({
        source: SB_MLSAreasAutocompleteSource,
        minLength: 0,
        select: function (event, ui) {
            if (ui && ui.item && ui.item.countyItem) {
                $("[id $= 'hidSelectedMLSArea']").val(ui.item.countyItem);
                SB_SubmitSearch();
            }
        }
    })
    
    txtMLSAreas.showDefaultText("Add MLS area", "ac_defaultTextActive");
    
    // drop down the full list on first click
    txtMLSAreas.focus(function () {
        if ($(this).val() == "")
            txtMLSAreas.autocomplete("search", "");
    });
}

var SB_SchoolDistricts = null;
var SB_SchoolDistrictBasedOnCountyItems = null
var SB_SchoolDistrictAutocompleteSource = function (request, response) {
     if (SB_IsMapSearch() || $("[id $= 'hidCountyItemIDs']").val() == '') {
        response(["Please narrow your search location before searching on school district"]);
    }    
    else if (SB_SchoolDistricts == null
        || $("[id $= 'hidCountyItemIDs']").val() != SB_SchoolDistrictBasedOnCountyItems) {
        
        SB_SchoolDistrictBasedOnCountyItems = $("[id $= 'hidCountyItemIDs']").val();
        var schoolDistrictUrl = "/common/publicpropsearch/actionhandler.aspx?"
            + "&searchtype=schooldistrictautocomplete&publicsearchid=" + $("[id $= 'hidPublicSearchID']").val()
            + "&" + MLX_UniqueString();
        $.getJSON(
	        schoolDistrictUrl,
            function (data) {
                if (data && data.length > 0) {
                    SB_SchoolDistricts = data;
                    response(data);
                }
                else
                    response(["No districts found"]);
            });
    }
    else if (SB_SchoolDistricts)
        response(SB_SchoolDistricts);
}

SR_SearchPage.prototype.loadSchoolDistricts = function() {
    var txtSchoolDistricts = $("[id $= 'txtSchoolDistricts']").autocomplete({
        source: SB_SchoolDistrictAutocompleteSource,
        minLength: 0,
        select: function (event, ui) {
            if (ui && ui.item && ui.item.countyItem) {
                $("[id $= 'hidSelectedSchoolDistrict']").val(ui.item.countyItem);                
                SB_SubmitSearch();
            }
        }
    })
    
    txtSchoolDistricts.showDefaultText("Add School District", "ac_defaultTextActive");

    // drop down the full list on first click
    txtSchoolDistricts.focus(function () {
        if ($(this).val() == "")
            txtSchoolDistricts.autocomplete("search", "");
    });
}


function SB_AddLocation(event) {

    var suggestor = eval(SB_ctlLocationSuggestorID + '_suggestor');
    var newLocationJSON = suggestor.getLocationQuery();
    if (newLocationJSON && newLocationJSON.value && newLocationJSON.value.length > 0) {
        suggestor.clearTextBox();
        SB_ShowResultsLoading();
        $("[id $= 'btnAddLocation']").click();
    }
    else {
        alert("Please select a location from the list.");
    }
}

function SB_ShowLocationFilters(show) {

    if (show == 'toggle') {
        $(".sb_vertical * [id $= 'divMoreLocationFiltersContent']").slideToggle();
    }
    else if (show) {
        $(".sb_vertical * [id $= 'divMoreLocationFiltersContent']").show();
    }
    else {
        $(".sb_vertical * [id $= 'divMoreLocationFiltersContent']").hide();
    }

    if ($(".sb_vertical * [id $= 'divMoreLocationFiltersContent'] :visible").length > 0) {
        $("[id $= 'hidMoreLocationFiltersState']").val("open");
        $('.sr_location_filters_link .ui-icon').toggleClass('ui-icon-carat-1-s');
    }
    else {
        $("[ id$= 'hidMoreLocationFiltersState']").val("closed");
        $('.sr_location_filters_link .ui-icon').toggleClass('ui-icon-carat-1-n');
    }
    $(".sr_search_container_vertical").height("auto");
}

function SB_ShowMoreOptions(show) {

    var oldStateIsOpen = $("[id $= 'divMoreOptions'] :visible").length > 0;
    var newStateIsOpen = false;
    if (show == 'toggle') {
        $("[id $= 'divMoreOptions']").toggle();
        newStateIsOpen = !oldStateIsOpen;
    }
    else if (show) {
        $("[id $= 'divMoreOptions']").show();
        newStateIsOpen = true;
    }
    else {
        $("[id $= 'divMoreOptions']").hide();
        newStateIsOpen = false;
    }

    if (newStateIsOpen) {
        $("[id $= 'hidMoreOptionsState']").val("open");
        $('.sr_more_options_link .ui-icon').addClass('ui-icon-carat-1-n');
        $('.sr_more_options_link .ui-icon').removeClass('ui-icon-carat-1-s');
    }
    else {
        $("[ id$= 'hidMoreOptionsState']").val("closed");
        $('.sr_more_options_link .ui-icon').addClass('ui-icon-carat-1-s');
        $('.sr_more_options_link .ui-icon').removeClass('ui-icon-carat-1-n');
    }
    $(".sr_search_container_vertical").height("auto");
}

function SB_LoadPrices() {
    if (__SearchPage.dropDownsLoadedByServer) 
        return;
        
    var minFirstOption = "<option value=''>Minimum</option>\
    ";
    var maxFirstOption = "<option value=''>Maximum</option>\
    ";
    var rentalOnlyOptions = '\
        <option value="0">$0</option>\
        <option value="100">$100</option>\
        <option value="200">$200</option>\
        <option value="300">$300</option>\
        <option value="400">$400</option>\
        <option value="500">$500</option\
        <option value="600">$600</option>\
        <option value="700">$700</option>\
        <option value="800">$800</option>\
        <option value="900">$900</option>\
        <option value="1000">$1,000</option>\
        <option value="1100">$1,100</option>\
        <option value="1200">$1,200</option>\
        <option value="1300">$1,300</option>\
        <option value="1400">$1,400</option>\
        <option value="1500">$1,500</option>\
        <option value="1600">$1,600</option>\
        <option value="1700">$1,700</option>\
        <option value="1800">$1,800</option>\
        <option value="1900">$1,900</option>\
        <option value="2000">$2,000</option>\
        <option value="2500">$2,500</option>\
        <option value="3000">$3,000</option>\
        <option value="4000">$4,000</option>\
        <option value="5000">$5,000</option>\
        <option value="10000">$10,000</option>';
    var saleOnlyOptions = '\
        <option value="25000">$25,000</option>\
        <option value="50000">$50,000</option>\
        <option value="75000">$75,000</option>\
        <option value="100000">$100,000</option>\
        <option value="125000">$125,000</option>\
        <option value="150000">$150,000</option>\
        <option value="175000">$175,000</option>\
        <option value="200000">$200,000</option>\
        <option value="225000">$225,000</option>\
        <option value="250000">$250,000</option>\
        <option value="275000">$275,000</option>\
        <option value="300000">$300,000</option>\
        <option value="325000">$325,000</option>\
        <option value="350000">$350,000</option>\
        <option value="375000">$375,000</option>\
        <option value="400000">$400,000</option>\
        <option value="425000">$425,000</option>\
        <option value="450000">$450,000</option>\
        <option value="475000">$475,000</option>\
        <option value="500000">$500,000</option>\
        <option value="525000">$525,000</option>\
        <option value="550000">$550,000</option>\
        <option value="575000">$575,000</option>\
        <option value="600000">$600,000</option>\
        <option value="625000">$625,000</option>\
        <option value="650000">$650,000</option>\
        <option value="675000">$675,000</option>\
        <option value="700000">$700,000</option>\
        <option value="725000">$725,000</option>\
        <option value="750000">$750,000</option>\
        <option value="775000">$775,000</option>\
        <option value="800000">$800,000</option>\
        <option value="825000">$825,000</option>\
        <option value="850000">$850,000</option>\
        <option value="875000">$875,000</option>\
        <option value="900000">$900,000</option>\
        <option value="925000">$925,000</option>\
        <option value="950000">$950,000</option>\
        <option value="975000">$975,000</option>\
        <option value="1000000">$1M</option>\
        <option value="1100000">$1.10M</option>\
        <option value="1200000">$1.20M</option>\
        <option value="1250000">$1.25M</option>\
        <option value="1300000">$1.30M</option>\
        <option value="1400000">$1.40M</option>\
        <option value="1500000">$1.50M</option>\
        <option value="1600000">$1.60M</option>\
        <option value="1700000">$1.70M</option>\
        <option value="1750000">$1.75M</option>\
        <option value="1800000">$1.80M</option>\
        <option value="1900000">$1.90M</option>\
        <option value="2000000">$2M</option>\
        <option value="2250000">$2.25M</option>\
        <option value="2500000">$2.50M</option>\
        <option value="2750000">$2.75M</option>\
        <option value="3000000">$3M</option>\
        <option value="3250000">$3.25M</option>\
        <option value="3500000">$3.50M</option>\
        <option value="3750000">$3.75M</option>\
        <option value="4000000">$4M</option>\
        <option value="4250000">$4.25M</option>\
        <option value="4500000">$4.50M</option>\
        <option value="4750000">$4.75M</option>\
        <option value="5000000">$5M</option>\
        <option value="6000000">$6M</option>\
        <option value="7000000">$7M</option>\
        <option value="8000000">$8M</option>\
        <option value="9000000">$9M</option>\
        <option value="10000000">$10M</option>\
        <option value="15000000">$15M</option>\
        <option value="20000000">$20M</option>\
        <option value="25000000">$25M</option>\
        <option value="30000000">$30M</option>';
    
    var options = "";
    switch ($("[ id $= 'hdnPriceListType']").val()) {
        case "NotRental":
            options = saleOnlyOptions;
            break;
        case "RentalOnly":
            options = rentalOnlyOptions;
            break;
        case "Mixed":
            options = rentalOnlyOptions
                + saleOnlyOptions
            break;
    }
    
    $("[ id $= 'cboMinPrice']").html(minFirstOption + options).val($("[ id $= 'hdnSelectedMinPrice']").val());
   
    $("[ id $= 'cboMaxPrice']").html(maxFirstOption + options).val($("[ id $= 'hdnSelectedMaxPrice']").val());
}

function SB_LoadSqFt() {
    if (__SearchPage.dropDownsLoadedByServer)
        return;
    var minFirstOption = "<option>Minimum</option>\
    ";
    var maxFirstOption = "<option>Maximum</option>\
    ";
    var options = '\
        <option value="500">500</option>\
        <option value="750">750</option>\
        <option value="1000">1,000</option>\
        <option value="1250">1,250</option>\
        <option value="1500">1,500</option>\
        <option value="1750">1,750</option>\
        <option value="2000">2,000</option>\
        <option value="2250">2,250</option>\
        <option value="2500">2,500</option>\
        <option value="2750">2,750</option>\
        <option value="3000">3,000</option>\
        <option value="3500">3,500</option>\
        <option value="4000">4,000</option>\
        <option value="5000">5,000</option>\
        <option value="7000">7,000</option>\
        <option value="10000">10,000</option>';

    $("[ id $= 'ddlMinSqft']").html(minFirstOption + options);
    $("[ id $= 'ddlMinSqft']").val($("[ id $= 'hdnSelectedMinSqFt']").val());
    $("[ id $= 'ddlMaxSqft']").html(maxFirstOption + options);
    $("[ id $= 'ddlMaxSqft']").val($("[ id $= 'hdnSelectedMaxSqFt']").val());
}



function SavedSearch_ToggleStatusChange() {

    var chk = $("[id $= 'chkSendDroppedListings']");

    if (chk.length > 0) {
        if (!chk.is(":checked")) {
            $(".sb_notifydropped").attr("disabled", "disabled");
            $(".sb_notifydropped").parent().attr("disabled", "disabled");
        }
        else {
            $(".sb_notifydropped").removeAttr("disabled");
            $(".sb_notifydropped").parent().removeAttr("disabled");
        }
    }
}

function SavedSearch_Setup() {

    var hasName = $("[id $= 'ctlSearchResults_txtProfileName']").val() != "";
    if ($("[ id$= 'ctlSearchResults_hidSavedSearchOptionsState']").val() == "closed") {
        SavedSearch_ShowOptions(false);
    }
    else if ($("[ id$= 'ctlSearchResults_hidSavedSearchOptionsState']").val() == "open") {
        SavedSearch_ShowOptions(true);
    }
    else {
        SavedSearch_ShowOptions(!hasName);
    }

    $("#spnProfileOptionSelector").click(
        function () {
            SavedSearch_ShowOptions('toggle');
        }
    )
    MLX_AddRequiredMark();

    $("[id $= 'chkSendDroppedListings']").click(SavedSearch_ToggleStatusChange);
    SavedSearch_ToggleStatusChange();
}

function SavedSearch_ValidateSave() {

    var maxListings = (SE_IsInteger(SR_MaxListings), SR_MaxListings.toString(), "1000");
    if (!SavedSearch_ReasonableCount()) {
        alert("Your search returned more than " + maxListings + " listings."
            + "\nThe maximum listing count allowed is " + maxListings + "."
            + "\nPlease narrow your search.");
        return false;
    }
    else if ($("[id $= 'ctlSearchResults_txtProfileName']").val() == "") {
        alert("Please enter a search name.");
        SavedSearch_ShowOptions(true);
        $("[id $= 'ctlSearchResults_txtProfileName']").focus();
        return false;
    }

    if (!$("#dialog-confirm-save-checked").is(":visible")
        && typeof (SE_List_MarkedItemsCSV) != 'undefined'
        && SE_List_MarkedItemsCSV != null
        && SE_List_MarkedItemsCSV.value != "") {
        {
            $("#dialog-confirm-save-checked").dialog({
                resizable: false,
                modal: true,
                buttons: {
                    "Save Checked": function () {
                        $("[id $= 'btnSaveSearch']").click();
                    },
                    "Save All": function () {
                        SE_List_MarkedItemsCSV.SetValue("");
                        $("[id $= 'btnSaveSearch']").click();
                    }
                }
            });

            return false;
        }
    }
    $("#dialog-confirm-save-checked").dialog("close");
    SR_ShowLoadingCover(true);
    return true;
}

function SavedSearch_ReasonableCount() {
    if ($("[ id$='divAdvancedSearch_Container']").length > 0)
        return SE_AdvSearch_ReasonableCount();
    else
        return $(".sr_pager_overlimit").length == 0;
}
 
var SavedSearch_SHOWOPTIONS = "Show Search & Notification Options";
var SavedSearch_HIDEOPTIONS = "Hide Search & Notification Options";
function SavedSearch_ShowOptions(show) {
    
    if (show == 'toggle') {
        $(".drawer").find(".drawer_content").toggle();
    }
    else if (show) {
        $(".drawer").find(".drawer_content").show();
    }
    else {
        $(".drawer").find(".drawer_content").hide();
    }
    
    if ($(".drawer").find(".drawer_content:visible").length > 0) {
        $("[id $= 'ctlSearchResults_hidSavedSearchOptionsState']").val("open");
        $("#spnProfileOptionSelector").text(SavedSearch_HIDEOPTIONS);
        $(".drawer").find(".drawer_toggle .ui-icon").removeClass('ui-icon-carat-1-s').addClass('ui-icon-carat-1-n');
    }
    else {
        $("[ id$= 'ctlSearchResults_hidSavedSearchOptionsState']").val("closed");
        $("#spnProfileOptionSelector").text(SavedSearch_SHOWOPTIONS);
        $(".drawer").find(".drawer_toggle .ui-icon").removeClass('ui-icon-carat-1-n').addClass('ui-icon-carat-1-s');
    }
}

$().ready(function () {
    var $scrollingDiv = $("#divAdvCount").parent();
    var $container = $("[id $= 'divAdvancedSearch_Container']");

    if ($scrollingDiv.length > 0 && $container.length > 0) {
        $(window).scroll(function () {
            $scrollingDiv.stop();
            $scrollingDiv.animate(
            { "marginTop": Math.max(20, ($(window).scrollTop() - $container.offset().top) + 20) + "px" }
            , "slow");
        });
    }

    $(".sr_list_item").hover(
            function () { $(this).addClass('ui-state-highlight'); },
            function () { $(this).removeClass('ui-state-highlight'); }
        );

//    $(".sr_resultitem_actions").click(function (event) {
//        event.stopPropagation();
//        return false;
//    }); 

});
