/* Fonction permettant la création d'un itinéraire Mappy (summary & roadbook) à partir d'éléments permettant de retrouver les adresses de départ et d'arrivée
 * @param string resume : libellé multilangue du paragraphe resume
 * @param string vehicle : libellé multilangue du paragraphe vehicle
 * @param string carburant : llibellé multilangue du paragraphe carburant
 * @param string jouney : libellé multilangue du paragraphe jouney
 * @param string distance : libellé multilangue du paragraphe distance
 * @param string consumption : libellé multilangue du paragraphe consumption
 * @param string douane : libellé multilangue du paragraphe douane
 * @param string feuille : libellé multilangue du paragraphe feuille
 * @param string liters : libellé multilangue du paragraphe liters
 * @param string km : libellé multilangue du paragraphe km
 * @param int parcours : définit s'il s'agit du trajet 'YAller' (1) ou 'enPartir'(2)
 */
function traceRouteWithAdressSearch(resume,vehicle,carburant,journey,distance,consumption,douane,feuille,liters,km,parcours) {
	var countryDepart; 
    var townDepart;
    var addressDepart;
    
    var countryArrivee;
    var townArrivee;
    var addressArrivee;

	if (parcours==1) {
		countryDepart= jQuery("#paysDepartA").val();
	   	townDepart = jQuery("#villeDepartA").val();
	   	addressDepart = jQuery("#adresseDepartA").val();
	   
	   	countryArrivee = jQuery("#paysArriveeA").val();
	   	townArrivee = jQuery("#villeArriveeA").val();
	   	addressArrivee = jQuery("#adresseArriveeA").val();
	}
	else {
    	countryDepart = jQuery("#paysDepartP").val();
	    townDepart = jQuery("#villeDepartP").val();
	    addressDepart = $("#adresseDepartP").val();
	    
	    countryArrivee = jQuery("#paysArriveeP").val();
	    townArrivee = jQuery("#villeArriveeP").val();
	    addressArrivee = jQuery("#adresseArriveeP").val();
	}
	
	var depart = "";
	var arrivee = "";
	if ((countryArrivee!=null)&&(countryArrivee!="")&&(townArrivee!=null)&&(townArrivee!="")&&(countryDepart!=null)&&(countryDepart!="")&&(townDepart!=null)&&(townDepart!="")) {
  		var depart = new Mappy.api.geolocation.AddressLocation(countryDepart, townDepart, addressDepart);
   		var arrivee = new Mappy.api.geolocation.AddressLocation(countryArrivee, townArrivee, addressArrivee);
	}

	// Fonction Itinéraire
  	traceRoute(resume,vehicle,carburant,journey,distance,consumption,douane,feuille,liters,km,depart,arrivee,lang);    
}

/* Fonction permettant la création d'un itinéraire Mappy (summary & roadbook) à partir d'adresses de départ et d'arrivée
 * @param string resume : libellé multilangue du paragraphe resume
 * @param string vehicle : libellé multilangue du paragraphe vehicle
 * @param string carburant : llibellé multilangue du paragraphe carburant
 * @param string jouney : libellé multilangue du paragraphe jouney
 * @param string distance : libellé multilangue du paragraphe distance
 * @param string consumption : libellé multilangue du paragraphe consumption
 * @param string douane : libellé multilangue du paragraphe douane
 * @param string feuille : libellé multilangue du paragraphe feuille
 * @param string liters : libellé multilangue du paragraphe liters
 * @param string km : libellé multilangue du paragraphe km
 */
function traceRouteWithoutAdressSearch(resume,vehicle,carburant,journey,distance,consumption,douane,feuille,liters,km) {
    var depart = jQuery("#adresse1").val(); 
    var arrivee = jQuery('#adresse2').val();
    
    // Fonction Itinéraire
	traceRoute(resume,vehicle,carburant,journey,distance,consumption,douane,feuille,liters,km,depart,arrivee);
}

/* Fonction permettant la création d'un itinéraire Mappy (summary & roadbook)
 * @param string resume : libellé multilangue du paragraphe resume
 * @param string vehicle : libellé multilangue du paragraphe vehicle
 * @param string carburant : llibellé multilangue du paragraphe carburant
 * @param string jouney : libellé multilangue du paragraphe jouney
 * @param string distance : libellé multilangue du paragraphe distance
 * @param string consumption : libellé multilangue du paragraphe consumption
 * @param string douane : libellé multilangue du paragraphe douane
 * @param string feuille : libellé multilangue du paragraphe feuille
 * @param string liters : libellé multilangue du paragraphe liters
 * @param string km : libellé multilangue du paragraphe km
 * @param object depart : objet créé à partir de l'API mappy
 * @param object arrivee : objet créé à partir de l'API mappy
 */
function traceRoute(resume,vehicle,carburant,journey,distance,consumption,douane,feuille,liters,km,depart,arrivee) {	
	// Error si depart ou arrivée null    
	jQuery(".errorMappy3").hide();
	jQuery(".errorMappy4").hide();
	jQuery(".errorMappy5").hide();
	jQuery(".errorMappy6").hide();

		
    if (depart == null || depart=="" || arrivee == null || arrivee == "") {
    	if (jQuery("#paysDepartA").val() == null || jQuery("#paysDepartA").val()==""){
    		jQuery(".errorMappy3").show();
    	}
    	if (jQuery("#villeDepartA").val() == null || jQuery("#villeDepartA").val()==""){
    		jQuery(".errorMappy4").show();
    	}
    	if (jQuery("#paysArriveeA").val() == null || jQuery("#paysArriveeA").val()==""){
    		jQuery(".errorMappy5").show();
    	}
    	if (jQuery("#villeArriveeA").val() == null || jQuery("#villeArriveeA").val()==""){
    		jQuery(".errorMappy6").show();
    	}
    		
    	jQuery(".errorMappy").hide();
    	jQuery("#summary").hide();
    	jQuery("#roadbook").hide();
		
		shapeLayer.clean();
    }
    else {
    	jQuery(".errorMappy").hide();
    	jQuery(".errorMappy2").hide();
    	jQuery(".errorMappy3").hide();
    	jQuery(".errorMappy4").hide();
    	jQuery(".errorMappy5").hide();
    	jQuery(".errorMappy6").hide();
    	jQuery("#mymap").show();
    	jQuery("#mymapPoint").hide();
		
    	jQuery("#summary").empty();
    	jQuery("#summary").show();
		jQuery("#roadbook").empty();
		jQuery("#roadbook").show();

		
	    shapeLayer.clean();
	    var tab = [depart, arrivee];
	    var rs = new Mappy.api.route.RouteService();
	    // Throw the request
	    rs.loadRoute(
	        tab,
	        {	        	
	            Vehicle: jQuery('#vehicle').val(),
	            caravane: (jQuery('#caravane').attr("checked") ) ? 1 : 0,
	            gas: jQuery('#gas').val(),
	            gascost: jQuery('#gascost').val(),
	            cost: jQuery('[name=cost]').val(),
	            notoll: (jQuery('#notoll').attr("checked")) ? 1 : 0,
	            nopass: (jQuery('#nopass').attr("checked")) ? 1 : 0,
	            language : lang
	        },
	        function (roadbook) {
	            shapeLayer.addShape(roadbook.shapes[0]);
	            var bounds = shapeLayer.getBounds();
	            map.setCenter(bounds.center, map.getBoundsZoomLevel(bounds));

	           var summary = jQuery('#summary');
	           summary.empty();
			   summary.append('<h1 id="resume">'+ resume +'</h1><br/>');
	           summary.append('<span id="resumeDetail">' + vehicle+' : </span><span id="vehicle">' + roadbook.summary.vehicle + '</span><br/>');
	           summary.append('<span id="resumeDetail">' +carburant+' : </span><span id="carburant">' + roadbook.summary.gasName + '</span><br/>');
	           summary.append('<span id="resumeDetail">' +journey+' : </span><span id="journey">' + dateHMS(roadbook.summary.time) + '</span><br/>');
	           summary.append('<span id="resumeDetail">' +distance+' : </span><span id="distance">' + Math.round(((roadbook.summary.length)/1000)*10)/10 + ' '+ km +'</span><br/>');
	           summary.append('<span id="resumeDetail">' +consumption+' : </span><span id="consumption">' + Math.round(roadbook.summary.gasConsumption*10)/10+' '+ liters +'</span><br/>');
	            if (roadbook.summary.tolls && roadbook.summary.tolls.length > 0) {
	                var strings = [];
	                for (i = 0; i < roadbook.summary.tolls.length; i += 1) {
	                    toll = roadbook.summary.tolls[i];
	                    if (toll.amount > 0) {
		                    strings.push(
		                        toll.country + " : " + '<span class="bold">' + toll.amount + " " + toll.currency + "</span>"
		                    );
						}
	                }
	                summary.append(douane+' : ' + strings.join(", "));
	              }
	            summary.append('<hr/><br/>');
	           summary.append('<h1>'+ feuille +'</h1>');
	

	   		traceRouteItineraire(Math.round(((roadbook.summary.length)/1000)*10)/10);	
	           
	           jQuery("#roadbook").html(roadbook.toHtml());
	        },
	        function(e) {
	        	jQuery(".errorMappy").show();
	        }
    	);
    }
}

/* Fonction gérant l'affectation des variables constituant une adresse (countryDdepart, ...)à partir de l'API Mappy (contentMap.jsp)
 * @param int time : le temps en secondes.
 * @reurn object result : le temps découpé en hh::mm::ss
 */
function dateHMS(time) {
	var reste=time;
	var result='';
	
	var nbJours=Math.floor(reste/(3600*24));
	reste -= nbJours*24*3600;
	
	var nbHours=Math.floor(reste/3600);
	reste -= nbHours*3600;
	
	var nbMinutes=Math.floor(reste/60);
	reste -= nbMinutes*60;

	var nbSeconds=reste;

	if (nbJours>0)
		result=result+nbJours+'j ';

	if (nbHours>0)
		result=result+nbHours+'h ';

	if (nbMinutes>0)
		result=result+nbMinutes+'min ';

	if (nbSeconds>0)
		result=result+nbSeconds+'s ';
	
	return result;  
}

/** Fonction gérant le texte de decription des infobulles des clients sur la carte.
 * @param string raisonSocial : le temps en secondes.
 * @param string url : l'url réécrite du client
 * @param string adresse : l'adresse du client
 * @param string codPostal : le code postal du client
 * @param string ville : la ville du client
 * @param string tel : le numero de telephone du client
 * @reurn string texte : renvoie la description du client en format html
 */
function markerContent(raisonSocial,url,adresse,codPostal,ville,tel){
	var texte ="";

	if ((raisonSocial!=null)&&(raisonSocial!="")&&(url!=null)&&(url!="")) {
		texte += "<strong><a target=\"_blank\" href=\""+url+"\">"+raisonSocial+"</a></strong><br/>";
	}
	else if ((raisonSocial!=null)&&(raisonSocial!="")){
		texte += "<strong>"+raisonSocial+"</strong><br/>";
	}
	if((adresse!=null)&&(adresse!="")){
		texte += "<span>"+adresse+"</span><br/>";
	}
	if((codPostal!=null)&&(codPostal!="")&&(ville!=null)&&(ville!="")){
		texte += "<span>"+codPostal+" "+ville+"</span><br/>";
	}
	if((tel!=null)&&(tel!="")){
		texte += "<span>"+tel+"</span><br/>";
	}
	return texte;
}

/*
 *  Fonction permettant de faire des points eclaté qui ne se supperpose pas.
 *  @param markerLayer : la couche marker de la page
 */

function burster() {
	reset();
	markerLayer.explode();
}

/*
 *  Fonction permettant de reset l etat du markerLayer
 *  @param markerLayer : la couche marker de la page.
 */
function reset() {
    markerLayer.reset();
}

	
function changeOptionGoto(){
	jQuery(".choix1").css({ 'background': "#DEDEDE",'font-weight': 'bolder'});
	jQuery(".choix2").css({ 'background': "#DCE4ED", 'font-weight': 'normal'});
	
	jQuery(".choix1").unbind("click", changeOptionGoto);
	jQuery(".choix2").bind("click", changeOptionGoBack);
	
	var paysArriveeA = jQuery("#paysArriveeA").val();
	var villeArriveeA = jQuery("#villeArriveeA").val();
	var adresseArriveeA = jQuery("#adresseArriveeA").val();

	jQuery("#paysArriveeA").val(jQuery("#paysDepartA").val());
	jQuery("#villeArriveeA").val(jQuery("#villeDepartA").val());
	jQuery("#adresseArriveeA").val(jQuery("#adresseDepartA").val());
	jQuery("#paysDepartA").val(paysArriveeA);
	jQuery("#villeDepartA").val(villeArriveeA);
	jQuery("#adresseDepartA").val(adresseArriveeA);
	
}

function changeOptionGoBack(){
	jQuery(".choix2").css({ 'background': "#DEDEDE",'font-weight': 'bolder'});
	jQuery(".choix1").css({ 'background': "#DCE4ED",'font-weight': 'normal'});

	jQuery(".choix1").bind("click", changeOptionGoto);
	jQuery(".choix2").unbind("click",changeOptionGoBack);

	var paysDepartA = jQuery("#paysDepartA").val();
	var villeDepartA = jQuery("#villeDepartA").val();
	var adresseDepartA = jQuery("#adresseDepartA").val();
	
	jQuery("#paysDepartA").val(jQuery("#paysArriveeA").val());
	jQuery("#villeDepartA").val(jQuery("#villeArriveeA").val());
	jQuery("#adresseDepartA").val(jQuery("#adresseArriveeA").val());
	jQuery("#paysArriveeA").val(paysDepartA);
	jQuery("#villeArriveeA").val(villeDepartA);
	jQuery("#adresseArriveeA").val(adresseDepartA);
}


function traceRouteItineraire(km){
	var country = jQuery("#paysArriveeA").val();
	var town = jQuery("#villeArriveeA").val();
	var address = jQuery("#adresseArriveeA").val();

	var addr = new Mappy.api.geolocation.AddressLocation(country, town, address);
	geocode(addr);

	function geocode (addr)
	{
	    var geo = new Mappy.api.geolocation.Geocoder();
	    geo.geocode(addr, function (results)
	    {        
	        for (var i = 0; i < results.length; i += 1)
	        {
	            var coor1 = (results[i].Placemark.Point.coordinates[0]);
	            var coor2 = (results[i].Placemark.Point.coordinates[1]);
	            if(km<50){
	            	map.setCenter(new Mappy.api.geo.Coordinates(coor1,coor2),5); 
	            }else if(km<110) {
	            	map.setCenter(new Mappy.api.geo.Coordinates(coor1,coor2),4); 
	            }else if(km<450) {
	            	map.setCenter(new Mappy.api.geo.Coordinates(coor1,coor2),3); 
	            }else{
	            	map.setCenter(new Mappy.api.geo.Coordinates(coor1,coor2),2); 
	            }
			}       
	    });
	}  
}

function mapMarker(){
	jQuery("#mymap").hide();
	jQuery("#mymapPoint").show();
	
	var country = jQuery("#paysArriveeA").val();
	var town = jQuery("#villeArriveeA").val();
	var address = jQuery("#adresseArriveeA").val();

	var markerLayer = new Mappy.api.map.layer.MarkerLayer(40);
	mapPoint.addLayer(markerLayer);
	
	var icon = new Mappy.api.ui.Icon(Mappy.api.ui.Icon.DEFAULT);
	icon.image = "http://webfiles/images/habiter/mappy/pointerMap.png";
	
	var addr = new Mappy.api.geolocation.AddressLocation(country, town, address);
	geocode(addr);

	function geocode (addr)
	{
	    var geo = new Mappy.api.geolocation.Geocoder();
	    geo.geocode(addr, function (results)
	    {        
	        for (var i = 0; i < results.length; i += 1)
	        {
	            var coor1 = (results[i].Placemark.Point.coordinates[0]);
	            var coor2 = (results[i].Placemark.Point.coordinates[1]);
	            if(address!="" && address!=null){
		            mapPoint.setCenter(new Mappy.api.geo.Coordinates(coor1,coor2),8); 
	            }else{
	            	mapPoint.setCenter(new Mappy.api.geo.Coordinates(coor1,coor2),5); 
	            }
	            var marker = new Mappy.api.map.Marker(new Mappy.api.geo.Coordinates(coor1, coor2), icon);
			    marker.addToolTip(town);
			    marker.addListener("click", function ()
			    {
			        marker.openPopUp(address);
			    });
			    markerLayer.addMarker(marker);
			}       
	    });
	}  
}

function selectPays(select,order) {
	var pays = select.options[select.selectedIndex].value;
	if(order==1){
	  jQuery("#paysArriveeA").val(pays);
	}else if(order ==2){
		jQuery("#paysDepartA").val(pays);
	}
}

/*
 * 
Fonction pour afficher/cacher un élément
*/
function showHideSearch(anId)
{
	var id = jQuery("#"+anId);
	if (jQuery(id).is(":visible"))
	{
		// Contenu caché, le rendre visible
		jQuery(id).hide("normal");
	}else{
		// Contenu visible, le cacher
		jQuery(id).show("normal");
	}
}



