//<![CDATA[

/////////////////////////////////////////////////////////////////////////////////////
/////	VARS DEFINITION

var xmlHttp;
var period;
var active;
var search;
var autoReload = "On";

var status;
var realDate = Date.today();


if (!lat) { lat = 40.7545 ;}
if (!lng) { lng = -73.9849;}

/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
/////
/////	GOOGLE MAPS STUFF
/////	
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////

	if (GBrowserIsCompatible()) { 

		// A function to create the marker and set up the event window
		// Dont try to unroll this function. It has to be here for the function closure
		// Each instance of the function preserves the contends of a different instance
		// of the "marker" and "html" variables which will be needed later when the event triggers.    
		function createMarker(point,html,id,status) {

			if (status == "active") {
				var color = "green";
			} else {
				var color = "red";
			}
			
			// Create our "tiny" marker icon
			var tinyIcon = new GIcon();
			tinyIcon.image = "_imgs/icons/flag_"+color+".png";
			tinyIcon.iconSize = new GSize(24, 24);
			tinyIcon.iconAnchor = new GPoint(6, 20);
			tinyIcon.infoWindowAnchor = new GPoint(5, 1);
			                
			// Set up our GMarkerOptions object
			markerOptions = { icon:tinyIcon };
		
			var marker = new GMarker(point, markerOptions);
			
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(html);
				showRideInfo(id);
				});
			return marker;
		}

		// Display the map, with some controls and set the initial location 
		var map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.enableScrollWheelZoom();
		map.addControl(new GMapTypeControl());
		// map.setCenter(new GLatLng( lat , lng ), 7);
		map.setCenter(new GLatLng( 30 , 0 ), 2);

		GEvent.addListener(map, "dragend", function(){
			reloadMarkers(period)
		});
		GEvent.addListener(map, "zoomend", function(){
			reloadMarkers(period)
		});
		

		function changeAutoReload() {
			window.autoReload = "On";
			map.clearOverlays();
			reloadMarkers();
		}

		// Reload when something happens !!

		function reloadMarkers(reload) {

		if (reload == 'yes') { autoReload = "On"; }
		
		 if (autoReload=="On") { // AVOID AUTORELOADING THE MAP WHEN A MARKER IS OPEN

			if (active == 'yes') {
				active		= 'yes';
			} else {
				active		= 'all';
			}

			if (period==null || period == 'all') {
				period 		= 'all';
				textLeft	= "All trips.";
				textCenter 	= "";
				textRight	= "";
			} else if (period == 'today') {
				textLeft	= "";
				textCenter 	= "Displaying trips for today."
				textRight 	= "<a href='javascript:void(0)' onclick='javascript: period = 1; reloadMarkers(\"yes\")' style='float: right;'>|| >>>></a>";
			} else if (period != null && period != 'all' && period != 'today') {
				searchDate 	= Date.today().addDays(period);
				searchDateSup 	= searchDate.toString("S");
				searchDateYear 	= searchDate.toString("yyyy");
				searchDate 	= searchDate.toString("dddd, MMMM d");
				minus 		= period - 1;
				plus		= period + 1;
				textLeft 	= "<a href='javascript:void(0)' onclick='javascript: period = "+minus+"; reloadMarkers(\"yes\")'><<<< ||</a>";
				textCenter 	= searchDate +"<sup>"+ searchDateSup+"</sup>, "+searchDateYear;
				textRight 	= "<a href='javascript:void(0)' onclick='javascript: period = "+plus+"; reloadMarkers(\"yes\")' style='float: right;'>|| >>>></a>";
			}

			// document.getElementById("infoSearchLeft").innerHTML = textLeft;
			// document.getElementById("infoSearchCenter").innerHTML = textCenter;
			// document.getElementById("infoSearchRight").innerHTML = textRight;

			var bounds = map.getBounds();
			var southWest = bounds.getSouthWest();
			var northEast = bounds.getNorthEast();	

			// FOR TESTS // textlat = "Lat southwest: " + southWest.lat() + " <br> Lat northeast: " + northEast.lat();
			// FOR TESTS // textlng = "<br> Long southwest: " + southWest.lng() + " <br> Long northeast: " + northEast.lng();
			
			var lat1 = southWest.lat();
			var lat2 = northEast.lat();
			var lng1 = southWest.lng();
			var lng2 = northEast.lng();
			
			map.clearOverlays();
		
			var url="mapProcessor.php";
			url = url+"?lat1="+lat1+"&lat2="+lat2+"&lng1="+lng1+"&lng2="+lng2+"&period="+period+"&active="+active;
			url = url+"&sid="+Math.random();

			// FOR TESTS // document.getElementById("info").innerHTML = url;

			xmlHttp = GetXmlHttpObject();
			if (xmlHttp==null) {
				alert ("Browser does not support HTTP Request");
				return;
			}
		
			xmlHttp.onreadystatechange = stateChanged;
			xmlHttp.open("GET",url,true);
			xmlHttp.send(null);

			// FOR TESTS // document.getElementById("info").innerHTML = textlat + textlng + "<br>";
			// FOR TESTS // document.getElementById("info").innerHTML = url; 
		  } // END OF AutoReload LIMITATION (TO AVOID RELOADING THE MAP IF AUTORELOAD IS OFF)
	
		} // ENF OF RELOAD FUNCTION

		function stateChanged() {

			if (xmlHttp.readyState>1 || xmlHttp.readyState<4 ) { 
			document.getElementById("list").innerHTML = "<img src='../_imgs/ajax-loader.gif'> Loading the trips ....";
			// document.getElementById("infoListTrips").innerHTML = "...";
			}
			if (xmlHttp.readyState==4 || xmlHttp.readyState=="Complete") { 
				var result = xmlHttp.responseText;
				var object = eval("(" + result + ")");
				var resultnumber = object.markers.length;
				
				if (resultnumber > 10) {
					var text = "First 10 trips of this area: <br>";
				} else {
					var text = "";
				}
				var counter;
				
				if (resultnumber == 0) {
					document.getElementById("list").innerHTML = "No trips in this area ... yet !";
					// document.getElementById("infoListTrips").innerHTML = 
						"<br />Indeed, <strong>create your own cab ride now</strong> ! <br /><br />" + 
						"<a href='save-new'>Click here</a> to create a cab ride in that area.";
				} else if (resultnumber > 0) {

					document.getElementById("list").innerHTML = resultnumber + " trips start in that area.";
	
					for (var i=0 ; i < resultnumber ; i++) {
						
						if (i < 10) {
							counter = i+1;
							text = text + counter + ' - <a href="'+ object.markers[i].permalink +'">';
							text += object.markers[i].name + '</a><br>'
						}
						
						// IF THE TRIP IS IN THE FUTURE, ACTIVE = GREEN FLAG, ELSE INACTIVE = RED FLAG
						var tripDate = Date.parse(object.markers[i].rawdate);
						if ( tripDate >= realDate ) { status = "active"; } else { status = "inactive"; };
						
						var point = new GLatLng(object.markers[i].lat1,object.markers[i].lng1);
						var markerInfo = '<div><font size="2">' + object.markers[i].name + '<br>';
						markerInfo = markerInfo + 'On '+object.markers[i].date+' at '+object.markers[i].time+'<br>';
						markerInfo = markerInfo + '<a href="'+object.markers[i].permalink+'">More details ...</a></font></div>';
						var id = object.markers[i].id;
						var marker = createMarker(point,markerInfo,id, status);
						map.addOverlay(marker);
					}
					// document.getElementById("infoListTrips").innerHTML = text;
				}
			}
		}

		function GetXmlHttpObject() {
			var xmlHttp=null;
			try { // Firefox, Opera 8.0+, Safari
				xmlHttp=new XMLHttpRequest();
			} catch (e) { //Internet Explorer
				try {
					xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
				}
			}
			return xmlHttp;
		}

// SEARCH THE MAP - GEOCODING TO NEW LOCATION

		// ====== Create a Client Geocoder ======
			var geo = new GClientGeocoder(new GGeocodeCache()); 

		// ====== Array for decoding the failure codes ======
			var reasons=[];
			reasons[G_GEO_SUCCESS]            = "Success";
			reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
			reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
			reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
			reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
			reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
			reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

		// ====== Geocoding ======
			function showAddress(search) {
				if (search == undefined) { var search = document.getElementById("search").value; }
		// ====== Perform the Geocoding ======        
				geo.getLatLng(search, function (point) { 
				// ===== If that was successful, plot the point and centre the map ======
					if (point) {
						var marker = new GMarker(point);
						map.addOverlay(marker);
						map.setCenter(point,12);
				map.clearOverlays();
				reloadMarkers('yes');
					}
				// ====== Decode the error status ======
					else {
				// ==Look to see if the query was cached ==
						var result=geo.getCache().get(search);
						if (result) {
							var reason="Code "+result.Status.code;
							if (reasons[result.Status.code]) {
								reason = reasons[result.Status.code]
							}
						} 
						else {
							var reason = "";
						} 
						alert('Could not find "'+search+ '" ' + reason);
					}
				});
			}
		// ====== END OF Geocoding ======


	function clearAllMarkers() {
		map.clearOverlays();
	}

	reloadMarkers('yes');

	} else {
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}

/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
/////
/////	AJAX STUFF TO: 	RELOAD MARKERS WHEN MAP IS DRAGGED, LOAD TRIPS INFO, 
/////			SHOW TRIPS ON THE MAP, ....
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////

function showRideInfo(id){

	var url="homeShowRideInfo.php";
	url = url+"?id="+id;
	url = url+"&sid="+Math.random();

	xmlHttp = GetXmlHttpObject();
	if (xmlHttp==null) {
		alert ("Browser does not support HTTP Request");
		return;
	}
	xmlHttp.onreadystatechange = stateChangedInfo;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function stateChangedInfo() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="Complete") { 
		var result = xmlHttp.responseText;
		var object = eval("(" + result + ")");
		var resultnumber = object.markers.length;

		for (var i=0; i<object.markers.length; i++) {

			var pointB = new GLatLng(object.markers[i].lat2,object.markers[i].lng2);
			var markerInfo = '<div>Arrival from: '+object.markers[i].name+' - <br><a href="tripDetails.php?id='+object.markers[i].id+'">More details ...</a></div>';
			var id = object.markers[i].id;
			var marker = createMarker(pointB,markerInfo,id);
			map.addOverlay(marker);

	// === The basis of the arrow icon information ===
	var arrowIcon = new GIcon();
      	arrowIcon.iconSize = new GSize(24,24);
	arrowIcon.shadowSize = new GSize(1,1);
      	arrowIcon.iconAnchor = new GPoint(12,12);
	arrowIcon.infoWindowAnchor = new GPoint(0,0);
      
	// === Returns the bearing in degrees between two points. ===
	// North = 0, East = 90, South = 180, West = 270.
	var degreesPerRadian = 180.0 / Math.PI;
	function bearing( from, to ) {
		// See T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.
		// Convert to radians.
		var lati1 = from.latRadians();
		var lon1 = from.lngRadians();
		var lati2 = to.latRadians();
		var lon2 = to.lngRadians();

		// Compute the angle.
		var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lati2 ), Math.cos( lati1 ) * Math.sin( lati2 ) - Math.sin( lati1 ) * Math.cos( lati2 ) * Math.cos( lon1 - lon2 ) );
		if ( angle < 0.0 )
		angle  += Math.PI * 2.0;

		// And convert result to degrees.
		angle = angle * degreesPerRadian;
		angle = angle.toFixed(1);

		return angle;
	}

	// === A function to create the arrow head at the end of the polyline ===
	function arrowHead(points) {
		// == obtain the bearing between the last two points
		var p1=points[points.length-1];
		var p2=points[points.length-2];
		var dir = bearing(p2,p1);
		// == round it to a multiple of 3 and cast out 120s
		var dir = Math.round(dir/3) * 3;
		while (dir >= 120) {dir -= 120;}
		// == use the corresponding triangle marker 
		arrowIcon.image = "http://www.google.com/intl/en_ALL/mapfiles/dir_"+dir+".png";
		map.addOverlay(new GMarker(p1, arrowIcon));
	}


	var pointA = new GLatLng(object.markers[i].lat1,object.markers[i].lng1);
	// var pointB = new GLatLng(lat2,lng2);

	var points = [pointA, pointB];
	map.addOverlay(new GPolyline(points,"#ff0000", 5));
	// === add the arrow head
	arrowHead(points);

	window.autoReload = "Off";

		}
	}
}


    //]]>
