﻿// JScript File
//<![CDATA[
var map;

var PropertySearchLocationParameters = "[initial value]";
var PropertySearchCriteriaParameters = "[initial value]";

var MarkerActive = [];   
var MarkersLoaded = false;
var MarkerActiveCount = 0;

var CurrentPropertyListPage = 1;

var iconimage = [];
iconimage["normal"] = "../Graphics/mapicon-normal.png";
iconimage["selected"] = "../Graphics/mapicon-selected.png";
iconimage["new"] = "../Graphics/mapicon-new.png";
iconimage["green"] = "../Graphics/mapicon-green.png";

var icon = new GIcon();
icon.iconSize = new GSize(20, 20);
icon.shadowSize = new GSize(20, 20);
icon.iconAnchor = new GPoint(6, 20);

function CancelSubmit(e)
{
  if (e && e.preventDefault)
    e.preventDefault(); // DOM style
  return false; // IE style
}

function SearchMapOnEnter(e, daddress) 
{ 
    var key = window.event ? e.keyCode : e.which;
    if (key == 13)
    { 
        return GNWShowAddress(daddress); 
    } 
    return true;
}

function GNWGetAddress() 
{
    var daddress = document.getElementById('MapSearchTextBox').value;
    GNWShowAddress(daddress);
    return false;
}

function GNWShowAddress(address) 
{  
    if (!address || address.trim() == '')
    {
        return;
    } 
    var geocoder = new GClientGeocoder(); 
    geocoder.getLatLng(address,
        function(point) 
        {      
            if (!point) 
            {
                alert("The location " + address + " could not be found");      
            } 
            else 
            {   
/*                var infoTabs = [  
                    new GInfoWindowTab("Home",  "<table border=0 cellpadding=0 cellspacing=0><tr><td valign=top>" + 
                                                "<img src=\"http://216.216.92.236/NWMLS/111/27073111-00.jpg\" " + 
                                                "width=\"80\" height=\"65\" border=\"0\" style=\"border: 1px solid black;\" align=\"left\">" + 
                                                "</td><td width=4>&nbsp;</td><td valign=bottom>" + 
                                                address + "<br/><span style=\"color:green\">$599,000</span>" + 
                                                " - 3 bedrooms, 2 baths</td></tr>" + 
                                                "<tr><td colspan=99 align=right><br/>" + 
                                                "<a href=\"http://www.graysonnorthwest.com/Pages/PropertySearch.aspx?test=1&searchtypesent=5&mlsids[]=27093230\">See Details</a>" + 
                                                "</td></tr></table>"),  
                    new GInfoWindowTab("Description",   "<table border=0 cellpadding=0 cellspacing=0 width=300><tr><td>" +
                                                        "This is a long winded description about the house for sale. " + 
                                                        "I'm very curious how this little balloon will display such " + 
                                                        "long text. It must have a provision for this kind of thing.<br/><br/>" +
                                                        "This is a second paragraph because the description just goes " +
                                                        "on, and on, and on<br/>" +
                                                        "and on ..." +
                                                        "</td></tr><tr><td colspan=99 align=right><br/><a href=\"http://www.graysonnorthwest.com/Pages/PropertySearch.aspx?test=1&searchtypesent=5&mlsids[]=27093230\">See Details</a></td></tr></table>"),
                    new GInfoWindowTab("Features", "<table border=0 cellpadding=0 cellspacing=0 width=300><tr><td>Feature 1<br/>Feature 2<br/><Feature 3<br/></td><td width=4>&nbsp;</td><td>Feature 4<br/>Feature 5<br/><Feature 6<br/></td></tr><tr><td colspan=99 align=right><br/><a href=\"http://www.graysonnorthwest.com/Pages/PropertySearch.aspx?test=1&searchtypesent=5&mlsids[]=27093230\">See Details</a></td></tr></table>")  
                    ]; */
                map.setCenter(point,13);        
/*                var marker = new GMarker(point);        
                GEvent.addListener(marker, "click", function() 
                    {  marker.openInfoWindowTabsHtml(infoTabs);});
                map.addOverlay(marker);        
//                        marker.openInfoWindowTabsHtml(infoTabs);      }
//                        marker.openInfoWindowHtml(address);      */
            }    
        }   
    );  
    }

function GNWMapLoad() 
{
    if (GBrowserIsCompatible()) 
    {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(47.6205, -122.1802), 11);
        GEvent.addListener(map, "moveend", function() { UpdateCountAndMarkers(); });
//        GNWShowAddress("40 Lake Bellevue, Bellevue, WA 98005");
    } 
}
    
function GotoPropertyListPage(gotoPageString) {
    var nextPage = 1;
    if (gotoPageString == "Next")
    {
         nextPage = CurrentPropertyListPage + 1;
    }
    else if (gotoPageString == "Previous")
    {
        if (CurrentPropertyListPage > 1)
        {
            nextPage = CurrentPropertyListPage - 1;
        }
    }
    else
    {
        nextPage = parseInt(gotoPageString);
    }
    ReloadPropertyList(nextPage); 
}

function UpdateLocationParameters()
{
    var bounds = map.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();

    var north = ne.lat();
    var south = sw.lat();
    var east = ne.lng();
    var west = sw.lng();

    PropertySearchLocationParameters =
        "&mapnorth=" + north + "&mapsouth=" + south + "&mapeast=" + east + "&mapwest=" + west;
}    

function SearchCountMessage(message) {
	var newsearchcount = document.getElementById('PropertyCountTD');
    newsearchcount.innerHTML = message;
}

function PropertyListMessage(message) {
    var divPreFormat = "<div style=\"text-align:center; vertical-align:top; margin-left:5; margin-right:5;\"><br/><br/><br/><br/>";
    var divPostFormat = "</div>";
    var PropertyListDiv = document.getElementById('PropertyListDiv');
    PropertyListDiv.innerHTML = divPreFormat +
                                message +
                                divPostFormat;
}    
        
function ReloadPropertyList(gotoPageInt) {

    PropertyListMessage("Retrieving properties ...");

    if (gotoPageInt < 1 || gotoPageInt > 99)
    {
        return false;
    } 
    var nextRow = (gotoPageInt - 1) * 10 + 1;
    CurrentPropertyListPage = gotoPageInt;
    ret = PropertySearch.PropertyList(  PropertySearchLocationParameters,
                                        PropertySearchCriteriaParameters, 
                                        nextRow, 
                                        OnCompletePropertySearch,
                                        OnTimeOutPropertySearch,
                                        OnErrorPropertySearch );
    
    return false;
}

// OnComplete
function OnCompletePropertySearch(arg) 
{
    var PropertyListDiv = document.getElementById('PropertyListDiv');
    PropertyListDiv.innerHTML = arg;
}

// OnTimeOut
function OnTimeOutPropertySearch(arg) 
{
    PropertyListMessage("A time out occurred attempting to retrieve the list of properties.");
}

// OnError
function OnErrorPropertySearch(arg) 
{
    PropertyListMessage("An error occurred attempting to retrieve the list of properties.");
}        

function UpdateCountAndMarkers() {
    
    SearchCountMessage("Searching ...");
    PropertyListMessage("");
    UpdateLocationParameters();
    ret = PropertySearch.CountAndMarkers(   PropertySearchLocationParameters,
                                            PropertySearchCriteriaParameters, 
                                            OnCompleteCountAndMarkers,
                                            OnTimeOutCountAndMarkers,
                                            OnErrorCountAndMarkers );
}

// OnComplete
function OnCompleteCountAndMarkers(arg) 
{
    var propertyCount = 0;
    var lines = arg.split("\n");
    
	ResetMarkers();
    
    propertyCount = parseInt(lines[0]);
    if (propertyCount > 1)
    {
    	SearchCountMessage('There are <b>' + lines[0] + '</b> homes for sale within your search');
    }
    else if (propertyCount == 1)
    {
    	SearchCountMessage('There is <b>1</b> home for sale within your search');
    }
    else
    {
    	SearchCountMessage('There are no homes for sale within your search');
    }
    
    if (propertyCount > 80)
    {
        PropertyListMessage("We found too many homes to display. Please zoom the map to a smaller search area or refine your search criteria.");
    }
    else if (propertyCount < 1)
    {
        PropertyListMessage("There are no homes for sale.  Please choose a different or larger search area or broaden your search criteria.");
    }
    else 
    {
        ReloadPropertyList(1);
        for (var i=1; i<lines.length; i++) 
		{
            if (lines[i].length > 1)
            {
                parts = lines[i].split("|");
                var lat = parseFloat(parts[0]);
                var lng = parseFloat(parts[1]);
                var listing = parts[2];
                var label = parts[3];
                var point = new GLatLng(lat,lng);
                CreateMarkerPoint(lat,lng,listing); 
            }
        } 
    } 
}

function ResetMarkers() 
{
    for (var i=0; i<MarkerActiveCount; ++i)
    {
        GEvent.clearInstanceListeners(MarkerActive[i]);
        map.removeOverlay(MarkerActive[i]); 		
    }
    MarkerActiveCount = 0;
} 


function CreateMarkerPoint(lat,lng,listing)
{
    var NewMarkerIndex = MarkerActiveCount;
    var point = new GLatLng(lat,lng);
    var newIcon = new GIcon();
    newIcon.image = iconimage["normal"];
    newIcon.iconSize = new GSize(20, 20);
    newIcon.iconAnchor = new GPoint(10, 10);

    MarkerActive[NewMarkerIndex] = new GMarker(point,{icon:newIcon,title:"MLS #" + listing});
    map.addOverlay(MarkerActive[NewMarkerIndex]); 		
    
    GEvent.clearInstanceListeners(MarkerActive[NewMarkerIndex]); 
    GEvent.addListener(MarkerActive[NewMarkerIndex], "click", function() { open('../Pages/FeaturedListing.aspx?action=property.view&slistingview=' + listing, 'GNWFeaturedListing')});
    ++MarkerActiveCount;
}

function createmarkerselected(j, k, l)
{
}

// OnTimeOut
function OnTimeOutCountAndMarkers(arg) 
{
    PropertyListMessage("A time out occurred attempting to retrieve the number of properties.");
}

// OnError
function OnErrorCountAndMarkers(arg) 
{
    PropertyListMessage("An error occurred attempting to retrieve the number of properties.");
}        

function CriteriaSaved() {


    //  Build new criteria display text and criteria parameter string.
    //  ==============================================================

    var newCriteriaDisplayText = "";
    var newPropertySearchCriteriaParameters = "";
    
    //  At least one property type is required.
    //  =======================================
    
    var PropertyTypeSFR = document.getElementById('PropertyTypeSFR');
    var PropertyTypeCondo = document.getElementById('PropertyTypeCondo');
    
    if (!PropertyTypeSFR.checked && !PropertyTypeCondo.checked) 
    {
        PropertyTypeSFR.checked = true;
        PropertyTypeCondo.checked = true;
    }
    
    if (PropertyTypeSFR.checked && PropertyTypeCondo.checked) 
    {
        newCriteriaDisplayText = "Houses&nbsp;&&nbsp;Condos";
        newPropertySearchCriteriaParameters = "&type=1,2";
    }
    else if (PropertyTypeSFR.checked)
    {
        newCriteriaDisplayText = "Houses";
        newPropertySearchCriteriaParameters = "&type=1";
    }
    else
    {
        newCriteriaDisplayText = "Condos";
        newPropertySearchCriteriaParameters = "&type=2";
    }

    //  Price.
    //  ======
    
    var spricemin = document.getElementById('spricemin');
    var spricemax = document.getElementById('spricemax');
    
    if (spricemin.value != '-1') 
    {
        newPropertySearchCriteriaParameters += "&pricemin=" + spricemin.value;
    }
    if (spricemax.value != "-1") 
    {
        newPropertySearchCriteriaParameters += "&pricemax=" + spricemax.value;
    }
    
    if (spricemin.value == "-1" && spricemax.value == "-1")
    {
        newCriteriaDisplayText += ", all&nbsp;prices";
    }
    else if (spricemin.value != "-1")
    {
        newCriteriaDisplayText += ", " + spricemin.options[spricemin.selectedIndex].text;
        if (spricemax.value != "-1")
        {
            newCriteriaDisplayText += "&nbsp;to&nbsp;" + spricemax.options[spricemax.selectedIndex].text;
        }
        else
        {
            newCriteriaDisplayText += "&nbsp;and&nbsp;up";
        }
    }
    else
    {
        newCriteriaDisplayText += ", up&nbsp;to&nbsp;" + spricemax.options[spricemax.selectedIndex].text;
    }
    
    //  Bedrooms.
    //  =========
    
    var sbed = document.getElementById('sbed');
    if (sbed.value != "-1")
    {            
        newPropertySearchCriteriaParameters += "&bed=" + sbed.value;
        newCriteriaDisplayText += ", " + sbed.options[sbed.selectedIndex].text + "&nbsp;beds";
    }
    
    //  Bathrooms.
    //  ==========
    
    var bath = document.getElementById('bath');
    if (bath.value != "-1")
    {            
        newPropertySearchCriteriaParameters += "&bath=" + bath.value;
        newCriteriaDisplayText += ", " + bath.options[bath.selectedIndex].text + "&nbsp;baths";
    }
    
    //  Home size.
    //  ==========
    
    var ssqft = document.getElementById('ssqft');
    if (ssqft.value != "-1")
    {            
        newPropertySearchCriteriaParameters += "&sqft=" + ssqft.value;
        newCriteriaDisplayText += ", " + ssqft.options[ssqft.selectedIndex].text + "&nbsp;sq&nbsp;ft";
    }
    
    //  Lot size.
    //  =========
    
    var sacre = document.getElementById('sacre');
    if (sacre.value != "-1")
    {            
        newPropertySearchCriteriaParameters += "&acre=" + sacre.value;
        newCriteriaDisplayText += ", " + sacre.options[sacre.selectedIndex].text + "&nbsp;acres";
    }
    
    //  Features.
    //  =========
    
    var vw = document.getElementById('vw');
    if (vw.checked) 
    {
        newCriteriaDisplayText += ", view";
        newPropertySearchCriteriaParameters += "&vw=1";
    }
    var swft = document.getElementById('swft');
    if (swft.checked) 
    {
        newCriteriaDisplayText += ", waterfront";
        newPropertySearchCriteriaParameters += "&wft=1";
    }
    var snew = document.getElementById('snew');
    if (snew.checked) 
    {
        newCriteriaDisplayText += ", new&nbsp;listing";
        newPropertySearchCriteriaParameters += "&new=1";
    }
    var snc = document.getElementById('snc');
    if (snc.checked) 
    {
        newCriteriaDisplayText += ", new&nbsp;const";
        newPropertySearchCriteriaParameters += "&nc=1";
    }
        
    //  If the criteria changed, update everything.
    //  ===========================================
    
    if (newPropertySearchCriteriaParameters != PropertySearchCriteriaParameters)
    {
        PropertySearchCriteriaParameters = newPropertySearchCriteriaParameters;
        var CurrentSearchLabel = document.getElementById('CurrentSearchLabel');
        CurrentSearchLabel.innerHTML = newCriteriaDisplayText;
        UpdateCountAndMarkers();
    }
}

function DisplayCriteriaForm(action) {
    var CriteriaAndShadowDiv = document.getElementById('CriteriaAndShadowDiv');
    var mapDiv = document.getElementById('map');
    var ChangeCriteriaButton = document.getElementById('ChangeCriteriaButton');
    
    if (action == 'open')
    {
        mapDiv.style.display='none';
        CriteriaAndShadowDiv.style.display='';
        ChangeCriteriaButton.enable=false;
    }
    else
    {
        CriteriaAndShadowDiv.style.display='none';
        mapDiv.style.display='';
        ChangeCriteriaButton.enable=true;
        if (action == 'save')
        {
            CriteriaSaved();
        }
    }
}

function imageload(listingphoto)
{
    var photosource = document.getElementById(listingphoto);
    photosource.style.display = 'inline';
}

function imageerror(listingphoto)
{
    var photosource = document.getElementById(listingphoto);
    photosource.src = '../Graphics/NoPhotoAvailable.gif';
    photosource.style.display = 'inline';
}


    //]]>

