var geocoder = null;
var map = null;
var circle = null;
var circleRadius = 1; // Miles
var names = '';
var indent = 1;
var current_step = 1;
var ths_city = "";
var ths_state = "";
var ths_zip = "";
var high_price = null;
var low_price = null;
var total_dollar = 0;
var avg_price = null;
var ww = null;
var wh = null;
var market_high = null;
var market_low = null;
var market_average = null;
var zillow_high = null;
var zillow_low = null;
var zillow_average = null;
var ep_high = null;
var ep_low = null;
var ep_average = null;
var returnValuation = 0;


$(document).ready(function(){
	ww = $(window).width();
	wh = $(window).height();
	// Set up the Google Map
	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(37.4419, -122.1419), 12);
		map.setUIToDefault();
		map.disableScrollWheelZoom();
	}
	
	$("#container2").css("display","none");
});

function goTo(panel) {
	if (panel == 2) {
		$("#container1").fadeOut("fast",function() {
			$("#container2").css("visibility","visible");
			$("#container2").fadeIn("fast");
		});
		
	} else {
		$("#container2").fadeOut("fast",function() {
			$("#container1").fadeIn("fast");
		});
	}
	
}

function showAddress(address) {
	
	geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				alert(address + " not found");
			} else {
				map.clearOverlays();
				map.setCenter(point);
				var marker = new GMarker(point);
				map.addOverlay(marker);
				
				map.setCenter(point);
				var marker = new GMarker(point);
				map.addOverlay(marker);
				circle = new CircleOverlay(map.getCenter(), circleRadius, "#336699", 1, 1, '#336699', 0.25);
				map.addOverlay(circle);
				
				geocoder.getLocations(address, lookup);
				
				$.ajax({
					type: "GET",
					url: "utility/plotListings/" + address + "/" + map.getCenter().lat() + "/" + map.getCenter().lng() + "/" + circleRadius + "/" + document.cma_form.sf.value + "/" + document.cma_form.ybt.value + "/",
					success: function(xml){
						var count = 0;
						var total_listings = $(xml).find('listing').length;
						$(xml).find('listing').each(function(){
							
							var thsImage = null;
							var thisLat = null;
							var thisLon = null;
							var thisListPrice = $(this).find('listPrice').text();
							var thisBed = $(this).find('bedrooms').text();
							var thisBath = $(this).find('bathrooms').text();
							var thisAddress = null;
							var thisMLS = setMLS( $(this).find('mls').text() );
							if ($(this).find('company').text() != '') {
								var thisCourt = thisMLS + ' / ' + $(this).find('company').text();
							} else {
								var thisCourt = thisMLS + ' / ' + 'Windermere Real Estate';
							}
							
							total_dollar = parseInt(total_dollar) + parseInt(removedollar(thisListPrice));
							
							if (count == 0) {
								high_price = thisListPrice;
							} else {
								low_price = thisListPrice;
							}
							
							
							$(this).find('location').each(function(){
								thisLat = $(this).find('latitude').text();
								thisLon =  $(this).find('longitude').text();
								thisAddress = $(this).find('address').text();
							});
							
							$(this).find('image').each(function(){
								thsImage = '<div style="float: left; width:85px; height: 55px; background: url(' + $(this).find('thumbUrl').text() + '); background-repeat: no-repeat;"><img src="listing-images/18726-edspeua-335671-ghminsi-3532ac.png" border="0"></div>';
							});
							
							// Create our "tiny" marker icon
							var tinyIcon = new GIcon();
							tinyIcon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
							tinyIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
							tinyIcon.iconSize = new GSize(12, 20);
							tinyIcon.shadowSize = new GSize(22, 20);
							tinyIcon.iconAnchor = new GPoint(6, 20);
							tinyIcon.infoWindowAnchor = new GPoint(5, 1);

							// Set up our GMarkerOptions object literal
							markerOptions = { icon:tinyIcon };
							
							
							var center = new GLatLng(thisLat, thisLon);
							
							var marker = new GMarker(center, markerOptions);
							
							var thisHTML = '<div>' +  thsImage + '<div style="float: right; font-size: 10px; color: #000; font-family: arial;">' + thisListPrice + '<br />' + thisAddress + '<br />' + thisBed + ' bedrooms / ' + thisBath + ' bathrooms' + '<br />Courtesy of: ' + thisCourt + '</div>' + '</div><div style="clear: both;></div>"';
							
							GEvent.addListener(marker, "click", function() {
								map.openInfoWindow(center, thisHTML); 
							});
							
							
							map.addOverlay(marker);
							
							count++;
							
						});
						
						var avg_price = parseInt(total_dollar) / parseInt(total_listings);
						
						var low_ybt = parseInt(document.cma_form.ybt.value) - 5;
						var high_ybt = parseInt(document.cma_form.ybt.value) + 5;
						var low_sqft = parseInt(document.cma_form.sf.value) - 400;
						var high_sqft = parseInt(document.cma_form.sf.value) + 400;
						
						$("#poss_sqft").html(low_sqft + " and " + high_sqft);
						$("#poss_ybt").html(low_ybt + " and " + high_ybt);
						$("#hp").html('High Price:<br />' + high_price);
						$("#lp").html('Low Price:<br />' + low_price);
						$("#ap").html('Average Price:<br />' + formatCurrency(avg_price));
						$("#radius").html(circleRadius);
						$("#address").html(address);
						
						market_high = removedollar(high_price);
						market_low = removedollar(low_price);
						market_average = avg_price;
						
						initZillow(address,ths_city + " " + ths_state + " " + ths_zip);
						eppraisal(address + " " + ths_city + " " + ths_state + " " + ths_zip);
						
						total_dollar = 0;
					}
				});
				// END - markers
			}
		}
);
}

function initZillow(addr,csz) {
	$.ajax({
		type: "GET",
		url: "utility/getZillow/" + addr + "/" + csz,
		dataType: "xml",
		success: function(xml) {
			var thsId = 0;
			$(xml).find('zpid').each(function(){
				thsId = $(this).text();
			});
			$(xml).find('zestimate').each(function(){
				if ($(this).find("amount").text() > 0) {
					$("#zimedval").html("Medium Valuation:<br />" + formatCurrency($(this).find("amount").text()));
					zillow_average = $(this).find("amount").text();
					//alert(($(this).find("amount").text()));
				} else {
					$("#zimedval").html('N/A');
				}
				
			});
			$(xml).find('valuationRange').each(function(){
				if ($(this).find("low").text() > 0) {
					$("#zilowval").html("Low Valuation:<br />" + formatCurrency($(this).find("low").text()));
					zillow_low = $(this).find("low").text();
				} else {
					$("#zilowval").html('N/A');
				}
				if ($(this).find("high").text() > 0) {
					$("#zihighval").html("High Valuation:<br />" + formatCurrency($(this).find("high").text()));
					zillow_high = $(this).find("high").text();
				} else {
					$("#zihighval").html('N/A');
				}
			});
			returnValuation = returnValuation + 1;
			totalAverages();
		}
	});
}

function eppraisal( addr ) {
	$.ajax({
		type: "GET",
		url: 'utility/getEp/' + addr,
		dataType: "xml",
		success: function(xml) {
			if ($(xml).find("LowValue").text() > 0) {
				$("#eplowval").html("Low Valuation:<br />" + formatCurrency($(xml).find("LowValue").text()));
				ep_low = $(xml).find("LowValue").text();
			} else {
				$("#eplowval").html('N/A');
			}
			if ($(xml).find("MidValue").text() > 0) {
				$("#epmedval").html("Medium Valuation:<br />" + formatCurrency($(xml).find("MidValue").text()));
				ep_average = $(xml).find("MidValue").text();
			} else {
				$("#epmedval").html('N/A');
			}
			if ($(xml).find("HighValue").text() > 0) {
				$("#ephighval").html("High Valuation:<br />" + formatCurrency($(xml).find("HighValue").text()));
				ep_high = $(xml).find("HighValue").text();
			} else {
				$("#ephighval").html('N/A');
			}
			
			returnValuation = returnValuation + 1;
			totalAverages();
		}
	});
}

function totalAverages() {
	if (returnValuation == 2) {
		var average_high = (parseInt(market_high) + parseInt(zillow_high) + parseInt(ep_high)) / 3;
		$("#avhighval").html("High Average<br />" + formatCurrency(average_high));
		var average_medium = (parseInt(market_average) + parseInt(zillow_average) + parseInt(ep_average)) / 3;
		$("#avmedval").html("Medium Average<br />" + formatCurrency(average_medium));
		var average_low = (parseInt(market_low) + parseInt(zillow_low) + parseInt(ep_low)) / 3;
		$("#avlowval").html("Low Average<br />" + formatCurrency(average_low));
		returnValuation = 0;
	}
}


function cyberhomes( addr ) {
	
	$.ajax({
		type: "GET",
		url: 'utility/getCyberHomes/' + addr,
		dataType: "xml",
		success: function(xml) {
			if ($(xml).find("ValueFrom").text() > 0) {
				$("#cylowval").html('$' + dollarFormat($(xml).find("ValueFrom").text()));
			} else {
				$("#cylowval").html('N/A');
			}
			if ($(xml).find("EstimateValue").text() > 0) {
				$("#cymedval").html('$' + dollarFormat($(xml).find("EstimateValue").text()));
			} else {
				$("#cymedval").html('N/A');
			}
			if ($(xml).find("ValueTo").text() > 0) {
				$("#cyhighval").html('$' + dollarFormat($(xml).find("ValueTo").text()));
			} else {
				$("#cyhighval").html('N/A');
			}	
		}
	});
}

function showSubmit () {
	if (document.cma_form.ybt.value.length == 3) {
		$("#submit_button").fadeIn("fast");
	} else {
		$("#submit_button").fadeOut("fast");
	}
}

function lookup(response) {
	    place = response.Placemark[0];
		evalObj(place);
}

function evalObj(obj) {
	walkGeoCodeObj(obj,0);
}

function setRadius() {
	map.removeOverlay(circle);
	circle = new CircleOverlay(map.getCenter(), circleRadius, "#336699", 1, 1, '#336699', 0.25);
	map.addOverlay(circle);
}

function walkGeoCodeObj(obj,indent) {
	obj = eval(obj);
	indent = indent + 1;
	for (var i = 0; i<indent; i++) {
		names += "&nbsp;&nbsp;&nbsp;&nbsp;";
	}
	for (var i in obj) {	
		names += i + '(' + typeof obj[i] + ')' + '<br>';
		if (typeof obj[i] == "object") {
			if (obj[i].PostalCode != undefined) {
				//$('input:hidden[name=zip]').val(obj[i].PostalCode.PostalCodeNumber);
				ths_zip = obj[i].PostalCode.PostalCodeNumber;
			}
			if (obj[i].AdministrativeArea != undefined) {
				//$('input:hidden[name=state]').val(obj[i].AdministrativeArea.AdministrativeAreaName);
				ths_state = obj[i].AdministrativeArea.AdministrativeAreaName
			}
			if (obj[i].Locality != undefined) {
				//$('input:hidden[name=city]').val(obj[i].Locality.LocalityName);
				ths_city = obj[i].Locality.LocalityName;
			}
			walkGeoCodeObj(obj[i],indent);
		}
	}
	//return names;
}

function dN() {
	var foo = "bar";
}

function showObjInfo(obj) {
	var names = '';
	for (var i in obj) {
		names += i + '\n';
	}
	return names;
}

function setMLS ( mls ) {
	
	var mlsFull = '';
	
	if (mls == 	1) { mlsFull = "Northwest"; }
	if (mls == 	2) { mlsFull = "Spokane"; }
	if (mls == 	3) { mlsFull = "Portland"; }
	if (mls == 	4) { mlsFull = "na4"; }
	if (mls == 	5) { mlsFull = "Whatcom"; }
	if (mls == 	6) { mlsFull = "Boise"; }
	if (mls == 	7) { mlsFull = "Santa Clara"; }
	if (mls == 	8) { mlsFull = "Walla Walla"; }
	if (mls == 	9) { mlsFull = "Medford"; }
	if (mls == 	10) { mlsFull = "Palm Springs"; }
	if (mls == 	11) { mlsFull = "na11"; }
	if (mls == 	12) { mlsFull = "Arizona"; }
	if (mls == 	13) { mlsFull = "Bend"; }
	if (mls == 	14) { mlsFull = "Lincoln"; }
	if (mls == 	15) { mlsFull = "na15"; }
	if (mls == 	16) { mlsFull = "San Diego"; }
	if (mls == 	17) { mlsFull = "Yakima"; }
	if (mls == 	18) { mlsFull = "Sun Valley"; }
	if (mls == 	19) { mlsFull = "Tri Cities"; }
	if (mls == 	20) { mlsFull = "Salem"; }
	if (mls == 	21) { mlsFull = "Pleasanton"; }
	if (mls == 	22) { mlsFull = "Tucson"; }
	if (mls == 	23) { mlsFull = "Las Vegas"; }
	if (mls == 	24) { mlsFull = "Shasta"; }
	if (mls == 	25) { mlsFull = "Commercial"; }
	if (mls == 	26) { mlsFull = "Commercial Manual"; }
	if (mls == 	27) { mlsFull = "Teton"; }
	if (mls == 	28) { mlsFull = "Prescott"; }
	if (mls == 	29) { mlsFull = "Bay Area"; }
	if (mls == 	30) { mlsFull = "Park City"; }
	if (mls == 	31) { mlsFull = "Wasatch"; }
	if (mls == 	32) { mlsFull = "Claw"; }
	if (mls == 	33) { mlsFull = "Sedona"; }
	if (mls == 	34) { mlsFull = "Missoula"; }
	if (mls == 	35) { mlsFull = "Northwest Montana"; }
	if (mls == 	36) { mlsFull = "Northeast Washington"; }
	if (mls == 	37) { mlsFull = "Whitman"; }
	if (mls == 	38) { mlsFull = "Wenatchee"; }
	if (mls == 	39) { mlsFull = "Lc"; }
	if (mls == 	40) { mlsFull = "Coeur d alene"; }
	if (mls == 	41) { mlsFull = "Selkirk"; }
	if (mls == 	42) { mlsFull = "Latah"; }
	if (mls == 	43) { mlsFull = "Clatsop"; }
	if (mls == 	44) { mlsFull = "Klamath"; }
	if (mls == 	45) { mlsFull = "Tillamook"; }
	if (mls == 	46) { mlsFull = "BC"; }
	if (mls == 	47) { mlsFull = "Rancho"; }
	if (mls == 	48) { mlsFull = "Crisnet"; }
	if (mls == 	49) { mlsFull = "East Bay"; }
	if (mls == 	50) { mlsFull = "Gallatin"; }
	if (mls == 	51) { mlsFull = "Hawaii"; }
	if (mls == 	52) { mlsFull = "Reno"; }
	if (mls == 	53) { mlsFull = "Santa Barbara"; }
	if (mls == 	54) { mlsFull = "Helena"; }
	if (mls == 	55) { mlsFull = "na55"; }
	if (mls == 	56) { mlsFull = "Chelan"; }
	if (mls == 	57) { mlsFull = "Sacramento"; }
	if (mls == 	58) { mlsFull = "McCall"; }
	if (mls == 	59) { mlsFull = "Washington County"; }
	if (mls == 	60) { mlsFull = "Bitterroot"; }
	if (mls == 	61) { mlsFull = "Arrowhead"; }
	if (mls == 	62) { mlsFull = "San Francisco"; }
	
	return mlsFull + ' MLS';
	
}

function removedollar(str) {
	re = /^\$|,/g;
	return str.replace(re, "");
}


function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num);
}

