var map = null, geocoder = null;
var bounds = null, closest_marker = null;
var terr_infos = null;

var shadow_icon = '/img4/temp/shadow.png';
var mouseover_icon = '/img4/h_circle_box.png';
var mouseout_icon = '/img4/temp/blue_marker.png';
var mouseout_nearest_icon = '/img4/temp/blue_marker.png';

var price_range_icon = ['/img4/heatmap-v5/0.png',
			'/img4/heatmap-v5/100.png',
			'/img4/heatmap-v5/200.png',
			'/img4/heatmap-v5/300.png',
			'/img4/heatmap-v5/400.png',
			'/img4/heatmap-v5/500.png',
			'/img4/heatmap-v5/600.png',
			'/img4/heatmap-v5/700.png',
			'/img4/heatmap-v5/800.png',
			'/img4/heatmap-v5/1000.png'];

var price_range = [ [0,100000],
			[100001,200000],
			[200001,300000],
			[300001,400000],
			[400001,500000],
			[500001,600000],
			[600001,700000],
			[700001,800000],
			[800001,1000000],
			[1000001,100000000]];
										
function getPriceRangeIcon(price)
{
	if(price) {
		var priceInt = parseInt(price.replace(/[^0-9]/g,""));
		for (var i=0; i<price_range.length; ++i ){
			if(priceInt > price_range[i][0] && priceInt < price_range[i][1]) {
				return price_range_icon[i];
			}
		}
	}
	return price_range_icon[4];
}

function createMarker(point, html, link, i, price) {
	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = shadow_icon;
	baseIcon.iconSize = new GSize(20, 27);
	baseIcon.shadowSize = new GSize(37, 27);
	var custIcon = new GIcon(baseIcon);
	var icon = getPriceRangeIcon(price);
	custIcon.image = icon;
	markerOptions = { icon:custIcon };
	var marker = null, label = null;
	marker = new GMarker(point, markerOptions);
	marker.i = i;
	marker.sRow = '#row'+i;
	marker.icon = icon;
	var attachment;
	var center = bounds.getCenter();
	if(point.lat() > center.lat()) {
		if(point.lng() > center.lng())
			attachment = 'ne';
		else
			attachment = 'nw';
	}
	else {
		if(point.lng() > center.lng())
			attachment = 'se';		
		else
			attachment = 'sw';		
	}
	label = new BpLabel(point,html,'myLabelClass',attachment, true);
	marker.tltp = label;
	map.addOverlay(label);
	GEvent.addListener(marker, "click", function() {
		//this.openInfoWindowHtml(html);
		window.location = link;
	});
	
	GEvent.addListener(marker, 'mouseover', function(ll){
		jQuery(""+this.sRow).addClass('over');
		this.setImage(mouseover_icon);
		this.tltp.show();
		//this.openInfoWindowHtml(html);
	});
	
	GEvent.addListener(marker, 'mouseout', function(ll){
		jQuery(""+this.sRow).removeClass('over');
		this.setImage(this.icon);
		this.tltp.hide();
		//map.closeInfoWindow();
	});
	
	jQuery(''+marker.sRow).data("marker", marker);
	return marker;
}

function addAllMarkers() {
	if(terr_infos.length != 0) {
		var points = new Array(terr_infos.length);

		for (i in terr_infos) {
			var point = new GLatLng (terr_infos[i][3], terr_infos[i][4]);
			bounds.extend(point);
			points[i] = point;
		}
	
		for (i in terr_infos) {
			var terr_info = terr_infos[i];
			var terr_name = terr_info[1];
			var terr_link = terr_info[2];
			var info_html = 
				'<div>' +
				'<strong style="font-size:14px;">'+ terr_info[1] +'<\/strong><br\/>' +
				'<p><b>average home price*:<\/b> '+ terr_info[10] + '<\/p>' +
				'<p><b>average sqft*:<\/b> '+ terr_info[11] + '<\/p>';
				//+ '<p><b>Agent:<\/b> '+ terr_info[6] + ' ' + terr_info[7] + ', ' + terr_info[8] + '<\/p>' +				
				//'<p><b>phone:<\/b> '+ terr_info[9] + '<\/p>';
			
			//if(terr_info[2] != "") info_html += '<br/><p><a href="'+ terr_link +'">view all listings in this area<\/a><\/p>';
			if(terr_info[2] != "") info_html += '<br/><p>click to view all listings in the area<\/p>';
				
			info_html += '<\/div>';
			
			var point = points[i];
			var marker = createMarker(point, info_html, terr_link, i, terr_info[10]);
			if (marker != null) {
				map.addOverlay(marker);
				//bounds.extend(point);
			}
		}
		var center = bounds.getCenter();
		map.setCenter(center, map.getBoundsZoomLevel(bounds));
	}
	else {
		if((cur_lat!=0) || (cur_long!=0)) {
			var point = new GLatLng (cur_lat, cur_long);
			//var marker = createMarker(point, "", "center", 0);
			//if (marker != null) {
			//	map.addOverlay(marker);
			//}
			map.setCenter(point, 11);
		}
	}
}

function bindBehaviors() {
	jQuery('.terr_row0,.terr_row1').hover(
		function(){
			var $this = jQuery(this);
			$this.addClass('over');
			var marker = $this.data("marker");
			marker.setImage(mouseover_icon);
			marker.tltp.show();
			//GEvent.trigger(marker, 'click');
		},
		function(){
			var $this = jQuery(this);
			$this.removeClass('over');
			var marker = $this.data("marker");
			marker.setImage(marker.icon);
			marker.tltp.hide();
		}
	);
}

function initMap() {
	bindBehaviors();
	if (map) {
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		bounds = new GLatLngBounds;
		if((cur_lat==0) && (cur_long==0)) map.setCenter(new GLatLng(38, -97),3);
		else map.setCenter(new GLatLng(cur_lat,cur_long),8);
		addAllMarkers();
		//GEvent.trigger(closest_marker, 'click');
	} 
}


function createMap()
{
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("terr_map"));
		geocoder = new GClientGeocoder();
	}
	else {
		mapObject = document.getElementById("terr_map");
		mapObject.innerHtml = "<p>Sorry, the Google Maps API is not compatible with this browser</p>";
		//alert("Sorry, the Google Maps API is not compatible with this browser");
	}
}

function process_city_list(city_list_string)
{
	if (!city_list_string || city_list_string.length == 0) {		
		jQuery("#result_message").hide();
		jQuery("#error_message").show();
	}
	else {
		jQuery("#result_message").show();
		jQuery("#error_message").hide();
	
		var city_lists = city_list_string.split("\n");
		terr_infos = new Array(city_lists.length);

		var row_no = 0;
		var count = 0;
		
		var tbody_html = "";
				
		for (i in city_lists) {
			if (city_lists[i] && city_lists[i].length != 0) {
				var terr_info = city_lists[i].split("|");
				terr_infos[i] = terr_info;
			
				var city_distance = terr_info[12];
				var city_search_url = terr_info[2];
				var city_name = terr_info[1];
				var city_name_short = city_name.substr(0, 30);
				var avg_sqft = terr_info[11];
				var avg_price = terr_info[10];
			
				var tr_html = "<tr class=\"terr_row" + row_no + "\" id=\"row"+ count + "\">";
			
				tr_html += "<td align=\"right\">" + city_distance + " mi &nbsp;</td>"; //printf("%01.1f", $city_distance);
				
				tr_html += "<td align=\"left\" style=\"padding-left:5px\">";
				if (city_search_url.length != 0)
					tr_html += "<a href=\"" + city_search_url +"\" title=\"" + city_name + "\">" + city_name_short + "</a>";
				else 
					tr_html += city_name_short;
				tr_html += "</td>";
				
				tr_html += "<td align=\"right\">" + avg_sqft + "&nbsp;</td>"; // number_format($avg_sqft,0);
				tr_html += "<td align=\"right\">" + avg_price + "&nbsp;</td>"; // number_format($avg_price,0);
				tr_html += "<td align=\"center\">";
				if (city_search_url.length != 0)
					tr_html += "<a href=\"" + city_search_url + "\">View Homes</a>";
				tr_html += "</td>";
				
				tr_html += "</tr>\n";
				//alert(tr_html);

				tbody_html += tr_html;

				row_no = (row_no+1)%2;
				count++;
			}
		}

		jQuery("#city_count").html(count);
		jQuery(".terr_table tbody").html(tbody_html);
		initMap();
		sortTable();
	}
	jQuery("#loader_msg").hide();
}

function process_geopoint(point)
{	
	cur_lat = point.lat();
	cur_long = point.lng();

	var url = "http://www.househunt.com/radius-search/terr_map_city_list.php";
	url += "?lat="+cur_lat+"&long="+cur_long+"&distance_limit="+distance_limit;
	url += "&search_script="+search_script+"&from_script="+from_script;
	
	jQuery.get(url, function(data) {
		process_city_list(data);
	}); 
}

function process_address(address)
{
	if(geocoder) {
		geocoder.getLatLng(address, function(point) {
			process_geopoint(point);
		});
	}
}

// add parser through the tablesorter addParser method 
$.tablesorter.addParser({ 
	// set a unique id 
	id: 'miles', 
	is: function(s) { 
		// return false so this parser is not auto detected 
		return false; 
	}, 
	format: function(s) { 
		// format your data for normalization 
		//return s.replace(/ mi./,'');
		return s.substr(0, s.length-4);
	}, 
	// set type, either numeric or text 
	type: 'numeric' 
}); 

function sortTable()
{
	if ($(".terr_table tbody").length != 0 &&
		$(".terr_table tbody").html() != null &&
		$(".terr_table tbody").html() != "") {		
		
		$(".terr_table")
		.tablesorter({
			// sort on the first column and third column, order asc
			sortList: [[0,0]],
			headers: {
				0: {
					sorter: 'miles'
				},
				4: { 
					sorter: false 
				}
			},
			widgets: ['zebra']
		})
		.tablesorterPager({container: $("#pager"), size: 20})
	}
}

$(document).ready(function() 
	{
		createMap();
		process_address(address);
	}
); 
    

