
var zord_url = 'http://www.zordania.com';

// this variable will collect the html which will eventualkly be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
var Icons = new Array;
var mm;
var toolTip = document.createElement("div");
var map;

function fn_start_loading() 
{
   if (GBrowserIsCompatible())
	{
		// ====== Definition des icones marqueurs ======
		for(var i=1; i<6; i++)
		{
		  var Icon = new GIcon();
		  Icon.image = "../img/"+i+"/"+i+".png";
		  Icon.iconSize = new GSize(15, 12);
		  //Icon.shadow = "myshadow.png";
		  //Icon.shadowSize = new GSize(36, 34);
		  Icon.iconAnchor = new GPoint(1, 12);
		  Icon.infoWindowAnchor = new GPoint(15, 1);
		  //Icon.transparent = "mytran.png";
		  //Icon.printImage = "mymarkerie.gif";
		  //Icon.mozPrintImage = "mymarkerff.gif";
		  //Icon.printShadow = "myshadow.gif";
		  Icons[i] = Icon;
		}

      // ====== Create the Euclidean Projection for the flat map ======
      // == Constructor ==
      function EuclideanProjection(a){
        this.pixelsPerLonDegree=[];
        this.pixelsPerLonRadian=[];
        this.pixelOrigo=[];
        this.tileBounds=[];
        var b=256;
        var c=1;
        for(var d=0;d<a;d++){
          var e=b/2;
          this.pixelsPerLonDegree.push(b/360);
          this.pixelsPerLonRadian.push(b/(2*Math.PI));
          this.pixelOrigo.push(new GPoint(e,e));
          this.tileBounds.push(c);
          b*=2;
          c*=2
        }
      }


      // == Attach it to the GProjection() class ==
      EuclideanProjection.prototype=new GProjection();

      // == A method for converting latitudes and longitudes to pixel coordinates == 
      EuclideanProjection.prototype.fromLatLngToPixel=function(a,b){
        var c=Math.round(this.pixelOrigo[b].x+a.lng()*this.pixelsPerLonDegree[b]);
        var d=Math.round(this.pixelOrigo[b].y+(-2*a.lat())*this.pixelsPerLonDegree[b]);
        return new GPoint(c,d)
      };

      // == a method for converting pixel coordinates to latitudes and longitudes ==
      EuclideanProjection.prototype.fromPixelToLatLng=function(a,b,c){
        var d=(a.x-this.pixelOrigo[b].x)/this.pixelsPerLonDegree[b];
        var e=-0.5*(a.y-this.pixelOrigo[b].y)/this.pixelsPerLonDegree[b];
        return new GLatLng(e,d,c)
      };

      // == a method that checks if the y value is in range, and wraps the x value ==
      EuclideanProjection.prototype.tileCheckRange=function(a,b,c){
        var d=this.tileBounds[b];
        if (a.y<0||a.y>=d) {
          return false;
        }
        if(a.x<0||a.x>=d){
          a.x=a.x%d;
          if(a.x<0){
            a.x+=d;
          }
        }
        return true
      }

      // == a method that returns the width of the tilespace ==      
      EuclideanProjection.prototype.getWrapWidth=function(zoom) {
        return this.tileBounds[zoom]*256;
      }

		// ====== Create a single layer "Fractal" custom maptype ======
		// ===== It has one tile layer =====
		var tilelayers = [new GTileLayer(new GCopyrightCollection("Contr&eacute;es Zordaniennes"), 0, 4)];
		tilelayers[0].getCopyright = function(a,b) {
			return {prefix:'<a href="http://www.zordania.com" title="zordania">zordania</a>', copyrightTexts:['Endri Cartography']};
		}

		// ===== Instead of calling a script to load the tile =====
		// ===== Generate the actual tile filename            =====
		tilelayers[0].getTileUrl = function (a,b) {
			return "http://zordania.free.fr/map/tiles/part_z"+(b)+"_x"+(a.x)+"_y"+(a.y)+".png";
		} ;

		// ====== Create the MapType ==============
		//var custommap = new GMapType(tilelayers, G_NORMAL_MAP.getProjection(), '<a href="'+zord_url+'" title="zordania"><img href="../img/zord.png"></a>',{errorMessage:"Terra Incognita"});
		var custommap = new GMapType(tilelayers, new EuclideanProjection(18), "Euclidean", {errorMessage:"Terra Incognita",alt:"No cartography"});

		// === create the map ===
		map = new GMap2(document.getElementById("map"));

		// === add the new maptype to it ===
		map.addMapType(custommap);
		map.addControl(new GLargeMapControl());
		map.enableScrollWheelZoom();
		map.setCenter(new GLatLng(0,0), 1, custommap);
      // ====== set up marker mouseover tooltip div ======
      document.getElementById("map").appendChild(toolTip);
      toolTip.style.visibility="hidden";

		// Listen for when the user moves either map
		GEvent.addListener(map, 'click', fn_Clic);
		// Listen for when the user moves either map
		GEvent.addListener(map, 'zoomend', fn_Move);

		if (window.location.search!="")
			loadMarkers( 'users.xml.php'+window.location.search);
		else
			fn_LoadRace(0);
		
		// creation des groupes de marqueurs
		//mm = new GMarkerManager(map);
		//for (var j=1; j<=5; j++) mm.addMarkers(gmarkers[j], 0, 6);
		//mm.refresh();
	}
    
   // display a warning if the browser was not compatible
    else {
		alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}

function fn_Move() {
	fn_LoadRace(0);
	return;
}

function fn_Clic(overlay, point) {
	if (point) document.getElementById('pos_x').innerHTML = 'Clic en ('+lng2x( point.lng())+' x '+lat2y( point.lat())+'), double-clic pour zoomer.';
	return;
}

// This function picks up the click and opens the corresponding info window
function myclick(race, i) {
	GEvent.trigger(gmarkers[race][i], "click");
}

function loadMarkers( url)
{
	document.getElementById("pos_x").innerHTML = 'Chargement en cours... ';
	// (re)initialiser les variables
	side_bar_html = "";
	gmarkers = [];
	// separation des marqueurs par race:
	for (var i=1; i<=5; i++) gmarkers[i] = [];
	map.clearOverlays();
	var request = GXmlHttp.create();
	request.open("GET", url, true);
	request.onreadystatechange = function() 
	{
		if (request.readyState == 4) 
		{
			var xmlDoc = GXml.parse(request.responseText);
			// obtain the array of markers and loop through it
			var markers = xmlDoc.documentElement.getElementsByTagName("result");

			for (var i = 0; i < markers.length; i++) 
				// create the marker
				map.addOverlay( createMarker(markers[i])); //pos_x, pos_y, pseudo, html, race, titletext));
				
			// put the assembled side_bar_html contents into the side_bar div
			document.getElementById("side_bar").innerHTML = side_bar_html;
			if (markers.length==100) 
				document.getElementById("pos_x").innerHTML = 'Limité aux 100 meilleurs sur la zone.';
			else
				document.getElementById("pos_x").innerHTML = 'Chargement terminé, '+markers.length+' villages dans cette zone.';
		}
	}
	request.send(null);
}

function loadTable( url) {
	document.getElementById("pos_x").innerHTML = 'Chargement en cours...';
	// (re)initialiser les variables
	var request = GXmlHttp.create();
	request.open("GET", url, true);
	request.onreadystatechange = function() 
	{
		if (request.readyState == 4) 
		{
			var xmlDoc = GXml.parse(request.responseText);
			var tbl=document.getElementById('tbl_result');
			if (tbl) document.getElementById('debugg').removeChild( tbl);
			document.getElementById('debugg').appendChild( CreateTableFromXMl( xmlDoc, 'result', new Array('pseudo', 'pop_util', 'al_nom', 'or', 'points')));

			if (markers.length==100) 
				document.getElementById("pos_x").innerHTML = 'Limité aux 100 meilleurs sur la zone.';
			else
				document.getElementById("pos_x").innerHTML = 'Chargement terminé, '+markers.length+' villages dans cette zone.';
		}
	}
	request.send(null);
}

function lng2x(lng) {
	//return Math.floor(lng*25/9)+250;
	return Math.floor((lng+180)*25/18);
}
function lat2y(lat) {
	//return 250-Math.floor(lat*50/9);
	return Math.floor((90-lat)*25/9);
}

function fn_reload() // relancer le chargement des markers sur request xml
{
	var C = map.getCenter();
	var rech;
	var url = "users.xml.php?x="+lng2x(C.lng())+"&y="+lat2y((C.lat()))+"&z="+(map.getZoom()-1);
	// regarder le filtre sur la (les) races
	var races='';
	var notraces=0;
	for (var i=1; i<=5; i++) {
		rech = document.getElementById('chk_r'+i).checked;
		if (rech) races += ','+i; else notraces+=1;
	}
	if (notraces==4) // 1 seule race sélectionnée
		url +='&race='+races.substring(1);
	else if (races!='' && notraces==0) // plusieurs races
		url +='&races='+races.substring(1);
	rech = document.getElementById('txt_nom').value;
	if (rech != "") 
		url += "&nom="+rech;
	else {
		rech = document.getElementById('txt_ally').value;
		if (rech != "")
			url += "&ally="+rech;
		else {
			rech = document.getElementById('txt_points').value;
			if (rech != "") url += "&points="+rech;
		}
	}
	loadMarkers( url);
}
function fn_LoadRace(race) // relancer le chargement des markers sur request xml
{
	var C = map.getCenter();
	if (race==0)
		loadMarkers( 'users.xml.php?x='+lng2x(C.lng())+"&y="+lat2y((C.lat()))+"&z="+(map.getZoom()-1));
	else
		loadMarkers( 'users.xml.php?x='+lng2x(C.lng())+"&y="+lat2y((C.lat()))+"&z="+(map.getZoom()-1)+"&race="+race);
}

// A function to create the marker and set up the event window
function createMarker(mark) //pos_x, pos_y, name, html, race, titletext) 
{
	// obtain the attribues of each marker
	var pos_x = parseFloat(mark.getAttribute("pos_x"));
	var pos_y = parseFloat(mark.getAttribute("pos_y"));
	var race = mark.getAttribute("race_rid");
	var id = mark.getAttribute("Id");
	var name = mark.getAttribute("pseudo");
	var points = mark.getAttribute("points");
	var pop_util = mark.getAttribute("pop_util");
	var pop_max = mark.getAttribute("pop_max");
	var al_id = mark.getAttribute("al_id");
	var al_nom = mark.getAttribute("al_nom");
	if (al_id != "") { al_id = '<br /><a href="' + zord_url + '/alliances-view.html?al_aid=' +al_id+ '" title="'+ al_nom +'>'+al_nom+'</a>'; }
	
	var html = '<span class="font-size: 9px;"><a href="'+zord_url+'/member-view.html?mid='+id+'" title="'+name+'">'+name+'</a><br />points : <b>'+points+'</b>, pop='+pop_util+'/'+pop_max+al_id+'<br />position : '+pos_x+' x '+pos_y+'</span>';
	var titletext = name+"<br />\n"+points+" points, pop="+pop_util+(al_id==""? "":"<br />\n"+al_nom);

	var point = new GLatLng(90-9/25*pos_y, -180+18/25*pos_x)
	//var point = new GLatLng(45-9/50*pos_y, 9/25*pos_x-90)
	var marker = new GMarker(point, {icon:Icons[race], title:name});
	marker.toolTip = '<div id="toolTip" style="width: 120px;">'+titletext+'</div>';
	GEvent.addListener(marker, "click", function() {
	  marker.openInfoWindowHtml(html);
	});
	//  ======  The new marker "mouseover" and "mouseout" listeners  ======
	GEvent.addListener(marker,"mouseover", function() {
		showTooltip(marker);
	});
	GEvent.addListener(marker,"mouseout", function() {
		toolTip.style.visibility="hidden"
	});
	// add a line to the side_bar html
	side_bar_html += '<a href="javascript:myclick(' + race+', '+gmarkers[race].length + ')">' + name + '</a><br>';
	gmarkers[race][gmarkers[race].length] = marker;
	return marker;
}

// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a side_bar mouseover
function showTooltip(marker) {
	toolTip.innerHTML = marker.toolTip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y)); 
	pos.apply(toolTip);
	toolTip.style.visibility="visible";
}

// This Javascript is based on code provided by the
// Blackpool Community Church Javascript Team
// http://www.commchurch.freeserve.co.uk/   
// http://www.econym.demon.co.uk/googlemaps/
//


// génère un tableau HTML sur la base d'un noeud XML, le nom des noeuds qu'on veut extraire,
// et la liste des attributs contenant les données
// XMLnode : objet XML noeud à parcourir
// return : objet table à ajouter (appendChild)
function CreateTableFromXMl(XMLnode) {
 var elts = XMLnode.getElementsByTagName('result');
 if (!elts) return; // rien si vide

 var tbl = document.createElement("TABLE");
 tbl.setAttribute('class', 'border');
 tbl.setAttribute('id', 'tbl_result');
 var tr = document.createElement("TR");
 var tbody=document.createElement("TBODY");
 var thead=tbl.createTHead();
 var tfoot=tbl.createTFoot();

 // Liste des ATTRIBUTS retournés : 
 // Id pseudo pos_x pos_y race_rid al_id al_nom pop_util pop_max or nourriture
 for (var j = 0; j < n; j++) {
	 var td = document.createElement("TH");
	 td.appendChild(document.createTextNode('node_name'));
	 tr.appendChild(td);
 }
 thead.appendChild(tr);

 m = elts.length;
 for(var i = 1; i < m; i++){
	 var tr = document.createElement("TR");
	 for(var j = 0; j < n ;j++){
		 var td=document.createElement("TD");
		 td.appendChild(document.createTextNode(ValeurAttribut(elts[i], 'node_name')));
		 tr.appendChild(td);
	 }
	 tbody.appendChild(tr);
 }

 tbl.appendChild(thead);
 tbl.appendChild(tfoot);
 tbl.appendChild(tbody);
 return tbl;
}

function ValeurAttribut(noeud, attribut) {
 if (!noeud) return "";
 if ((!attribut) || (attribut=="")) return "";
 if (noeud.getAttribute(attribut)) return noeud.getAttribute(attribut);
 if (noeud.attributes[attribut]) return noeud.attributes[attribut].value;
 return "";
}

