// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var centerLatitude = 43.471708;
var centerLongitude = -80.543197;
var startZoom = 13;
var boundaries = new GLatLngBounds(new GLatLng(43.445799, -80.594072),new GLatLng(43.490678, -80.494381));
var busRoutes = new GGroundOverlay("/images/bus_route.png",boundaries);
var curr = 0;
var map; // Main big map
var markersLoaded=[]; // Markers currently on map
var infoWindows=[]; // array of information bubbles 
var markerInFocus; // current marker in focus
var uploadMap; // map in upload form
var geocoder; // geocoder for upload form

// Local Search variables
var gLocalSearch;
var gCurrentResults = [];
var gSelectedResults = [];
var gSearchForm;
var gSmallIcon = null;

// Map mouse over variables
var markerInFocusIcon = "/images/markers/lqpaleblue_Marker.png";
var markerNotInFocusIcon = "/images/markers/lqred_Marker.png";
var rowStyle = ""

/******** Helper Functions ************/
function toggleExtraInfo (id)
{
	var extraInfoDiv = document.getElementById(id+'_ExtraInfo');
	var arrowCollapsed = document.getElementById(id+'_ArrowCollapsed');
	var arrowExpanded = document.getElementById(id+'_ArrowExpanded');
	if (extraInfoDiv.style.display != "none")
	{
		//Effect.SlideUp(id, {duration: 0.5});
		extraInfoDiv.style.display = "none";
		arrowCollapsed.style.display = "";
		arrowExpanded.style.display = "none";
	}	
	else
	{
		//Effect.SlideDown(id,{duration: 0.5});
		extraInfoDiv.style.display = "";
		arrowCollapsed.style.display = "none";
		arrowExpanded.style.display = "";
		
	}
	
}

String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/, "");
}

// Calculate distance from waterloo to a house. 
// This uses the Haversine formula
function calculateDistance (lat, lng)
{
	var R = 6371; // km
	var lat1 = parseFloat(lat);
	var lng1 = parseFloat(lng);
	var dLat = (centerLatitude - lat1) * Math.PI / 360;
	var dLon = (centerLongitude - lng1) * Math.PI / 360;
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	        Math.cos(centerLatitude * Math.PI / 360) * Math.cos(lat1 * Math.PI / 360) * 
	       Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c;
	d = d * 1000;
	return d;
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}


function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}




function toggleMap (toggle)
{
	//toggle = document.getElementById("toggleMapCheckBox");
	if (toggle.checked == true)
	{
		map.addOverlay(busRoutes);
		createCookie('bus', true, 1);
		
	}
	else
	{
		map.removeOverlay(busRoutes);
		eraseCookie('bus');
	
	}
}


function disablePan(toggle)
{
	if (toggle.checked == true)
	{
		//map.addOverlay(busRoutes);
		createCookie('pan', true, 1);
		
	}
	else
	{
		//map.removeOverlay(busRoutes);
		eraseCookie('pan');
	
	}
}




/******** End Common Functions ********/


/******** Roll Over Functions  ********/

function focusMarker (tooltip)
{
	var skipFocus = document.getElementById("disableMapMovement");	
	var i = 0;
	for (i = 0;i<markersLoaded.length;i++)
	{
		if (markersLoaded[i].getTitle() == tooltip && (markerInFocus != markersLoaded[i] || markerInFocus == null))
		{
			markerInFocus = markersLoaded[i];
			//markersLoaded[i].openInfoWindowHtml(infoWindows[i]);
			markerInFocus.setImage(markerInFocusIcon);
			if (skipFocus.checked == 0) //more efficient than reading cookies? probably yes
			{
				map.panTo(markersLoaded[i].getLatLng());
			}
			// switchColour(markerInFocus);
		}
	}
}

function focusPropertyRow (id)
{
	var row = document.getElementById(id);
	var style = row.className;
	row.className = "highlight" + style;
}

function unFocusPropertyRow (id)
{
	var row = document.getElementById(id);
	var style = row.className;
	if (style.indexOf("even") != -1)
	{
		row.className="even";
	}
	else
	{
		row.className="odd";
	}
//	row.className = style.substring(9);	
}

function unFocusMarker ()
{
	if (markerInFocus != null)
	{
		markerInFocus.setImage(markerNotInFocusIcon);
		markerInFocus = null;
	}
}

/******** End Roll Over Functions *****/

function addEvents (marker, id, description)
{
	GEvent.addListener(marker,"mouseover", 
							function() 
							{								
								marker.setImage(markerInFocusIcon);
								//marker.openInfoWindowHtml(description);								
								focusPropertyRow(id);
							});
	
	GEvent.addListener(marker,"mouseout", 
							function() 
							{
								marker.setImage(markerNotInFocusIcon);
								unFocusPropertyRow(id);
								//marker.closeInfoWindow();
							});
	GEvent.addListener(marker, 'click',
							function() 
							{
								marker.openInfoWindowHtml(description);
								//window.open('/property/show/' + id,'','');
							}
					);
	GEvent.addListener(marker, 'dblclick',
							function() 
							{
								marker.closeInfoWindow();
							}
					);
	return marker;
}

function addProperty(lat, lng, description, tooltip, id) 
{
	var address = location.href;
	var redIcon = new GIcon(G_DEFAULT_ICON);
	redIcon.image = markerNotInFocusIcon;
	var markerOptions = {title:tooltip, icon:redIcon};
	
	var marker = new GMarker(new GLatLng(lat, lng), markerOptions);
	if (address.indexOf("/property",0) != -1)
	{
		map.setCenter (marker.getLatLng(), startZoom);
	}
	else
	{	
		marker = addEvents(marker, id, description);
	}
	map.addOverlay(marker);
	markersLoaded.push(marker);;
	infoWindows.push(description);
	return marker;
}
    
function initMap() 
{
	if (map != null)
	{
		map.clearOverlays();
	}
	map = new GMap2(document.getElementById("map"));
	
	// Set map center
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	
	// Set various map controls
	// map.addControl(new GLargeMapControl());
	// map.addControl(new GMapTypeControl());
	map.addControl(new GSmallMapControl());	
	
	// Create options for local search	
	if ((location.href).indexOf("search") != -1 || (location.href).indexOf("property") == -1 || (location.href).indexOf("my_property") != -1)
	{
		/*
		var options = {
	    	resultList : document.getElementById("test"),
			suppressInitialResultSelection : true,
			suppressZoomToBounds : true,
			searchFormHint : "Search Coffee"
	  	};
		map.addControl(new google.maps.LocalSearch(options));
		*/

		// Initialize search bar		
		gSearchForm = new google.search.SearchForm(false, document.getElementById("searchform"));
		gSearchForm.setOnSubmitCallback(null, CaptureForm);
		gSearchForm.input.focus();

		
		// Initialize the local searcher
		gLocalSearch = new google.search.LocalSearch();
		gLocalSearch.setCenterPoint(map);
		gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
		gLocalSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET);		
		
		gSmallIcon = new google.maps.Icon();
      	gSmallIcon.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";
      	gSmallIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
      	gSmallIcon.iconSize = new google.maps.Size(12, 20);
      	gSmallIcon.shadowSize = new google.maps.Size(22, 20);
      	gSmallIcon.iconAnchor = new google.maps.Point(6, 20);
      	gSmallIcon.infoWindowAnchor = new google.maps.Point(5, 1);
      	
      
	}

	// set up globals
	markersLoaded=[]; // Markers currently on map
	infoWindows=[]; // array of information bubbles 
	markerInFocus = null; // current marker in focus
	
	// List all properties
	var address = location.href;
	 	
	if (address.indexOf("user",0) != -1 && address.indexOf("short_list",0) != -1)
	{
		var page = address.substring (address.lastIndexOf("page=")+5, address.lastIndexOf("page=")+6);
		if (address.lastIndexOf("page=") != -1)
		{
			plotMarkers("plot_my_short_list/" + page);
		}
		else
		{
			plotMarkers("plot_my_short_list/1");
		}
	}
	else if (address.indexOf("user",0) != -1 && address.indexOf("my_property",0) != -1)
	{
		plotMarkers("plot_my_property_list");
	}
	else if (address.indexOf("site", 0) != -1 && address.indexOf("search?", 0) != -1)
	{
		var page = address.substring (address.lastIndexOf("page=")+5, address.lastIndexOf("page=")+6);
		if (address.lastIndexOf("page=") != -1)
		{
			plotMarkers("plotSearchResults/" + page);
		}
		else
		{
			plotMarkers("plotSearchResults/1");
		}
	}
	else if (address.indexOf("property",0) != -1)
	{
		var pid = address.substring (address.lastIndexOf("/"));
		plotMarkers("plotProperty" + pid);
	}
	else if (address.indexOf("regions", 0) != -1)
	{
		var regionId = address.substring(address.indexOf("regions/") + 8,  address.indexOf("?"));
		var page = address.substring (address.lastIndexOf("=")+1);
		plotMarkers("plotRegion/" + regionId + "?page=" + page);
	}
	else
	{
		var page = address.substring (address.lastIndexOf("=")+1);
		if (address.lastIndexOf("=") != -1)
		{
			plotMarkers("getMarkers/" + page);
		}
		else
		{
			plotMarkers("getMarkers/1");
		}
	}
	
	
	

}

function plotMarkers (action) 
{
	//alert(action);
	var request = GXmlHttp.create();
	request.open('GET', action, true);
	request.onreadystatechange = function() {
			var lat, lng, price, building_type, id, address, latlon, infoWindow, marker, title, distance, results;
			var index = 0;
			var endIndex = 0;
			if (request.readyState == 4)
			{
				results = request.responseText;				
				endIndex = results.indexOf("]");
				while (index < results.length)
				{
					index = results.indexOf("property_marker", index);
					if (results.indexOf("property_marker", index+19) == -1)
					{
						marker = results.substring(index + 19, results.length - 3);	
						index = results.length + 1;
					}
					else
					{
						marker = results.substring(index + 19, results.indexOf("property_marker", index+19)-6);						
					}
					marker = "[{" + marker + "}]";
					if (marker == "[{[]}]")
					{
						break;
					}
					markers = eval(marker);
					index = index + 19;
					lat = markers[0].lat;
					lng = markers[0].lng;
					price = markers[0].rent_from;
					building_type = markers[0].choice
					id = markers[0].id;
					address = markers[0].street_address
					if (lat && lng)
					{
						//distance = calculateDistance (lat, lng);
						//distance = Math.round(distance);
						latlon = new GLatLng(parseFloat(lat), parseFloat(lng));
						infoWindow = "<div id=\"infowindow\">";
						infoWindow = infoWindow + "<table><tr><td>Address: </td><td>" + address + "</td></tr>";
						infoWindow = infoWindow + "<tr><td>Rent: </td><td>$" + price + "</td></tr>";
						infoWindow = infoWindow + "<tr><td>Building Type: </td><td>" + building_type + "</td></tr>";
						//infoWindow = infoWindow + "<tr><td>Distance: </td><td>" + distance.toString() + "m</td></tr>";
						infoWindow = infoWindow + "<tr<td><a href=\"/property/show/" + id + "\">";
						infoWindow = infoWindow + "More Info</a></td><td></td></tr></table></div>";
						marker = addProperty (lat, lng, infoWindow, address, id);
					} // end adding marker
				}
			} // end if
		} // end function
	request.send(null);
}


function initPage ()
{
	var address = location.href;
	if (address.indexOf("property/upload") == -1 && address.indexOf("property/edit") == -1)
	{
		initMap();
	}
	else
	{
		uploadMap = new GMap2(document.getElementById("map_canvas"));
		geocoder = new GClientGeocoder();
		if (address.indexOf("property/edit") != -1)
		{
			geoCode();
		}
	}	
	Shadowbox.init();

	 
		toggle = document.getElementById("toggleMapCheckBox");
		toggleMap(toggle);
	
}

/********  property form  ********/
function geoCode ()
{
	var address = document.getElementById("property_street_address").value;
	var city = document.getElementById("tmp_property_city").value;
	if (address != null && address != "" && city != null && city != "")
	{
		if (city == "46")
		{
			city = "Waterloo"
		}
		else
		{
			city = "Kitchener"
		}
		showAddress (address + ", " + city + ", ON");
	}	
}


function showAddress(address) {
  geocoder.getLatLng(
	address,
	function(point) {
	  if (!point) {
		alert("Sorry we could not find \"" + address + "\" please double check the address you entered");
	  } else {	  
//	  	uploadMap.clearOverlays();
		uploadMap.setCenter(point, 14);
		var marker = new GMarker(point);
		uploadMap.addOverlay(marker);		
	  }
	}
  );
}

/******** End Upload property form  ********/

/******** Local Result Stuff ********/ 

// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result) 
{
	this.result_ = result;
	this.resultNode_ = this.unselectedHtml();
	document.getElementById("searchwell").appendChild(this.resultNode_);
	map.addOverlay(this.marker(gSmallIcon));
}

// Returns the GMap marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function(opt_icon) 
{
	if (this.marker_) return this.marker_;
	var marker = new google.maps.Marker(new google.maps.LatLng(parseFloat(this.result_.lat),
										 parseFloat(this.result_.lng)),
								opt_icon);
	GEvent.bind(marker, "click", this, function() {
		marker.openInfoWindow(this.selected() ? this.selectedHtml() :
											this.unselectedHtml());
	});
  this.marker_ = marker;
  return marker;
}

// "Saves" this result if it has not already been saved
LocalResult.prototype.select = function() 
{
	if (!this.selected()) 
	{
		this.selected_ = true;

		// Remove the old marker and add the new marker
		map.removeOverlay(this.marker());
		this.marker_ = null;
		map.addOverlay(this.marker(G_DEFAULT_ICON));
		// Add our result to the saved set
		document.getElementById("selected").appendChild(this.selectedHtml());

		// Remove the old search result from the search well
		this.resultNode_.parentNode.removeChild(this.resultNode_);
	}
}

// Returns the HTML we display for a result before it has been "saved"
LocalResult.prototype.unselectedHtml = function() 
{
	var container = document.createElement("div");
	container.className = "unselected";
	container.appendChild(this.result_.html.cloneNode(true));
	var saveDiv = document.createElement("div");
	saveDiv.className = "select";
	saveDiv.innerHTML = "Save this location";
	GEvent.bindDom(saveDiv, "click", this, function() {
		map.closeInfoWindow();
		this.select();
		gSelectedResults.push(this);
	});
	container.appendChild(saveDiv);
	return container;
}

// Returns the HTML we display for a result after it has been "saved"
LocalResult.prototype.selectedHtml = function() 
{
	return this.result_.html.cloneNode(true);
}

// Returns true if this result is currently "saved"
LocalResult.prototype.selected = function() 
{
	return this.selected_;
}

// Called when Local Search results are returned, we clear the old
// results and load the new ones.

function OnLocalSearch() 
{

	gLocalSearch.setCenterPoint(map);
	if (!gLocalSearch.results) 
		return;
	var searchWell = document.getElementById("searchwell");
	
	// Clear the map and the old search well
	searchWell.innerHTML = "";
	for (var i = 0; i < gCurrentResults.length; i++) 
	{
		if (!gCurrentResults[i].selected()) 
		{
		  map.removeOverlay(gCurrentResults[i].marker());
		}
	}
	
	gCurrentResults = [];
	for (var i = 0; i < gLocalSearch.results.length; i++) 
	{
		gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));
	}
	
	var attribution = gLocalSearch.getAttribution();
	if (attribution) 
	{
		document.getElementById("searchwell").appendChild(attribution);
	}
}

   // Cancel the form submission, executing an AJAX Search API search.
function CaptureForm(searchForm) 
{
	gLocalSearch.execute(searchForm.input.value);
  	return false;
}

function executeSearch (searchValue)
{
	gSearchForm.input.value = searchValue;
	CaptureForm(gSearchForm);
}
    
/******** End Local Result ********/    



window.onload = initPage; 
window.onunload = GUnload
