
var Balade = Class.create({

	initialize: function(carte) {
		this.name = "Balade sans nom";
		this.description = "";
		this.waypoints = Array();
		this.carte = carte;
		this.itineraire = new google.maps.Directions();
		this.wpi = 0;
		google.maps.Event.addListener(this.itineraire, "load", this.onGDirectionsLoad);
		google.maps.Event.addListener(this.itineraire, "addOverlay", function(){carteItineraire.removeOverlay(this);});
		google.maps.Event.addListener(this.itineraire, "error", this.handleErrors);
	},

	addWaypoint: function() {
		this.waypoints[this.waypoints.length] = new Waypoint(this.waypoints.length);
	},

	addWaypoint: function(lat, lng) {
		wpIndex = this.waypoints.length;
		this.waypoints[wpIndex] = new Waypoint(wpIndex);
		this.waypoints[wpIndex].lat = lat;
		this.waypoints[wpIndex].lng = lng;
		this.waypoints[wpIndex].setGeoByLatLng();
		// Il faut laisser le geoCoder rafraichir quand il aura reçu la réponse de Google...
		// this.drawWpList();
		maBalade.doItineraire();
	},
	
	loadWaypoint: function(name, lat, lng) {
		var wpIndex = parseInt(this.waypoints.length);
		this.waypoints[wpIndex] = new Waypoint(wpIndex);
		this.waypoints[wpIndex].name = name;
		this.waypoints[wpIndex].lat = lat;
		this.waypoints[wpIndex].lng = lng;
		//this.waypoints[wpIndex].setGeoByLatLng();
	},
	
	drawWpList : function(){
		// Construction d'une ligne dans la liste de waypoints.
		var nbWp = maBalade.waypoints.length;
		var bloc;
		$("wpList").innerHTML = "";
		for(var i = 0; i < nbWp; i++){		
			bloc = document.createElement('li');
			bloc.id = "ctn"+i;
			bloc.className = "baladeWaypoint";
			bloc.WpId = i; 
			bloc.onclick = maBalade.infoPointStudio;
			bloc.innerHTML += "<div class='num'>"+i+".</div>";
	   		bloc.innerHTML += maBalade.waypoints[i].name;
	   		$("wpList").appendChild(bloc);
	   	}
	},
	
	infoPoint : function(wpId) {
		if( this.getTitle ) wpId = this.getTitle();
		var point = new GLatLng(maBalade.waypoints[wpId].lat, maBalade.waypoints[wpId].lng, false);
		if(maBalade.waypoints[wpId].name == '') maBalade.waypoints[wpId].name = "Waypoint "+wpId;
		var content = "<div class='infobulleTitle'>"+maBalade.waypoints[wpId].name+"</div>";
		content += "<hr/>";
		content += "<div class='infobulleLatLng'>";
		content += "Lattitude : "+maBalade.waypoints[wpId].lat + "<br/>";
		content += "Longitude : "+maBalade.waypoints[wpId].lng + "<br/>";
		content += "Localité : "+maBalade.waypoints[wpId].geoName;
		content += "</div>";
		content += "<hr/>";
		content += "<table class='infobulleTable' style='width:90%;'>";
		content += "<tr><td class='corner'>&nbsp;</td><td class='t'>Partiel</td><td class='t'>Total</td></tr>";
		content += "<tr><td class='t'>KM</td><td>"+maBalade.waypoints[wpId].partialKm+" km</td><td>"+maBalade.waypoints[wpId].totalKm+" km</td></tr>";
		content += "<tr><td class='t'>Durée</td><td>"+maBalade.getTimeFromSec(maBalade.waypoints[wpId].partialTime)+"</td><td>"+maBalade.getTimeFromSec(maBalade.waypoints[wpId].totalTime)+"</td></tr>";
		content += "</table>";
		carteItineraire.openInfoWindow(point,content);
	},
	
	infoPointStudio : function() {
		if( this.getTitle ) wpId = this.getTitle();
		else wpId = this.id.substr(3, this.id.length);
		//if(this.wpId) wpId = this.wpId;
		//else wpId = this.getTitle();
		var point = new GLatLng(maBalade.waypoints[wpId].lat, maBalade.waypoints[wpId].lng, false);
		if(maBalade.waypoints[wpId].name == '') maBalade.waypoints[wpId].name = "Waypoint "+wpId;
		var content = "<div class='infobulleTitle'><span class='title'>"+maBalade.waypoints[wpId].name+"</span><br/><span class='localite'>"+maBalade.waypoints[wpId].geoName+"</span></div>";
		content += "<hr/>";
		content += "<div class='infobulleButton' onclick='maBalade.waypoints["+wpId+"].moveUpImplicite();'><img src='"+$('publicUrl').value+"images/icons/arrow_up.png' alt='' title='' /> Déplacer ce point vers le haut</div>";
		content += "<div class='infobulleButton' onclick='maBalade.waypoints["+wpId+"].moveDownImplicite();'><img src='"+$('publicUrl').value+"images/icons/arrow_down.png' alt='' title='' /> Déplacer ce point vers le bas</div>";
		content += "<div class='infobulleButton' onclick='maBalade.waypoints["+wpId+"].renameImplicite(prompt(\"Nouveau nom pour le waypoint : \"));'><img src='"+$('publicUrl').value+"images/icons/pencil.png' alt='' title='' /> Renommer</div>";
		content += "<div class='infobulleButton' onclick='maBalade.waypoints["+wpId+"].deleteImplicite();'><img src='"+$('publicUrl').value+"images/icons/cross.png' alt='' title='' /> Supprimer</div>";
		content += "<hr/>";
		content += "<div class='infobulleLatLng'>";
		content += "Lattitude : "+maBalade.waypoints[wpId].lat + "<br/>";
		content += "Longitude : "+maBalade.waypoints[wpId].lng + "<br/>";
		content += "</div>";
		content += "<hr/>";
		content += "<table class='infobulleTable' style='width:90%;'>";
		content += "<tr><td class='corner'>&nbsp;</td><td class='t'>Partiel</td><td class='t'>Total</td></tr>";
		content += "<tr><td class='t'>KM</td><td>"+maBalade.waypoints[wpId].partialKm+" km</td><td>"+maBalade.waypoints[wpId].totalKm+" km</td></tr>";
		content += "<tr><td class='t'>Durée</td><td>"+maBalade.getTimeFromSec(maBalade.waypoints[wpId].partialTime)+"</td><td>"+maBalade.getTimeFromSec(maBalade.waypoints[wpId].totalTime)+"</td></tr>";
		content += "</table>";
		carteItineraire.openInfoWindow(point,content);
	},
	
	doItineraire : function() {
		clearMap();
		if( this.waypoints.length > 1 ) this.boundCarte();			
		this.wpi = 0;
		if( maBalade.waypoints[0] ) maBalade.waypoints[0].setGeoByLatLng();
		this.doNextIti();
	},
	
	doNextIti : function() {
		var wpi = maBalade.wpi;
		var fromWp;
		var toWp;
		if(maBalade.waypoints[wpi]){
			if( maBalade.waypoints[wpi].lat != 0 && maBalade.waypoints[wpi].lng != 0 ){
				maBalade.waypoints[wpi].buildMarker();
				fromWp = new GLatLng(maBalade.waypoints[wpi].lat, maBalade.waypoints[wpi].lng, false);
				if(maBalade.waypoints[wpi+1]){
					if(maBalade.waypoints[wpi+1].lat != 0 && maBalade.waypoints[wpi+1].lng != 0){
						toWp = new GLatLng(maBalade.waypoints[wpi+1].lat, maBalade.waypoints[wpi+1].lng, false);
						maBalade.itineraire.loadFromWaypoints(Array(fromWp,toWp), optionsItineraire);
					}
				}
			}
		}
	},
	
	onGDirectionsLoad : function(e) {
		var route = this.getRoute(0);
		var distance = route.getDistance().meters;
		var cumul = 0;
		var cumulT = 0;
		var trace = this.getPolyline();
		
		distance = parseInt(distance / 1000)
		//cumul = parseInt($("wpSTot"+maBalade.wpi).value) + distance;
		cumul = parseInt(maBalade.waypoints[parseInt(maBalade.wpi)].totalKm) + distance;
		duree = route.getDuration().seconds;
		//cumulT = parseInt($("wpTSTot"+maBalade.wpi).value) + duree;
		cumulT = parseInt(maBalade.waypoints[parseInt(maBalade.wpi)].totalTime) + duree;
		
		maBalade.waypoints[parseInt((maBalade.wpi)+1)].partialKm = distance;
		maBalade.waypoints[parseInt((maBalade.wpi)+1)].totalKm = cumul;
		maBalade.waypoints[parseInt((maBalade.wpi)+1)].partialTime = duree; 
		maBalade.waypoints[parseInt((maBalade.wpi)+1)].totalTime =  cumulT;
		
		//$("wpPar"+(parseInt(maBalade.wpi)+1)).innerHTML = distance;
		//$("wpDistanceTotale"+(parseInt(maBalade.wpi)+1)).value = cumul;
		//$("wpTot"+(parseInt(maBalade.wpi)+1)).innerHTML = cumul;
		
		//$("wpTPar"+(parseInt(maBalade.wpi)+1)).innerHTML = maBalade.getTimeFromSec(duree); ;
		//$("wpDureeTotale"+(parseInt(maBalade.wpi)+1)).value = cumulT;
		//$("wpTTot"+(parseInt(maBalade.wpi)+1)).innerHTML = maBalade.getTimeFromSec(cumulT);
		
		carteItineraire.addOverlay(trace);
		
		maBalade.wpi += 1;
		if( maBalade.waypoints[maBalade.wpi] ) maBalade.waypoints[maBalade.wpi].setGeoByLatLng();
		// DELAI DE 100mS ENTRE CHAQUE POINT POUR EVITER LE BUG 
		window.setTimeout(maBalade.doNextIti, 200);
	},
	
	getTimeFromSec : function(sec){
		response = "";
		var h = parseInt(sec / 3600);
		var m = parseInt(sec / 60) - (h * 60);
		if( h > 0 ) response += h + " h";
		if( m > 0 ){
			if(m > 9) response += " " + m;
			else response += " 0" + m;
		}
		if( h == 0 ) response += " min";
		return response;
	},
	
	boundCarte : function() {
		if( $('map') || ( $('recadrage')&&$('recadrage').checked ) ){
			var bounds = new GLatLngBounds();
			for(var i=0; i<this.waypoints.length; i++){
				var point = new GLatLng(this.waypoints[i].lat, this.waypoints[i].lng, false);
				bounds.extend(point);
			}
			carteItineraire.setZoom( carteItineraire.getBoundsZoomLevel(bounds) - 1 );
			carteItineraire.setCenter(bounds.getCenter());
		}
	},
	
	submitStudioForm : function() {
		maBalade.serialize();
		$("studioForm").submit();
	},
	
	serialize : function() {
		
		var baladeFields = {'name':'', 'description':''};
		var waypointFields = {'wpIndex':'', 'name':'', 'geoName':'', 'lat':'', 'lng':'', 'partialKm':'', 'partialTime':'', 'totalKm':'', 'totalTime':''};
		//var waypointFields = {'wpIndex':'', 'name':''};
		
		var encode = function(str){
			str = str.toString().replace(/\\/g, "");
			return str.toString().replace(/\"/g, '\'');
		}
		
		var JSON_Balade = '{';
		
		for (var i in baladeFields)
		{
		  if(maBalade[i]) JSON_Balade += '"'+i+' ": "'+encode(maBalade[i])+'", ';
		}
		
		JSON_Balade += '"waypoints": [ ';
		for(var j = 0; j < maBalade.waypoints.length; j++){
			JSON_Balade += '{';
			for (var i in maBalade.waypoints[j])
			{
			  if(i in waypointFields) JSON_Balade += '"'+i+'": "'+encode(maBalade.waypoints[j][i])+'", ';
			}
			// Retrait de la virgule qui vient après le dernier waypoint.
			JSON_Balade = JSON_Balade.substr(0, JSON_Balade.length - 2);
			JSON_Balade += '},';
		}
		
		// Retrait de la virgule qui vient après le dernier waypoint.
		JSON_Balade = JSON_Balade.substr(0, JSON_Balade.length - 1) + ' ] }';
		
		$('jsonContainer').value = JSON_Balade;
	},
	
	handleErrors : function() {
		maBalade.handleErrorsByCode( this.getStatus().code );
	},
	
	handleErrorsByCode : function(code) {
		code = code.toString();
		/* Ouvre une fenêtre d'alerte, dans laquelle s'affiche un message suivi du code erreur */
		switch(code){
			case '200':
				alert('Tout va bien.');
				break;
			case '400':
				alert('Impossible de parser la requête. Il y a peut être trop de waypoints.');
				break;
			case '601':
				alert('Adresse vide ou requête vide.');
				break;
			case '602':
				alert('Adresse inconnue pour une des raisons suivantes :\n- Trop récente \n- Incorrecte');
				break;
			case '603':
				alert('Impossible de traiter cette adresse pour des raisons légales ou contractuelles.');
				break;
			case '604':
				alert('Impossible de trouver une route entre ces 2 points.');
				break;
			case '610':
				alert('La clé pour l\'API Google Map est incorrecte.');
				break;
			case '620':
				alert('Surcharge ! Veuillez différer votre requête.');
				break;
			case '500':
			default:
				//alert('Raison inconnue.');
				break;
		}
	}

});

