var centerLatitude = c_lat;
var centerLongitude = c_long;
var startZoom = zoom;
var currZoom = startZoom;
var currMarker;
var map;
//TODO implement the marker manager to reduce the load time of the page
var markerManager = ""
var gmarkers = [];
var votes = [];
var listeBas = [];

var courriel = "";
var codepostal = "";
var markers_init = false;
var lastid 	= 0

YAHOO.util.Event.onDOMReady(init);

function soumettreLieu(latitude,longitude,nom) {
	var url = url_root+"ajouterlieu.php?latitude=" + latitude + "&longitude=" + longitude + "&nom=" + nom + "&v="+ville;
	var httpRequest;
	var retour;

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			httpRequest.overrideMimeType('text/xml');
		}
		} else if (window.ActiveXObject) { // IE
			try {
				httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} 
			catch (e) {
				try {
					httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
 				} 
				catch (e) {
				}
			}
		}

		if (!httpRequest) {
			alert('Une erreur est survenue.');
			return false;
		}
		retour = httpRequest.onreadystatechange = function() {traiterRetourAjout(httpRequest)};
		httpRequest.open('GET', url, true);
		httpRequest.send('');
		return retour;
};

function traiterRetourAjout(httpRequest) {
	if (httpRequest.readyState == 4) {
		if (httpRequest.status == 200) {
			return ajouterVote(httpRequest.responseText);
		} else {
			alert('Erreur.');
		}
	}
}

function ajouterVote(id) {
	return votes.push(id);
}

function Marker(marker,description) {
  this.marker = marker;
  this.description = description;
}

function init()
{
	document.getElementById("loading").style.display= "block";
   if (GBrowserIsCompatible()) 
   {
      map = new GMap2(document.getElementById("carte"),{draggableCursor:'url('+url_root+'medias/img/hand.png),default'});
	  map.addControl(new GLargeMapControl());
	  map.disableDoubleClickZoom();
      
      // adding click event for the map
      GEvent.addListener(map, "dblclick", function(overlay, location) {
         
         if( overlay )
         {
            // clicked on something other than the map
            
         }
         else
         {
            newUserMarker(location);
         }
      });
      var location = new GLatLng(centerLatitude, centerLongitude);
      map.setCenter(location, startZoom);
	if(isPostback)
	{
		load_markers();
	}else{
		ShowModeEmploi();
		stop_loading();
	}
	
    }

}

function createMarker(latitude,longitude,description,votes,id,type,draggable) {
  
   description = description.replace(/[<>]/g,"");

   // create new location object
   var location = new GLatLng(latitude, longitude);
   
   // add marker
   addMarker(location,description,votes,id,type,draggable,0,0);   
}

function addMarker(location,description,votes,id,type,draggable,noNoeud,noVote) {
   // create new marker
	var pointer_type = type
	if(isPostback && pointer_type == "requested"){ pointer_type = "friend";}
   var icon = new GIcon(G_DEFAULT_ICON, url_root+"medias/img/markers/"+pointer_type+".png");
   icon.iconSize = new GSize(15,38);
   var marker = new GMarker(location, {icon: icon, draggable: draggable});
   
   var latitude = location.lat();
   var longitude = location.lng();
	
	if(id == 0){
		marker.id = lastid++;
	}else{
		marker.id = id;
	}
   gmarkers[gmarkers.length] = marker;

   if(marker.id > lastid){ lastid = marker.id; }

   GEvent.addListener(marker, 'click',
      function() 
      {
         var htmlString;
		 htmlString = '<div class="infowindow"><p class="lieuNom">'+description+'</p><p>'+lang.zap_demande+'</p><p class="ctrl"><a href="javascript:return false;" onclick="supprimerZap('+noNoeud+','+noVote+'); return false;" class="changer_idee action"></a></p></div><div class="clearer"></div>';
		if(type == "requested") {
			if(isPostback){ htmlString = '<div class="infowindow"><p class="lieuNom">'+description+'</p><p>'+lang.zap_demande+'</p></p></div>';}else{
				htmlString = '<div class="infowindow"><p class="lieuNom">'+description+'</p><p>'+lang.zap_internautes+'</p><p class="ctrl"><a href="#" onclick="voter(\''+id+'\',\''+escapeAp(description)+'\'); return false;" class="moi_aussi action"></a></p></div><div class="clearer"></div>';
			}
		};
		if(type == "active") {
			htmlString = '<div class="infowindow"><p class="lieuNom">'+description+'</p><p>'+lang.zap_deja_active+'</p><p class="ctrl"><a href="#" onclick="fermerMarker(); return false;" class="jy_cours action"></a></div></p><div class="clearer"></div>';	
		};
		if(type == "future") {
			htmlString = '<div class="infowindow"><p class="lieuNom">'+description+'</p><p>'+lang.zap_bientot+'</p><p class="ctrl"><a href="#" onclick="fermerMarker(); return false;" class="genial action"></a></p></div><div class="clearer"></div>';	
		}
		if(type == "friend") {
		
		 htmlString = '<div class="infowindow"><p class="lieuNom">'+description+'</p><p>'+lang.zap_par_refereur+'</p><p class="ctrl"><a href="#" onclick="voter(\''+id+'\',\''+escapeAp(description)+'\'); return false;" class="moi_aussi action"></a></p></div><div class="clearer"></div>';
		};


         marker.openInfoWindowHtml(htmlString);
		 currMarker = marker;     
		}
   );

   // place new marker in the map
   map.addOverlay(marker);    
   
   return marker;
}

// function to trim string
function trim(word)
{
   while (word.substring(0,1) == ' ')
      word = word.substring(1, word.length);

   while (word.substring(word.length-1, word.length) == ' ')
      word = word.substring(0,word.length-1);
      
   return word;
}

function newUserMarker(location) {
	//Place le marqueur � la position cliqu�e
	currMarker = addMarker(location,"",0,0,"user",true);
	var htmlString = '<div class="infowindow"><p class="lieuNom">'+lang.zap_ici+'</p><p><input type="text" id="nomZap" name="nomZap" value="'+lang.zap_nom_endroit+'" onclick="document.getElementById('+"'nomZap'"+').value=\'\';" class="input_ajouter" /></p><p class="ctrl"><a href="#" onclick="addThisZap(); return false;" class="action ajouter"></a></p></div>';

	currMarker.openInfoWindowHtml(htmlString);
}

function retirerListItem(node) {
	var myList = document.getElementById('listeZAP');
	
	disparu = myList.removeChild(node);	
};

function addThisZap() {
	var noVote;
	var myZap = new Array();
	myZap.push(currMarker.getLatLng());
	myZap.push(document.getElementById("nomZap").value);
		
	//ajouter � la liste des votes
	
	currMarker.closeInfoWindow();
	currMarker.hide();

	//L'ajoute � la liste de l'usager
	var myItem = document.createElement('li');
	var noNoeud = listeBas.push(myItem) - 1;
	var noVote = soumettreLieu(currMarker.getPoint().lat(),currMarker.getPoint().lng(),myZap[1])
	var myList = document.getElementById('listeZAP');
	myItem.className = "nouv_zap";
	//myItem.appendChild(myNom);
	myList.appendChild(myItem);
	
	if(votes.length==0) {
		ShowVotes();
	}
	
	//Ajoute un "vrai" marqueur
	newMarker = addMarker(myZap[0],myZap[1],0,0,"user",false,noNoeud,noVote);
	myItem.innerHTML = lang.zap_proposez+" <strong>" +myZap[1]+"</strong>. <span onclick=\"supprimerZap("+noNoeud+","+noVote+",false,"+newMarker.id+")\"></span>";
}

function voter(id,nom) {
	var cpt = 0;
	var existe = false;
	
	while(cpt < votes.length && existe == false) {
		if(votes[cpt] == id) {
			existe = true;	
		}
		
		cpt++;
	}
	
	if(nom != "" && existe == false) {

		
		if(votes.length==0) {
			ShowVotes();
		}
		
		//L'ajoute au tableau
		var noVote = ajouterVote(id);

		//L'ajoute � la liste de l'usager
		var myItem = document.createElement('li');
		var myList = document.getElementById('listeZAP');
		myItem.innerHTML = lang.zap_app_implantation + " <strong>" +nom+"</strong>. <span onclick=\"supprimerZap("+id+","+noVote+", this)\"></span>";
		myItem.className = "vote_zap";
		//myItem.appendChild(myNom);
		myList.appendChild(myItem);	
	}	
	return false;
}

function escapeAp(chaine) {
	return chaine.replace("'","\\'");	
}

function soumettreVotes(courriel,codeP,refer) {
	if(validerCourriel(courriel) == true) {
		document.getElementById("formulaireEnvoi").action = url_root+"usagers/" + ville + "/" + courriel + "/";
		document.getElementById("listeVotes").value = votesString();
		document.getElementById("codePostal").value = codeP;
		document.getElementById("refer").value = refer;
		document.getElementById("formulaireEnvoi").submit();
	}
}

function votesString() {
	var chaine = "";
	var cpt = 0;
	while (cpt<votes.length){
		chaine += votes[cpt]+"|";
		cpt++;
	}
	
	chaine = chaine.substr(0,chaine.length -1);
	return chaine;
}

function fermerMarker() {
	currMarker.closeInfoWindow();	
}

function echeck(str) {

		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1){
		   alert(courriel_invalide);
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert(courriel_invalide);
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		   alert(courriel_invalide);
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
 		    alert(courriel_invalide);
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
 	 	    alert(courriel_invalide);
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert(courriel_invalide);
		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert(courriel_invalide);
		    return false;
		 }

 		 return true;					
	}

function validerCourriel(adresse){
	
	if ((adresse==null)||(adresse=="")){
		alert(courriel_invalide);
		return false;
	}
	if (echeck(adresse)==false){
		return false;
	}
	return true;
}

// TODO: This function should be named 
// setRollover. It should have 3 params
// @id
// @imgmouseout
// @imgmouseon
// The html areafunction should find th id and set the events using javascript 
function remplacerImage(id,fichier) {
	document.getElementById(id).src = fichier;	
}

function supprimerZap(noNoeud,noVote, isVote, markerid) {
	if(isVote)
	{
		// We remove the vote fomr the parent UL element
		isVote.parentNode.parentNode.removeChild(isVote.parentNode);
	}else{
		if(markerid > -1)
		{
			var target_marker = getMarkerById(markerid);
			target_marker.hide();
		}
		currMarker.closeInfoWindow();
		currMarker.hide();
		retirerListItem(listeBas[noNoeud]);
	}
	// Remove the vote from the votes array
	votes.splice(noVote -1,1);
	// If there are no vote left we hide the panel that displays them
	if(votes.length==0) {
		HideVotes();
	}
};

function getMarkerById(id)
{
	for(i = 0; i < gmarkers.length; i++)
	{
		if(gmarkers[i].id == id){ return gmarkers[i];}
	}
	return false;
}

function focusToMarkerById(id)
{
	var marker = getMarkerById(id);
	if(marker != false){ 	
		GEvent.trigger(marker, 'click');
		map.setCenter(marker.getPoint()); 	
	} 
}

function stop_loading()
{
	document.getElementById("loading").style.display = "none";
}

function loading()
{
	document.getElementById("loading").style.display = "block";
}

//Load the markers on the map
function load_markers()
{
		// === Define the function thats going to process the text file ===
	process_it = function(doc) {
		loading();
		// === split the document into lines ===
	lines = doc.split("\n");
	for (var i=0; i<lines.length; i++) {
		if (lines[i].length >= 1) {
		// === split each line into parts separated by "|" and use the contents ===
		parts = lines[i].split("|");
		var lat = parseFloat(parts[0]);
		var lng = parseFloat(parts[1]);
		var desc = parts[2];
		var votes = parts[3];
		var id = parts[4];
		var status = parts[5];
		if(parts[6] == 1 && !isPostback) {
			status = "4";
		}
		// create the marker
		var types = new Array('requested','active','future','user','friend');
		if(votes > 0) {
			createMarker(lat, lng, desc, votes, id, types[parseInt(status)], false);
		}
	  }
	markers_init = true;
	stop_loading();
	}
	
	}
	if(myUser && myUser != "" && isPostback){
		GDownloadUrl(url_root+"markers.php?user="+myUser+"&v="+ville, process_it);
	}else{
		if(myUser && myUser != ""){
			GDownloadUrl(url_root+"markers.php?ref="+myUser+"&v="+ville, process_it);
		}else{
			GDownloadUrl(url_root+"markers.php?v="+ville, process_it);
		}
	}

}

function ShowVotes()
{
	var newHeight = { height: "484px"}
	$("#boxListe").show();
	$("#bas").hide();
	$("#gauche").css(newHeight);
	$("#droite").css(newHeight);
	$("#boxListe").css({borderTop: "none"});
	$("#carte_cont").css({marginBottom: "0"});
	
}

function HideVotes()
{
	var newHeight = { height: "473px"}
	$("#boxListe").hide();
	$("#bas").show();
	$("#gauche").css(newHeight);
	$("#droite").css(newHeight);
	$("#carte_cont").css({marginBottom: "1em"});
}
