﻿/***********************************************************************************************
    Start it out
***********************************************************************************************/
google.load("maps", "2.x");     

var map;
var mgr;
var icons = {};
var allmarkers = [];

// Call this function when the page has been loaded  
function initialize() {    
	map = new google.maps.Map2(document.getElementById("map"));    
	map.setCenter(new google.maps.LatLng(startingLatitude, startingLongitude), startingZoom);  
	
	map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    mgr = new MarkerManager(map, {trackMarkers:true});

    // show streetview    
    // svOverlay = new GStreetviewOverlay();
    // map.addOverlay(svOverlay);
	
	// set the icon
	var baseIcon = new GIcon();
	baseIcon.iconSize = new GSize(18, 17);
	//baseIcon.shadowSize = new GSize(37, 34);
	//baseIcon.iconAnchor = new GPoint(0, 0);
	//baseIcon.infoWindowAnchor = new GPoint(9, 2);
	//baseIcon.infoShadowAnchor = new GPoint(0, 0);	
		
	SearchFeatured();
}

/********************************
    JS to Flash calls
********************************/
function SearchByMLS() {
    if(arguments[0]) mlsnumber = arguments[0];
    else mlsnumber = document.Form.txtMls.value
    GDownloadUrl(feedURL + "?mlsnumber=" + mlsnumber, searchResponse);
    
    // show the detail tab
    tabhandler2.show(3);
    
    GDownloadUrl(feedURL + "?detail=full&mlsnumber=" + mlsnumber + "&moduleid=" + moduleid, detailResponse);
}

function SearchQuick(searchtype) {
    GDownloadUrl(feedURL + "?searchtype=" + searchtype, searchResponse);
}

function SearchFeatured() {
    if(featuredType != "") {
        //prompt("Code", feedURL + "?searchtype=featured&agentcode=" + siteAgentCode + "&officecode=" + siteOfficeCode + "&featuredtype=" + featuredType);
        GDownloadUrl(feedURL + "?searchtype=featured&agentcode=" + siteAgentCode + "&officecode=" + siteOfficeCode + "&featuredtype=" + featuredType, searchResponse);
    }
}

function SaveSearch(obj) {    
    if(userid > 0) {
        var title = prompt("What would you like to call this search?", "");    
        var qs = getQS(obj);
        if(title != "") {
            qs += "&title=" + title;
        }
        else {
            var d = new Date();
            qs += "&title=" + d.getDate() + "-" + d.getMonth() + "-" + d.getFullYear() + "-" + d.getMilliseconds();
        }
        
        GDownloadUrl(feedURL + "?" + qs, saveResponse);
    }
    else {
        alert("Please register or login to save searches");
    }
}

function SearchSaved() {
    var qs = "";
    qs += "pricemin=" + arguments[0];
    qs += "&pricemax=" + arguments[1];
    qs += "&sizemin=" + 0;
    qs += "&sizemax=" + 10000000;
    qs += "&beds=" + arguments[2];
    qs += "&baths=" + arguments[3];
    qs += "&garages=" + arguments[4];
    qs += "&lotsize=" + arguments[5];
    qs += "&yearmin=" + arguments[6];
    qs += "&yearmax=" + arguments[7];
    qs += "&listoption=" + arguments[8];
    qs += "&officecode=" + siteOfficeCode;
    
    //prompt("code", feedURL + "?" + qs);
    GDownloadUrl(feedURL + "?" + qs, searchResponse);
}

function SearchNormal(obj) {
    var qs = getQS(obj);
    //prompt("code", feedURL + "?" + qs);
    GDownloadUrl(feedURL + "?" + qs, searchResponse);
}

function getQS(obj) {
    var qs = "";
    qs += "pricemin=" + obj.priceMin;
    qs += "&pricemax=" + obj.priceMax;
    qs += "&sizemin=" + obj.sizeMin;
    qs += "&sizemax=" + obj.sizeMax;
    qs += "&beds=" + obj.beds;
    qs += "&baths=" + obj.baths;
    qs += "&garages=" + obj.garages;
    qs += "&lotsize=" + obj.lotsize;
    qs += "&yearmin=" + obj.yearMin;
    qs += "&yearmax=" + obj.yearMax;
    qs += "&listoption=" + obj.listOption;
    qs += "&officecode=" + siteOfficeCode;
    qs += "&userid=" + userid;
    return qs;
}

function saveResponse(data, responseCode) {
    if(responseCode == 200) {
        alert("Your search has been saved.");
        searchResponse(data, responseCode);
    }
    else {
        alert("The search was not saved due to a technical difficulty.  Please try again soon.");
    }
}

function searchResponse(data, responseCode)
{
    var xml = GXml.parse(data);
    var nodeRoot = xml.documentElement;
    var markers = [];    
    var table = "<table width='100%' id='listingtable' class='tablesorter'>";
    table += "<thead><tr><th>&nbsp;</th><th>Address</th><th>Price</th></tr></thead><tbody>";
    
    if(responseCode == 200) {
        clearMarkers();
        allmarkers.length = 0; // clear out any previous markers in the array
        counterAll = counterCondo = counterVacant = 0;
        averagePrice = averageBeds = averageBaths = averageSqFt = 0;
        
        var properties = nodeRoot.getElementsByTagName("property");
        for (var i = 0; i < properties.length; i++) {
        
            // make the markers
            marker = createMarker(properties[i]);
            table += createTableRow(properties[i], i, true);
            
            markers.push(marker);
            allmarkers.push(marker);
        }
        
        table += "</tbody></table>"; 
        
        document.getElementById("countAll").innerHTML = counterAll;    
        document.getElementById("countFeatured").innerHTML = counterCondo;
        document.getElementById("countVacant").innerHTML = counterVacant;
        
        if(properties.length) {
            document.getElementById("avgPrice").innerHTML = FormatMoney(Math.round(averagePrice / properties.length));
            document.getElementById("avgBeds").innerHTML = Math.round(averageBeds / properties.length);
            document.getElementById("avgBaths").innerHTML = Math.round(averageBaths / properties.length);
            document.getElementById("avgSqFt").innerHTML = Math.round(averageSqFt / properties.length);           
            document.getElementById("listpanel").innerHTML = table;
        }
        else {
            document.getElementById("listpanel").innerHTML = "&nbsp;";
            alert("There were no properties found with your criteria. Please try again.");
        }
        
        mgr.addMarkers(markers, 1, 17);
        mgr.refresh();
        
        // center the map
        if(properties.length == 1)
            map.setCenter(new google.maps.LatLng(getElementValue(properties[0], "latitude"), getElementValue(properties[0], "longitude")), startingZoom);
        //else
            //map.setCenter(new google.maps.LatLng(startingLatitude, startingLongitude), startingZoom);  
            
        // show the map tab
        tabhandler2.show(1);
    }
    else {
        alert("The data feed in currently unavailable.  Please try again soon.");
    }
}
	
/********************************
    Flash to JS calls
********************************/
function getValues(boo) {
    isSaveSearch = boo;
	flashProxy.call('JSToFlash', getSelectedRadioValue(document.Form.listing));
}

function FlashToJS(obj) {
    if(!isSaveSearch)
        SearchNormal(obj);
    else
        SaveSearch(obj);
}

function resetSearch() {
    document.Form.reset();
    flashProxy.call('JSToFlashReset');
}
	
function goToPropertyDetails() {
    location.href = detailURL.replace("{0}", selectedMLSNumber);
}

function goToMarker(marker) {
    // move the map to the selected marker
    map.setCenter(marker.getLatLng(), map.getZoom());    
    
    // show the correct tab
    tabhandler2.show(1);
    
    // trigger the marker click
    GEvent.trigger(marker, "click");
}


function GetPoint(latitude,longitude)
{
	return new GLatLng(parseFloat(latitude),parseFloat(longitude))
}

function createMarker(property) {

    var mlsnumber = getElementValue(property, "mlsnumber");
    var latitude = getElementValue(property, "latitude");
    var longitude = getElementValue(property, "longitude");
    var displayaddress = getElementValue(property, "displayaddress");
    var listprice = getElementValue(property, "listprice");
    var bedrooms = getElementValue(property, "bedrooms");
    var totalbathrooms = getElementValue(property, "bathstotal");    
    var totalsqft = getElementValue(property, "totalsqft");
    var officecode = getElementValue(property, "officecode");
    var listingtypeid = getElementValue(property, "listingtypeid");
    var myicon;
    
    // calculate the icon
    if(listingtypeid == 2) {
        myicon = iconFeatured;
        counterCondo++;
    }
    else if (listingtypeid == 7) {
        myicon = iconVacant;
        counterVacant++;
    }
    else {
        myicon = iconGeneral;
        counterAll++;
    }
    
    // get the point
    point = GetPoint(latitude, longitude)

    // Set up our GMarkerOptions object - give the title the mlsnumber for later reference
    markerOptions = { icon:myicon, title:displayaddress };
    var marker = new GMarker(point, markerOptions);
    
    // calculations
    averagePrice += parseInt(listprice, 10);
    if(bedrooms.length > 0) averageBeds += parseInt(bedrooms, 10);
    if(totalbathrooms.length > 0) averageBaths += parseInt(totalbathrooms, 10);
    if(totalsqft.length > 0) averageSqFt += parseInt(totalsqft, 10);

    // events
    GEvent.addListener(marker, "click", function() {    
        
        // show the popup
        marker.openInfoWindowHtml("<table><tr><td><img src='" + imagePathSmall.replace("{0}", mlsnumber).replace("{0}", mlsnumber) + "' width='80' height='60' border='0'></td><td><strong>Price: " + FormatMoney(listprice) + "<br />MLS# " + mlsnumber + "</strong><br />" + displayaddress + "</td></tr></table>");
        
        // show the details of the property
        loadDetails(mlsnumber);
        
        // show the detail tab
        tabhandler2.show(3);
        
        // load comparisons
        loadComparisons(mlsnumber);
    });
    // mouse over
    GEvent.addListener(marker, "mouseover", function() {
        marker.openInfoWindowHtml("<table><tr><td><img src='" + imagePathSmall.replace("{0}", mlsnumber).replace("{0}", mlsnumber) + "' width='80' height='60' border='0'></td><td><strong>Price: " + FormatMoney(listprice) + "<br />MLS# " + mlsnumber + "</strong><br />" + displayaddress + "</td></tr></table>");
    });
                	
    return marker;
}

function getElementValue(property, element) {
    return (property.getElementsByTagName(element)[0].firstChild != null) ? property.getElementsByTagName(element)[0].firstChild.nodeValue : "";
}

function clearMarkers() {
  mgr.clearMarkers();
}

function getIcon(path) {
    // set the icon
	var baseIcon = new GIcon();
	baseIcon.iconSize = new GSize(18, 17);
	//baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(0, 0);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);		
	
	var icon = new GIcon(baseIcon);		  
    icon.image = path;
    
    return icon;
}

function loadComparisons(mlsnumber) {
    GDownloadUrl(feedURL + "?querytype=comparison&mlsnumber=" + mlsnumber, comparisonResponse);
}

function loadDetails(mlsnumber) {
    GDownloadUrl(feedURL + "?detail=full&mlsnumber=" + mlsnumber + "&moduleid=" + moduleid + "&portalid=" + portalid + "&ran=" + RandomValue(), detailResponse);
}

function comparisonResponse(data, responseCode)
{
    var xml = GXml.parse(data);
    var nodeRoot = xml.documentElement;
    var properties = nodeRoot.getElementsByTagName("property");
    var table = "<table width='100%' id='comparisontable'>";
    table += "<tr><th>Property</th><th>Detail</th></tr>";
        
    for (var i = 0; i < properties.length; i++) {
        
        table += createTableRow(properties[i], i, false);
        
        // only show the first 6
        if(i == 6) break;
    }
    
    table += "</table>";
        
    document.getElementById("comparisonTableDiv").innerHTML = table;
}

function detailResponse(data, responseCode) 
{
    jQuery("#detailpanel").html(data);
}

function createTableRow(property, count, isResult) {
    var mlsnumber = getElementValue(property, "mlsnumber");
    var latitude = getElementValue(property, "latitude");
    var longitude = getElementValue(property, "longitude");
    var displayaddress = getElementValue(property, "displayaddress");
    var listprice = getElementValue(property, "listprice");
    var classname = (count % 2 == 0) ? "odd" : "even";
    
    if(isResult)
        return "<tr class=" + classname + "><td><a href='javascript:goToMarker(allmarkers[" + count + "])'><img src='" + imagePathSmall.replace("{0}", mlsnumber).replace("{0}", mlsnumber) + "' border='0' /></a></a></td><td>" + displayaddress + "</td><td>" + FormatMoney(listprice) + "</td></tr>";
    else
        return "<tr class=" + classname + "><td><img src='" + imagePathSmall.replace("{0}", mlsnumber).replace("{0}", mlsnumber) + "' border='0' /></td><td valign='top'><a href='javascript:SearchByMLS(\"" + mlsnumber + "\")'>MLS#: " + mlsnumber + "</a><br />" + displayaddress + "<br />" + FormatMoney(listprice) + "</td></tr>";
}

/*
function loadDetails(property) {
    alert("hello!");
    var mlsnumber = getElementValue(property, "mlsnumber");
    var displayaddress = getElementValue(property, "displayaddress");
    var listprice = getElementValue(property, "listprice");
    var bedrooms = getElementValue(property, "bedrooms");
    var bathstotal = getElementValue(property, "bathstotal");
    var totalsqft = getElementValue(property, "totalsqft");
    var approximateacreage = getElementValue(property, "approximateacreage");
    var officename = getElementValue(property, "officename");
    var lotsize = getElementValue(property, "lotsize");
    
    selectedMLSNumber = mlsnumber;
    getPropertyDetailsURL(); // setup the link for the details page
    
    document.getElementById("details_photo").src = imageResolver + "?imagepath=" + imagePath.replace("{0}", mlsnumber).replace("{0}", mlsnumber);
    document.getElementById("detail_listprice").innerHTML = FormatMoney(listprice);    
    document.getElementById("detail_mls").innerHTML = mlsnumber;
    document.getElementById("detail_totalbeds").innerHTML = bedrooms;
    document.getElementById("detail_totalsqft").innerHTML = totalsqft;
    document.getElementById("detail_bathstotal").innerHTML = bathstotal;
    document.getElementById("detail_lotsize").innerHTML = lotsize;
    document.getElementById("detail_approximateacreage").innerHTML = approximateacreage;		
    document.getElementById("detail_officename").innerHTML = officename;    
}*/

function FormatMoney(str) {
	var tempArray = String(str).split("");
	var temp = "";
	var counter = 0;
	
	for (var i = tempArray.length-1; i >= 0; i--) {
		temp = tempArray[i] + temp;
		if(++counter % 3 == 0 && i > 0) temp = "," + temp;
		if(counter >= 15) break;
	}
	
	return "$" + temp;
}

function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
}

function getSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
}

// streetmap view
var myPano;
var panoClient;

function initpano(lat,lng) {
    var propLatLng = new GLatLng(lat,lng);
    var propPOV = {yaw:90,pitch:0};

    myPano = new GStreetviewPanorama(document.getElementById("pano"));
    myPano.setLocationAndPOV(propLatLng, propPOV);
    GEvent.addListener(myPano, "error", handleNoFlash);  
    panoClient.getNearestPanorama(propLatLng, showPanoData);
}

function showPanoData(panoData) {
    if (panoData.code != 200) {
    return;
    }
    myPano.setLocationAndPOV(panoData.location.latlng);
}

function handleNoFlash(errorCode) {
    if (errorCode == 603) {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
    }
    jQuery("#pano").html("There is no street view data for this property");
}

function RandomValue()
{
	var d = new Date();
	return d.getDate() + d.getHours() + d.getMinutes() + d.getSeconds();
}

function tabBlock(name,defaultId){
this.name=name;this.tabs=new Array();this.pages=new Array();this.tabs['T1']=jQuery('#'+defaultId);this.add=function(id)
{this.pages.push(jQuery('#'+id));if(this.pages.length==1)
this.show(1);else
this.hide(this.pages.length-1);}
this.hide=function(index)
{this.pages[index].css('display','none');}
this.show=function(index,obj)
{if(typeof obj!='undefined'&&obj!=null)
{this.tabs['T'+index]=jQuery(obj);}
for(var i=0;i<this.pages.length;i++)
{if(i==index-1)
{this.pages[i].css('display','block');if(typeof this.tabs['T'+(i+1)]!='undefined'&&this.tabs['T'+(i+1)]!=null)
this.tabs['T'+(i+1)].addClass('current');}
else
{this.hide(i);if(typeof this.tabs['T'+(i+1)]!='undefined'&&this.tabs['T'+(i+1)]!=null)
this.tabs['T'+(i+1)].removeClass('current');}}}
}

function calculateMortgage(price, down, years, air) {
/*
P = principal, the initial amount of the loan
I = the annual interest rate (from 1 to 100 percent)
L = length, the length (in years) of the loan, or at least the length over which the loan is amortized.
J = monthly interest in decimal form = I / (12 x 100)
N = number of months over which loan is amortized = L x 12
M = P * ( J / (1 - (1 + J) ** -N))
*/
    var p = parseInt(price,10) - parseInt(down,10);
    var i = parseFloat(air);
    var l = parseInt(years,10);
    var j = i / (12 * 100);
    var n = l * 12;
    var m = Math.round(100*(p * (j/(1-Math.pow((1+j),-n)))))/100;
    return (m != "NaN") ? "$" + m + " / month" : "Error in calculating";
}
		
google.setOnLoadCallback(initialize);