/*variables*/
var filter = null; var map = null; var pins; var targetPoi = null; var infoBoxListingId = null; var infoBoxX = 0; var infoBoxY = 0;
var currentZoomLevel = null; var infoBox = false; var hoverBox = false; var boxMinX = 0; var boxMaxX = 0; var doBestFit = false;
var latLongOld = null; var panThreshold = 10; var dontLoadPins = false; var retryCenterOnMap = 0; var earthRadius = 3961.3;
var centerLat; var centerLong; var enableMapSearch = false; var state = null;
var locn = null; var _lat, _lng; var brenderNearby = true;
var pagetype = 'HL';
/*Home page*/
function ToggleSelects(visibility) {
    var Sel = document.getElementsByTagName("select");
    for (var x = 0; x < Sel.length; x++) {
        Sel[x].style.visibility = visibility;
    }
}

function search_alert_close() {
    if (gE("suggest")) {
        if (gE("suggest").style.display == "none") {
            ToggleSelects("visible");
        }
    }
    if (gE("search_alert")) {
        $('#search_alert').css('display', 'none');
    }
}

function processFeature(elem, value){
    var pfs = $("#AmenityMask").val();
    var op;
    if ($(elem).is(':checked')) {
        if (parseInt(pfs)) {
            op = parseInt(pfs) + parseInt(value);
        }
        else {
            op = parseInt(value);
        }
    } else {
        op = parseInt(pfs) - parseInt(value);
        if (op < 0) { op = 0; }
    }
    $("#AmenityMask").val(op);
}

function AutoFill(index) {

    if (CountryOps[index][1] != "") {
        $('#SearchText').val(CountryOps[index][1]);
        $('#Keyword').val(CountryOps[index][1]);
        $('#KeywordType').val(CountryOps[index][2]);
    }
    else {
        $('#Keyword').val("");
        $('#KeywordType').val("");
    }
    $('#Country').val(CountryOps[index][0]);
}

function SelectSearchType(index, name) {
    var title = "";
    if (index == 0) {
        title = "<h1>Search millions of homes across the country and around the world.</h1>";
        $("#search_country_lnk").attr("href", "javascript:CountryDrop();");
    } else if (index == 1) {
        title = "<h1>Search thousands of foreclosures across the country.</h1>";
        $("#Country").val("USA");
        //if ($("#SearchText").val().indexOf('Cities In') != -1) {
            $("#SearchText").val('');
        //}
        $("#search_country_lnk").attr("href", "javascript:void();");
        $("#search_country_lnk").text("United States");
    } else if (index == 2) {
        $("#search_country_lnk").attr("href", "javascript:CountryDrop();");
        title = "<h1>Search for agents around the corner or around the world.</h1>";
    }
    $("#SearchTitle").html(title);
    $('#SearchType').val(index);
    gE("Set_SearchType").innerHTML = "<a id='Section' class='select_flyout' onclick=' javascript:SectionDrop(); ' href='javascript:void(0);' title='select a country'>" + name + "</a>";
    $('#section_drop').css('display', 'none');
    $('#SearchText').focus();
}

function SelectCountry(value, name) {
	if (value == 'USA' || value == 'CAN') {
		$('#SearchText').val('City and State, or Zip Code');
        $('#KeywordType').val('');
        $('#Keyword').val('');
    }
    else {
        $('#SearchText').val('Cities In The ' + name + ', ' + value);
        $('#Keyword').val('Cities In The ' + name + ', ' + value);
        $('#KeywordType').val(7);
    }

    $('#CountryName').val(name);
    $('#Country').val(value);
    gE("search_country").innerHTML = "<a id='search_country_lnk' class='select_flyout' onmouseout='CountryOut();' onmouseover='CountryHover();' title='select a country' name='choose_country' href='javascript:CountryDrop();' >" + name + "</a>";
    $('#country_drop').css('display', 'none');
    $("#SearchText").flushCache();
}

function SelectPriceMin(index, name) {
    
    $('#PriceMin').val(name);
    gE("divsearch_pricemin").innerHTML = "<a class='advancedsearch_price' name='search_pricemin' href='javascript:PriceMinDrop();' id='search_pricemin'>" + name + "</a>";
    $('#more_pricemin').css('display', 'none');
}

function SelectPriceMax(index, name) {
    
    $('#PriceMax').val(name);
    gE("divsearch_pricemax").innerHTML = "<a id='search_pricemax' class='advancedsearch_price' href='javascript:PriceMaxDrop();' name='search_pricemax'>" + name + "</a>"
    $('#more_pricemax').css('display', 'none');
}
function SelectSqFt(index, name) {
    $('#SqFt').val(index);
    gE("search_SqFt").innerHTML = "<a id='selectsqft' class='advancedsearch_price' name='selectsqft' href='javascript:SqftDrop();' >" + name + "</a>"
    $('#more_sqft').css('display', 'none');
}
function Selectbed(index, name) {
    $('#Bed').val(index);
    gE("search_bed").innerHTML = "<a onclick='javascript:BedsDrop();' class='button_short' id='selectbeds' href='javascript:void(0);' >" + name + "</a>";
    $('#more_beds').css('display', 'none');
}
function Selectbath(index, name) {
    $('#Bath').val(index);
    gE("search_bath").innerHTML = "<a onclick='javascript:BathsDrop();' class='button_short' id='selectbaths' href='javascript:void(0);'>" + name + "</a>";
    $('#more_baths').css('display', 'none');
}
/******Search*****/
//function PriceFacet(elem) {
//    $("#priceSort  li.off").removeClass("off");
//    $(elem).addClass("off");
//    $("#MaxPriceFacet").val($(elem).attr("value"));
//    ApplyFacets();
//}



/*Pager*/
PageClick = function (pageclickednumber) {
    var link = window.location.href;
    if (link.indexOf('page') != -1) {
        link = link.substring(0, link.lastIndexOf('/'));
    }
    link = link + '/page' + pageclickednumber;
    window.location = link;
}

/*Home Details Agent listings*/
AgentPaged = function (pageclickednumber) {
    var d = {
        agentId: $("#hdnAgentId").val(),
        pageNo: pageclickednumber
    };
    $.ajax({
        url: '/Homes/PageAgentListing',
        type: "POST",
        dataType: "json",
        cache: false,
        data: d,
        success: function (result) {
            if (result.Total > 0) {
                $("#AgentsList").empty();
                $("#AgentsListtemp").tmpl(result.Results).appendTo("#AgentsList");
                $("#fromto").html(result.Start + ' - ' + result.End + ' of');
                //$("#results_title").html("<h3>" + result.AgentName + "'s Listings</h3>");
                $("#prev").empty().append(renderButton('< Prev', parseInt(pageclickednumber), parseInt(result.PageCount), AgentPaged));
                $("#next").empty().append(renderButton('Next >', parseInt(pageclickednumber), parseInt(result.PageCount), AgentPaged));
                $("#pagecount").val(result.PageCount);
                //$("#pagenumber").val(pageclickednumber);
                if (result.Start != 1) {
                    $("#prev li").css("color", "#0072BC");
                }
                else {
                    $("#prev li").css("cursor", "default");
                }

                if (result.Total != result.End) {
                    $("#next li").css("color", "#0072BC");
                }
                else {
                    $("#next li").css("cursor", "default");
                }

                $("#pagenumber").val(pageclickednumber);
                RegisterScripts();
            }
        }
    });
}

/*Home Details Agent listings*/
SimilarListPaged = function (pageclickednumber) {
    var d = {
        pageNo: pageclickednumber
    };
    $.ajax({
        url: '/Homes/PageSimilarListing',
        type: "POST",
        dataType: "json",
        cache: false,
        data: d,
        success: function (result) {
            if (result.Total > 0) {
                $("#RenderSimilarList").empty();
                $("#SimilarListTemp").tmpl(result.Results).appendTo("#RenderSimilarList");
                $("#sfromto").html(result.Start + ' - ' + result.End + ' of');
                $("#sprev").empty().append(renderButton('< Prev', parseInt(pageclickednumber), parseInt(result.PageCount), SimilarListPaged));
                $("#snext").empty().append(renderButton('Next >', parseInt(pageclickednumber), parseInt(result.PageCount), SimilarListPaged));
                $("#spagecount").val(result.PageCount);

                if (result.Start != 1) {
                    $("#sprev li").css("color", "#0072BC");
                }
                else {
                    $("#sprev li").css("cursor", "default");
                }

                if (result.Total != result.End) {
                    $("#snext li").css("color", "#0072BC");
                }
                else {
                    $("#snext li").css("cursor", "default");
                }

                $("#spagenumber").val(pageclickednumber);
                RegisterScripts();
            }
        }
    });
}

RegisterScripts = function () {
    SetupColorbox('#contact-agent-pop', '.colorbox');
}

/****** facet search - start *******/
function ApplyFacets(id) {

    if (enableMapSearch) {
        ApplyMapFacets();
        return;
    }

    $.ajax({
    	url: '/Search/Facets',
    	type: "POST",
    	dataType: "json",
    	cache: false,
    	data: PopulateFacets(id),
    	success: function (result) {
    		$("#results_title").html("<h2>" + result.ResultsTitle + "</h2>");
    		$("#location_header").html("<h1>" + result.BreadCrumbTitle + "<h1>");
    		$("#facetControl").empty();
    		$("#FacetTemp").tmpl(result.Facets).appendTo("#facetControl");
    		$("#facetingOptionsList").empty();
    		$("#facetingOptionsListTemp").tmpl(result.Facets).appendTo("#facetingOptionsList");
    		$("#hdnPriceRangeS").val(result.Facets.PriceRangeValS);
    		$("#hdnPriceRangeM").val(result.Facets.PriceRangeValM);
    		$("#hdnPropertyType").val(result.Facets.SelPropertyTypesVal);
    		$("#nbOpenHouse").empty();
    		
    		if (result.Facets.OpenFacet.Visible) {
    			$("#OpenHouseTemplate").tmpl(result.Facets.OpenFacet).appendTo("#nbOpenHouse");
    		}
    		$("#hdnPage").val(result.Page);
    		$("#hdnSort").val(result.Sort);
    		$("#hdnPageCount").val(result.PageCount);
    		$("#OmnitureLiteral").empty().html(result.Omniture);

    		if (result.Count > 0) {
    			$("#results_listings").empty();
    			$("#SearchListingsTemp").tmpl(result.Results).appendTo("#results_listings");
    			$("#status").html(result.Status);
    			$("#page_status").html(result.Status);
    			if (result.PageCount > 1) {
    				$("#pager").pager({ pagenumber: result.Page, pagecount: result.PageCount, buttonClickCallback: PageClick });
    			} else {
    				$("#pager").html("");
    			}
    			SetupColorbox('#contact-agent-pop', '.colorbox');
    		}
    		else {
    			$("#results_listings").empty();
    			//$("#pager").html("<p>No results were returned for your search</p>");
    			$("#status").html("<h3>No results were returned for your search</h3>");
    			$(".subheader_row_noborder").hide();
    			$("#page_status").html("<h3>No results were returned for your search</h3>");
    		}
    		if (map != null) {
    			LoadPushpins(false, true);
    		}

    		if ($('#DataSourceChanged').val() == '1') {
    			$('#DataSourceChanged').val('0')
    			renderNearby();
    		}
    	}
    });
}
function PopulateFacets(id) {
    var tempArray = [];

    var selectedOptions = $("input[name='Options']:checked");
    if (selectedOptions) {
        selectedOptions.each(function (index) {
            tempArray.push($(this).val());

        });
    }
    $("#DataSources").val(tempArray.join(","));
    var data = {
        SelectedOption: id,
        PriceRangeM: $("#hdnPriceRangeM").val(),
        PriceRangeS: $("#hdnPriceRangeS").val(),
        PropertyType: $("#hdnPropertyType").val(),
        DataSource: tempArray.join(","),
        Sort: $("#hdnSort").val(),
        Page: $("#hdnPage").val(),
        SearchText: $("#SearchText").val(),
        PriceMin: $("#PriceMin").val(),
        PriceMax: $("#PriceMax").val(),
        Bed:$("#Bed").val(),
        Bath:$("#Bath").val(),
        SqFt:$("#SqFt").val(),
        AmenityMask: $("#AmenityMask").val()
    };
    return data;
}

function ApplyAgentFacets() {
    $.ajax({
        url: '/Agents/Facets',
        type: 'POST',
        dataType: "json",
        cache: false,
        data: PopulateAgentFacets(),
        success: function (result) {
            $("#OmnitureLiteral").empty().html(result.om);
            if (result.Count > 0) {
                $("#results_listings").empty();
                $("#SearchListingsTemp").tmpl(result.Results).appendTo("#results_listings");
                $("#facetingOptionsList").empty();
                $("#facetingOptionsListTemp").tmpl(result.Facets).appendTo("#facetingOptionsList");
                $("#status").html(result.Status);
                $("#hdnPage").val(result.Page);
                $("#hdnSort").val(result.Sort);
                $("#hdnPageCount").val(result.PageCount);
                $("#pager").pager({ pagenumber: result.Page, pagecount: result.PageCount, buttonClickCallback: PageClick });
            }
            else {
                $("#results_listings").html("<h3>No results were returned for your search</h3>");
                $("#pager").html("");
                $("#status").html("<h3>No results were returned for your search</h3>");
            }
        }
    });
}
function PopulateAgentFacets() {
    var tempArray = [];

    var selectedOptions = $("input[name='Options']:checked");
    if (selectedOptions) {
        selectedOptions.each(function (index) {
            tempArray.push($(this).val());

        });
    }

    var data = {
        AgentId: $("#hdnAgent").val(),
        DataSource: tempArray.join(","),
        Sort: $("#hdnSort").val(),
        SearchText: $("#SearchText").val()
    };
    return data;
}

function ApplyMapFacets() {

    $.ajax({
        url: '/Maps/RectangleSearch',
        type: "POST",
        dataType: "json",
        cache: false,
        data: PopulateMapFacets(),
        success: function (result) {
        	$("#results_title").html("<h2>" + result.ResultsTitle.Replace("-", " ") + "</h2>");
        	$("#location_header").html("<h1>" + result.BreadCrumbTitle.Replace("-", " ") + "<h1>");
            $("#facetControl").empty();
            $("#FacetTemp").tmpl(result.Facets).appendTo("#facetControl");
            $("#facetingOptionsList").empty();
            $("#facetingOptionsListTemp").tmpl(result.Facets).appendTo("#facetingOptionsList");
            $("#hdnPriceRangeS").val(result.Facets.PriceRangeValS);
            $("#hdnPriceRangeM").val(result.Facets.PriceRangeValM);
            $("#hdnPropertyType").val(result.Facets.SelPropertyTypesVal);
            $("#hdnPage").val(result.Page);
            $("#hdnSort").val(result.Sort);
            $("#hdnPageCount").val(result.PageCount);
            $("#omniture").html(result.Omniture);
            centerLat = result.CenterLat;
            centerLong = result.CenterLong;
            nwLat = result.NWLat;
            nwLong = result.NWLong;
            seLat = result.SELat;
            seLong = result.SELong;
            locn = result.Location;
            state = result.State;
            enableMapSearch = result.EnableMap;
            if (result.Count > 0) {
                $("#results_listings").empty();
                $("#SearchListingsTemp").tmpl(result.Results).appendTo("#results_listings");
                $("#status").html(result.Status);
                $("#pager").pager({ pagenumber: result.Page, pagecount: result.PageCount, buttonClickCallback: PageClick });
                LoadMap();
                LoadPushpins(false, false);
            }
            else {
                $("#results_listings").html("<h3>No results were returned for your search</h3>");
                $("#pager").html("");
                $("#status").html("<h3>No results were returned for your search</h3>");
            }
        }
    });
}
function PopulateMapFacets() {
    var tempArray = [];

    var selectedOptions = $("input[name='Options']:checked");
    if (selectedOptions) {
        selectedOptions.each(function (index) {
            tempArray.push($(this).val());
        });
    }

    var data = {
        PriceRangeM: $("#hdnPriceRangeM").val(),
        PriceRangeS: $("#hdnPriceRangeS").val(),
        PropertyType: $("#hdnPropertyType").val(),
        DataSource: tempArray.join(","),
        Sort: $("#hdnSort").val(),
        SearchText: $("#SearchText").val(),
        CenterLat: centerLat,
        CenterLong: centerLong,
        NWLat: nwLat,
        NWLong: nwLong,
        SELat: seLat,
        SELong: seLong,
        Location: locn,
        State: state        
    };
    return data;
}

function GetNoMatchHtml(text, url, urlText, cityArray) {
    var tempArray = [];
    var cityJsonArray = $.parseJSON(cityArray);
    if (cityJsonArray != null) {
        tempArray.push("<div class=\"af-no-results\"><p>");
        tempArray.push(text);
        tempArray.push("</p><ul class=\"no-result-options\">");
        tempArray.push("<a href=\"javascript:ClearSearchCriteria('" + url + "');\">" + urlText + "</a> ");
        tempArray.push("</li>");
        tempArray.push("<li class=\"no-result-option\">Or search nearby:");
        tempArray.push("<ul class=\"nearby-options\">");
        for (var index = 0; index < cityJsonArray.length; index++) {
            tempArray.push("<li><a href='" + cityJsonArray[index].Url + "'>" + cityJsonArray[index].Text + " home for sale</a></li>");
        }

        tempArray.push("</ul></li></li></ul></div>");
    }
    return tempArray.join("");
}

/*Advance search*/
function InitAdvanceSearch() {
    $("input[name='PropertyType']").change(function () {
        $("#PropertyTypeId").val($("input[name='PropertyType']:checked").val());
    });
}

function setPropertyvalue(value,addKeyword) {
    $("#PropertyTypeFacet  li.off").removeClass("off");
    elem = "li#" + value;
    $(elem).addClass("off");
    var txt = $(elem).text();
    var elen = txt.length - 4;
    txt = txt.substring(0, elen);
    gE("search_property").innerHTML = "<a class='sortby_form select_flyout' onclick=' javascript:PopertyTypeDrop(); ' href='javascript:void(0);'>" + txt + "</a>";
    $('#hdnPropertyType').val(value);
    closePopertyTypeDrop();
    RemoveKeyword('words_pt');
    if(addKeyword){
        AddKeyword($(elem).text(), value, 'pt');
    }
}

function PropertyTypeSelect(elem, value) {
    setPropertyvalue(value, true);
    $("#hdnPage").val("1");
    if (enableMapSearch) {
        ApplyMapFacets();
    }
    else {
        ApplyFacets();
    }
}

function setPricerangeValue(value, addKeyword) {
    elem = "li#" + value;
    $("#priceRangeFacet  li.off").removeClass("off");
    $(elem).addClass("off");
    var txt = $(elem).text();
    var elen = txt.length - 4;
    txt = txt.substring(0, elen); 
    if(txt == '') txt = 'Refine';
    gE("search_pricerange").innerHTML = "<a class='sortby_form select_flyout' onclick=' javascript:PriceRangeDrop(); ' href='javascript:void(0);'>" + txt + "</a>";
    if ($('a#words_prs').size() == 1) {
        RemoveKeyword('words_prs');
        RemoveKeyword('words_prm');
        $('#hdnPriceRangeM').val('');
        $('#hdnPriceRangeS').val('');
    }
    if(value <= 207){
        $('#hdnPriceRangeM').val(value);
    }
    else{
        $('#hdnPriceRangeS').val(value);
    }
    closePriceRangeDrop();
    if(addKeyword){
        AddKeyword($(elem).text(), value, 'pr');
    }
}
function PriceRangeSelect(elem, value) {
    setPricerangeValue(value, true)
    $("#hdnPage").val("1");
    if (enableMapSearch) {
        ApplyMapFacets();
    }
    else {
        ApplyFacets();
    }
}

function setSort(elem,value) {
    $("#sortOrder  li.off").removeClass("off");
    $(elem).addClass("off");
    gE("search_sort").innerHTML = "<a class='sortby_form select_flyout' onclick=' javascript:SortOptionsDrop(); ' href='javascript:void(0);'>" + $(elem).text() + "</a>";
    $("#hdnSort").val(value);
    closesortOptionsDrop();
}

function ResultSort(elem, value) {
    setSort(elem, value);
    $("#hdnPage").val("1");
    if (enableMapSearch) {
        ApplyMapFacets();
    }
    else {
        ApplyFacets();
    }
}

function AgentHomesSort(elem, value) {
    $("#sortOrder  li.off").removeClass("off");
    $(elem).addClass("off");
    gE("search_sort").innerHTML = "<a class='sortby_form select_flyout' onclick=' javascript:SortOptionsDrop(); ' href='javascript:void(0);'>" + $(elem).text() + "</a>";
    $("#hdnSort").val(value);
    closesortOptionsDrop();
    ApplyAgentFacets();
}
/****** facet search - start *******/
function RemoveFilter(type, value) {
    if (type == 'pt') {
        $("#PropertyTypeFacet  li.off").removeClass("off");
        gE("search_property").innerHTML = "<a class='sortby_form select_flyout' onclick=' javascript:PopertyTypeDrop(); ' href='javascript:void(0);'>Refine</a>";
        $('#hdnPropertyType').val('');
    }
    if (type == 'pr') {
        $('#hdnPriceRangeM').val('');
        $('#hdnPriceRangeS').val('');
        if( $('a#words_prs').size() == 0 && $('a#words_prm').size() == 0 ) {
            $("#priceRangeFacet  li.off").removeClass("off");
            gE("search_pricerange").innerHTML = "<a class='sortby_form select_flyout' onclick=' javascript:PriceRangeDrop(); ' href='javascript:void(0);'>Refine</a>";
        }
        if ($('a#words_prs').size() == 1 && $('a#words_prm').size() == 0) {
            $('#hdnPriceRangeS').val($("#hdnwords_prs").val());
        }
        if ($('a#words_prs').size() == 0 && $('a#words_prm').size() == 1) {
            $('#hdnPriceRangeM').val($("#hdnwords_prm").val());
        }
    }
    if (type == 'am') {
        var am = $("#AmenityMask").val();
        am = am - parseInt(value);
        $("#AmenityMask").val(am);
    }
    if (type == 'bed') {
        $("#Bed").val('');
    }
    if (type == 'bath') {
        $("#Bath").val('');
    }
    if (type == 'sf') {
        $("#SqFt").val('');
    }
    if (type == 'prma') {
        $("#PriceMax").val('');
    }
    if (type == 'prmi') {
        $("#PriceMin").val('');
    }
    ApplyFacets();
}

function RemoveKeyword(elem) {
    $("#" + elem).closest('li').remove();
    
    if ($("#keyList li").size() == 0) {
        $('#selection').css('display','none');
    }
}

function AddKeyword( txt, value, type) {
    var tmpArray = [];
    var newID;
    if (type == 'pr') {
        if (value > 207) {
            newID = "words_" + type + 's';
        } else {
            newID = "words_" + type + 'm';
        }
    }
    else {
        if (type == 'pt') {
            newID = "words_" + type;
        } else {
            newID = "words_" + type + $("#keyList li").size();
        }
    }

    newID = $.trim(newID);
    $("#keyList").append('<li value=\'' + txt + '\'>' + txt + '<a id=' + newID + ' href="javascript:RemoveKeyword(\'' + newID + '\');RemoveFilter(\'' + type + '\');">  (x)  </a><input id=\'hdn' + newID + '\' type="hidden" value=\'' + value + '\' /></li>');
    $('#selection').css('display','block');
}

/*Mapquest Map area start*/

function ShowMap(description) {
    $("#map_state_hidden").css('display', 'none');
    $("#map_function_toggle").css('display', 'block');
    $("#map").removeClass().addClass("map_default");
    $("#map_status").css('display', 'block');
    $("#map_state").css('display', 'block');
    mapExposed(this, description);
}

function HideMap() {
    $("#map_state_hidden").css('display', 'block');
    $("#map_function_toggle").css('display', 'none');
    $("#map").removeClass().addClass("map_hidden");
    $("#map_status").css('display', 'none');
    $("#map_state").css('display', 'none');
}

function ToggleNearBy(parentElement, text) {
    var additionalLinks = $('#' + parentElement + ' .nearest_more');
    if (additionalLinks.is(":visible")) {
        additionalLinks.hide();
    }
    else {
        additionalLinks.show();
    }
}

function InitAgentMap() {
    if ($("#map").is(":visible")) {
    //use the agent address lat long here
    //centerLat = 39.743943;
    //centerLong = -105.020089;
        LoadMap();
    }
}

function InitDetailMap() {
    if ($("#map").is(":visible")) {
        centerLat = 39.743943;
        centerLong = -105.020089;
        LoadMap();
    }
} 

function InitMap() {
    $('#mapResults_lnk').click(function () {
        if (!$("#map").is(":visible")) {
            ShowMap(""); 
        }
        brenderNearby = false;
        //geoCode($('#SearchText').val());

        LoadMap();

    });
}
function ToggleMap() {
    if ($("#map").is(":visible")) {
        HideMap();
    }
    else {
        ShowMap("");
    }
}

function LoadMap() {
    if (map == null) {
        InitializeMap();
        LoadPushpins(true, true); 
        RememberPreviousCenter();
    }
}
function ZoomToLocation(latitude, longitude, level) {
    map.setCenter(new MQA.LatLng(latitude, longitude), level);
    RememberPreviousCenter();
    CloseInfoBox(true);
    CloseRolloverBox(true);
}

function Initdetail_map() {
 
    _lat = parseFloat($("#Lat").val());
    _lng = parseFloat($("#Lng").val());
    if ($("#Lat").val() == '' && $("#Lng").val() == '') {
        _lat = 90;
        _lng = -180;
    }
    poiLL = new MQA.LatLng(_lat, _lng);
    map = new MQA.TileMap(document.getElementById('detail_map'), 11, poiLL, 'map');

    if (pins != null) {
        pins.removeAll();
        map.removeShapeCollection("pushpins");
    }

    pins = new MQA.ShapeCollection();
    pins.collectionName = 'pushpins';

    var poi = new MQA.Poi({ lat: _lat, lng: _lng });
    var icon = new MQA.Icon("/Content/images/mapIcons/singlepoint_off.png", 24, 24);
    icon.borderWidth = 0;
    poi.setIcon(icon);
    MQA.EventManager.addListener(poi, "click", showDetailMap, poi);
    pins.add(poi);
    map.addShapeCollection(pins);
    //map.bestFit();
}

function showDetailMap() {
    $("#map").empty();
    $('#TB_window').css('display', 'block');
    initShape();
    $('html, body').animate({ scrollTop: '0px' }, 300);
    $('#fromaddr').focus();
    OmPropertyActivity(this, "toggle map");
}

function InitializeMap() {
    currentZoomLevel = 5;
    poiLL = new MQA.LatLng(centerLat, centerLong);
    var viewcontrol = new MQA.ViewControl();
    map = new MQA.TileMap(document.getElementById('map'), currentZoomLevel, poiLL, 'map');
    map.addControl(new MQA.ZoomControl(), new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT));
    map.addControl(viewcontrol, new MQA.MapCornerPlacement(MQA.MapCorner.BOTTOM_RIGHT));
    MQA.EventManager.addListener(map, "moveend", OnMapChanged);
    MQA.EventManager.addListener(map, "zoomend", OnMapChanged);
    $("ul.map-view li").click(function () {
        var classname = $(this).attr("class");
        var type = classname.substring(9, 15) + " view";
        OmProp(42, type);
    });
}

function toggleMapSearch() {
    enableMapSearch = $("#mlo_map").is(':checked');
    if (enableMapSearch){
        getMapStats();
        ApplyMapFacets();
        LoadPushpins(false, false);  
    }
}

function OnMapChanged(evt) {
    enableMapSearch = $("#mlo_map").is(':checked');
    if (!enableMapSearch) return;
    getMapStats();
    CloseInfoBox(true);    
}

function getMapStats(){
    var mapCenter = map.getCenter();
    var mapRect = map.getBounds();
    var city, state;

    //center lat lng
    centerLat = mapCenter.getLatitude();
    centerLong = mapCenter.getLongitude();
    //rect points
    ul = mapRect.ul;
    lr = mapRect.lr;
    
    nwLat = ul.lat;
    nwLong = ul.lng;
    seLat = lr.lat;
    seLong = lr.lng;
    doReverse();
}
var HOST_URL, APP_KEY;
HOST_URL = "http://www.mapquestapi.com/";
////APP_KEY = 'Fmjtd%7Cluu7n90bn1%2C25%3Do5-5rang';
APP_KEY = 'Gmjtd%7Cluu7296znl%2C2w%3Do5-lyt0d';
var SAMPLE_POST_KVP = HOST_URL + 'geocoding/v1/reverse?key=YOUR_KEY_HERE&lat=LATITUDE&lng=LONGITUDE&callback=renderReverse';
var TREB_GEO_LOC = HOST_URL + 'geocoding/v1/address?key=YOUR_KEY_HERE&callback=renderGeoLatLng&inFormat=kvp&outFormat=json&location=YOURLOCATION';
var safe;
var mapcentered = false;
function doReverse() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    safe = SAMPLE_POST_KVP;
    var newURL = safe.replace('YOUR_KEY_HERE', APP_KEY);
    newURL = newURL.replace('LATITUDE', centerLat);
    newURL = newURL.replace('LONGITUDE', centerLong);
    script.src = newURL;
    document.body.appendChild(script);
}

function renderReverse(response) {
    var location = response.results[0].locations[0];
    locn = location.adminArea5;
    state = location.adminArea3;
    $("#maplocn").html("<label id='mlo_loc'>Location: " + locn + "</label>");
    ApplyMapFacets();    
    if (locn == '' || locn == null) {return;}
    renderNearby();
}

function geoCodeandLoadNearBy(citystate) {
    if(centerLat!=null && centerLong != null && locn!=null && state!=null){
        renderNearby();
        return;
    }
    mapcentered = true;
    geoCode(citystate);

}
function geoCode(citystate) {
	if (citystate.indexOf('Cities In') != -1 || citystate.indexOf('Cities-In') != -1) { return false; }
    var script = document.createElement('script');
    script.type = 'text/javascript';
    safe = TREB_GEO_LOC;
    var newURL = safe.replace('YOUR_KEY_HERE', APP_KEY);
    if (citystate == "int" || citystate == 'set') {
        newURL = newURL.replace('YOURLOCATION', $('#searchcountry li.off').text());
    }
    else {
        newURL = newURL.replace('YOURLOCATION', citystate);
    }
    script.src = newURL;
    document.body.appendChild(script);
}
function renderGeoLatLng(response) {
    var location = response.results[0].locations[0];
    if (location != null) {
        centerLat = location.latLng.lat;
        centerLong = location.latLng.lng;
        locn = location.adminArea5;
        state = location.adminArea3;
        var newCenter = new MQLatLng(centerLat, centerLong);
        if (map != null && !mapcentered) {
            map.setCenter(newCenter, 7);
        }         
        if (brenderNearby) { renderNearby(); }
    }
}

function getmorelist(lat, lon) {
	//alert(lat + " - " + lon);
	if (lat > 1 && lon != 0.0) {
		var page = $("#hdnPage").val();
		var mstat = $("#mlState").val();
		//alert(lat + " - " + lon + " - " + mstat + " - " + page);
		if (page == null) {
			page = 1;
		}
		var d = {
			CenterLat: lat,
			CenterLong: lon,
			Country: $("#Country").val(),
			Location: locn,
			State: mstat,
			Page: page
		};
		$.ajax({
				url: '/homes/RenderNearBy',
				type: "POST",
				dataType: "json",
				cache: false,
				data: d,
				success: function(result) {
					$("#nbCitiesMore").empty();
					$("#nbNeighborMore").empty();
					$("#nbStatesMore").empty();

					if (result.hasCities) {
						$("#nearbyMoreListTemp").tmpl(result.cities).appendTo("#nbCitiesMore");
					}

					if (result.hasStates) {
						$("#nearbyMoreListTemp").tmpl(result.states).appendTo("#nbStatesMore");
					}

					if (result.hasNbrhood) {
						$("#nearbyMoreListTemp").tmpl(result.nbrhood).appendTo("#nbNeighborMore");
					}
				}
			});
	}
}

function renderNearby() {
    
    var page = $("#hdnPage").val();
    if (page == null) {
        page = 1;
    }
    var d = {
        CenterLat: centerLat,
        CenterLong: centerLong,
        Country: $("#Country").val(),
        Location: locn,
        State: state,
        Page: page
    };
    $.ajax({
    	url: '/homes/RenderNearBy',
    	type: "POST",
    	dataType: "json",
    	cache: false,
    	data: d,
    	success: function (result) {
    		$("#nbCities").empty();
    		$("#nbNeighbor").empty();

    		//Province need just a "See All Cities" link
    		if (result.isProvince) {
    			$("#provinceTemp").tmpl(result).appendTo("#nbCities");
    		}
    		if (result.hasCities) {
    			$("#nearbyTemp").tmpl(result.cities).appendTo("#nbCities");
    		}

    		if (result.hasStates) {
    			$("#nearbyTemp").tmpl(result.states).appendTo("#nbCities");
    		}

    		if (result.hasNbrhood) {
    			$("#nearbyTemp").tmpl(result.nbrhood).appendTo("#nbNeighbor");
    		} else { $("#Neighborhood").hide(); }
    	}
    });
}

function calculateView() {
    var defaultScales = new Array(48.62866424, 24.31433212, 12.15716606, 6.07858303, 3.039291515, 1.519642651, 0.759821326, 0.379913769, 0.189956885, 0.094975336, 0.047490774, 0.023745387, 0.011872694, 0.00593324, 0.002969727, 0.001484863, 0.000739325, 0.000372769, 0.000186385); centerLat = (parseFloat(maxLat) + parseFloat(minLat)) / 2; centerLong = (parseFloat(maxLong) + parseFloat(minLong)) / 2;
    var meanDistanceX = distance(centerLat, minLong, centerLat, maxLong); 
    var meanDistanceY = distance(maxLat, centerLong, minLat, centerLong) * 2;
    var mapWidth = parseFloat($("#mapPanel").width());
    var mapHeight = parseFloat($("#mapPanel").height());
    var meanScaleValueX = meanDistanceX / mapWidth;
    var meanScaleValueY = meanDistanceY / mapHeight; 
    var meanScale;
    if (meanScaleValueX > meanScaleValueY)
        meanScale = meanScaleValueX; else
        meanScale = meanScaleValueY; var zoom = 1; currentZoomLevel = 0; for (var i = 0; i < 19; i++) {
        if (meanScale >= defaultScales[i] / 10) {
            if (i <= 7) { zoom = 8; }
            else { zoom = i + 2; }
            currentZoomLevel = zoom; break;
        }
    }
    if (currentZoomLevel == 0) { zoom = 11; currentZoomLevel = zoom; }
}
function distance(lat1, lon1, lat2, lon2) {
    var factor = Math.PI / 180;
    var dLat = (lat2 - lat1) * factor;
    var dLon = (lon2 - lon1) * factor;
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * factor) * Math.cos(lat2 * factor) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = earthRadius * c;
    return d;
}

//LoadPushpins - this method is designed to get the pins for the results shown on the page and plot on the map.
function LoadPushpins(byRadius, bestFit) {
    var isAgent = gE('SearchType').value == "2" || gE('SearchType').value == "Agents";
    var u;
    if (pagetype == 'AS') {
        u = "/Maps/GetAgentSearchMapPoints";
    }
    else if (pagetype == 'AL') {
        u = "/Maps/GetAgentMapPoints";
    }
    else {
        u = "/Maps/GetMapPoints";
    }
    if (pins != null) {
        pins.removeAll();
        map.removeShapeCollection("pushpins"); 
    }
    mapcentered = false;
    pins = new MQA.ShapeCollection();
    pins.collectionName = 'pushpins';

    $.ajax({
        type: "GET",
        dataType: "json",
        cache: false,
        url: u,
        success: function (result) {
            $.each(result.pois, function (i, item) {
                if (item.Latitude != null && item.Longitude != null) {
                    mapcentered = true;
                    var poi = new MQA.Poi({ lat: item.Latitude, lng: item.Longitude });
                    poi.setInfoContentHTML(item.Id);
                    var iconpath;
                    if (!item.IsFeatured) {
                        iconpath = "/Content/images/mapIcons/" + (i + 1) + "singlepoint_on.png";
                    } else {
                        iconpath = "/Content/images/mapIcons/" + (i + 1) + "featured_on.png";
                    }
                    poi.setIcon(new MQA.Icon(iconpath, 24, 24));
                    pins.add(poi);
                }
            });
            if (!mapcentered) {
                var newCenter = new MQLatLng(90, -180);
                if (map != null) {
                    map.setCenter(newCenter, 7);
                    return false;
                }
            }
            else {
                doBestFit = bestFit;

                MQA.EventManager.addListener(pins, 'dataloaded', onDataLoaded);

                map.addShapeCollection(pins);

                if (bestFit) map.bestFit();

                onDataLoaded();
            }
            //map.declutter = new ForceDeclutter();
        }
    });
    
    //do something to get the map centered.
}

function SaveMapStates() {
    var bounds = map.getBounds(); var topleft = bounds.ul; var bottomright = bounds.lr; maxLat = bottomright.lat; minLat = topleft.lat
    maxLong = bottomright.lng; minLong = topleft.lng;
}
function RememberPreviousCenter() {
    if (map != null) {
        //latLongOld = map.getCenter();
    } 
}
function OnMapMoved() {
    if (IsMapMovedBeyondThreshold()) {
        CloseInfoBox(true);
        LoadPushpins(false, false);
        RememberPreviousCenter();
    } 
}
function IsMapMovedBeyondThreshold() {
    var cpLatLongNew = map.getCenter();
    var cpPixelOld = map.llToPix(latLongOld);
    var cpPixelNew = map.llToPix(cpLatLongNew);
    var x = Math.abs(cpPixelOld.x - cpPixelNew.x);
    var y = Math.abs(cpPixelOld.y - cpPixelNew.y);
    if (x > panThreshold || y > panThreshold) {
        return true; 
    }
    else {
        return false; 
    }
}

function ToggleContentDivHeight() { $('#contentdiv').css("height", "2700px").html(" ."); $('#dummydiv').css("height", "auto").html(""); }
function OnMapZoomed() {
    if (!dontLoadPins) { currentZoomLevel = map.getZoomLevel(); LoadPushpins(false, false); }
    RememberPreviousCenter(); 
    //ToggleContentDivHeight();
}
function onDataLoaded() {
    for (var i = 0; i < pins.getSize(); i++) {
        var item = pins.getAt(i); 
                
        
        item.setKey(item.infoContentHTML); 
                
        item.setInfoContentHTML(null);
        //MQA.EventManager.addListener(item, "mouseover", onPoiMouseover, item);
        //MQA.EventManager.addListener(item, "mouseout", onPoiMouseout, item); 
        MQA.EventManager.addListener(item, "click", onPoiMouseclick, item);
        MQA.EventManager.addListener(item, 'infowindowclose', onInfoClosed, item);       
    }
    if (infoBoxListingId != null) {
        for (var j = 0; j < pins.getSize(); j++) {
            var poi = pins.getAt(j); 
            if (item.key == infoBoxListingId) {
                targetPoi = poi;
            } 
        }
        infoBoxListingId = null;
        if (targetPoi != null) {
            showHover(targetPoi); 
        }
    }
    map.addShapeCollection(pins);
    if (doBestFit == true) {
        doBestFit = false;
        map.bestFit();
    }
}
function onInfoClosed(e) {
    targetPoi = this;
    
    targetPoi.setInfoContentHTML(null);
    //targetPoi.infoContentHTML = '';
    
}
function onPoiMouseover(e) {
    if (infoBox) { return; }
    targetPoi = this; $('#rolloverBox').css("display", "none");
    $('#rolloverBoxText').css("height", "auto");
    if (targetPoi.key.indexOf("+") == 0) {
        OnCallRolloverBoxComplete(targetPoi.key.substring(1), targetPoi);
    }
    else {
        $.ajax({
            type: "GET",
            cache: false,
            url: "/Map/Getrolloverbox/" + targetPoi.key,
            success: function (data) {
                if (data != null && data.length > 0) {
                    OnCallRolloverBoxComplete(data, targetPoi)
                }
            }
        });
    }
    //ToggleContentDivHeight();
}
function closeMapInfo() {
    $('#infoBox').css("display", "none");
}

function OnCallInfoBoxComplete(result, targetPoi) {
    var box = $('#infoBox');

    $("#infoBoxText").empty();

    $("#InfoBoxHtml").tmpl(result).appendTo("#infoBoxText");

    var offset = getCenterOffset();
    
    var point = map.llToPix(targetPoi.getLatLng()); 
    
    var x = point.getX();
    
    var y = point.getY();
    //targetPoi.infoContentHTML = $('#infoBox').html();
    //targetPoi.setInfoContentHTML($('#infoBox').html());
    if (pagetype == 'AL') {
        box.css("left", parseInt(x + offset.x - 166));
        box.css("top", parseInt(y + offset.y - 141));
    }
    else {
        box.css("left", parseInt(x + offset.x - 128 + 50));
        box.css("top", parseInt(y + offset.y - 90));
    }
    box.css("display", "block");
    
    infoBox = true;

    //targetPoi.showInfoWindow();
}

function getCenterOffset() {
    var point = map.getDragOffset();
    var point2 = map.llToPix(map.getCenter());
    var x = point2.getX();
    var y = point2.getY();
    return new MQA.PointXY(x, y)
}

function OnCallRolloverBoxComplete(result, targetPoi) {
    var box = $("#rolloverBox"); var boxtext = $("#rolloverBoxText");
    var beak = $("#rolloverBeak"); boxtext.html(result);
    var numitems = targetPoi.key.split(',').length;
    boxMinX = infoBoxX - 240;
    boxMaxX = infoBoxX + 20; boxMinY = infoBoxY - 30; boxMaxY = infoBoxY + (25 * numitems);
    var offset = getCenterOffset();
    var point = map.llToPix(targetPoi.getLatLng()); var x = point.getX();
    var y = point.getY();
    box.css("left", (x + 160 + offset.x));
    box.css("top", (y + 143 + offset.y)); box.css("display", "block");
    hoverBox = false; //ToggleContentDivHeight();
}
function OnCallBoxError(error, userContext, methodName) {
    if (error !== null) { alert(error.get_message()); }
    //ToggleContentDivHeight();
}
function onPoiMouseout(e) { 
//ToggleContentDivHeight(); 
}
function onPoiMouseclick(e) {
    CloseRolloverBox(true); 
    CloseInfoBox(true);
    targetPoi = this;
    RenderInfoBox(targetPoi);
}

function RenderInfoBox(targetPoi) {
    var box = document.getElementById('infoBox');
    var boxtext = document.getElementById('infoBoxText');

    box.style.display = "none";
    boxtext.style.height = "auto";
    var url;
    if (pagetype == 'AS') {
        url = "/Maps/GetAgentSearchInfoBox/" + targetPoi.key;
    }
    else
    {
        url = "/Maps/GetInfoBox/" + targetPoi.key;
    }
    $.ajax({
        type: "GET",
        cache: false,
        url: url,
        success: function (result) {
            OnCallInfoBoxComplete(result, targetPoi);
        }
    });
}

function DisplayInfoWindow(pid, la, ln) {
    ShowMap('show map-property');
    LoadMap();

    var poi = new MQA.Poi({ lat: la, lng: ln });
    poi.setKey(pid);
    RenderInfoBox(poi);
    $('html, body').animate({ scrollTop: '0px' }, 300);
    
}

function showHover(targetPoi) { var box = $('#infoBox'); var boxtext = $('#infoBoxText'); box.css("diplay", "none"); box.css("height", "auto"); $.ajax({ type: "GET", cache: false, url: "/Map/GetInfoBox/" + targetPoi.key, success: function (data) { if (data != null && data.length > 0) { OnCallCenterBoxComplete(data, targetPoi) } } }); }
function CloseRolloverBox(force) {
    if (!hoverBox || force) { var box = $('#rolloverBox'); if (box != null) { box.css("display", "none"); hoverBox = false; } }
    //ToggleContentDivHeight();
}
function CloseInfoBox(force) {
    if (force) { var box = $('#infoBox'); if (box != null) { box.css("display", "none"); infoBox = false; hoverBox = false; } }
    //ToggleContentDivHeight();
}
function OnCallCenterBoxComplete(result, targetPoi, methodName) { var box = $('#infoBox'); var boxtext = $('#infoBoxText'); boxtext.html(result); box.css("left", "-35px"); box.css("top", "94px"); box.css("display", "block"); infoBox = true; 
//ToggleContentDivHeight(); 
}
function GetRefineMapView() {
    if (jQuery.browser.msie) { $("#mapModal").html("<div class=\"mapmodelcontainer\"><div class=\"map-top\"></div><div class=\"map-bg\"><div class=\"inter-om\"><p>Loading</p></div></div><div class=\"map-bottom\"></div></div>"); $("#mapModal").jqmShow(); }
    $.ajax({ type: "GET", cache: true, url: "/Results/get-map-search-view", success: function (data) { if (data != null && data.length > 0) { $("#mapModal").jqmHide(); $("#mapModal").html(data); $("#mapModal").jqmShow(); } } });
    OmnitureEvent9("search map refine");
    scrollToObject(0);
}

/*Mapquest Map area end*/
function RenderPager(pagerData) {
    var pagerArray = [];
    if (pagerData.CurrentPage == 1) {
        pagerArray.push("<a class='prevSugg disabled'>Back</a>");
    }
    else {
        pagerArray.push("<a class='prevSugg' href='" + pagerData.BaseURL + "/Page" + (pagerData.CurrentPage - 1) + "'>Back</a>");
    }
    pagerArray.push("<div class='pagLabel'>Page</div><ul class='pagination'>");
    for (var index = pagerData.Start; index <= pagerData.End; index++) {
        if (pagerData.CurrentPage == index) {
            pagerArray.push("<li><a class='current' href='" + pagerData.BaseURL + "/Page" + index + "'>" + index + "</a></li>");
        } else {
            pagerArray.push("<li><a href='" + pagerData.BaseURL + "/Page" + index + "'>" + index + "</a></li>");
        }

    }
    if (pagerData.CurrentPage >= pagerData.PageCount) {
        pagerArray.push("</ul><a class='nextSugg disabled'>Next</a></div></div>");
    }
    else {
        pagerArray.push("</ul><a class='nextSugg' href='" + pagerData.BaseURL + "/Page" + (pagerData.CurrentPage + 1) + "'>Next</a></div>");
    }

    pagerArray.push("<div class='pagTitle'>Listings " + (((pagerData.CurrentPage - 1) * pagerData.Size) + 1) + " - " + (pagerData.CurrentPage * pagerData.Size) + "</div><div class='pagOptions'>");

    return pagerArray.join("");
}
/*Drop downs*/
function CountryDrop() {
    if (gE("country_drop").style.display != 'block') {
        strStatus = "open";
    } else {
        strStatus = "close";
    }
    if (strStatus == "open") {
        $('#country_drop').css('display','block');
        $('#country_drop_backOpen').css('display','block');
        $('#section_drop').css('display','none');
        $('#section_drop_backOpen').css('display','none');
        if (gE("srt")) {
            gE("srt").style.zIndex = 0;
        }
        if (gE("results_pricerange")) {
            closePriceRangeDrop();
        }
        if (gE("results_propertytype")) {
            closePopertyTypeDrop();
        }
        if (gE("listings_sortoptions")) {
            closesortOptionsDrop();
        }
        if (gE("agents_sortoptions")) {
            closeAgentssortOptionsDrop();
        }
        if (gE('search_pricemin')) {
            closepriceMinDrop();
        }
        if (gE('search_pricemax')) {
            closepriceMaxDrop();
        }
        if (gE('selectsqft')) {
            closesqftDrop();
        }
        if (gE('selectbeds')) {
            closebedsDrop();
        }
        if (gE('selectbaths')) {
            closebathsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;
        
    } else {
        $('#country_drop').css('display','none');
        
        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        $('#SearchText').focus();
    }
}
function SectionDrop() {
    if (gE("section_drop").style.display != 'block') {
        section_strStatus = "open";
    } else {
        section_strStatus = "close";
    }
    if (section_strStatus == "open") {
        $('#section_drop').css('display','block');
        
        $('#country_drop').css('display','none');
        
        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        if (gE("results_pricerange")) {
            closePriceRangeDrop();
        }
        if (gE("results_propertytype")) {
            closePopertyTypeDrop();
        }
        if (gE("listings_sortoptions")) {
            closesortOptionsDrop();
        }
        if (gE("agents_sortoptions")) {
            closeAgentssortOptionsDrop();
        }
        if (gE('search_pricemin')) {
            closepriceMinDrop();
        }
        if (gE('search_pricemax')) {
            closepriceMaxDrop();
        }
        if (gE('selectsqft')) {
            closesqftDrop();
        }
        if (gE('selectbeds')) {
            closebedsDrop();
        }
        if (gE('selectbaths')) {
            closebathsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;
        
    } else {
        $('#section_drop').css('display','none');
        $('#SearchText').focus();
    }
}
function PriceRangeDrop() {
    if (gE("results_pricerange").style.display != 'block') {
        pricerange_strStatus = "open";
    } else {
        pricerange_strStatus = "close";
    }
    if (pricerange_strStatus == "open") {
        $('#results_pricerange').css('display','block');
        $('#PriceRange_drop_backOpen').css('display','block');
        $('#country_drop').css('display','none');
        $('#country_drop_backOpen').css('display','none');
        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        $('#section_drop').css('display','none');
        $('#section_drop_backOpen').css('display','none');
        if (gE("results_propertytype")) {
            closePopertyTypeDrop();
        }
        if (gE("listings_sortoptions")) {
            closesortOptionsDrop();
        }
        if (gE("agents_sortoptions")) {
            closeAgentssortOptionsDrop();
        }
        if (gE('search_pricemin')) {
            closepriceMinDrop();
        }
        if (gE('search_pricemax')) {
            closepriceMaxDrop();
        }
        if (gE('selectsqft')) {
            closesqftDrop();
        }
        if (gE('selectbeds')) {
            closebedsDrop();
        }
        if (gE('selectbaths')) {
            closebathsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;
    } else {
        $('#results_pricerange').css('display','none');
    }
}
function PopertyTypeDrop() {
    if (gE("results_propertytype").style.display != 'block') {
        propertyType_strStatus = "open";
    } else {
        propertyType_strStatus = "close";
    }
    if (propertyType_strStatus == "open") {
        $('#results_propertytype').css('display', 'block');
        //gE("results_propertytype").style.display = 'block';
        //gE("country_drop").style.display = 'none';
        $("#country_drop").hide();
        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        $('#section_drop').css('display','none');

        if (gE("results_pricerange")) {
            closePriceRangeDrop();
        }
        if (gE("listings_sortoptions")) {
            closesortOptionsDrop();
        }
        if (gE("agents_sortoptions")) {
            closeAgentssortOptionsDrop();
        }
        if (gE('search_pricemin')) {
            closepriceMinDrop();
        }
        if (gE('search_pricemax')) {
            closepriceMaxDrop();
        }
        if (gE('selectsqft')) {
            closesqftDrop();
        }
        if (gE('selectbeds')) {
            closebedsDrop();
        }
        if (gE('selectbaths')) {
            closebathsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;

    } else {
        $('#results_propertytype').css('display','none');

    }
}
function AgentsSortOptionsDrop() {
    if (gE("agents_sortoptions").style.display != 'block') {
        sortOptions_strStatus = "open";
    } else {
        sortOptions_strStatus = "close";
    }
    if (sortOptions_strStatus == "open") {
        $('#agents_sortoptions').css('display','block');
        //$('#Agents_SortOptions_drop_backOpen').css('display','block');
        $('#country_drop').css('display','none');
        //$('#country_drop_backOpen').css('display','none');
        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        $('#section_drop').css('display','none');
        //$('#section_drop_backOpen').css('display','none');
        if (gE("results_pricerange")) {
            closePriceRangeDrop();
        }
        if (gE("results_propertytype")) {
            closePopertyTypeDrop();
        }
        if (gE('search_pricemin')) {
            closepriceMinDrop();
        }
        if (gE('search_pricemax')) {
            closepriceMaxDrop();
        }
        if (gE('selectsqft')) {
            closesqftDrop();
        }
        if (gE('selectbeds')) {
            closebedsDrop();
        }
        if (gE('selectbaths')) {
            closebathsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;
    } else {
        gE("agents_sortoptions").style.display = 'none';

    }
}
function SortOptionsDrop() {
    if (gE("listings_sortoptions").style.display != 'block') {
        sortOptions_strStatus = "open";
    } else {
        sortOptions_strStatus = "close";
    }
    if (sortOptions_strStatus == "open") {
        gE("listings_sortoptions").style.display = 'block';        
        gE("country_drop").style.display = 'none';        
        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        if (gE("section_drop")) {
            gE("section_drop").style.display = 'none';
        }
        
        if (gE("results_pricerange")) {
            closePriceRangeDrop();
        }
        if (gE("results_propertytype")) {
            closePopertyTypeDrop();
        }
        if (gE('search_pricemin')) {
            closepriceMinDrop();
        }
        if (gE('search_pricemax')) {
            closepriceMaxDrop();
        }
        if (gE('selectsqft')) {
            closesqftDrop();
        }
        if (gE('selectbeds')) {
            closebedsDrop();
        }
        if (gE('selectbaths')) {
            closebathsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;
    } else {
        gE("listings_sortoptions").style.display = 'none';

    }
}
function PriceMinDrop() {
    if (gE("more_pricemin").style.display != 'block') {
        priceminStatus = "open";
    } else {
        priceminStatus = "close";
    }
    if (priceminStatus == "open") {
        gE("more_pricemin").style.display = 'block';
        
        gE("country_drop").style.display = 'none';
        
        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        if (gE("section_drop")) {
            gE("section_drop").style.display = 'none';
        }
        if (gE("results_pricerange")) {
            closePriceRangeDrop();
        }
        if (gE("results_propertytype")) {
            closePopertyTypeDrop();
        }
        if (gE("listings_sortoptions")) {
            closesortOptionsDrop();
        }
        if (gE("agents_sortoptions")) {
            closeAgentssortOptionsDrop();
        }
        if (gE('search_pricemax')) {
            closepriceMaxDrop();
        }
        if (gE('selectsqft')) {
            closesqftDrop();
        }
        if (gE('selectbeds')) {
            closebedsDrop();
        }
        if (gE('selectbaths')) {
            closebathsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;
        
    } else {
        gE("more_pricemin").style.display = 'none';
    }
}
function PriceMaxDrop() {
    if (gE("more_pricemax").style.display != 'block') {
        pricemaxStatus = "open";
    } else {
        pricemaxStatus = "close";
    }
    if (pricemaxStatus == "open") {
        gE("more_pricemax").style.display = 'block';
        
        gE("country_drop").style.display = 'none';
        
        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        if (gE("section_drop")) {
            gE("section_drop").style.display = 'none';
        }
        if (gE("results_pricerange")) {
            closePriceRangeDrop();
        }
        if (gE("results_propertytype")) {
            closePopertyTypeDrop();
        }
        if (gE("listings_sortoptions")) {
            closesortOptionsDrop();
        }
        if (gE("agents_sortoptions")) {
            closeAgentssortOptionsDrop();
        }
        if (gE('search_pricemin')) {
            closepriceMinDrop();
        }
        if (gE('selectsqft')) {
            closesqftDrop();
        }
        if (gE('selectbeds')) {
            closebedsDrop();
        }
        if (gE('selectbaths')) {
            closebathsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;
        
    } else {
        gE("more_pricemax").style.display = 'none';

    }
}
function SqftDrop() {
    if (gE("more_sqft").style.display != 'block') {
        sqftStatus = "open";
    } else {
        sqftStatus = "close";
    }
    if (sqftStatus == "open") {
        gE("more_sqft").style.display = 'block';
        
        gE("country_drop").style.display = 'none';
        
        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        if (gE("section_drop")) {
            gE("section_drop").style.display = 'none';
        }
        if (gE("results_pricerange")) {
            closePriceRangeDrop();
        }
        if (gE("results_propertytype")) {
            closePopertyTypeDrop();
        }
        if (gE("listings_sortoptions")) {
            closesortOptionsDrop();
        }
        if (gE("agents_sortoptions")) {
            closeAgentssortOptionsDrop();
        }
        if (gE('search_pricemin')) {
            closepriceMinDrop();
        }
        if (gE('search_pricemax')) {
            closepriceMaxDrop();
        }
        if (gE('selectbeds')) {
            closebedsDrop();
        }
        if (gE('selectbaths')) {
            closebathsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;
    } else {
        gE("more_sqft").style.display = 'none';

    }
}
function BedsDrop() {
    if (gE("more_beds").style.display != 'block') {
        bedsStatus = "open";
    } else {
        bedsStatus = "close";
    }
    if (bedsStatus == "open") {
        gE("more_beds").style.display = 'block';

        gE("country_drop").style.display = 'none';
        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        if (gE("section_drop")) {
            gE("section_drop").style.display = 'none';
        }
        if (gE("results_pricerange")) {
            closePriceRangeDrop();
        }
        if (gE("results_propertytype")) {
            closePopertyTypeDrop();
        }
        if (gE("listings_sortoptions")) {
            closesortOptionsDrop();
        }
        if (gE("agents_sortoptions")) {
            closeAgentssortOptionsDrop();
        }
        if (gE('search_pricemin')) {
            closepriceMinDrop();
        }
        if (gE('search_pricemax')) {
            closepriceMaxDrop();
        }
        if (gE('selectsqft')) {
            closesqftDrop();
        }
        if (gE('selectbaths')) {
            closebathsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;
       
    } else {
        gE("more_beds").style.display = 'none';
    }
}
function BathsDrop() {
    if (gE("more_baths").style.display != 'block') {
        bathsStatus = "open";
    } else {
        bathsStatus = "close";
    }
    if (bathsStatus == "open") {
        gE("more_baths").style.display = 'block';
        gE("country_drop").style.display = 'none';

        if (gE("srt")) {
            gE("srt").style.zIndex = 3;
        }
        if (gE("section_drop")) {
            gE("section_drop").style.display = 'none';
        }
        if (gE("results_pricerange")) {
            closePriceRangeDrop();
        }
        if (gE("results_propertytype")) {
            closePopertyTypeDrop();
        }
        if (gE("listings_sortoptions")) {
            closesortOptionsDrop();
        }
        if (gE("agents_sortoptions")) {
            closeAgentssortOptionsDrop();
        }
        if (gE('search_pricemin')) {
            closepriceMinDrop();
        }
        if (gE('search_pricemax')) {
            closepriceMaxDrop();
        }
        if (gE('selectsqft')) {
            closesqftDrop();
        }
        if (gE('selectbeds')) {
            closebedsDrop();
        }
        var G = new GetWindowBunds();
        var width = G.VisibleWidth - 50;
        var left = 944 - width;

    } else {
        gE("more_baths").style.display = 'none';
    }
}
function closeCountryDrop() {
    $('#country_drop').css('display', 'none');

    gE("search_country").className = "";
    $('#SearchText').focus();
}
function closeSectionDrop() {
    $('#section_drop').css('display', 'none');
    $('#SearchText').focus();
}
function closePriceRangeDrop() {
    $('#results_pricerange').css('display','none');
}
function closePopertyTypeDrop() {
    //$('#results_propertytype").css('display', 'none');
    $('#results_propertytype').css('display', 'none');
}
function closesortOptionsDrop() {
    $('#listings_sortoptions').css('display', 'none');
}
function closeAgentssortOptionsDrop() {
    $('#agents_sortoptions').css('display', 'none');
}
function closepriceMinDrop() {
    $('#more_pricemin').css('display', 'none');
}
function closepriceMaxDrop() {
    $('#more_pricemax').css('display', 'none');
}
function closesqftDrop() {
    $('#more_sqft').css('display', 'none');
}
function closebedsDrop() {
    $('#more_beds').css('display', 'none');
}
function closebathsDrop() {
    $('#more_baths').css('display', 'none');
}
function CountryHover() {}
function CountryOut() { }

/*Omniture start*/
function addOmEvent(ev) {
    addOmEventeVar(ev, null, null);
}
function addOmEventeVar(ev, evar, evarTxt) {
    
    s.events='event'+ev;
    if (evar != null) {
        evar = evarTxt;
    }
    var s_code = s.t();
    if (s_code) { document.write(s_code); }
}
function addOmeVar(evar, evarTxt) {
    if (evar != null) {
        evar = evarTxt;
    }
}
function addOmeVent(ev) {
    s.events = 'event' + ev;
}
function writeOm() {
    var s_code = s.t();
    if (s_code) { document.write(s_code); }
}

function createCookie(name, value, days) {
    var expires = ""; 
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } 
        
    document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
function omfeaturedClick(featuredPage, featuredMethod, featuredid) {
    createCookie('featuredclick', featuredPage + '|' + featuredMethod + '|' + featuredid, 365);
}

function gets_account()
{
 if(window.location.host=="www.realestatebook.com" || window.location.host=="beta.realestatebook.com")
    return"ncirealestatebookprod";
 else
    return"ncirealestatebookdev";
}

var s_account=gets_account() 

//function omVirtualtour()
//{ 
// s.eVar36 = 'inView';
// s.events = 'event18';
// var s_code = s.t();
// if (s_code) { document.write(s_code); }
//}


/*Omniture end*/

function openPartnerURL(url) {
    var wdth, hght;
    if (typeof (window.innerWidth) == 'number') {
        wdth = window.innerWidth;
        hght = window.innerHeight;
    }
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        wdth = document.documentElement.clientWidth;
        hght = document.documentElement.clientHeight;
    }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        wdth = document.body.clientWidth;
        hght = document.body.clientHeight;
    }

    wdth = wdth * 40 / 100;
    hght = hght * 40 / 100;

    window.open(url, 'partnerWindow', 'location=no,toolbar=no,resizable=yes,scrollbars=yes,width=' + wdth + ',height=' + hght + '');
} 

