//39.537, -119.788 is I80 & Hwy 395 intersection 
var center_latlng = new GLatLng (39.537, -119.788);
//var search_latlng = new GLatLng (39.525, -119.78); // off center
var search_latlng = new GLatLng (39.525, -119.78);
var startZoom = 13;
var radius = 20;
var bedrooms = "09"; // any
var search_address = "";

var map;
var geocoder;
var iter = 0;
var max_iter = 120;
//max_iter = 2; // for speeding up debugging
// Start from today
var full_date = new Date ();
var temp_month = full_date.getMonth () + 1; // months start with 0
var cur_date = full_date.getFullYear () + '-' + temp_month + '-' + full_date.getDate();
//cur_date = '2007-11-19'; // for debugging

var one_day_in_ms = 60 * 1000 *60 * 24;
// Make last_search_date 1 month before toady to reduce loading time of first page
var one_months_ago = new Date ();
one_months_ago.setTime (one_months_ago.getTime () - one_day_in_ms * 30);
var temp_month = one_months_ago.getMonth () + 1; // months start with 0
var one_months_ago_string = one_months_ago.getFullYear () + '-' + temp_month + '-' + one_months_ago.getDate(); 

var two_months_ago = new Date ();
two_months_ago.setTime (two_months_ago.getTime () - one_day_in_ms * 61);
temp_month = two_months_ago.getMonth () + 1; // months start with 0
var two_months_ago_string = two_months_ago.getFullYear () + '-' + temp_month + '-' + two_months_ago.getDate(); 

var three_months_ago = new Date ();
three_months_ago.setTime (three_months_ago.getTime () - one_day_in_ms * 61);
temp_month = three_months_ago.getMonth () + 1; // months start with 0
var three_months_ago_string = three_months_ago.getFullYear () + '-' + temp_month + '-' + three_months_ago.getDate(); 

var six_months_ago = new Date ();
six_months_ago.setTime (six_months_ago.getTime () - one_day_in_ms * 182);
temp_month = six_months_ago.getMonth () + 1; // months start with 0
var six_months_ago_string = six_months_ago.getFullYear () + '-' + temp_month + '-' + six_months_ago.getDate(); 

var nine_months_ago = new Date ();
nine_months_ago.setTime (nine_months_ago.getTime () - one_day_in_ms * 243);
temp_month = nine_months_ago.getMonth () + 1; // months start with 0
var nine_months_ago_string = nine_months_ago.getFullYear () + '-' + temp_month + '-' + nine_months_ago.getDate(); 

var last_search_date = two_months_ago_string; 

var request_date = cur_date;
var request_index = 0;
var icons = new Array ();

var user_id = 0;
var user_name = "";
var marker_window_showing = false;
var marker_quote = 1;
var d1, d2;
//var comp_file = 'retrieve_markers_test.php';
//var oodle_file = 'retrieve_oodle_markers_test.php';
var comp_file = 'retrieve_markers.php';
var oodle_file = 'retrieve_oodle_markers.php';

var search_overlays = new Array ();

// Oodle variables
var cur_oodle_ad = 0;
var oodle_total = 0;
var oodle_icons = new Array ();

var lat_points = new Array ();
var lng_points = new Array ();
var marker_count = 0;

var search_count = 0;

window.onload = init;

function init() {
		geocoder = new GClientGeocoder();
    map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(center_latlng, startZoom);
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
		map.addControl(new GScaleControl(90)); // displays a scale bar with a maximum length of x pixels, where x defaults to 125. 

    //----- Stop page scrolling if wheel over map ----
    function wheelevent(e) {
        if (!e)
						e = window.event;
        if (e.preventDefault)
						e.preventDefault();
        e.returnValue = false;
    }
		GEvent.addDomListener(map.getContainer(), "DOMMouseScroll", wheelevent);
		map.getContainer().onmousewheel = wheelevent; 

    GEvent.addListener(map, 'click', function(overlay, latlng) {
				//only perform the click if the window is closed and the click was directly on the map.
				if(!overlay) {
						//alert (search_latlng);
						openSearchWindow (latlng, 0)
				}
		});

		addCustomControls ();

		retrieveOodleAds ();
}

function retrieveOodleAds () {
		var request = GXmlHttp.create();
		window.status = cur_oodle_ad;
		// tell the request where to retrieve data from.
		request.open('GET', 'RentalRates/' + oodle_file + '?i=' + cur_oodle_ad
								 + '&c=housing/rent/home' + '&la=' + search_latlng.lat() + '&ln=' + search_latlng.lng()
								 + '&r=' + radius + "&b=" + bedrooms + '&sr=' + search_count, true);
		
		//tell the request what to do when the state changes.
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
					processResults (request, 'oodle');
					cur_oodle_ad = parseInt (d1, 10);
					oodle_total = parseInt (d2, 10);
					//alert ('cur_oodle_ad=' + cur_oodle_ad + ' oodle_total=' + oodle_total);
					// Now that the the previous request is complete, do new request
					if (++iter < max_iter) {// for debugging to spead things up
							if (cur_oodle_ad < oodle_total) {  // Make sure these are integers, otherwise "402" > "3306" as strings
								setTimeout ("retrieveOodleAds ()", 1000); // wait a little before doing it again
							} else {
								//alert ('All done!');
							}
					} else
							iter = 0;
		
			} //if
		} //function
		request.send(null);			
}

function processResults (request, marker_type) {	
		var xmlObj;
		var xmlDoc = request.responseXML;
		if (xmlDoc)
				xmlObj = xmlDoc.documentElement;
		if (!xmlObj) {
				if (user_id == 1) alert ('xmlObj = 0');
		}
		else {
				var result_status = xmlObj.getElementsByTagName("rs"); // rs = result_status
				if (!result_status[0]) {
						//if (user_id == 1)
						//		alert ('result_status[0] = 0');
				}	else {
						var request_status = parseInt (result_status[0].getAttribute("st")); // st = status
						d1 = result_status[0].getAttribute("d1");
				
						// This will also get rid of results of prevoius search
						if (request_status == search_count) {
								d2 = result_status[0].getAttribute("d2");
								//alert (request_status + ' ' + d1 + ' ' + d2);
								
								var markers = xmlObj.getElementsByTagName("m"); // m = marker
								// It's possible to have no marker at all
								for (var i = 0; i < markers.length; i++) {
										var marker_lng = parseFloat (markers[i].getAttribute("Ln"));
										var marker_lat = parseFloat (markers[i].getAttribute("La"));
										var price = parseInt (markers[i].getAttribute("Pr"), 10); // Pr = Price
										var br = parseInt (markers[i].getAttribute("BR"), 10);
										// Decode header
										var title = decodeURIComponent (markers[i].getAttribute("Tl")); // Tl = Title
										// Don't change format of date, since it's used to get post details
										var date = markers[i].getAttribute("Dt"); // Dt = Date
										// Create date in format mm/dd/yyyy
										var date_fields = date.split ("-");
										var date_string = date_fields[1] + "/" + date_fields[2] + "/" + date_fields[0];
										//alert ("date_string = " + date_string); // hard to get rid of this alert
										var post_id = markers[i].getAttribute("ID");
										// URL is coming only from OOdle
										var post_url = decodeURIComponent (markers[i].getAttribute("URL"));
										if (price && marker_lng && marker_lat) {
												var marker_title = '$' + price + '/mo';
												if (marker_quote > 0) {
														if (br > 0) {
																marker_title += ', ' + br + ' bd';
																if (br > 1)
																		marker_title += 's';                            
														}
														var title_link = '<a href="';
														if (post_id > 0)
																title_link += 'RentalRates/post_details.php?i=' + post_id
																		+ '&d=' + date + '&u=' + user_id;
														else // It's Oodle's ad, just use URL
																title_link += post_url;
														
														title_link += '" target="_blank">' + title + '</a>';
														var html = '<div><b>' + marker_title + '</b></div><div>'
																		 + title_link + '</div><div>Posted: ' + date_string + '</div>';
														marker_title += ', ' + date_string;
												}
												else {
														// Only unregistered users will get here
														var html = '<div><b><a href="user">Login</a> or '
																+ '<a href="user/register">Register</a> to see full details.<BR>'
																+ "It's free and easy.</div>";
												}
												var marker_latlng = makeUniquePoint (marker_lat, marker_lng);
												createMarker (marker_latlng, html, price, marker_title, marker_type);
												marker_count++;
										}           
								} //for
						} // if
				} // if
		}
}


// Make sure that no point overlaps another point
// This is the order in which point location will change
/*
												X
         -6 -5 -4 -3 -2 -1  0  1  2  3  4  5
      5              73 74 75 76 77 
      4           72 47 48 49 50 51 78
		  3        71 46    28 29 30    52 79
			2	 99 70 45    27 14 15 16 31    53 80
			1	 98 69 44 26 13 04 05 06 17 32 54 81
	  Y 0  97 68 43 25 12 03 00 07 18 33 55 82
		 -1	 96 67 42 24 11 02 01 08 19 34 56 83
		 -2	 95 66 41    23 10 09 20 35    57 84
		 -3     94 65 40    22 21 36    58 85 
		 -4        93 64 39 38 37    59 86
		 -5           92 63 62 61 60 87
     -6              91 90 89 88
     
//   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24
//X  0,  0, -1, -1, -1,  0,  1,  1,  1,  0, -1, -2, -2, -2, -1,  0,  1,  2,  2,  2,  1,  0, -1, -2, -3, 
//Y  0, -1, -1,  0,  1,  1,  1,  0, -1, -2, -2, -1,  0,  1,  2,  2,  2,  1,  0, -1, -2, -3, -3, -2, -1,

//  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49
//X -3, -3, -2, -1,  0,  1,  2,  3,  3,  3,  2,  1,  0, -1, -2, -3, -4, -4, -4, -4, -4, -3, -2, -1,  0, 
//Y  0,  1,  2,  3,  3,  3,  2,  1,  0, -1, -2, -3, -4, -4, -4, -3, -2, -1,  0,  1,  2,  3,  4,  4,  4,

//  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74
//X  1,  2,  3,  4,  4,  4,  4,  4,  3,  2,  1,  0, -1, -2, -3, -4, -5, -5, -5, -5, -5, -4, -3, -2, -1,
//Y  4,  4,  3,  2,  1,  0, -1, -2, -3, -4, -5, -5, -5, -5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5,  5,

//  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99  
//X  0,  1,  2,  3,  4,  5,  5,  5,  5,  5,  4,  3,  2,  1,  0, -1, -2, -3, -4, -5, -6, -6, -6, -6, -6
//Y  5,  5,  5,  4,  3,  2,  1,  0, -1, -2, -3, -4, -5, -6, -6, -6, -6, -5, -4, -3, -2, -1,  0,  1,  2
*/ 				 
function makeUniquePoint (lat, lng) {
  var x = new Array ( 0,  0, -1, -1, -1,  0,  1,  1,  1,  0, -1, -2, -2, -2, -1,  0,  1,  2,  2,  2,  1,  0, -1, -2, -3,
										 -3, -3, -2, -1,  0,  1,  2,  3,  3,  3,  2,  1,  0, -1, -2, -3, -4, -4, -4, -4, -4, -3, -2, -1,  0,
										  1,  2,  3,  4,  4,  4,  4,  4,  3,  2,  1,  0, -1, -2, -3, -4, -5, -5, -5, -5, -5, -4, -3, -2, -1,
										  0,  1,  2,  3,  4,  5,  5,  5,  5,  5,  4,  3,  2,  1,  0, -1, -2, -3, -4, -5, -6, -6, -6, -6, -6);
  var y = new Array ( 0, -1, -1,  0,  1,  1,  1,  0, -1, -2, -2, -1,  0,  1,  2,  2,  2,  1,  0, -1, -2, -3, -3, -2, -1,
										  0,  1,  2,  3,  3,  3,  2,  1,  0, -1, -2, -3, -4, -4, -4, -3, -2, -1,  0,  1,  2,  3,  4,  4,  4,
										  4,  4,  3,  2,  1,  0, -1, -2, -3, -4, -5, -5, -5, -5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5,  5,
										  5,  5,  5,  4,  3,  2,  1,  0, -1, -2, -3, -4, -5, -6, -6, -6, -6, -5, -4, -3, -2, -1,  0,  1,  2);
	var point_exists = 0;
	var multiplier_lat = 8500; // this determines how far apart are markers
	var multiplier_lng = 7000; // this determines how far apart are markers
	var original_lat = parseInt (lat * multiplier_lat);
	var original_lng = parseInt (lng * multiplier_lng);
  var number_of_changes = x.length; 
	var run_out = 0;
	for (var change = 0; change < number_of_changes; change++) {
		point_exists = 0;
		var discrete_lat = parseInt (lat * multiplier_lat);
		var discrete_lng = parseInt (lng * multiplier_lng);
		for (var m = 0; m < marker_count; m++) {
			if (discrete_lat == lat_points [m] && discrete_lng == lng_points [m]) { 
				//alert ("Point like this already exists:" + discrete_lat + ", " + discrete_lat);
				// Point like this already exists, change location randomly
		    // Instead of modifying location permanently, just change location on the map
				lat = (original_lat + y [change]) / multiplier_lat;
				lng = (original_lng + x [change]) / multiplier_lng;
				point_exists = 1;
				break;
			}
		}
		if (point_exists == 0)
			break;
		else {
			// if we ran out of changes, move origin and try more changes
			if (change == number_of_changes - 1) {
			  // Start over
				change = 0;
				run_out++;
				original_lat += 2 * y [run_out];
				original_lng += 2 * x [run_out];
			}
		}
	}
	
	// Store descrete marker location
	lat_points [marker_count] = parseInt (lat * multiplier_lat)
	lng_points [marker_count] = parseInt (lng * multiplier_lng)

  return new GLatLng (lat_points [marker_count] / multiplier_lat, lng_points [marker_count] / multiplier_lng);
}

function createMarker (marker_latlng, html, price_string, marker_title, marker_type) {
		//alert (marker_type);
		var marker;
		var marker_opts;
		var price = parseInt (parseInt (price_string, 10) / 100, 10) * 100;
		if (price > 2700) price = 2700;
		if (price < 300) price = 300;
		
		if (marker_type == 'oodle') {			
				var icons_type = 'files/Icons_oodle/';
				// Define new icon only if it doesn't exist already
				if (oodle_icons [price] == undefined) {
						oodle_icons [price] = new GIcon();
						var image_url = icons_type + price + '.png';
						oodle_icons [price].image = image_url; 
						oodle_icons [price].iconSize = new GSize(16, 16);
						oodle_icons [price].iconAnchor = new GPoint(8, 8);
						oodle_icons [price].infoWindowAnchor = new GPoint(15, 1);
				}
				marker_opts = { icon : oodle_icons [price],
												title : marker_title };
		} else {
				var icons_type = 'files/Icons_round/';
				// Define new icon only if it doesn't exist already
				if (icons [price] == undefined) {
						icons [price] = new GIcon();
						var image_url = icons_type + price + '.png';
						icons [price].image = image_url; 
						icons [price].iconSize = new GSize(16, 16);
						icons [price].iconAnchor = new GPoint(8, 8);
						icons [price].infoWindowAnchor = new GPoint(15, 1);
				}
				marker_opts = { icon : icons [price],
												title : marker_title };
		}
		
		if (marker_type == 'copms_center') {
				marker = new GMarker(marker_latlng);
		} else {
				marker = new GMarker(marker_latlng, marker_opts);
		}
		GEvent.addListener(marker, 'click', function() {
				marker.openInfoWindowHtml(html, { noCloseOnClick : true });
		});
		GEvent.addListener(marker, 'infowindowopen', function() {
				marker_window_showing = true;
		});
		GEvent.addListener(marker, 'infowindowbeforeclose', function() {
				marker_window_showing = false;
		});

		map.addOverlay (marker);
		// Save markers so that later they could be removed from the map
		if (marker_type == 'comps' || marker_type == 'copms_center' || marker_type == 'oodle')
				search_overlays [search_overlays.length] = marker;
}

function addCustomControls () {
    // Explain heatmap
		function HeatMapLegendControl() {}
		HeatMapLegendControl.prototype = new GControl();
		HeatMapLegendControl.prototype.initialize = function() {
				var contents = document.createElement("div");
				contents.innerHTML='<img style="border:none;" src = "files/Heat_map_legend.png" alt="Rental Rates HeatMap Legend"/>';
				document.getElementById('map').appendChild(contents);
				return contents;
		}
		HeatMapLegendControl.prototype.getDefaultPosition=function(){
				return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 40));
		}
		HeatMapLegendControl.prototype.selectable=function(){return true};
		HeatMapLegendControl.prototype.printable=function(){return true};
		map.addControl(new HeatMapLegendControl());
}

