// Original file by Barry Hunter www.nearby.org.uk (c) July 2007
// http://www.nearby.org.uk/google/googleMapsv2.js
// Ajax function to get the event window upon clicking on a marker
var receiveReq = getHTTPObject();

//the google map object
var map;

//the geocoder object
var geocoder;

var addressMarker;

//the ajax request object
var request;

//the 'default' icons
var icons = new Array();
var icon_green;
var icon_blue;

//array of markers so we can keep track of which to remove
var marks = new Array();

//shortcut to the message div
//var m;

//is the a fetch in progress?
var running = false;

//these are for zoomin optimization (if prev zoom had all markers then no need to load them again for zooming in)
var prevZoom = 20;
var shownall = false;
var sentBounds = '';

//<![CDATA[

/*function GG_onLoad(latitude, longitude, zoom) {
	if (GBrowserIsCompatible()) {
	
		map = new GMap2(document.getElementById("map"));
	
		map.addControl(new GSmallMapControl());
		//map.addControl(new GScaleControl());
		map.addControl(new GMapTypeControl());
	
		map.setCenter(new GLatLng(latitude, longitude), zoom);
	
		// Create our "tiny" marker icon 
		create_icons();
	
		GEvent.addListener(map, "moveend", function() { update_map(latitude, longitude); });
		update_map(latitude, longitude);
		
		 geocoder = new GClientGeocoder();
		 geocoder.setBaseCountryCode('FR');
	} else {
		alert("You don't seem to have a version of Javascript Compatible with Google Maps, Sorry this page will not fully function");
	}
}*/

//]]>

function map_load() {
	//alert('map load');
	if (GBrowserIsCompatible()) {
		//container = document.getElementById("map");
		//check_resize();

		map = new GMap2(container, {draggableCursor:"crosshair"});
		map.setCenter(centerPoint, zoom);
		map.addControl(new GScaleControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());

		// Create our "tiny" marker icon 
		create_icons();
		
		// Update map listener, and initial update map
		GEvent.addListener(map, "moveend", function() { update_map(); });
		GEvent.addListener(map, "zoomend", function() { update_map(); });
		update_map();
	}
}

function map_resize(width) {
	container.style.width = width;
	// alert(document.body.clientHeight);
	//var windowheight = getWindowHeight();
	// 700 = 600 (adsense) + 10 (p padding) + 5+5 (droite padding) + 80 statistiques
	// 100 = 70 (header)  + 30 (pied)
	//container.style.height = ((windowheight > 800)?windowheight-200:630)  + 'px'; 
	container.style.height = '400px';
	if (map) {
		map.checkResize();
	}
}

// Fonction retournant la hauteur de la fenetre, quel que soit le browser
function getWindowHeight() {
    var windowHeight=0;
    if (typeof(window.innerHeight)=='number') {
        windowHeight=window.innerHeight;
    }
    else {
     if (document.documentElement&&
       document.documentElement.clientHeight) {
         windowHeight = document.documentElement.clientHeight;
    }
    else {
     if (document.body&&document.body.clientHeight) {
         windowHeight=document.body.clientHeight;
      }
     }
    }
    return windowHeight;
}


// function that initialises the icons
function create_icons() {
	icons["red"] = new GIcon(); 
	icons["red"].image = "http://labs.google.com/ridefinder/images/mm_20_red.png"; 
	icons["red"].shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png"; 
	icons["red"].iconSize = new GSize(12, 20); 
	icons["red"].shadowSize = new GSize(22, 20); 
	icons["red"].iconAnchor = new GPoint(6, 20); 
	icons["red"].infoWindowAnchor = new GPoint(5, 1); 
	icons["red"].imageMap = [4,0,0,4,0,7,3,11,4,19,7,19,8,11,11,7,11,4,7,0]; 
	icons["red"].transparent = "/images/mm_20_transparent.png";
	icon_green = get_icon('green');
	icon_blue  = get_icon('blue');
	icon_red  = get_icon('red');
	icons["man"] = new GIcon(icons["red"]);
	icons["man"].image = "/images/man.png";
	icons["man"].shadow = "/images/man_shadow.png";
	icons["man"].iconSize = new GSize(15, 22); 
	icons["man"].shadowSize = new GSize(25, 20); 
	icon_man  = icons["man"];
	icons["manonline"] = new GIcon(icons["man"]);
	icons["manonline"].image = "/images/man_online.png";
	icon_manonline  = icons["manonline"];
	icons["woman"] = new GIcon(icons["man"]);
	icons["woman"].image = "/images/woman.png";
	icons["woman"].shadow = "/images/woman_shadow.png";
	icons["woman"].iconSize = new GSize(15, 22); 
	icons["woman"].shadowSize = new GSize(25, 20); 
	icon_woman  = icons["woman"];
	icons["womanonline"] = new GIcon(icons["woman"]);
	icons["womanonline"].image = "/images/woman_online.png";
	icon_womanonline  = icons["womanonline"];
}

// function associate which creates an icon based on a color		
function get_icon(iconColor) {
   if ((typeof(iconColor)=="undefined") || (iconColor==null)) { 
	  iconColor = "red"; 
   }
   if (!icons[iconColor]) {
	  icons[iconColor] = new GIcon(icons["red"]);
	  icons[iconColor].image = "http://labs.google.com/ridefinder/images/mm_20_"+ iconColor +".png";
   } 
   return icons[iconColor];
}

function createMarker(point, is_user, type) {
	if (type !=1 && is_user) {
		var marker = new GMarker(point, icon_green);
	} else {
		switch (type) {
			case 1: // type = city
				var marker = new GMarker(point, icon_red);
				break;
			case 2:
				var marker = new GMarker(point, icon_man);
				break;
			case 3:
				var marker = new GMarker(point, icon_woman);
				break;
			case 4:
				var marker = new GMarker(point, icon_manonline);
				break;
			case 5:
				var marker = new GMarker(point, icon_womanonline);
				break;	
		}
	}

	GEvent.addListener(marker, "click", function() {
		getMarkerInfo(marker.getPoint().lat(), marker.getPoint().lng(), type);
	});

	return marker;
}

function getMarkerInfo(lat, lng, type) { 
 if (receiveReq.readyState == 4 || 
	 receiveReq.readyState == 0) 
 {     
   receiveReq.open("GET", '/main/ajax/get_marker_info.php?lat='+lat+'&lng='+lng+'&type='+type, true);
   receiveReq.onreadystatechange = getMarkerInfoCallback;
   receiveReq.send(null);       
 } // end  if   
} // end  function

function getMarkerInfoCallback() {
 // state == 4 is when the response is complete
 if (receiveReq.readyState == 4) {
	/* var response = receiveReq.responseText;
	response = response.split(',') */
	//alert(receiveReq.responseText);
	var response = eval(receiveReq.responseText);

	map.openInfoWindowHtml(new GLatLng(response[0],response[1]),response[2]);				
 } // end   if (state == 4)
} // end   function

function update_map() {
	if (running) {
		request.abort();
		running = false;
	}

	// alert(shownall+'-'+map.getZoom()+'-'+prevZoom); <= changé dessous.. bug de concept? 
	if (shownall == false || map.getZoom() <= prevZoom) {
		var bounds = map.getBounds();
		var center = map.getCenter();
		var zoom = map.getZoom();
		// sentBounds = bounds.toString();
		sentBounds = '('+bounds.getSouthWest().lat()+','+bounds.getSouthWest().lng()+','+bounds.getNorthEast().lat()+','+bounds.getNorthEast().lng()+')';
		
		//build a list of layers to request
		var ob = document.getElementById("select_layers");
		if (ob != null) { // Presence d'un menu layers
			var layers = '';
			for (var i = 0; i < ob.elements.length; i++)
				if (ob.elements[i].checked)
					layers = layers + ',' +ob.elements[i].name;
			layers = layers.substr(1);
		} else { // Absence d'un menu layers
			layers = 'all';
		}
		
		request = GXmlHttp.create();
		request.open("GET", "/main/ajax/googleMaps.xml.php?bounds="+sentBounds+"&layers="+layers, true);
		
		request.onreadystatechange = function() {
			if ((request.readyState == 4) && (request.responseText != '' )&& (request.status == 200) && (running)) {
				//alert(request.responseText);
				//alert(request.readyState);
				var xmlDoc = GXml.parse(request.responseText);
				//var xmlDoc = request.responseText;
				//alert(xmlDoc);
				if (!xmlDoc.documentElement) {
					alert("Error: Unable to Parse XML");
					running = false;
					return;
				}
				var markers = xmlDoc.documentElement.getElementsByTagName("marker");
				
				//flag all current markers as old
				for (i in marks) 
					if (marks[i] != null) {
						//alert('Old marker: ' + i);
						marks[i].old = true;
					}

				for (var i = 0; i < markers.length; i++) {
					lng = parseFloat(markers[i].getAttribute("lng"));
					lat = parseFloat(markers[i].getAttribute("lat"));
					type = parseFloat(markers[i].getAttribute("type"));
					id = lng+' '+lat+' '+type;
					if (marks[id] && marks[id] != null) {
						//we have this one so lets flag it as valid
						//alert('Flag old marker OK: ' + id);


						marks[id].old = false;
					} else {
						var point = new GPoint(lng, lat);
						var is_user = ((ulat==lat) && (ulng==lng))?true:false;

						//alert('New marker OK: ' + id);


						//add any extra fields to this line
						marks[id] = createMarker(point, is_user, type);
						marks[id].old = false;
						
						map.addOverlay(marks[id]); 
						
					}
				}
				
				for (i in marks) 
					if (marks[i] != null) 
						if (marks[i].old == true) {
							//alert('Delete marker: ' + i);
							map.removeOverlay(marks[i]);
							marks[i] = null; //marks.splice(i,1);
						}

				//print out a message
				var count = xmlDoc.documentElement.getElementsByTagName("count");
				if (count && count.length > 0) {
					c = count[0].getAttribute("value");
					if (markers.length == c) {
						// m.innerHTML = "Finished, showing "+markers.length+" markers.";
						shownall = true;
					} else {
						//m.innerHTML = "Finished, showing random "+markers.length+" of "+c+" markers, Zoom-in to see more!";
						shownall = false;
					}
				} else {
					//m.innerHTML = "Finished, showing "+markers.length+" of unknown markers.";
					shownall = true;
				}
				running = false;
			}
		}//end function
		
		running = true;
		request.send(null);
	}
	prevZoom = map.getZoom();
}
