Search = {};

var resizeWidth = 245;
var countFromCache = 1;
var counting = 1;
var _searchSummary = new SearchSummary();

Search.load = function() {
  

    var isSummaryLoaded = false;
    $(document).bind("criteriachange", function(e, eventData) {
        if (!isSummaryLoaded) {
            _searchSummary.load(eventData.activeTab); 
            isSummaryLoaded = true;
        }
    });

    // Let listeners know we're done (such as the search summary)
    $(document).trigger("criteriachange", [{ activeTab: $("#SearchType").val()}]); 
    var $acc = $('#mapsearch-left-accordion');
    if ($acc.length > 0) {
        $acc.accordion('option', 'collapsible', false);
        $acc.accordion('activate', 0);
    }
    $("#mapsearch-advisory-box").mouseover(function() {
        positionAdvisory(true);
    });
//    $(window).resize(function() {
//        positionAdvisory();
//    });
    //$(window).unload(dispose);
}
Search.sort = function(obj) {
    if (window.frames.SearchResultsFrame && window.frames.SearchResultsFrame.postbackSort)
        window.frames.SearchResultsFrame.postbackSort(obj.value);
}
Search.toggleTabs = function(name, postback, sortExp, sortDir) {
    if (postback == undefined)
        postback = 1;

    var sort = document.getElementById('mapsearch-sort-list');
    if (sort && sortExp != undefined && sortDir != undefined)
        sort.value = sortExp + "-" + sortDir;

    switch (name) {
        case 'sc': // search criteria
            Search.hideAllTabs();
            display('divSearchCriteria');
            break;
        case 'dd': // driving directions
            Search.hideAllTabs();
            display('divDrivingDirection');
            break;
        case 'poi': // points of interest
            Search.hideAllTabs();
            display('divPOI');
            break;
        case 'map':
            //alert('m');
            document.getElementById('SearchResultsFrame').style.visibility = 'hidden';
            display('mapsearch-view-loading');
            if (counting == 0) // if not counting
            {
                activeView = "map";
                $("#mapsearch-map").show();
                $("#mapsearch-toolbar").show();
                $("#mapsearch-viewtab-map").removeClass("ms_tab_off").addClass("ms_tab_on");
                $("#mapsearch-viewtab-list").removeClass("ms_tab_on").addClass("ms_tab_off");
                $("#mapsearch-viewtab-gallery").removeClass("ms_tab_on").addClass("ms_tab_off");
                if (postback != 0) {
                    if (window.frames.SearchResultsFrame && window.frames.SearchResultsFrame.postbackView)
                        window.frames.SearchResultsFrame.postbackView('list');
                    positionAdvisory();

                }
                else {
                    document.getElementById('SearchResultsFrame').style.visibility = 'visible';
                    hide('mapsearch-view-loading');
                }
                try { resizeIFrameH(parent.window.document.getElementById("IFrameMain"), 2000) } catch (e) { }
            }
            break;
        case 'list':
            //alert('l');
            document.getElementById('SearchResultsFrame').style.visibility = 'hidden';
            display('mapsearch-view-loading');
            if (counting == 0) // if not counting
            {
                activeView = "list";
                $("#mapsearch-map").hide();
                $("#mapsearch-toolbar").hide();
                $("#mapsearch-viewtab-map").removeClass("ms_tab_on").addClass("ms_tab_off");
                $("#mapsearch-viewtab-list").removeClass("ms_tab_off").addClass("ms_tab_on");
                $("#mapsearch-viewtab-gallery").removeClass("ms_tab_on").addClass("ms_tab_off");

                //resizeIFrameW(document.getElementById('SearchResultsFrame'), document.getElementById('divMap').style.width);

                if (postback == 0) {
                    //if (document.getElementById('divDetailedViewMsg').style.visibility != 'visible')
                    document.getElementById('SearchResultsFrame').style.visibility = 'visible';
                    hide('mapsearch-view-loading');
                }
                else {
                    if (window.frames.SearchResultsFrame && window.frames.SearchResultsFrame.postbackView)
                        window.frames.SearchResultsFrame.postbackView('detail');
                    positionAdvisory();
                }
                try { resizeIFrameH(parent.window.document.getElementById("IFrameMain"), 4000) } catch (e) { }
            }
            break;
        case 'gallery':
            //alert('g');
            document.getElementById('SearchResultsFrame').style.visibility = 'hidden';
            display('mapsearch-view-loading');
            if (counting == 0) // if not counting
            {
                activeView = "gallery";
                $("#mapsearch-map").hide();
                $("#mapsearch-toolbar").hide();
                $("#mapsearch-viewtab-map").removeClass("ms_tab_on").addClass("ms_tab_off");
                $("#mapsearch-viewtab-list").removeClass("ms_tab_on").addClass("ms_tab_off");
                $("#mapsearch-viewtab-gallery").removeClass("ms_tab_off").addClass("ms_tab_on");

                //resizeIFrameW(document.getElementById('SearchResultsFrame'), document.getElementById('divMap').style.width);

                if (postback == 0) {
                    //if (document.getElementById('divDetailedViewMsg').style.visibility != 'visible')
                    document.getElementById('SearchResultsFrame').style.visibility = 'visible';
                    hide('mapsearch-view-loading');
                }
                else {
                    if (window.frames.SearchResultsFrame && window.frames.SearchResultsFrame.postbackView)
                        window.frames.SearchResultsFrame.postbackView('gallery');
                    positionAdvisory();
                }
                try { resizeIFrameH(parent.window.document.getElementById("IFrameMain"), 3000) } catch (e) { }
            }
            break;
    }
if ($('#mapsearch-advisory-box').is(":visible"))
       hide('mapsearch-view-loading');
}
Search.setListingStatusFromIcon = function(status)
{
    // Update the dropdowns and icons
    var chkbx;
    var statusDD = document.frmSearch.elements['Status']; 
    if (statusDD)
    {  
        var len=statusDD.length;
        if (len > 0)
        {
            for(var i=0;i<len;i++)
            { 
                var chkstatus = statusDD[i];
                if (chkstatus.value == status)
                {
                    chkbx = chkstatus;
                    break;    
                }
            }
        }
        else
        {
            statusDD.checked = true;
        }
    }
    var pre = 'listing_' + status;
    if (chkbx)
    {
        chkbx.checked = (isHidden(pre + '_on'))
        Search.setListingStatus(chkbx); // set rest
    }  
}
Search.toggleCriteria = function(name, obj) {
    switch (name) {
        case 'basic':
            Search.hideAllCriteria();
            display('basicSearch');
            document.getElementById('SearchType').value = 1;
            $(document).trigger("criteriachange", [{ activeTab: $("#SearchType").val()}]);
            break;
        case 'advanced':
            //Search.hideAllCriteria();
            var $advanced = $("#advancedSearch");
            if ($advanced.is(":visible")) {
                $advanced.hide();
                $("span.arrow", obj).removeClass("arrow-down").addClass("arrow-left");
                $("#moreCriteria").html("MORE SEARCH CRITERIA");
                $("#moreCriteria2").html("Click here to view advanced criteria");
                $("#searchButton2").hide();
            } else {
                $advanced.show();
                $("span.arrow", obj).removeClass("arrow-left").addClass("arrow-down");
                $("#moreCriteria").html("LESS SEARCH CRITERIA");
                $("#moreCriteria2").html("Click here to hide advanced criteria");
                $("#searchButton2").show();
            }
            document.getElementById('SearchType').value = 2;
            $(document).trigger("criteriachange", [{ activeTab: $("#SearchType").val()}]);
            break;
        case 'mlsID':
            Search.hideAllCriteria();
            display('mlsIDSearch');
            document.getElementById('SearchType').value = 3;
            self.scrollTo(0, 20);
            $(document).trigger("criteriachange", [{ activeTab: $("#SearchType").val()}]);
            break;
        case 'address':
            Search.hideAllCriteria();
            display('addressSearch');
            document.getElementById('SearchType').value = 4;
            self.scrollTo(0, 20);
            $(document).trigger("criteriachange", [{ activeTab: $("#SearchType").val()}]);
            break;
        case 'school':
            Search.hideAllCriteria();
            display('schoolSearch');
            document.getElementById('SearchType').value = 5;
            self.scrollTo(0, 20);
            $(document).trigger("criteriachange", [{ activeTab: $("#SearchType").val()}]);
            break;
    }
}
Search.hideAllTabs = function()
{
    hide('divSearchCriteria');
    hide('divDrivingDirection');
    hide('divPOI');
}
Search.hideAllCriteria = function()
{
    hide('basicSearch');
    hide('advancedSearch');
    hide('mlsIDSearch');
    hide('addressSearch');
    hide('schoolSearch');
}
Search.toggleFeature = function(obj)
{
    if (obj)
    {
        var len = obj.length;
        for (i=0; i<len; i++) // hide all
            hide('feature_' + i);
        //alert(obj.selectedIndex);
        display('feature_' + obj.selectedIndex); // display selected
            
    }
    
}
Search.setListingStatus = function(obj)
{
    // Update the dropdowns and icons
    //Search.setListingStatusWithoutSubmit(obj);
   
    // And submit the search
    Search.submit(0);    
}

Search.setListingStatusWithoutSubmit = function(obj)
{
    // First make sure that the select is set
    // (in case this is coming from the POI icons)
   //alert(obj.value);
  
    var textVal = document.getElementById('selectedStatus').innerHTML;
    var objVal = obj.value;
    var statusDesc = '';
    if (objVal == 'A,B,C')
        statusDesc = 'Active';
    else if (objVal == 'S')
        statusDesc = 'Sold';
    else if (objVal== 'P')
        statusDesc = 'Pending';
    if (obj.checked) // Add status
    {
        textVal += statusDesc + ',';
        display('listing_' + objVal+ '_on');
        hide('listing_' + objVal + '_off');
    }
    else
    {
        textVal = textVal.replace(statusDesc + ',', '');
        display('listing_' + obj.value + '_off');
        hide('listing_' + obj.value + '_on');
        if (textVal == '')
        {
            alert('At least one status should be selected.');
            // select Active by default
            var statusDD = document.getElementById('Status');

            if (statusDD)
            {   var len = statusDD.length;
                if (len > 0)
                {
                    for(var i=0;i<len;i++)
                    {
                        if (statusDD[i].value == 'A,B,C')
                        {
                            statusDD[i].checked = true;
                            break;
                        }
                    }
                }
                else
                {
                    statusDD.checked = true;
                }
                //textVal = 'Active,';                        
                //hide('listing_A,B,C_off');
                //display('listing_A,B,C_on');
            }
            
        }
              
     }   
     
   document.getElementById('selectedStatus').innerHTML = textVal;
   
}
Search.open = function()
{
    //Search.slide(1);
    map.resizeMapWidth(resizeWidth);
    self.setTimeout("hide('searchCriteriaOpen');display('searchCriteria');display('searchCriteriaClose');",100); // wait for the map to finish resizing
}
Search.close = function()
{
    //Search.slide(0);
    hide('searchCriteria');
    hide('searchCriteriaClose');
    display('searchCriteriaOpen');
    map.resizeMapWidth(resizeWidth - 200);
}
Search.lock = function(lock)
{
    if (lock == 1)
    {
        map.resizeMapWidth(resizeWidth + 202);
        display('lockClose');
        hide('lockOpen');
        hide('searchCriteriaClose');
        document.getElementById("searchCriteriaSpacer").width = "222";
        document.getElementById("searchCriteriaDiv").style.left = "-225px";
        map.moveDashboard(0);
    }
    else
    {
        map.resizeMapWidth(resizeWidth);
        hide('lockClose');
        display('lockOpen');
        display('searchCriteriaClose');
        document.getElementById("searchCriteriaSpacer").width = "20";
        document.getElementById("searchCriteriaDiv").style.left = "-23px";
        map.moveDashboard(199);
    }
}
var COUNT_DELAY_MS = 1500; // The submission to refresh the Map Search 'count' is delayed by this amount after each criteria change.
var MAX_COUNT_DELAY_MS = 12000; // The submission to refresh the Map Search 'count' is delayed by at most this amount before refreshing.

var delayTimerID = null;
var delayTimerRunning = false;
var maxDelayTimerID = null;
var maxDelayTimerRunning = false;
Search.submitWithTimer = function()
{
    // If the delay timer is already running, stop it
    Search.setCount(-1); // Processing
	 if (delayTimerRunning) {
	 clearTimeout(delayTimerID);
	 }

	 // Start the delay timer
	 delayTimerRunning = true;
	 delayTimerID = self.setTimeout('Search.submit(0)', COUNT_DELAY_MS);

	 // If the max delay timer isn't already running, start it
	 if (!maxDelayTimerRunning) {
	 maxDelayTimerRunning = true;
	 maxDelayTimerID = self.setTimeout('Search.submit(0)', MAX_COUNT_DELAY_MS);
	 }

}
Search.submit = function(buttonClicked) {
    // Stop the timers
    if (veMap && veMap.GetMapStyle() != VEMapStyle.Birdseye && veMap.GetMapStyle() != 'b') {
        if (delayTimerRunning) {
            clearTimeout(delayTimerID);
            delayTimerRunning = false;
        }
        if (maxDelayTimerRunning) {
            clearTimeout(maxDelayTimerID);
            maxDelayTimerRunning = false;
        }
        if (document.frmSearch) {
            Search.setCount(-1); // Processing
            document.frmSearch.target = 'SearchResultsFrame';

            if (countFromCache == 1)
                document.frmSearch.action = document.getElementById('SearchResultsFrame').src + "&cache=1";
            else
                document.frmSearch.action = document.getElementById('SearchResultsFrame').src;

            if (buttonClicked == 1) {
                mapGoto(); // this will fire a submit
                //self.setTimeout("document.frmSearch.submit();", 800); // submit after waiting for the map to goto location otherwise it submits twice
            }
            //else

            if (document.getElementById('SearchType').value == 3) // MLS Search
            {
                //self.setTimeout('if (pin1[0]) map.PanToLatLong(pin1[0][1], pin1[0][2], 0)', 4000); // pan without submitting search
                bestview = true;
            }
            document.frmSearch.submit(); // submit right away
            //alert('trigger');
            $(document).trigger("criteriaitemchange", [{}]);
            countFromCache = 0;

        }
    }
}
Search.onChangeSubmit = function(obj, validation, justValidate)
{
    var objVal = null;
    if (obj)
        objVal = obj.value;

    // Changing from switch to if statements for perf reasons, per IE perf team
    if (validation == 'numeric') {
        if (IsNumeric(objVal))
        {
            if (justValidate != 1) {
                Search.submit(0);
            }
        }
        else
        {
            if (justValidate == 1)
            {
                alert('Invalid entry. Please enter a numeric value.');
                obj.value = "";
                obj.focus();
            }
        }
    } else if (validation == 'nocomma') {
        if (objVal.indexOf(",") == -1)
        {
            if (justValidate != 1)
                Search.submit(0);
        }
        else
        {
            if (justValidate == 1)
            {
                alert('Multiple MLS IDs are not supported.');
                obj.focus();
            }
            
        }
    } else if (validation == 'numeric4') {
        
        if (IsNumeric(objVal) && (objVal.length == 0 || objVal.length == 4))
        {
            if (justValidate != 1)
                Search.submit(0);
        }
        else
        {
            if (justValidate == 1)
            {
                alert('Please enter a valid year. Ex: 1995.');
                obj.value = "";
                obj.focus();
            }
            
        }
    } else if (validation == 'mmddyyyy') {
        /**--------------------------
        //* Validate Date Field script- By JavaScriptKit.com
        //* For this script and 100s more, visit http://www.javascriptkit.com
        //* This notice must stay intact for usage
        ---------------------------**/
        var validformat = /^\d{2}\/\d{2}\/\d{4}$/;
        var isValid = false;
        
        if (validformat.test(objVal)) {// This RegEx is a basic check for format validity { // Begin detailed check for valid date ranges
            var monthfield = objVal.split("/")[0];
            var dayfield = objVal.split("/")[1];
            var yearfield = objVal.split("/")[2];
            var dayobj = new Date(yearfield, monthfield - 1, dayfield);
            if ((dayobj.getMonth() + 1 == monthfield) && (dayobj.getDate() == dayfield) && (dayobj.getFullYear() == yearfield))
                isValid = true;
        }
        if (isValid) {
            if (justValidate != 1)
                Search.submit(0);
        } else {
            alert('Please enter a date in the format MM/DD/YYYY.');
            obj.value = "";
            obj.focus();
        }
    } else {
      if (justValidate != 1)
          Search.submit(0);
    }
  
}
Search.setCount = function(count, label)
{
    if (document.getElementById('mapsearch-count'))
    {
        if (count == -1)
        {
            document.getElementById('mapsearch-count').innerHTML = "<font style=\"background:#fbd956\">Searching...</font>";
            setAdvisoryText("Searching...", 'In a moment we will show you the matching properties.');
            counting = 1;
        }
        else if (count == -2)
        {
            document.getElementById('mapsearch-count').innerHTML = "Sorry Please Try Again";
            counting = 0;
        }
        else
        {
            document.getElementById('mapsearch-count').innerHTML = count + " " + label;
            counting = 0;
        }
        
    }
}
Search.clear = function()
{
    window.location.href = location.href + "&clear=1";
}
Search.save = function(url) {
   // alert(document.getElementById("hdnSearchCriteria").value);
    url += "&criteria=" + document.getElementById("hdnSearchCriteria").value;
    open_save(url);
}
Search.LoadFormValues = function(xml) {

    var str = "";

    var elem = document.getElementById('frmSearch').elements;
    var polygonType = getValueFromXml(xml, 'PolygonType');
    try {

        for (var i = 0; i < elem.length; i++) {
            if ((elem[i].type == "text" || elem[i].type == "hidden") && elem[i].name.indexOf("sc_") > -1) {
                var id = elem[i].id;
                if (id == '')
                    continue;
                var val = getValueFromXml(xml, elem[i].id);
                if (val == '')
                    continue;
                val = val.split('(')[0];
                if ((elem[i].id == "City" || elem[i].id == "Location") && val != "" && polygonType == "city")
                    self.setTimeout("Shape.DrawBoundaryByCity('" + val + "',1)", 1500);
                else if ((elem[i].id == "ZipCode" || elem[i].id == "Location") && val != "" && polygonType == "zip")
                    self.setTimeout("Shape.DrawBoundaryByZip('" + val + "',1)", 1500);
                else if (elem[i].id == "selNeighborhood" && val != "" && polygonType == "neighborhood") {
                    self.setTimeout("Shape.DrawBoundaryByNeighborhood('" + val + "',1,1);", 1500);
                }
                else if (elem[i].id == "Keyword" && val != "")
                    val = val.replace('11xx11', '');
                else if (elem[i].id == "MLSID" && getValueFromXml(xml, 'SearchType') == '3')
                    Search.toggleCriteria('mlsID');
                document.getElementById(id).value = val;
            }
            else if (elem[i].type == "select-one" && elem[i].name.indexOf("sc_") > -1) {
                var val = getValueFromXml(xml, elem[i].id);
                var sel = document.getElementById(elem[i].id);
                for (var j = 0; j < sel.length; j++) {
                    if (sel.options[j].value == val) {
                        sel.selectedIndex = j;
                        break;
                    }
                }
            }
            else if (elem[i].type == "checkbox" && elem[i].name.indexOf("sc_") > -1) {
                if (elem[i].id != 'Status') {
                    var val = getValueFromXml(xml, elem[i].id);
                    var chkbx = document.getElementById(elem[i].id);

                    if (val == "on")
                        chkbx.checked = true;
                    else
                        chkbx.checked = false;
                }
            }
        }
    }
    catch (e) { }
    //var polyPoints = getValueFromXml(xml , 'PolyPoints');
    //if (polyPoints != "" && (polygonType == "custom" || polygonType == "" || polygonType == undefined))
    //{
    //    self.setTimeout("Shape.DrawPolygon('" + getValueFromXml(xml , 'PolyPoints') + "');Search.submit(0);", 3500);
    //}
}
function getValueFromXml(xml, xpath)
{
    return xml.substring(xml.indexOf("<" + xpath + ">"), xml.indexOf("</" + xpath + ">")).replace("<" + xpath + ">","");
}
Search.ChkCheckbox = function(name, value) {
    try {
        cb = document.getElementsByName(name);
        
        if (!cb)
            return;
        if (name == "sc_Status" && value == "" && cb[0]) // select Active by default
        {
            display('listing_A,B,C_on');
            hide('listing_A,B,C_off');
            cb[0].checked = true;
            Search.setListingStatusWithoutSubmit(cb[0]);
            return;
        }
        for (i = 0; i < cb.length; i++) {
            cb[i].checked = false;
            if (value.indexOf(cb[i].value) > -1) {
                cb[i].checked = true;
                if (name == "sc_Status")
                    Search.setListingStatusWithoutSubmit(cb[i]);
            }
        }
    }
    catch (e) { }
}

Search.mapGoto = function(loc)
{
    if (loc != '')
        map.SmartFind(loc); 
    else
       Search.submit(1); 
}
function mapGoto()
{
    //if (document.getElementById('SearchType').value == 1) // Basic Search
    //{
    //   if (document.getElementById('ZipCode') && document.getElementById('ZipCode').value != '')
    //        map.GotoFirst(document.getElementById('ZipCode').value);
        //else if(document.getElementById('City') && document.getElementById('City').value != '')
            //map.Find(document.getElementById('City').value + ',usa'); 
    //}
    if (document.getElementById('SearchType').value == 4) // Address Search
    {
        Search.addressGoto('AS');
    }
    if (document.getElementById('SearchType').value == 5) // School District Search
    {
        Search.addressGoto('SS');
    }
}
Search.addressGoto = function(prefix)
{
    if (prefix == null || prefix == '')
        prefix = 'AS';
        
   
    pushpin.deletePin('1_999');
    
    var street = '';
    if (document.getElementById(prefix + '_StreetAddress'))
        street = document.getElementById(prefix + '_StreetAddress').value;
    var city = document.getElementById(prefix + '_City').value;
    var state = document.getElementById(prefix + '_State').value;
    var zip = document.getElementById(prefix + '_ZipCode').value;
    
    if (!((city.length > 0 && state.length > 0) || zip.length > 0)) 
        return;
        
    // Need at least city+state or zip to zoom
    var address = '';
    if (city.length > 0 && state.length > 0)
        address = city + ',' + state;
    if (city.length == 0 && state.length > 0)
        address = state;
            
    if (address.length == 0 && zip.length > 0)
        address = zip;
    
    if (address.length == 0)
        return;
        
    // If we have a street name, add that to the address

    if (street.length > 0)
        address = street + ',' + address
    
   //alert(address);
    // Zoom to the address
    map.GotoFirst(address, 1); 
    if (street.length > 0)
    {   // add address pin
        self.setTimeout("pushpin.addPin('1_999', veMap.vemapcontrol.GetCenterLatitude(), veMap.vemapcontrol.GetCenterLongitude(), 34, '', '" + address + "');", 800);
    }
}


Search.GotoZip = function(zip)
{
    Shape.DrawBoundaryByZip(zip);
}
Search.GotoCity = function(city) {
    Shape.DrawBoundaryByCity(city);
}
Search.GotoNeighborhood = function(nid)
{
    Shape.DrawBoundaryByNeighborhood(nid, 0, 1);
}
Search.GotoLocationByName = function(neighborhood, city, state) {
    bestview = true; 
    Shape.DrawBoundaryByNeighborhoodName(neighborhood, city, state);
}
Search.GotoLocation = function(loc, locType) {
    //pushpin.deletePin('1_999');
    if (!Shape.DeletePolygons())
        return;
    
    //alert(locType + ": " + loc);
    if (locType == 'Address') {
        if (!loc) {
            return;

        }


        map.GotoFirst(loc, 1);
        //self.setTimeout("pushpin.addPin('1_999', veMap.vemapcontrol.GetCenterLatitude(), veMap.vemapcontrol.GetCenterLongitude(), 34, '', '" + loc + "');", 800);
    }
    else {
        bestview = true;
        Search.submit(0);
    }
}
Search.SetupAutoComplete = function() {
    var defaultState = document.getElementById("OrgState").value;
    // MinPrice/MaxPrice autocompletes
    $(":input[name*=Price]").each(function() {
        if (this.value != "" && this.value.indexOf("$") == -1)
            this.value = "$" + Utils.Format.addCommas(this.value);
        $(this).autocomplete("numeric", {
            maxChars: 8,
            formatResult: function(row) { return "$" + Utils.Format.addCommas(row); },
            formatItem: function(row) { return "$" + Utils.Format.addCommas(row); },
            highlight: false,
            selectFirst: false
        })
            .result(function(event, data, formatted) {
                $(this).change();
            });
    });
    // MinSqFt/MaxSqFt autocompletes
    $(":input[name*=SqFt]").each(function() {
        this.value = Utils.Format.addCommas(this.value);
        $(this).autocomplete("numeric", {
            maxChars: 5,
            formatResult: function(row) { return Utils.Format.addCommas(row); },
            formatItem: function(row) { return Utils.Format.addCommas(row); },
            highlight: false,
            selectFirst: false
        })
            .result(function(event, data, formatted) {
                $(this).change();
            });
    });

    $("#City").autocomplete("/Search/AJAX/GetLocations.aspx", {
        dataType: "json",
        extraParams: { type: "City", org_id: companyID },
        minChars: 2,
        max: 50,
        width: "auto",
        cacheLength: 50,
        parse: function(data) {
            var parsed = [];
            for (var i = 0, len = data.length; i < len; i++) {
                var d = data[i];
                parsed[parsed.length] = {
                    data: d,
                    value: d.Name,
                    result: formatLocationItem(d, false)
                };
            }
            return parsed;
        },
        formatItem: function(data) { return "<nobr>" + formatLocationItem(data, false) + "</nobr>"; },
        delay: 100
    })
            .result(function(event, data, formatted) {
                if (!data) {
                    data = { Name: $(this).val(), Type: "City", State: defaultState };
                    $(this).val($(this).val() + ", " + defaultState);
                }
                var city = data.Name;
                if (data.State && data.State.length > 0) {
                    city += "," + data.State;
                }
                Search.GotoCity(city);
            });
    $("#SS_SchoolDistrict").autocomplete("/Search/AJAX/GetLocations.aspx", {
        dataType: "json",
        extraParams: { type: "school district", org_id: companyID },
        minChars: 2,
        max: 50,
        width: "auto",
        cacheLength: 50,
        parse: function(data) {
            var parsed = [];
            for (var i = 0, len = data.length; i < len; i++) {
                var d = data[i];
                parsed[parsed.length] = {
                    data: d,
                    value: d.Name,
                    result: formatLocationItem(d, false)
                };
            }
            return parsed;
        },
        formatItem: function(data) { return "<nobr>" + formatLocationItem(data, false) + "</nobr>"; },
        delay: 100
    })
            .result(function(event, data, formatted) {
                if (!data) {
                    data = { Name: $(this).val(), Type: "School District", City: "", State: defaultState };
                    $(this).val($(this).val() + ", " + defaultState);
                }

                var name = data.Name;
                if (data.City && data.City.length > 0)
                    name += "," + data.City;
                if (data.State && data.State.length > 0)
                    name += "," + data.State;

                Search.GotoLocation(name, data.Type);
            });
    $("#Subdivision").autocomplete("/Search/AJAX/GetLocations.aspx", {
        dataType: "json",
        extraParams: { type: "Subdivision", org_id: companyID },
        minChars: 2,
        max: 50,
        width: "auto",
        cacheLength: 50,
        parse: function(data) {
            var parsed = [];
            for (var i = 0, len = data.length; i < len; i++) {
                var d = data[i];
                parsed[parsed.length] = {
                    data: d,
                    value: d.Name,
                    result: formatLocationItem(d, false)
                };
            }
            return parsed;
        },
        formatItem: function(data) { return "<nobr>" + formatLocationItem(data, false) + "</nobr>"; },
        delay: 100
    })
            .result(function(event, data, formatted) {
                if (!data) {
                    data = { Name: $(this).val(), Type: "Subdivision", City: "", State: defaultState };
                    $(this).val($(this).val() + ", " + defaultState);
                }

                var name = data.Name;
                if (data.City && data.City.length > 0)
                    name += "," + data.City;
                if (data.State && data.State.length > 0)
                    name += "," + data.State;

                Search.GotoLocation(name, data.Type);
            });

    var $el = $("#Location");
    var $hiddenType = $("#LocationType");
    var locationType = "";
    $el.autocomplete("/Search/AJAX/GetLocations.aspx", {
        dataType: "json",
        extraParams: { type: "city,subdivision,high school,school district,middle school,elementary school,neighborhood", org_id: companyID },
        minChars: 2,
        max: 50,
        width: "auto",
        cacheLength: 50,
        matchSubset: false,
        parse: function(data) {
            // Add the json results
            var parsed = [];
            var lastCity = -1;
            for (var i = 0, len = data.length; i < len; i++) {
                var d = data[i];
                if (d.Type.toLowerCase() == "city") {
                    lastCity = i;
                }
                parsed.push({
                    data: d,
                    value: d.Name,
                    result: formatLocationItem(d, 1)
                });
            }
            // Always put an Address location type in the results, if we're supporting addresses,
            // and there's not already a supported embedded type in the textbox
            //            if (locationType == "" || (locationType.indexOf(",") != -1 && locationType.toLowerCase().indexOf("address") != -1)) {
            //                var val = $el.val().trim();
            //                if (val.length > 0) {
            //                    var embeddedType = extractLocationType(val, locationType);
            //                    if (embeddedType.length === 0) {
            //                        var addressData = { Name: val, Type: "Address" };
            //                        parsed.splice(lastCity + 1, 0, { data: addressData, value: addressData.Name, result: formatLocationItem(addressData, 1) });
            //                    }
            //                }
            //            }
            return parsed;
        },
        formatItem: function(data) { return "<nobr>" + formatLocationItem(data, 1) + "</nobr>"; }
    })
            .result(function(event, data, formatted) {
                // If there's no data that means we got here onblur,
                // and we need to add a type for disambiguation

                //if (data == undefined)
                //   return;
                var embeddedZip = "";
                if (!data) {
                    var val = $el.val().trim();
                    if (val.length > 0) {
                        // Get a type embedded in the location
                        var type = extractLocationType(val, locationType);
                        // If no embedded type, use a default type
                        if (type.length == 0) {
                            // If no accepted location types configured, try to figure out a type
                            var regexZip = /^\d{5}$/;
                            var valWords = val.replace(",", " ").trim().replace(/\s+/g, " ").split(" ");
                            if (valWords.length == 1) {
                                if (regexZip.test(val)) {
                                    type = "Zip Code";
                                } else {
                                    type = "Address";
                                }
                            } else {
                                // The last word is a zip
                                var lastWord = valWords[valWords.length - 1];
                                if (regexZip.test(lastWord)) {
                                    // If there's no comma before the zip, add one, to make it easier for the address parser
                                    if (val.indexOf(",") == -1) {
                                        valWords.splice(valWords.length - 1, 0, ",");
                                        val = valWords.join(" ").replace(" , ", ", ");
                                    }
                                    type = "Address";
                                    embeddedZip = lastWord;
                                } //else if (lastWord.length == 2 && $.inArray(lastWord.toUpperCase(), Utils.Lookups.stateCodes) != -1) { // The last word is a state?
                                // If there's no comma before the state, add one, to make it easier for the address parser
                                //                                    if (val.indexOf(",") == -1) {
                                //                                        valWords.splice(valWords.length - 1, 0, ",");
                                //                                        val = valWords.join(" ").replace(" , ", ", ");
                                //                                    }
                                //                                    // If there's only one comma, assume it's a city
                                //                                    if (val.split(",").length == 2) {
                                //                                        type = "City";
                                //                                    } else {
                                //                                        type = "Address";
                                //                                    }
                                //} 
                                else {
                                    type = "Address";
                                }
                            }
                            // Make sure our new default is in the list of acceptable types
                            if (locationType && locationType != "") {
                                var acceptable = false;
                                var locationTypes = locationType.split(",");
                                for (var i = 0; i < locationTypes.length; i++) {
                                    if (type.toLowerCase() == locationTypes[i].toLowerCase()) {
                                        acceptable = true;
                                        break;
                                    }
                                }
                                if (!acceptable) {
                                    type = locationType.split(",")[0];
                                }
                            }
                            // If more than one type is acceptable, embed it in the location
                            if (locationType == "" || locationType.indexOf(",") != -1) {
                                $el.val(val + " (" + type + ")");
                            }
                        }
                        data = { Name: val, Type: type };
                    }
                }
                if (data.Type == "Address" && data.Name.length < 8) { // HACK to prevent double zooming
                    return;
                }
                if (data && data.Type) {
                    // Set the hidden location type
                    $hiddenType.val(data.Type.toLowerCase());
                    // Set the cursor to before the type
                    var last = $el.val().lastIndexOf("(");
                    if (last != -1 && this.setSelectionRange) {
                        this.setSelectionRange(last - 1, last - 1);
                    }

                    // Take the proper action - the first ones are for showing boundaries, the last one will set the map view to fit
                    var gotoZip = false;
                    if (embeddedZip.length > 0) {
                        gotoZip = true;
                    } else {
                        embeddedZip = data.Name;
                    }
                    if (data.Type.toLowerCase() == "city") {
                        var city = data.Name;
                        if (data.State && data.State.length > 0) {
                            city += "," + data.State;
                        }
                        //$('#City').val(city);
                        Search.GotoCity(city);
                    } else if (gotoZip || data.Type.toLowerCase() == "zip code") {
                        //$('#ZipCode').val(embeddedZip);
                        Search.GotoZip(embeddedZip);
                    } else if (data.Type.toLowerCase() == "neighborhood") {
                        Search.GotoNeighborhood(data.BID);
                    } else if (data.BID && data.BID > 0) {
                        Search.GotoNeighborhood(data.BID);
                    } else {
                        var name = data.Name;
                        if (data.City && data.City.length > 0)
                            name += "," + data.City;
                        if (data.State && data.State.length > 0)
                            name += "," + data.State;

                        Search.GotoLocation(name, data.Type);
                    }
                }
            })
        .keydown(function(event) {
            // Alphanumeric
            if (event.keyCode > 47 && event.keyCode < 91) {
                // Clear the type when new stuff is entered
                $hiddenType.val("");
                var val = $el.val();
                if (val && val.length > 0) {
                    var lastIndex = val.lastIndexOf("(");
                    if (lastIndex != -1) {
                        $el.val(val.substring(0, lastIndex).trim());
                    }
                }
            }
        })
        .focus(function() {
            // Clear the type when new stuff is entered
            $hiddenType.val("");
            var val = $el.val();
            if (val && val.length > 0) {
                var lastIndex = val.lastIndexOf("(");
                if (lastIndex != -1) {
                    $el.val(val.substring(0, lastIndex).trim());
                }
            }
            this.select();
        })
    //.blur(function(){alert("blur")})
        .change(function() {

            var val = $el.val();
            if (val.length <= 0) {
                $hiddenType.val("");
                Shape.DeletePolygons();
                Search.submit();
                return;
            }

            $el.search();
        });

}

        function formatLocationItem(data, includeType) {
            var item = "";
            if (data) {
                item = data.Name;
                if (data.City && data.City.length > 0) {
                    item += ", " + data.City;
                }
                if (data.State && data.State.length > 0) {
                    item += ", " + data.State;
                }
                if (includeType) {
                    item += " (" + data.Type + ")";
                }
            }

            return item;
        }

        function extractLocationType(location, acceptedLocationTypes) {
            var matches = location.match(/\((.*?)\)/);
            var match = "";
            // If we got matches, take the last one.
            // This accounts for locations like Los Angeles (County) (School District)
            if (matches && matches.length > 0) {
                match = matches[matches.length - 1];
            }
            if (!acceptedLocationTypes || acceptedLocationTypes.length === 0 || acceptedLocationTypes.toLowerCase().indexOf(match.toLowerCase()) != -1) {
                return match;
            } else {
                return "";
            }
        }
        function toggleSlide(id) {
            var $div = $("#" + id);
            if ($div.is(":visible")) {
                $div.hide("slow");
                $("span.arrow", this).removeClass("arrow-down").addClass("arrow-left");
            } else {
                $div.show("slow");
                $("span.arrow", this).removeClass("arrow-left").addClass("arrow-down");
            }
        }