/// <reference path="WebServices/ListingSearchManagerService" />

// ########## AJAX Functions ##########
// ####################################
function InitHttpRequest()
{
    var request = null;   
    if (window.XMLHttpRequest)
    {
        request = new XMLHttpRequest();
        if (request.overrideMimeType) 
        {
            request.overrideMimeType("text/xml");
        }
    } 
    else if (window.ActiveXObject)
    {
        try
        {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (e)
        {
            try
            {
	            request = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (e)
            {}
        }
    } 
    return request;
}


// Approximation along one axis.
function epsilonClose(x,y) { // x and y coordinates are BOTH latitudes or BOTH longitudes.
    var dec = 6; // epsilon == 10 ** -6
    return Math.round(x * Math.pow(10, dec)) == Math.round(y * Math.pow(10, dec));
}

function setMapView() {
    var mapView = _map.GetMapView();
//        if (  
//          Math.abs(mapView.BottomRightLatLong.Latitude - _search.LatitudeMin) > 0.01
//               || Math.abs(mapView.TopLeftLatLong.Latitude - _search.LatitudeMax) > 0.01
//               || Math.abs(mapView.TopLeftLatLong.Longitude - _search.LongitudeMin) > 0.01
//               || Math.abs(mapView.BottomRightLatLong.Longitude - _search.LongitudeMax) > 0.01
//               ) {
        _search.SavedSearchCriteriaChanged = true;

        _search.LatitudeMin = mapView.BottomRightLatLong.Latitude;
        _search.LatitudeMax = mapView.TopLeftLatLong.Latitude;
        _search.LongitudeMin = mapView.TopLeftLatLong.Longitude;
        _search.LongitudeMax = mapView.BottomRightLatLong.Longitude;
    //}
     //document.getElementById('divResult').innerHTML += '|setMapView|' + '<br>' + _search.LatitudeMin + '|' + _search.LatitudeMax + '|' + _search.LongitudeMin + '|' + _search.LongitudeMax;
            
}

function setSearchParams(queryString) {
    //Iterate through all properties on _search object
	//Check for isNullOrEmpty, and add to querystring
    for(var i in _search){
        if(typeof(_search[i])!='function') {
            if (!(IsNullOrEmpty(_search[i])) && i != "SearchID") {
                queryString += i + '=' + _search[i] + '&';
            }
        }
   }
   return queryString;
}

function setSearchParamsPacket(pkt) {
    //Iterate through all properties on _search object
	//Check for isNullOrEmpty, and add to querystring
    for (var i in _search) {
        if (typeof (_search[i]) != 'function') {
            if (!(IsNullOrEmpty(_search[i])) && i != "SearchID") {
                {
                    pkt[i] = _search[i];                 
                }
            }
        }
   }
   return pkt;
}
function setSortAndPaging(queryString) {
    if(queryString.substring(queryString.length-1)!="&") {
        queryString +="&";
    }
    queryString +="Mode="+$("searchMode").value+"&Page="+_paging.pageNumber+"&";
    var arr = $('selSortList').value.split("|");
    var sortBy = arr[0];
    var sortDir = arr[1];
    if(sortBy!="" && sortDir!="") {
        queryString +="SortBy="+sortBy+"%20"+sortDir+"&";
    }
    return queryString;
}

function setSortAndPagingPacket( pkt) {
    var arr = $('selSortList').value.split("|");
    var sortBy = arr[0];
    var sortDir = arr[1];
    if (sortBy != "" && sortDir != "") {
        pkt.SortBy = sortBy + "%20" + sortDir;
    }
    pkt.Mode = $("searchMode").value 
    pkt.Page = _paging.pageNumber;
    return pkt;
}

function setShapes(queryString) {
    queryString+="PolyCount=" + _shapeSelectedShapes.length;
    // Check to see if there are any selected shapes
	    if (_shapeSelectedShapes.length > 0) {
	        _search.SavedSearchCriteriaChanged = true; // TODO: won't work when polygons are saved as part of a _search.
	        // Loop through all selected shapes
	        for(var shapeCounter = 0 ; shapeCounter < _shapeSelectedShapes.length; shapeCounter++)
	        {
	            var vertices = "";
	            var shape = _shapeSelectedShapes[shapeCounter]; // VEShape object
	            var polygonVertices = shape.GetPoints() // array of VELatLong objects
	            
	            // Loop through array of VELatLong objects
	            for(var verticeCounter = 1 ; verticeCounter < polygonVertices.length; verticeCounter++)
	            {
	                // Get VELatLong object from array
	                var vertice = polygonVertices[verticeCounter];
	                vertices += vertice.Latitude + " " + vertice.Longitude + ",";
	            }

	            // Add polygon to query string
	            queryString += "&Poly" + shapeCounter + "=" + vertices;
	        }
	    }
	    return queryString;
	}
	 
	function setShapesPacket( pkt) {
	    pkt.PolyCount = _shapeSelectedShapes.length;
	    pkt.Poly = null;
        var polygonStr =""
        // Check to see if there are any selected shapes
	     if (_shapeSelectedShapes.length > 0)
	        {   
	            // Loop through all selected shapes
	            for(var shapeCounter = 0 ; shapeCounter < _shapeSelectedShapes.length; shapeCounter++)
	            {
	                var vertices = "";
	                var shape = _shapeSelectedShapes[shapeCounter]; // VEShape object
	                var polygonVertices = shape.GetPoints() // array of VELatLong objects
    	            
	                // Loop through array of VELatLong objects
	                for(var verticeCounter = 1 ; verticeCounter < polygonVertices.length; verticeCounter++)
	                {
	                    // Get VELatLong object from array
	                    var vertice = polygonVertices[verticeCounter];
	                    vertices += vertice.Latitude + " " + vertice.Longitude + ",";
	                }
	                // Add polygon 
	                polygonStr += "&"+ vertices
	            }
	            pkt.Poly = polygonStr.split("&"); 
	        }	   
	    return pkt;
	}

function saveSearchWebService(actionType, searchName, searchId) {
    //$('divSaveBtn').innerHTML = "<img src=\"../App_Themes/Default/Images/Map/Working.gif\">";

    if(_search.ListingTypeId == null) {
        _search.SetListingTypeId(8);
    }
    var quickAlert = $("chkQuickAlert").checked?1:0;
    var boundingBox = $("chkMapBoundingBox").checked?1:0;
    var mlsID = $("MLSID").value;

    // Override properties of the search object
    _search.SearchName = searchName;

    var pkt = new HBM2.Business.FMListing.Entities.ListingManagerSearchPacket.ListingManagerSearchPacket();
    pkt.ActionType = actionType;
    pkt.QuickAlert = quickAlert;
    pkt.BoundingBox = boundingBox;       
    var service = new HBM2.BuyerPortal.WebServices.ListingSearchManagerService();   
    if (searchId != 0) { 
        pkt.SearchID = searchId; }

    var advancedQueryString = _advancedSearch.GetAdvancedSearchSelections();
    if(!IsNullOrEmpty(advancedQueryString)) {
        var advancedSelections = advancedQueryString.split("&");
        for (var i = 0; i < advancedSelections.length; i++) {
        var pair = advancedSelections.split("=");
        pkt.Form[pair[0]] = pair[1];        
        } // for
    } // if
    
    
    pkt = setSortAndPagingPacket(pkt);
	pkt = setSearchParamsPacket(pkt);
    pkt = setShapesPacket(pkt);
    document.getElementById('divResult').innerHTML = "/WebServices/ListingSearchManagerService";
    var userContext = searchName + "|" + actionType;
    service.ListingSearchManager(pkt, DisplayWebServiceOnSuccess, WebServiceOnFailure, userContext );
}

function saveSearchHttpHandler(actionType,searchName,searchId, doReload) {
    //$('divSaveBtn').innerHTML = "<img src=\"../App_Themes/Default/Images/Map/Working.gif\">";
    var postingPageUrl = "../WebServices/ListingSearchManager.ashx";

    var request = InitHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                SavedSearchReturn(request.responseText, searchName, actionType);
                if (doReload == true) {
                    if (window.ReloadDefaultSearch != undefined) {
                        ReloadDefaultSearch();
                    }
                }
            }
            else {
                DisplayError(request.responseText);
            }
        }
    } 
    if(_search.ListingTypeId == null) {
        _search.SetListingTypeId(8);
    }
    var quickAlert = $("chkQuickAlert").checked?1:0;
    var boundingBox = $("chkMapBoundingBox").checked?1:0;
    var mlsID = $("MLSID").value;

    // Override properties of the search object (which will end up in the query string)
    _search.SearchName = searchName;

    var queryString = "ActionType="+actionType+"&QuickAlert="+quickAlert+"&UseBoundingBox="+boundingBox;

    if (searchId != 0) {
        queryString += "&SearchID=" + searchId;
    }
   
    queryString += "&" + _advancedSearch.GetAdvancedSearchSelections();
    request.open("POST", postingPageUrl, true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    setMapView();
    queryString = setSortAndPaging(queryString);
	queryString = setSearchParams(queryString);
    queryString = setShapes(queryString);
    document.getElementById('divResult').innerHTML ="/WebServices/ListingSearchManager.ashx?"+queryString;
	request.send(queryString);
}

function SaveSearchAfterRegistration() {
    _userHasAcceptedTermsOfService = true;
    _action = "DoNotDisplay";
    if (_search.SearchID == undefined || _search.SearchID == 0 ) {
        saveSearchHttpHandler("create", escape("My First Search"), 0, true);
    }    
}

function newSavedSearchWebService() {
    saveSearchWebService("create", escape($(_txtNewSavedSearch).value), 0);
}

function newSavedSearchHttpHandler() {
    saveSearch("create", escape($(_txtNewSavedSearch).value), 0);
}



function updateExistingSavedSearchWebService() {
    var searchName = escape($("txtSearch_Save").value);
    var searchId = _search.SearchID;
    var actionType = "update";

    if ($("txtSearch_SaveAs").value != "") {
        searchName = escape($("txtSearch_SaveAs").value);
        searchId = 0;
        actionType = "create";
    }
    saveSearchWebService(actionType, searchName, searchId);
}

function updateExistingSavedSearchHttpHandler() {
    var searchName = escape($("txtSearch_Save").value);
    var searchId = _search.SearchID;
    var actionType = "update";

    if ($("txtSearch_SaveAs").value != "") {
        searchName = escape($("txtSearch_SaveAs").value);
        searchId = 0;
        actionType = "create";
    }
    saveSearch(actionType, searchName, searchId);
}

function DisplayWebServiceOnSuccess(result, userContext) {
    var searchName = "";
    var actionType = ""
    if (!IsNullOrEmpty(userContext)) {
        var pair = userContext.split('|');
        searchName = pair[0];
        actionType = pair[1];
    }
    SavedSearchReturn(result, searchName, actionType); 
}

function WebServiceOnFailure(error) {
    //alert("Error: returned status code " + error._message);
    DisplayError(error._message);
}


function SavedSearchReturn(result, searchName, actionType) {
	var items = result.split(":"); 	  
	var status = items[0];
	var msg = items[1]; // SUCCESS:Search Id - FAILED:Error Msg

	if(status=="SUCCESS") {   
	    var html = items[2].replace(/@/g, ":"); // Search Manager for top menu, replace special character placeholder with colon
	    $('divSavedSearches').innerHTML = html;

        if (actionType == 'update' || actionType == 'create')
        {
            SubmitRegistrationAction_ExecuteOtherRequests_Success();
        }
        // REUSE the current _search object rather than load and execute the newly created _search.
        _search.SearchName = searchName;
        _search.SearchID = msg;
        _search.SavedSearchCriteriaChanged = false;
        displayListHeader(_search.Criteria, _search.SearchName); // Saved Search Results ( <searchName> )
	}
	else {
	   alert("Error saving search.");
    }
    
    if ($('newSavedSearch') != null) {
        $('newSavedSearch').value = "";
    }
}

function newSavedSearch() { // forward the call    
    // newSavedSearchWebService(); 
    newSavedSearchHttpHandler();
}

function updateExistingSavedSearch() {
    //updateExistingSavedSearchWebService()
    updateExistingSavedSearchHttpHandler();
}

function saveSearch(actionType, searchName, searchId) {
   //saveSearchWebService(actionType, searchName, searchId);
   saveSearchHttpHandler(actionType, searchName, searchId, false);
}

//function LoadSavedSearches(buyerID, mlsID) {
//  //LoadSavedSearchesWebService(buyerID, mlsID);
//  LoadSavedSearches(buyerID, mlsID);
//}

function GetListings(shouldRepositionMap, UseBoundingBox) {
    GetListingsHttpHandler(shouldRepositionMap, UseBoundingBox);
    //GetListingsWebService(shouldRepositionMap);
}
	
function EnableQuickAlert(buyerID, searchID, mlsID) {
    EnableQuickAlertWebService(buyerID, searchID, mlsID);
    //EnableQuickAlertHTTPHandler(buyerID, searchID, mlsID);  
}

function DeleteSavedSearch(buyerID, searchID, searchName, mlsID) {
   // DeleteSavedSearchWebService(buyerID, searchID, searchName, mlsID);
     DeleteSavedSearchHTTPHandler(buyerID, searchID, searchName, mlsID);
}

function EnableQuickAlertWebService(buyerID, searchID, mlsID) {
    var quickAlertEnabled = $("lnkEnableQuickAlert" + searchID).innerHTML;
    if (quickAlertEnabled == "Y") 
      { return; }
    var service = new HBM2.BuyerPortal.WebServices.ListingSearchManagerService();
    service.EnableQuickAlertWithHTMLResult(buyerID, searchID, mlsID, DisplayWebServiceOnSuccess, WebServiceOnFailure);
}

function EnableQuickAlertHTTPHandler(buyerID, searchID, mlsID) {
    var quickAlertEnabled = $("lnkEnableQuickAlert" + searchID).innerHTML;
    if (quickAlertEnabled == "Y") {
        return;
    }
    var postingPageUrl = "../WebServices/ListingSearchManager.ashx";
    var request = InitHttpRequest();
    request.onreadystatechange = function()
    {         
        if (request.readyState == 4) {
	        if (request.status == 200) {
		        SavedSearchReturn(request.responseText, "");
            }	
	        else {
	            DisplayError(request.responseText);
	        }	
        }
    }    
    var queryString = "ActionType=EnableQuickAlert&BuyerID="+buyerID+"&SearchID="+searchID+"&MLSID="+mlsID;
    request.open("POST", postingPageUrl, true); 
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    $("divResult").innerHTML = "/WebServices/ListingSearchManager.ashx?"+queryString;
	request.send(queryString);
}

    function DeleteSavedSearchWebService(buyerID, searchID, searchName, mlsID) {
        var deleteConfirmed = confirm("Do you really want to delete your Saved Search named \"" + searchName + "\"?");
        if (!deleteConfirmed) return;
	    var service = new HBM2.BuyerPortal.WebServices.ListingSearchManagerService();
	    service.DeleteListingSearchWithHtmlResult(buyerID, searchID, mlsID, DisplayWebServiceOnSuccess, WebServiceOnFailure);
	}

	function DeleteSavedSearchHTTPHandler(buyerID, searchID, searchName, mlsID) {
    var deleteConfirmed = confirm("Do you really want to delete your Saved Search named \"" + searchName + "\"?");
    if (!deleteConfirmed) return;

    var postingPageUrl = "../WebServices/ListingSearchManager.ashx";
    var request = InitHttpRequest();
    request.onreadystatechange = function()
    {         
        if (request.readyState == 4) {
	        if (request.status == 200) {
		        SavedSearchReturn(request.responseText, "");
            }	
	        else { 
	            DisplayError(request.responseText); 
	        }	
        } 
    } 
    var queryString = "ActionType=Delete&BuyerID="+buyerID+"&SearchID="+searchID+"&MLSID="+mlsID;
    request.open("POST", postingPageUrl, true); 
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    document.getElementById('divResult').innerHTML ="/WebServices/ListingSearchManager.ashx?"+queryString;
	request.send(queryString);
}


function LoadSavedSearchesWebService(buyerID, mlsID) {   
    var service = new HBM2.BuyerPortal.WebServices.ListingSearchManagerService();
    service.FetchBuyerSearchesWithHTMLResult(buyerID, mlsID, DisplayWebServiceOnSuccess, WebServiceOnFailure);
}

function LoadSavedSearches(buyerID, mlsID) {
    var postingPageUrl = "../WebServices/ListingSearchManager.ashx";
    var request = InitHttpRequest();
    request.onreadystatechange = function()
    {         
        if (request.readyState == 4) {
	        if (request.status == 200) {
		        SavedSearchReturn(request.responseText, "", "load");
            }	
	        else { 
	            DisplayError(request.responseText);
	        }	
        } 
    } 
    var queryString = "ActionType=Load&BuyerID="+buyerID+"&MLSID="+mlsID;
    request.open("POST", postingPageUrl, true); 
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //if(!(IsNullOrEmpty($('divResult')))) {
		$('divResult').innerHTML ="/WebServices/ListingSearchManager.ashx?"+queryString;
	//}
	request.send(queryString);
}

function restoreSaveBtn() {
    $('divSaveBtn').innerHTML = "<a href=\"javascript:saveSearch();\"><img src=\"../App_Themes/Default/Images/button_Save_green.png\" align=\"middle\" border=\"0\" style=\"margin-bottom:2px;\" /></a>";
}

function GetListingsHttpHandler(shouldRepositionMap, UseBoundingBox) {


    if (_search.Criteria == "Address" && _search.ABasicOptionIsSet()) {
        _search.Address = "";
        _search.Criteria = "Basic";
        $("addr_id_search_txt").value = "House and Street #";
    }

    if (shouldRepositionMap == undefined) shouldRepositionMap = false;
    if (UseBoundingBox == undefined) UseBoundingBox = false;
    
    //if(_search.Criteria=="Advanced") {submitAdvancedSearch();return;}
    var queryString=''; 
    hideSearchingImage();
    queryString = _advancedSearch.GetAdvancedSearchSelections();
    
    if(!IsNullOrEmpty(queryString)) {
        if(_search.Criteria=="Basic") {_search.Criteria="Advanced";}
    }
    else if (_search.Criteria=="Advanced") {_search.Criteria="Basic";}
    
    // Check for error in processing Advanced Search Criteria
    var inner = $("divSearching").innerHTML;
    if (inner.length > 0 && ErrorCls.IsErrorMessage(inner)) {
        return;
    }

    var validateMsg = validateValues();
    if(validateMsg=='success') {
            var postingPageUrl= "../WebServices/ListingSearch.ashx";
            displaySearchingImage();
            var request = InitHttpRequest();
            request.onreadystatechange = function() {
                if (request.readyState == 4) {
                    if (request.status == 200) {
                        DisplayListings(request.responseText, shouldRepositionMap, UseBoundingBox);
                        if (
	                        (typeof (_search) !== 'undefined') &&
	                        (_search != null) &&
	                        (_search.Criteria.toLowerCase() === 'bluelabel')
	                    ) {
                            // this needs to be done so we quit short circuiting which
                            // icon gets display on subsequent searches
                            //_search.Criteria = '';
                        }
                    }
                    else { DisplayError(request.responseText); }
                }
            }
             
            request.open("POST", postingPageUrl, true); 
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	        
	        queryString = setSortAndPaging(queryString);
	        queryString = setSearchParams(queryString);
	        queryString += "UseBoundingBox=" + ( (shouldRepositionMap )? "false&": "true&" );
	        queryString += "SearchID=" + _search.SearchID + "&";
	        try {
	            if(
	                (typeof document.getElementById('boolIsSpecialInterest') !== 'undefined') &&
	                (document.getElementById('boolIsSpecialInterest').value !== null) &&
	                !isNaN(parseInt(document.getElementById('boolIsSpecialInterest').value))
	            ) {
	                queryString += "IsSpecialInterest=" + parseInt(document.getElementById('boolIsSpecialInterest').value).toString(10) + "&";
	            }
	        } catch(e) {}
            queryString = setShapes(queryString);   
            document.getElementById('divResult').innerHTML ="/WebServices/ListingSearch.ashx?"+queryString;
	        request.send(queryString);
    }
    else{ShowMessage(validateMsg);}
}

function DisplayError(responseText) {
    hideSearchingImage();
        alert(responseText);
}

function restoreSaveBtn() {
    $('divSaveBtn').innerHTML = "<a href=\"javascript:saveSearch();\"><img src=\"../App_Themes/Default/Images/button_Save_green.png\" align=\"middle\" border=\"0\" style=\"margin-bottom:2px;\" /></a>";
}

function GetListingsWebService(shouldRepositionMap) {
    //if(_search.Criteria=="Advanced") {submitAdvancedSearch();return;}
    hideSearchingImage();

    var pkt = new HBM2.Business.FMListing.Entities.ListingManagerSearchPacket.ListingManagerSearchPacket();
    var service = new HBM2.BuyerPortal.WebServices.ListingSearchManagerService();
    var advancedQueryString = _advancedSearch.GetAdvancedSearchSelections();
    if (!IsNullOrEmpty(advancedQueryString)) 
    {
        var advancedSelections = advancedQueryString.split("&");
        for (var i = 0; i < advancedSelections.length; i++) {
            var pair = advancedSelections.split("=");
            pkt.Form[pair[0]] = pair[1];
        } // for
        if (_search.Criteria != "Saved") 
            { _search.Criteria = "Advanced"; }
    }
    else if (_search.Criteria == "Advanced") { _search.Criteria = "Basic"; }
    // Check for error in processing Advanced Search Criteria
    if (   ErrorCls.IsErrorMessage($("divSearching").innerHTML)) {
        return;
    }

    var validateMsg = validateValues();
    if (validateMsg == 'success') {       
        displaySearchingImage();
        
        /*request.onreadystatechange = function() {
            if (request.readyState == 4) {
                if (request.status == 200) { DisplayListings(request.responseText, shouldRepositionMap); }
                else { alert("Error: returned status code " + request.status + " " + request.statusText); }
            }
        }
        */

        setMapView();
        pkt = setSortAndPagingPacket(pkt);
        pkt = setSearchParamsPacket(pkt);
        pkt = setShapesPacket(pkt);
        pkt.SearchID=_search.SearchID;
        document.getElementById('divResult').innerHTML = "/WebServices/ListingSearchManagerService.ListingService";
        var userContext = shouldRepositionMap;
        service.FetchListings(pkt, DisplayListingsWebServiceOnSuccess, WebServiceOnFailure, userContext);
    }
    else { ShowMessage(validateMsg); }
}


function DisplayListingsWebServiceOnSuccess(result, userContext) {
    // Convert List<BizListing> to text or make DisplayListingsFromList operate on the list.
    DisplayListingsFromList(request.responseText, userContext); ;
}

//function GetListingsAdvanced(qString) {
//    _search.Criteria="Advanced";
//    var postingPageUrl= "../WebServices/ListingSearch.ashx";
//    displaySearchingImage();
//    var request = InitHttpRequest();
//    request.onreadystatechange = function()
//    {         
//	    if (request.readyState == 4) {
//		    if (request.status == 200) {DisplayListings(request.responseText); }	
//		    else  { alert("Error: returned status code " + request.status + " " + request.statusText);  }	
//	    } 
//    }
//    var queryString = qString; 
//    request.open("POST", postingPageUrl, true); 
//    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//	setMapView();
//	queryString = setSortAndPaging(queryString);
//	queryString = setSearchParams(queryString);
//    queryString = setShapes(queryString);   
//    document.getElementById('divResult').innerHTML ="/WebServices/ListingSearch.ashx?"+queryString;
//	request.send(queryString);
//}

//##### This function used only when user wants to view all REOs, disregarding their search criteria ########
//##### So we have to include EntityID, MarketID and Lat/Longs, but ignore all other criteria ###############
function GetListingsREO_All() {   
    var postingPageUrl= "../WebServices/ListingSearch.ashx";
    displaySearchingImage();
    var request = InitHttpRequest();
    request.onreadystatechange = function()
    {         
	    if (request.readyState == 4) {
		    if (request.status == 200) {DisplayListings(request.responseText); }	
		    else  { DisplayError( request.responseText )  }	
	    } 
    }

	setMapView();

    var queryString = "Criteria=REO";
    queryString += "&EntityID="+_search.EntityID; 
    queryString += "&MarketAreaId="+_search.MarketAreaId;
    queryString += "&LatitudeMin="+_search.LatitudeMin;
    queryString += "&LatitudeMax="+_search.LatitudeMax;
    queryString += "&LongitudeMin="+_search.LongitudeMin;
    queryString += "&LongitudeMax="+_search.LongitudeMax;
    queryString = setSortAndPaging(queryString);
    queryString = setShapes(queryString);   

    document.getElementById('divResult').innerHTML =queryString;

    request.open("POST", postingPageUrl, true); 
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.send(queryString);
}


function GetSchools()  {
    // Check for birds eye view
    if (_map.GetMapStyle() == VEMapStyle.Birdseye) {
        ShowListingSearchWarning('Searching is not available in Birds Eye view');
        return;
    }
	
    var mapView = _map.GetMapView();
   
    // Check for null coordinates.
    if (null == mapView.BottomRightLatLong.Latitude
         || null == mapView.TopLeftLatLong.Longitude
         || null == mapView.TopLeftLatLong.Latitude
         || null == mapView.BottomRightLatLong.Longitude) {
        ShowListingSearchWarning('Search will fail: MapView bounding box has 1 or more null coordinates.');
        return;
    }

    if ((hjSchoolsWebService !== undefined) && (hjSchoolsWebService !== null)) {
        var viewCenter = {
            Latitude:((mapView.TopLeftLatLong.Latitude + mapView.BottomRightLatLong.Latitude)/2),
            Longitude:((mapView.TopLeftLatLong.Longitude + mapView.BottomRightLatLong.Longitude)/2)
        };

        var searchRadius = CalculateDistance(viewCenter, { 'Latitude': ((mapView.TopLeftLatLong.Latitude + mapView.BottomRightLatLong.Latitude) / 2), 'Longitude': mapView.BottomRightLatLong.Longitude });
        if (isNaN(parseInt(searchRadius, 10))) { searchRadius = 15; }
        if (searchRadius > 15) { searchRadius = 15; }
        
        displaySearchingImage();
        jq.getJSON(
	        hjSchoolsWebService,
	        {
	            'geoType': 'location',
	            'geoName': viewCenter.Latitude + ',' + viewCenter.Longitude,
	            'radius': searchRadius + 'mi',
	            'sortBy': 'schoolName',
	            'sortDir': 'asc',
	            'rpp': '50',
	            'page': '1'
	        },
	        function(jsonData) {
	            DisplaySchools(jsonData);
	        }
        );
	} else {
	    ShowListingSearchWarning('Oops! We did something wrong.  We are working to fix it.');
    }
}

function GetSchoolDetails(id, callback) {
    jq.getJSON(
	        hjSchoolDetailWebService,
	        {'id': id},
	        function(jsonData) {
	            DisplaySchools(jsonData);
	        }
        );
}

function GetSchoolDetailsS(id) {
    var retVal = null;
    jq.ajax({
        url: hjSchoolDetailWebService,
        dataType: 'json',
        data: { 'id': id },
        success: function(jsonData) { retVal = jsonData; },
        async: false
    });
}

function GetSolds() {
    displaySearchingImage();

    var mapView = _map.GetMapView(), boundingBox = '', minPrice, maxPrice, webServiceParms;

    // Per home junctions documentation
    // "No bounding box can exceed 0.105063 degrees latitude or 0.109863 degrees longitude  (EPSG:4326 / WGS84)."
    //
    // However Home Junction doesn't enforce this, and really their bounding box limitiation is too small.
    // so we'll just try to keep things sane by limiting the latitude and longitude to the values below
    // (about 20.0 miles)
    var castingTooWide = '<span style="color:red;">Search area too wide,<br />&nbsp;Please <a href="javascript:zoomIn(\'GetSolds()\');">zoom in</a></span>&nbsp;<a href="javascript:zoomIn(\'GetSolds()\');"><img src="../App_Themes/Default/Images/Map/circle_plus.png" border="0"></a>'
    if (Math.abs(mapView.TopLeftLatLong.Latitude - mapView.BottomRightLatLong.Latitude) >= 0.289654) {
        hideSearchingImage();
        ShowSoldSearchWarning(castingTooWide);
        return;
    } else {
        if (Math.abs(mapView.BottomRightLatLong.Longitude - mapView.BottomRightLatLong.Longitude) >= 0.409634) {
            hideSearchingImage();
            ShowSoldSearchWarning(castingTooWide);
            return;
        }
    }

    boundingBox =
        mapView.TopLeftLatLong.Longitude + ' ' + mapView.TopLeftLatLong.Latitude + ',' +
        mapView.BottomRightLatLong.Longitude + ' ' + mapView.BottomRightLatLong.Latitude;

    webServiceParms = {
        'geoType': 'bbox',
        'geoName': boundingBox,
        'days': parseInt(jq('select#SoldUpTo').val(), 10),
        'sortBy': (jq('input#sortBy2').is(':checked') ? 'distance' : 'recordingDate'),
        'sortDir': (jq('input#sortBy2').is(':checked') ? 'asc' : 'desc'),
        'rpp': 100,
        'page': 1
    };

    if (
        (jq('select#txtSoldPropType').length > 0) &&
        ('' + jq('select#txtSoldPropType').val() !== '') &&
        (jq('select#txtSoldPropType').val() !== 'RALL')
    ) {
        webServiceParms['propertyTypeCode'] = jq('select#txtSoldPropType').val();
    }

    if ((jq('input#txtSoldPriceMin').length > 0) || (jq('input#txtSoldPriceMax').length > 0)) {
        minPrice = jq('input#txtSoldPriceMin').val();
        maxPrice = jq('input#txtSoldPriceMax').val();

        minPrice = parseInt(minPrice.replace(/[^0-9\.]/g, ''), 10);
        maxPrice = parseInt(maxPrice.replace(/[^0-9\.]/g, ''), 10);

        if ((minPrice >= 0) || (maxPrice >= 0)) {
            if (!isNaN(minPrice)) {
                if ((minPrice > 0) && (minPrice > maxPrice)) {
                    minPrice = 0;
                    // to handle the instance where we've used both input and select
                    // type controls, and where we may/may not have named them the same
                    if (jq('select#selSoldPriceMin').length > 0) {
                        jq('select#selSoldPriceMin').val(0);
                    }
                    jq('input#txtSoldPriceMin').val(0);
                }

                webServiceParms['purchasePriceMin'] = minPrice;
            }

            if (!isNaN(maxPrice) && (maxPrice > 0)) {
                webServiceParms['purchasePriceMax'] = maxPrice;
            }
        }
    }

    var lameWorkAround = '', counter = 0;

    for (key in webServiceParms) {
        if (counter > 0) { lameWorkAround += '&'; }
        ++counter;
        lameWorkAround = lameWorkAround + (key + '=' + escape(webServiceParms[key]));
    }

    jq.ajax({
        url: hjRecentSalesWebService,
        async: 'true',
        cache: 'false',
        processData: 'false', // because the final webservice doesn't use RFC standards for URL encoding
        data: lameWorkAround,
        dataType: 'json',
        success: function(jsonData) { DisplaySolds(jsonData); },
        error: function(XMLHttpRequest, textStatus, error) { throw 've_ajax_calls.js::GetSolds error:\n' + textStatus; }
    });
}


function GetSchoolsForDetailPage() {

    var mapView = _map2.GetMapView();

    // Check for birds eye view
    if (_map2.GetMapStyle() == VEMapStyle.Birdseye) {
        ShowListingSearchWarning('Searching is not available in Birds Eye view');
        return;
    }

    // Check for null coordinates.
    if (null == mapView.BottomRightLatLong.Latitude
         || null == mapView.TopLeftLatLong.Longitude
         || null == mapView.TopLeftLatLong.Latitude
         || null == mapView.BottomRightLatLong.Longitude) {
        ShowListingSearchWarning('Search will fail: Map view bounding box has 1 or more null coordinates.');
        return;
    }

    if ((hjSchoolsWebService !== undefined) && (hjSchoolsWebService !== null)) {
        var viewCenter = {
            Latitude: ((mapView.TopLeftLatLong.Latitude + mapView.BottomRightLatLong.Latitude) / 2),
            Longitude: ((mapView.TopLeftLatLong.Longitude + mapView.BottomRightLatLong.Longitude) / 2)
        };

        var searchRadius = CalculateDistance(viewCenter, { 'Latitude': ((mapView.TopLeftLatLong.Latitude + mapView.BottomRightLatLong.Latitude) / 2), 'Longitude': mapView.BottomRightLatLong.Longitude });
        if (isNaN(parseInt(searchRadius, 10))) { searchRadius = 15; }
        if (searchRadius > 15) { searchRadius = 15; }

        displaySearchingImage();
        jq.getJSON(
	        hjSchoolsWebService,
	        {
	            'geoType': 'location',
	            'geoName': viewCenter.Latitude + ',' + viewCenter.Longitude,
	            'radius': searchRadius + 'mi',
	            'sortBy': 'schoolName',
	            'sortDir': 'asc',
	            'rpp': '50',
	            'page': '1'
	        },
	        function(jsonData) {
	            DisplaySchoolsForDetailPage(jsonData);
	        }
        );
    } else {
        alert('Oops! We did something wrong.  We are working to fix it.');
    }
}

//##### Functions for ajaxed listings hover box #############
function launchHoverBox(id,entityId)
{
    document.getElementById('divListingHoverText').innerHTML = 'loading...';
    // Fire off the loading of the InfoBox Data
    var request = InitHttpRequest();
    request.onreadystatechange = function()
        {         
            if (request.readyState == 4)
            {
                if (request.status == 200) { 
                    InfoBoxDataLoaded(request.responseText); }	
                else { 
                alert("Error: returned status code " + request.status + " " + request.statusText); }	
            } 
        }
        // Open http request and set header
        var postingPageUrl = "../WebServices/ListingHoverBox.ashx";
        var photoSource = document.getElementById('divPhotoSource').value;
        request.open("POST", postingPageUrl, true); 
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	request.send("ListingID="+id+"&MLSID="+MLSID+"&MetroAreaID="+MetroAreaID+"&EntityID="+entityId+"&photoSrc="+escape(photoSource));  //MetroAreaID coming from var at top of mapsearch.aspx
}
function InfoBoxDataLoaded(result)
{
    document.getElementById('divListingHoverText').innerHTML = result;
}
function InfoBoxDataLoadError(error)
{
    alert("Error Occurred Loading InfoBox Data\n" + error.get_message());
}


//###################################################################################################################
function loadSavedSearch() {
    var postingPageUrl = "../WebServices/ListingSearchManager.ashx";
    var request = InitHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                loadSavedSearchReturn(request.responseText);

                clearShapeLayers();
                var UseBoundingBox = false;
                var shouldRepositionMap = false;
                if (_search.LatitudeMin != undefined && _search.LatitudeMin.length > 0) {
                    UseBoundingBox = true;
                }
                else {
                    shouldRepositionMap = true;
                }
                GetListings(shouldRepositionMap, UseBoundingBox);
            }
            else {
                DisplayError(request.responseText);
            }
        }
    } 

    var queryString = "ActionType=Fetch&BuyerID="+_search.BuyerId+"&SearchID="+_search.SearchID;
    request.open("POST", postingPageUrl, true); 
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    document.getElementById('divResult').innerHTML ="/WebServices/ListingSearchManager.ashx?"+queryString;
	request.send(queryString);
}

function loadSavedSearchReturn(result) {
	var items = result.split("@^"); 	  
	var status = items[0];
	var msg = items[1]; // SUCCESS:Search Id - FAILED:Error Msg
    var values = items[2].split("@~");
    var advValues = items[3].split("@~");
	    if (status == "SUCCESS") {
	        for (i = 0; i < values.length; i++) { //set _search object basic values
	            var pair = values[i].split(":");
	            if (pair[0] == "LatitudeMin" || pair[0] == "LatitudeMax" || pair[0] == "LongitudeMin" || pair[0] == "LongitudeMax") {
	                _search[pair[0]] = pair[1];
	            }
	            if (typeof (_search[pair[0]]) != "undefined") { // has a name
	                _search[pair[0]] = pair[1];
	            }
	        }
	        
	        // Load advanced search controls
	        var selectBoxCriteriaCount = 0;
	        for (i = 1; i < advValues.length; i++) { //set _advancedSearch values
	           // var pair = advValues[i].split(":");
	            var key = "";
	            var val = "";
	            var pos = advValues[i].indexOf(":");
	            if (pos > 0)
	                key = advValues[i].substring(0, pos);	                
	            if ( advValues[i].length > pos )
	                 val = advValues[i].substring(pos + 1);

	             if (key.indexOf("checkbox_") != -1) { setCheckBox(key, val); }
	             if (key.indexOf("boolean_") != -1) { setBoolean(key, val); }
	             if (key.indexOf("textbox_") != -1 && $(key) != null) { $(key).value = val; }
	            
	            // Check to see if this is a select box criteria
	            if (key.indexOf("select") != -1) {
	                selectBoxCriteriaCount++;
	                setSelectBox(key,val);
	            }
	        }
	        
            // Check to see if there is more than one select box criteria
            if (selectBoxCriteriaCount > 1) {
                alert("Your saved search (created in the Classic site) contains " + selectBoxCriteriaCount + " different neighborhood types.\nHowever, our new system only allows one at a time.\n\nWe apologize for the inconvenience.");
            }
	    }
	    else {
	        alert("Error saving search.");
	    }	
	    _search.ShowSearchCriteria();
	    _advancedSearch.CollectAllValues();
	    // move map   
	    _search.SavedSearchCriteriaChanged = false;

}

function setBoolean(item,state) {
    var div=$("advSearch_"+_search.ListingTypeId); //get the parent div
        var controls = div.getElementsByTagName("input"); 
        for (var i = 0; i < controls.length; i++) { 
            if(controls[i].getAttribute("colType")=="Boolean") {
                if(controls[i].id==item && controls[i].value.toLowerCase()==state.toLowerCase()) {
                    controls[i].checked = true;
                }
            }
        }  
}
function setSelectBox(item,value) {
    var div = $("advSearch_" + _search.ListingTypeId); //get the parent div
    if (div == null || div.getElementsByTagName("select") == null ) return;

    var controls = div.getElementsByTagName("select"); 
    
    for (var i = 0; i < controls.length; i++) { 
            if(controls[i].id=="selNeighborhoodTypes_"+_search.GetListingTypeName(_search.ListingTypeId)) {
                var type=item.split("_");
                var selectbox=controls[i];
                for(b=0;b<selectbox.options.length;b++)
                {
                    if(selectbox.options[b].value==type[1]){selectbox.options[b].selected=true;}
                }
                InitStaticListValues('Neighborhood', _search.MarketAreaId, _search.ListingTypeId, type[1], _search.GetListingTypeName(_search.ListingTypeId));            
            }
     }
     
      for (var i = 0; i < controls.length; i++) { 
            if(controls[i].id=="selSelectedNeighborhoodValues_"+_search.GetListingTypeName(_search.ListingTypeId)) {
                var selectBox=controls[i];
                var items=value.split(";");
                for(x=0;x<items.length;x++) {
                    var values=items[x].split(",");
                    if((values[0]!="")&&(values[1]!="")) {
                        var selectBoxOptionNew = new Option(values[1], values[0]);
                        selectBox.options[selectBox.length] = selectBoxOptionNew;
                    }
                }      
             }
            
            
    }
}

function setCheckBox(name,value) {
    var div=$("advSearch_"+_search.ListingTypeId); //get the parent div
    var controls = div.getElementsByTagName("input");
    var values = value.split(",");
        for (var i = 0; i < controls.length; i++) { 
            if(controls[i].getAttribute("colType")=="Checkbox" && controls[i].getAttribute("name") == name) {
                    for (var j = 0; j < values.length; j++) {
                        if ( unescape(controls[i].value) == values[j]) {
                            controls[i].checked = true;
                            break;
                        }
                    }                
            }
        }  
}

