﻿var propertyMap;
var pageIndex = 1;
var pageSize = 200;
var lastInfoWindowClick = new Date();
var searchResults; 
var SearchType = {Unspecified:0,Lease:1,Investment:2,User:3,Land:4};

function PropertySearchMap() {
    this.map = new GMap2(document.getElementById("googleMap"));
    this.map.setCenter(propMapCenter, 10);
    this.map.addControl(new GLargeMapControl());
    GEvent.bind(this.map, "moveend", this, this.onMoveEnd);
    
    this.houseIcon = new GIcon();
    this.houseIcon.iconSize = new GSize(28, 28);
    this.houseIcon.iconAnchor = new GPoint(12, 25);
    this.houseIcon.infoWindowAnchor = new GPoint(12,2); 
    this.noResultsMessage = new HtmlControl('<div class="gmap-msg"><div class="gmap-msg-gutter"><p class="gmap-msg-noresults"><a href="javascript:propertyMap.hideNoResultsMessage();"><img src="' + ImagePath + '/close.gif" width="28" height="15" alt="Close window" border="0" align="right" style="margin: 0 5px 0 0" /></a>No matching properties found.  Please adjust the map and/or search options above and try again.</p></div></div>');
    this.searchingMessage = new HtmlControl('<div class="gmap-msg"><div class="gmap-msg-gutter"><img src="' + ImagePath + '/ajax-loader.gif"  width="50" height="50" alt="Please wait..." /><p class="gmap-msg-searching">Searching properties...</p></div></div>');
    this.searchSaveSuccessMessage = new HtmlControl('<div class="gmap-msg"><div class="gmap-msg-gutter"><div style="text-align: right; padding: 0 5px 0 0"><a href="javascript:propertyMap.hideSaveSuccessMessage();"><img src="' + ImagePath + '/close.gif" width="28" height="15" alt="Close window" border="0"/></a></div><p class="gmap-msg-noresults" style="clear: right; text-align: center; margin-top: 10px;">Your search has been successfully saved.</p></div></div>');
    this.searchSaveFailMessage = new HtmlControl('<div class="gmap-msg"><div class="gmap-msg-gutter"><div style="text-align: right; padding: 0 5px 0 0"><a href="javascript:propertyMap.hideSaveFailMessage();"><img src="' + ImagePath + '/close.gif" width="28" height="15" alt="Close window" border="0"/></a></div><p class="gmap-msg-noresults" style="clear: right; text-align: center; margin-top: 10px;">Your search could not be saved.</p></div></div>');
    this.refineSearchMessage = new HtmlControl('<div class="gmap-msg"><div class="gmap-msg-gutter"><div style="text-align: right; padding: 0 5px 0 0"><a href="javascript:propertyMap.hideRefineSearchMessage();"><img src="' + ImagePath + '/close.gif" width="28" height="15" alt="Close window" border="0"/></a></div><p class="gmap-msg-noresults" style="clear: right; text-align: center; margin-top: 5px;">Please narrow your search to less than ' + pageSize + ' properties.<br/><span style="font-size: .8em">HINT: Increase the maps zoom level.</span></p></div></div>');
}

PropertySearchMap.prototype.renderPropertySearchResults= function(results) {
    this.map.clearOverlays();
    for (var i = 0; i < results.PropertyInfoList.length; i++) {
        var propertyInfo =  results.PropertyInfoList[i];
        var latlng = new GLatLng(propertyInfo.Latitude, propertyInfo.Longitude);
        this.map.addOverlay(this.createPropertyMarker(latlng, i, propertyInfo));
    }
}

PropertySearchMap.prototype.UpdateBounds = function() {
    var bounds = this.map.getBounds();
    this.southwest = bounds.getSouthWest();
    this.northeast = bounds.getNorthEast();
}

PropertySearchMap.prototype.onMoveEnd = function() {
    this.UpdateBounds();
    var now = new Date();
    var searchDelay = 1500;
    // alert(now.getTime() - lastInfoWindowClick.getTime() + " milliseconds have elapased since last click.");
    if ((now.getTime() - lastInfoWindowClick.getTime()) > searchDelay)
    {
        SeachPropertiesByMap(this.southwest, this.northeast);
    }
}

PropertySearchMap.prototype.createPropertyMarker = function (point, index, propertyInfo) {
    var hitIcon = new GIcon(this.houseIcon);
    hitIcon.image = HitIconImagePath + "/" + (index + 1) + ".png";
    
    markerOptions = { icon:hitIcon };
    var marker = new GMarker(point, markerOptions);
    var infoHtml = this.buildPropertyInfoHtml(index, propertyInfo);
    GEvent.addListener(marker, "click", function() {
        lastInfoWindowClick = new Date();
        marker.openInfoWindowHtml(infoHtml, {maxWidth:275});
    });
    
    return marker;
}

PropertySearchMap.prototype.showNoResultsMessage = function() {
    this.map.addControl(this.noResultsMessage, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(253, 96)));
}

PropertySearchMap.prototype.hideNoResultsMessage = function() {
    this.map.removeControl(this.noResultsMessage);
}

PropertySearchMap.prototype.showSearchingMessage = function() {
    this.map.addControl(this.searchingMessage, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(253, 96)));
}

PropertySearchMap.prototype.hideSearchingMessage = function() {
    this.map.removeControl(this.searchingMessage);
}

PropertySearchMap.prototype.showSaveSuccessMessage = function() {
    this.map.addControl(this.searchSaveSuccessMessage, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(253, 96)));
}

PropertySearchMap.prototype.hideSaveSuccessMessage = function() {
    this.map.removeControl(this.searchSaveSuccessMessage);
}

PropertySearchMap.prototype.showSaveFailMessage = function() {
    this.map.addControl(this.searchSaveFailMessage, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(253, 96)));
}

PropertySearchMap.prototype.hideSaveFailMessage = function() {
    this.map.removeControl(this.searchSaveFailMessage);
}

PropertySearchMap.prototype.showRefineSearchMessage = function() {
    this.map.addControl(this.refineSearchMessage, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(253, 96)));
}

PropertySearchMap.prototype.hideRefineSearchMessage = function() {
    this.map.removeControl(this.refineSearchMessage);
}

PropertySearchMap.prototype.buildPropertyInfoHtml = function (index, propertyInfoList) {
    var html = new Array();
    html.push('<div class="gmap-propertyinfo">');
    if (propertyInfoList.PropertyImage) {
        html.push('<img src="');
        html.push(PropertyResourcesFolder);
        html.push("/TOKproperties/thumbs/");
        html.push(propertyInfoList.PropertyImage);
        html.push('" width="60" height="45" align="absmiddle" alt="');
        html.push(propertyInfoList.PropertyName);
        html.push('" />');        
    }
    html.push('<p>');
    if (propertyInfoList.PropertyFlyer) {
        html.push('<a href="');
        html.push(PropertyResourcesFolder);
	    html.push('/Webflyers/');
        html.push(propertyInfoList.PropertyFlyer);
        html.push('" target="_blank">');
        html.push(propertyInfoList.PropertyName);
        html.push('</a>');
    } else {
        html.push('<span style="font-weight: 700;">');
        html.push(propertyInfoList.PropertyName);
        html.push('</span>');
    }
    
    html.push('<br/>');
    for(var i = 0; i < propertyInfoList.ListingSummary.length; i++) {
        html.push(propertyInfoList.ListingSummary[i]);
        html.push('<br />');
    } 
    html.push('</p></div>');
    return html.join('');
}

function SearchPropertiesBySaved(southwest, northeast, searchType) {
    switch(searchType) {
        case SearchType.Lease:
            searchForLease(southwest, northeast, false);
            break;
        case SearchType.Investment: 
            searchForInvestment(southwest, northeast, false);
            break;
        case SearchType.User:
            searchForUser(southwest, northeast, false);
            break;
        case SearchType.Land: 
            searchForLand(southwest, northeast, false);
            break;
        default:
            searchForLease(southwest, northeast, false);
            break;
    }
}

function SeachPropertiesByMap(southwest, northeast) {
    switch(activeTab) {
        case 0:
            searchForLease(southwest, northeast, false);
            break;
        case 1: 
            searchForInvestment(southwest, northeast, false);
            break;
        case 2: 
            searchForUser(southwest, northeast, false);
            break;
        case 3:
            searchForLand(southwest, northeast, false);
            break;
        default:
            searchForLease(southwest, northeast, false);
            break;
    }
}

function mainExceptionHandler(e)
{
    var txt ="There was an error on this page.\n\n";
    txt+="Error name: " + e.name + "\n";
    txt+="Error description: " + e.description + "\n";
    txt+="Error message: " + e.message + "\n\n"; 
    txt+="Click OK to continue.\n\n";
    alert(txt);
}

function resultMapLoad()
{
    try
    {
      initLightbox();
      if (window.GBrowserIsCompatible && GBrowserIsCompatible()) {
        propertyMap = new PropertySearchMap(); 
        
        if (savedSearchGuid.length > 0)
        {
            SearchPropertiesBySaved(savedSouthwest, savedNortheast, savedSearchType);
        }  
      }    
    }
    catch(ex)
    {
        mainExceptionHandler(ex);
    }
}

function btnSearchLease_Click() {
    try {
        if (IsFormOnly) {
            var hiddenVisitorGuid = $get("hiddenVisitorGuid");
            hiddenVisitorGuid.value = VisitorGUID;
            return searchForLease(null, null, true);
        } else {
            propertyMap.UpdateBounds();
            searchForLease(propertyMap.southwest, propertyMap.northeast, false);
            return false;
        }
    } catch(err) {
        mainExceptionHandler(err);
        return false;
    }
}

function btnSearchInvestment_Click() {
    try {
        if (IsFormOnly) {
            var hiddenVisitorGuid = $get("hiddenVisitorGuid");
            hiddenVisitorGuid.value = VisitorGUID;
            return searchForInvestment(null, null, true);
        } else {
            propertyMap.UpdateBounds();
            searchForInvestment(propertyMap.southwest, propertyMap.northeast, false);
            return false;
        }
    } catch(err) {
        mainExceptionHandler(err);
        return false;
    }
}

function btnSearchUser_Click() {
    try {
        if (IsFormOnly) {
            var hiddenVisitorGuid = $get("hiddenVisitorGuid");
            hiddenVisitorGuid.value = VisitorGUID;
            return searchForUser(null, null, true);
        } else {
            propertyMap.UpdateBounds();
            searchForUser(propertyMap.southwest, propertyMap.northeast, false);
            return false;
        }
    } catch(err) {
        mainExceptionHandler(err);
        return false;
    }
}

function btnSearchLand_Click() {
    try {
        if (IsFormOnly) {
            var hiddenVisitorGuid = $get("hiddenVisitorGuid");
            hiddenVisitorGuid.value = VisitorGUID;
            return searchForLand(null, null, true);
        } else {
            propertyMap.UpdateBounds();
            searchForLand(propertyMap.southwest, propertyMap.northeast, false);
            return false;
        }
    } catch(err) {
        mainExceptionHandler(err);
        return false;
    }    
}

function MySavedItems_Click() {
    try {
        var savedItemsUrl = mySavedItemsUrl + "?returnpsid=" + searchResults.SearchGUID;
        //alert(savedItemsUrl);
        window.location = savedItemsUrl;
    } catch(err) {
        mainExceptionHandler(err);
        return false;
    }    
}

function showRangeInvalidMsg(validResult, msgElement, fieldName) {
    switch(validResult) {
        case RangeValidateType.LowMissing:
            msgElement.innerHTML = "Please enter a number for the " + fieldName + " starting value.";
            break;
        case RangeValidateType.HighMissing:
            msgElement.innerHTML = "Please enter a number for the " + fieldName + " end value.";
            break;
        case RangeValidateType.LowLessThanHigh:
            msgElement.innerHTML = "Please enter a starting value that is lower than the ending value.";
            break;
        default:
            msgElement.innerHTML = "Invalid entry.  Please correct your search criteria.";
            break;
    }  
}

function SetInputDefault(controlID, defaultValue) {
    if ($(controlID).val() == "") {
        $(controlID).val(defaultValue);
    }
}

function searchForInvestment(southwest, northeast, validateOnly) {
    SetInputDefault("#txtInvestPriceStart", "0");
    SetInputDefault("#txtInvestPriceEnd", "100,000,000");
    SetInputDefault("#txtInvestSqFtStart", "0");
    SetInputDefault("#txtInvestSqFtEnd", "1,000,000");

    var inputInvestIndustrial = $get("chkInvestIndustrial");
    var inputInvestOffice = $get("chkInvestOffice");
    var inputInvestRetail = $get("chkInvestRetail");
    var inputInvestMultiFamily = $get("chkInvestMultiFamily");
    
    var inputInvestPriceStart = $get("txtInvestPriceStart");
    var inputInvestPriceEnd = $get("txtInvestPriceEnd");
    
    var inputInvestSqFtStart = $get("txtInvestSqFtStart");
    var inputInvestSqFtEnd = $get("txtInvestSqFtEnd");
    
    var InvestSizeErrMsg = $get("InvestSizeErrMsg");
    var InvestPriceErrMsg = $get("InvestPriceErrMsg");
    
    var inputInvestKeywords = $get("txtInvestKeywords");
    var isValid = true;
    
    sizeValidationResult = validateRange(inputInvestSqFtStart, inputInvestSqFtEnd);
    priceValidationResult = validateRange(inputInvestPriceStart, inputInvestPriceEnd);
    
    if (sizeValidationResult != RangeValidateType.Valid) {
        isValid = false;
        InvestSizeErrMsg.style.display = "block";
        showRangeInvalidMsg(sizeValidationResult, InvestSizeErrMsg,  "size");
    } else {
        InvestSizeErrMsg.style.display = "none";
    }   
    
    if (priceValidationResult != RangeValidateType.Valid) {
        isValid = false;
        InvestPriceErrMsg.style.display = "block";
        showRangeInvalidMsg(priceValidationResult,InvestPriceErrMsg,  "price");
    } else {
        InvestPriceErrMsg.style.display = "none";
    }

    if (isValid && !validateOnly) {
        var isIndustrial = inputInvestIndustrial.checked;
        var isOffice = inputInvestOffice.checked;
        var isRetail = inputInvestRetail.checked;
        var isMultiFamily = inputInvestMultiFamily.checked;
        var isResidential = false;
        var propertyCategory = 'Building';
        var offerStatus = 'sale';
        var saleCategory = 'Investment';
         
        var sizeLow = parseInt(removeCommas(inputInvestSqFtStart.value));
        var sizeHigh = parseInt(removeCommas(inputInvestSqFtEnd.value));
        var priceLow = parseFloat(removeCommas(inputInvestPriceStart.value)).toFixed(2);
        var priceHigh = parseFloat(removeCommas(inputInvestPriceEnd.value)).toFixed(2);
            
        var startLongitude = southwest.lng();
        var endLongitude = northeast.lng();    
        var startLatitude = southwest.lat();
        var endLatitude = northeast.lat();
        
        var keywords = inputInvestKeywords.value;
        //alert("Searching buildings: Longitude from " + startLongitude + " to " + endLongitude + "\nLatidue from " + startLatitude + " to " + endLatitude);
        SearchProperties(pageIndex,pageSize,isIndustrial,isOffice,isRetail,isMultiFamily,isResidential,propertyCategory,offerStatus,saleCategory,sizeLow,sizeHigh,priceLow,priceHigh,startLongitude,startLatitude,endLongitude,endLatitude,keywords,SearchType.Investment);                
    } 
}

function searchForUser(southwest, northeast, validateOnly) {
    SetInputDefault("#txtUserPriceStart", "0");
    SetInputDefault("#txtUserPriceEnd", "100,000,000");
    SetInputDefault("#txtUserSqFtStart", "0");
    SetInputDefault("#txtUserSqFtEnd", "1,000,000");
    
    var inputUserIndustrial = $get("chkUserIndustrial");
    var inputUserOffice = $get("chkUserOffice");
    var inputUserRetail = $get("chkUserRetail");
    
    var inputUserPriceStart = $get("txtUserPriceStart");
    var inputUserPriceEnd = $get("txtUserPriceEnd");
    
    var inputUserSqFtStart = $get("txtUserSqFtStart");
    var inputUserSqFtEnd = $get("txtUserSqFtEnd");
    
    var UserSizeErrMsg = $get("UserSizeErrMsg");
    var UserPriceErrMsg = $get("UserPriceErrMsg");
    
    var inputUserKeywords = $get("txtUserKeywords");
    var isValid = true;
    
   
    sizeValidationResult = validateRange(inputUserSqFtStart, inputUserSqFtEnd);
    priceValidationResult = validateRange(inputUserPriceStart, inputUserPriceEnd);
    
    if (sizeValidationResult != RangeValidateType.Valid) {
        isValid = false;
        UserSizeErrMsg.style.display = "block";
        showRangeInvalidMsg(sizeValidationResult, UserSizeErrMsg,  "size");
    } else {
        UserSizeErrMsg.style.display = "none";
    }   
    
    if (priceValidationResult != RangeValidateType.Valid) {
        isValid = false;
        UserPriceErrMsg.style.display = "block";
        showRangeInvalidMsg(priceValidationResult,UserPriceErrMsg,  "price");
    } else {
        UserPriceErrMsg.style.display = "none";
    }

    if (isValid && !validateOnly) {
        var isIndustrial = inputUserIndustrial.checked;
        var isOffice = inputUserOffice.checked;
        var isRetail = inputUserRetail.checked;
        var isResidential = false;
        var isMultiFamily = false;
        var propertyCategory = 'Building';
        var offerStatus = 'sale';
        var saleCategory = 'User';
         
        var sizeLow = parseInt(removeCommas(inputUserSqFtStart.value));
        var sizeHigh = parseInt(removeCommas(inputUserSqFtEnd.value));
        var priceLow = parseFloat(removeCommas(inputUserPriceStart.value)).toFixed(2);
        var priceHigh = parseFloat(removeCommas(inputUserPriceEnd.value)).toFixed(2);
            
        var startLongitude = southwest.lng();
        var endLongitude = northeast.lng();    
        var startLatitude = southwest.lat();
        var endLatitude = northeast.lat();
        
        var keywords = inputUserKeywords.value;
        //alert("Searching buildings: Longitude from " + startLongitude + " to " + endLongitude + "\nLatidue from " + startLatitude + " to " + endLatitude);
        SearchProperties(pageIndex,pageSize,isIndustrial,isOffice,isRetail,isMultiFamily,isResidential,propertyCategory,offerStatus,saleCategory,sizeLow,sizeHigh,priceLow,priceHigh,startLongitude,startLatitude,endLongitude,endLatitude,keywords,SearchType.User);                
    } 
}


function searchForLand(southwest, northeast, validateOnly) {
    SetInputDefault("#txtLandAcresStart", "0");
    SetInputDefault("#txtLandAcresEnd", "1,000");
    SetInputDefault("#txtLandPriceStart", "0");
    SetInputDefault("#txtLandPriceEnd", "100,000,000");

    var SqFtPerAcre = 43560; // 43,560 sq ft/acrea
    var chkTokLandIndustrial = $get("chkTokLandIndustrial");
    var chkTokLandOffice = $get("chkTokLandOffice");
    var chkTokLandRetail = $get("chkTokLandRetail");
    var chkTokLandMultifamily = $get("chkTokLandMultifamily");
    var chkTokLandResidential = $get("chkTokLandResidential");
    
    var inputLandAcresStart = $get("txtLandAcresStart");
    var inputLandAcresEnd = $get("txtLandAcresEnd");
    
    var inputLandPriceStart = $get("txtLandPriceStart");
    var inputLandPriceEnd = $get("txtLandPriceEnd");
    
    var landAcresErrMsg = $get("landAcresErrMsg");
    var landPriceErrMsg = $get("landPriceErrMsg");
    var inputLandKeywords = $get("txtLandKeywords");
    var isValid = true;

    sizeValidationResult = validateRange(inputLandAcresStart, inputLandAcresEnd);
    priceValidationResult = validateRange(inputLandPriceStart, inputLandPriceEnd);
    
    if (priceValidationResult != RangeValidateType.Valid) {
        isValid = false;
        landPriceErrMsg.style.display = "block";
        showRangeInvalidMsg(priceValidationResult,landPriceErrMsg,  "price");
    } else {
        landPriceErrMsg.style.display = "none";
    }
        
    if (sizeValidationResult != RangeValidateType.Valid) {
        isValid = false;
        landAcresErrMsg.style.display = "block";
        showRangeInvalidMsg(sizeValidationResult,landAcresErrMsg,  "size");
    } else {
        landAcresErrMsg.style.display = "none";
    }   
    
    if (isValid  && !validateOnly) {
        var isIndustrial = chkTokLandIndustrial.checked;
        var isOffice = chkTokLandOffice.checked;
        var isRetail = chkTokLandRetail.checked;
        var isMultiFamily = chkTokLandMultifamily.checked;
        var isResidential = chkTokLandResidential.checked;
        var propertyCategory = 'Land';
        var offerStatus = 'sale';
        var saleCategory = '';
        
        var sizeLow = parseInt(removeCommas(inputLandAcresStart.value));
        var sizeHigh = parseInt(removeCommas(inputLandAcresEnd.value));
        var priceLow = parseFloat(removeCommas(inputLandPriceStart.value)).toFixed(2);
        var priceHigh = parseFloat(removeCommas(inputLandPriceEnd.value)).toFixed(2);
        
        sizeLow = sizeLow * SqFtPerAcre;
        if (sizeHigh <= 10000) {
            sizeHigh = sizeHigh * SqFtPerAcre;    
        }    
        var startLongitude = southwest.lng();
        var endLongitude = northeast.lng();    
        var startLatitude = southwest.lat();
        var endLatitude = northeast.lat();
        
        var keywords = inputLandKeywords.value;
        // alert("Longitude from " + startLongitude + " to " + endLongitude + "\nLatidue from " + startLatitude + " to " + endLatitude);
        SearchProperties(pageIndex,pageSize,isIndustrial,isOffice,isRetail,isMultiFamily,isResidential,propertyCategory,offerStatus,saleCategory,sizeLow,sizeHigh,priceLow,priceHigh,startLongitude,startLatitude,endLongitude,endLatitude,keywords,SearchType.Land);                
    }     
}

function searchForLease(southwest, northeast, validateOnly) {
    SetInputDefault("#txtLeaseSqFtEnd", "1,000,000");
    SetInputDefault("#txtLeaseSqFtStart", "0");
    SetInputDefault("#txtLeaseRentStart", "0");
    SetInputDefault("#txtLeaseRentEnd", "100,000");

    var chkTokLeaseIndustrial = $get("chkTokLeaseIndustrial");
    var chkTokLeaseOffice = $get("chkTokLeaseOffice");
    var chkTokLeaseRetail = $get("chkTokLeaseRetail");
    var inputLeaseSqFtStart = $get("txtLeaseSqFtStart");
    var inputLeaseSqFtEnd = $get("txtLeaseSqFtEnd");
    var inputLeaseRentStart = $get("txtLeaseRentStart");
    var inputLeaseRentEnd = $get("txtLeaseRentEnd");
    var inputLeaseKeywords = $get("txtLeaseKeywords");
    var sizeErrMsg = $get("sizeErrMsg");
    var rentErrMsg = $get("rentErrMsg");
    var isValid = true;

    sizeValidationResult = validateRange(inputLeaseSqFtStart, inputLeaseSqFtEnd);
    rentValidationResult = validateRange(inputLeaseRentStart, inputLeaseRentEnd);
    
    if (sizeValidationResult != RangeValidateType.Valid) {
        isValid = false;
        sizeErrMsg.style.display = "block";
        showRangeInvalidMsg(sizeValidationResult, sizeErrMsg , "size");  
    } else {
        sizeErrMsg.style.display = "none";
    }
       
    if (rentValidationResult != RangeValidateType.Valid) {
        isValid = false;
        rentErrMsg.style.display = "block";
        showRangeInvalidMsg(rentValidationResult, rentErrMsg,  "rent");  
    } else {
        rentErrMsg.style.display = "none";
    }
    
    if (isValid && !validateOnly) {
        var isIndustrial = chkTokLeaseIndustrial.checked;
        var isOffice = chkTokLeaseOffice.checked;
        var isRetail = chkTokLeaseRetail.checked;
        var isMultiFamily = false;
        var isResidential = false;
        var propertyCategory = 'Building';
        var offerStatus = 'Lease';
        var saleCategory = '';
        var sizeLow = parseInt(removeCommas(inputLeaseSqFtStart.value));
        var sizeHigh = parseInt(removeCommas(inputLeaseSqFtEnd.value));
        var priceLow = parseFloat(removeCommas(inputLeaseRentStart.value)).toFixed(2);
        var priceHigh = parseFloat(removeCommas(inputLeaseRentEnd.value)).toFixed(2);
            
        var startLongitude = southwest.lng();
        var endLongitude = northeast.lng();    
        var startLatitude = southwest.lat();
        var endLatitude = northeast.lat();
        var keywords = inputLeaseKeywords.value;
        //alert("Longitude from " + startLongitude + " to " + endLongitude + "\nLatidue from " + startLatitude + " to " + endLatitude);
        SearchProperties(pageIndex,pageSize,isIndustrial,isOffice,isRetail,isMultiFamily,isResidential,propertyCategory,offerStatus,saleCategory,sizeLow,sizeHigh,priceLow,priceHigh,startLongitude,startLatitude,endLongitude,endLatitude,keywords,SearchType.Lease);            
    }
    
    return isValid;
}

var RangeValidateType = {Valid:0,LowMissing:1,HighMissing:2,LowLessThanHigh:3};

function validateRange(beginValue, endValue) {
    if (beginValue.value.length > 0 && isNumeric(beginValue.value)) {
        var lowVal = parseFloat(removeCommas(beginValue.value));
        if(isNaN(lowVal))
            return RangeValidateType.LowMissing;   
    } else {
        return RangeValidateType.LowMissing;     
    }
    
    if (isNumeric(endValue.value)) {
        var highVal = parseFloat(removeCommas(endValue.value));
        if(isNaN(highVal))
            return RangeValidateType.HighMissing;    
    } else {
        return RangeValidateType.HighMissing;  
    }    

    if (lowVal > highVal) {
        return RangeValidateType.LowLessThanHigh;  
    }
    
    return RangeValidateType.Valid;
}

function SearchProperties(pageIndex,pageSize,isIndustrial,isOffice,isRetail,isMultiFamily,isResidential,propertyCategory,offerStatus,saleCategory,sizeLow,sizeHigh,priceLow,priceHigh,startLongitude,startLatitude,endLongitude,endLatitude,keywords,searchType) {
    ClearSearchResults();
    propertyMap.hideNoResultsMessage();
    propertyMap.hideSaveSuccessMessage();
    propertyMap.hideSaveFailMessage();    
    propertyMap.hideRefineSearchMessage();
    propertyMap.showSearchingMessage();

    TOK.DNN.Modules.PropertySearch.PropertySearchService.SearchProperties(VisitorGUID, pageIndex,pageSize,isIndustrial,isOffice,isRetail,isMultiFamily,isResidential,propertyCategory,offerStatus,saleCategory,sizeLow,sizeHigh,priceLow,priceHigh,startLongitude,startLatitude,endLongitude,endLatitude,keywords,searchType,
            OnSearchComplete, OnSearchError, 'PropertySearchContext');
}

function PrintSearch_Click() {
    window.open(PrintUrl + "&psid=" + searchResults.SearchGUID);
}

function OnSaveSearchComplete(result, userContext) {
    propertyMap.showSaveSuccessMessage();
}

function OnSaveSearchError(result) {
    propertyMap.searchSaveFailMessage();
}

function OnSearchError (result) {
    try {
        propertyMap.hideSearchingMessage();
        alert("Search failed. " + result.Message);
    } catch(err) {
        mainExceptionHandler(err);
        return false;
    }  
}
function OnSearchComplete (result, userContext) {
    try {
        searchResults = result;
        RenderSearchResults();
        propertyMap.hideSearchingMessage();
    } catch(err) {
        mainExceptionHandler(err);
        return false;
    }     
}

function ClearSearchResults() {
    var propertySearchListTable = $get("propertySearchListTable");
    var panelSearchControlBar = $get("panelSearchControlBar");
    if (propertySearchListTable) {
        propertySearchListTable.innerHTML = "";
    }
    propertyMap.map.clearOverlays();
    propertySearchListTable.innerHTML = "";
    panelSearchControlBar.style.display = "none";    
}

function RenderSearchResults() {
    var spanTotalSearchResults = $get("spanTotalSearchResults");
    var panelSearchControlBar = $get("panelSearchControlBar");
    var propertySearchListTable = $get("propertySearchListTable");
    if (spanTotalSearchResults) {
        spanTotalSearchResults.innerHTML = searchResults.TotalHits;
    }
    var  searchguid = $get("searchguid");
    
    if (searchResults.TotalHits > pageSize) {
        ClearSearchResults();
        propertyMap.showRefineSearchMessage();
    } else {
        if (searchResults.TotalHits > 0) {
            renderTOKTable(searchResults.PropertyInfoList, 10, 1, true);
            propertyMap.hideNoResultsMessage();
            propertyMap.renderPropertySearchResults(searchResults);
            panelSearchControlBar.style.display = "block";
        } else {
            ClearSearchResults();
            propertyMap.showNoResultsMessage();
        }
    }
}

function isNumeric(val) {
    var validChars = '0123456789.,';

    for(var i = 0; i < val.length; i++) {
        if(validChars.indexOf(val.charAt(i)) == -1)
        return false;
    }

    return true;
}

function removeCommas( strValue ) {
  var objRegExp = /,/g; //search for commas globally

  return strValue.replace(objRegExp,'');
}

function toggleLandMultiFamily( elementId ) {
    var inputMultiFamily = $get(elementId);
    
    if (inputMultiFamily) {
        if (inputMultiFamily.style.display == "none")
            inputMultiFamily.style.display = "inline";
        else 
            inputMultiFamily.style.display = "none"
    }
}

function OnSaveSuccess(result) {
    alert("Property Saved!");
}

function OnError(result) {
    alert("Error: " + result);
}
