   var map; /*mapa*/
   var gdir; /*gdirections*/
   var geocoder = null; /*Geocoder */
   var mgr; /*Marker manager*/
   var mgrloaded = false; /*Flag de carrega del marker manager*/
   
   var altaservei = ""; /*Text informatiu de la alta de servei*/
   var loader;
   var loader2;
   var resultats, toolsresultats, toolsmap;
   var queryroute = false;
   var litros = 50;
   
   var marklist = new Array();
   var infowindow = new Array();
   var pricelist = new Array();
   var origen_text;
   var desti_text;

/* ------------ Funcionalitats buscador ----------- */
   function togleVisibility(visible, invisible){
   		divVis = document.getElementById(visible);
		divInv = document.getElementById(invisible);	
		divVis.style.visibility="hidden";
		divInv.style.visibility="visible"
   }
   function submitForm(form, currEvent){
   	 	if((currEvent == "gasolinera.buscarPunt")||(currEvent=="gasolinera.buscarRuta")){
			var returnvalue = false;
			/*contar pàgina vista  per a analytics*/
			var pageTracker = _gat._getTracker("UA-4554843-1");
			pageTracker._initData();
			pageTracker._trackPageview();
			if(CheckForm(form)){
				if(form.id == "form_punt")
					returnvalue = showAddress(form.origen_punt.value);
				else
					returnvalue = setDirections(form.origen_ruta.value, form.desti_ruta.value, "es_ES");
	
			}
			return returnvalue;
		}
		else if(CheckForm(form)){
			if(form.id=="form_punt"){
				returnvalue = fillLatLang(form, form.origen_punt.value);
			}else{
				returnvalue = true;
			}
			return returnvalue;
		}
		return false;
   }
   function fillLatLang(form, address) {
      if (geocoder) {
	      geocoder.getLatLng(
          address+", spain",
          function(point) {
            if (!point) {
			  UnmarckAll();
			  MarckError(form.origen_punt.id, "textbuscador1", address + " no se ha encontrado");	
            } else {
				form.latitud_punt.value =point.x;
				form.longitud_punt.value = point.y;
				//Submit the form after all
			  	document.getElementById("form_punt").submit();
		    }
          }
        );
      }
	  return false;
    }
   function CheckForm(form) {
	 	UnmarckAll();
		var returnvalue = true;
	
		if(form.id=="form_punt"){
			if(form.origen_punt.value == ""){
				MarckError(form.origen_punt.id, "textbuscador1", "Por favor, introduce una direcciÃ³n vÃ¡lida.");
				form.origen_punt.focus();
				returnvalue = false;
			}else if(form.tcomb_punt.value=="0"){
				MarckError(form.tcomb_punt.id, "textbuscador1", "Por favor, selecciona el tipo de carburante de tu vehÃ­culo.");
				form.tcomb_punt.focus();
				returnvalue = false;
			}
		}else{
			if(form.origen_ruta.value == ""){
				MarckError(form.origen_ruta.id, "textbuscador2", "Porf avor, introduce una direcciÃ³n vÃ¡lida.");
				form.origen_ruta.focus();
				returnvalue = false;
			}else if(form.desti_ruta.value==""){
				MarckError(form.desti_ruta.id, "textbuscador2", "Por favor, introduce una direcciÃ³n vÃ¡lida.");
				form.desti_ruta.focus();
				returnvalue = false;
			}else if(form.tcomb_ruta.value=="0"){
				MarckError(form.tcomb_ruta.id, "textbuscador2", "Por favor, selecciona el tipo de carburante de tu vehÃ­culo.");
				form.tcomb_ruta.focus();
				returnvalue = false;
			}
		}
		return returnvalue;	
	}
   function MarckError(id, idtext, text){
   		if(id != ""){
			var field = document.getElementById(id);
			field.style.border ="2px solid red";	
		}
   		var errorbox = document.getElementById(idtext);
		errorbox.innerHTML= text;
		errorbox.style.display= "inline-block"
		var buscador = document.getElementById("buscador");
		buscador.style.height = "65px"
	}
   function UnmarckAll(){
		var field
		field = document.getElementById("origen_punt");
		field.style.border ="2px inset #ccc";
		field = document.getElementById("tcomb_punt");
		field.style.border ="2px inset #ccc";
		field = document.getElementById("origen_ruta");
		field.style.border ="2px inset #ccc";
		field = document.getElementById("desti_ruta");
		field.style.border ="2px inset #ccc";
		field = document.getElementById("tcomb_ruta");
		field.style.border ="2px inset #ccc";
		field = document.getElementById("textbuscador1");
		field.innerHTML="";
		field.style.display= "none"
		field = document.getElementById("textbuscador2");
		field.innerHTML="";
		field.style.display= "none"
		
		var buscador = document.getElementById("buscador");
		buscador.style.height = "53px"
	}

 /*------------ InicialitzaciÃ³ diferent pÃ gines ---- */
   function initialize(currEvent) {
	//Agafem els litres que tingui guardats l'usuari en el dipÃ²sit
	var tmplitros = getCookie("litresdiposit");
	if(tmplitros =="")
		litros = 50;
	else
		litros = parseInt(tmplitros); 
	
	
	if(currEvent == "gasolinera.dspHome")
			initialize_home();
	else if(currEvent =="gasolinera.dspProvincia")
			initialize_provincia();
	else if(currEvent =="gasolinera.dspMunicipi")
			initialize_llista_map();
	else if(currEvent =="gasolinera.dspGasolinera")
			initialize_gasolinera();
	else if(currEvent =="gasolinera.buscarPunt")
			initialize_buscarPunt();
	else if(currEvent =="gasolinera.buscarRuta")
			initialize_buscarRuta();
	else if(currEvent =="gasolinera.dspMarcaProvincia")
		initialize_llista_map();
	else if(currEvent.indexOf('gasolinera') == 0)
		initialize_generic_buscador();
	else if(currEvent.indexOf('seccio.dspSeccioEntitat') == 0)
		initialize_generic_buscador();
	else
		initialize_generic();
    }
   function initialize_generic(){
		
   }
   function initialize_generic_buscador(){
		   geocoder = new GClientGeocoder();
   }
   
   function initialize_home(){
  	   	adjustNavigatorHeight();
		window.onresize = adjustNavigatorHeight;
					
		if (GBrowserIsCompatible()) {
        
		/*Creem el objecte map, gdir i geocoder */
		map = new GMap2(document.getElementById("gmap"));
        gdir = new GDirections(map); 
 	 	geocoder = new GClientGeocoder();
        
		/*Afegim uns quants listeners */
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(map, "load", onGMapsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
        
		
		resultats = document.getElementById("resultats");
		toolsresultats = document.getElementById("toolsresultats");
		toolsmap = document.getElementById("toolsmap");
	    loader = document.getElementById("loader");
      	loader2 = document.getElementById("loader2");
	
		/*Configurem el mapa*/
		setonInitialState()
		
		/*Posem el mapa a la seva posiciÃ³ inicial */
		setToInitialPosition();
		}
	}
   function initialize_buscarPunt(){
	 	adjustNavigatorHeight();
	 	window.onresize = adjustNavigatorHeight;
	 	
	 	if (GBrowserIsCompatible()) {
	 	
	 		/*Creem el objecte map, gdir i geocoder */
			map = new GMap2(document.getElementById("gmap"));
			gdir = new GDirections(map);
			geocoder = new GClientGeocoder();
				
			/*Afegim uns quants listeners */
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
			GEvent.addListener(map, "load", onGMapsLoad);
			GEvent.addListener(gdir, "error", handleErrors);
				
			
			resultats = document.getElementById("resultats");
			toolsresultats = document.getElementById("toolsresultats");
			toolsmap = document.getElementById("toolsmap");
			loader = document.getElementById("loader");
			loader2 = document.getElementById("loader2");
				
			/*Configurem el mapa*/
			setonInitialState()
			
			if ((typeof(URLlatitud) == 'undefined') || (typeof(URLlongitud) == 'undefined') ||(URLlatitud == "") || (URLlongitud == "")) {
				showAddress(URLorigen);
			}
			else {
				origen_text = URLorigen;
				var point = new GLatLng(URLlatitud, URLlongitud);
				map.setCenter(point, 13);
					
					
				var marker = new GMarker(point);
				map.addOverlay(marker);
				title = "Gasolineras cerca de " + URLorigen;
				
				generateAltaServeiPunt(URLtcomb,URLlatitud,URLlongitud,URLorigen);
				paintGasData(title, markarray);
				// alert("Hola!!!");
			}
		}
	}
   function initialize_buscarRuta(){
	 	adjustNavigatorHeight();
	 	window.onresize = adjustNavigatorHeight;
	 	
	 	if (GBrowserIsCompatible()) {
	 	
	 		/*Creem el objecte map, gdir i geocoder */
			map = new GMap2(document.getElementById("gmap"));
			gdir = new GDirections(map);
			geocoder = new GClientGeocoder();
				
			/*Afegim uns quants listeners */
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
			GEvent.addListener(map, "load", onGMapsLoad);
			GEvent.addListener(gdir, "error", handleErrors);
				
			
			resultats = document.getElementById("resultats");
			toolsresultats = document.getElementById("toolsresultats");
			toolsmap = document.getElementById("toolsmap");
			loader = document.getElementById("loader");
			loader2 = document.getElementById("loader2");
				
			/*Configurem el mapa*/
			setonInitialState()
			
			setDirections(URLorigen, URLdesti, "es_ES");
			
		}
	}
	
   function initialize_provincia(){
	   var bound = new GLatLngBounds(new GLatLng(latitud_min, longitud_min), new GLatLng(latitud_max,longitud_max));
	   var map = new GMap2(document.getElementById("gmap"));
	   var latlng = bound.getCenter();
	   
	   geocoder = new GClientGeocoder();
	   var zoomlevel = map.getBoundsZoomLevel(bound) 	
	   // map.setMapType(G_SATELLITE_TYPE);
	   map.addControl(new GSmallMapControl());
	   map.setCenter(latlng, zoomlevel, G_NORMAL_MAP );
	}
	
   function initialize_llista_map(){
		adjustNavigatorHeight();
		window.onresize = adjustNavigatorHeight;
		
		var bound = new GLatLngBounds(new GLatLng(latitud_min, longitud_min), new GLatLng(latitud_max,longitud_max));
	  	map = new GMap2(document.getElementById("gmap"));
	 	var latlng = bound.getCenter();
	   	geocoder = new GClientGeocoder();
		
		loader = document.getElementById("loader");
		
		/*Afegim uns quants listeners */
		GEvent.addListener(map, "load", onGMapsLoad);
		
		  
		var zoomlevel = map.getBoundsZoomLevel(bound) 	
	  	map.addControl(new GSmallMapControl());
	 	map.setCenter(latlng, zoomlevel, G_NORMAL_MAP );
	  
	  	if(mgrloaded==false){
			var mgrOptions = { borderPadding: 50, maxZoom: 15, trackMarkers: true };
			mgr = new MarkerManager(map, mgrOptions);
			mgrloaded=true;
		}
		pricelist = new Array();
	  	
		 //Fill Marker manager
		for (var i = 0; i < markarray.length; i++) {
			marklist[i] = afegirGasolinera2(markarray[i].icon,
			markarray[i].shadow,
			markarray[i].lat,
			markarray[i].lng,
			markarray[i].url,
			markarray[i].rtl,
			markarray[i].prcBIO,
			markarray[i].prcG95,
			markarray[i].prcG98,
			markarray[i].prcG97,
			markarray[i].prcGA,
			markarray[i].prcNGA,
			markarray[i].prcGB,
			markarray[i].prcGC,
			markarray[i].dir,
			markarray[i].loc, i);
			
			if(typeof(markarray[i].prc) != 'undefined')
				pricelist[i] = parseFloat(markarray[i].prc.replace(",", "."));
				
			/*afegirGasolinera2(iconpic, shadowpic, lat, lng, url, rtl, prcBIO, prc95, 
			prc98, prc97, prcgA, prcngA, prcgB, prcgC, dir, loc, index)*/
	 }

	 mgr.addMarkers(marklist, map.getZoom());
	 mgr.refresh();
	 loader.style.visibility = "hidden";
	}
   function initialize_gasolinera(){
	   map = new GMap2(document.getElementById("gmap"));
	   var latlng = new GLatLng(latitud, longitud);
		
	   geocoder = new GClientGeocoder();
	   // map.setMapType(G_SATELLITE_TYPE);
	   map.addControl(new GSmallMapControl());
	   map.setCenter(latlng, 14, G_NORMAL_MAP );
	
	   // icono refer mida
	   var icon = new GIcon(G_DEFAULT_ICON);
	         
	   markerOptions = { icon:icon };
	   mark = new GMarker(latlng,markerOptions);
	
	   map.addOverlay(mark);
	}
   
 /*------------ Funcionalitats de busqueda ---- */   
   function setonInitialState(){
		map.addControl(new GSmallMapControl());
	}
   function setToInitialPosition(){
		bound = new GLatLngBounds(new GLatLng(35.91, -10), new GLatLng(43.82, 4.41));
		var zoomlevel = map.getBoundsZoomLevel(bound)
		map.setCenter(new GLatLng(40, -3.706512), zoomlevel);
		
		/*Amagem els loaders */
		loader.style.visibility = "hidden";
		loader2.style.visibility = "hidden";
		
	}
   function setDirections(fromAddress, toAddress, locale) {
      /*Show loaders */
		loader.style.visibility = "visible";
		loader2.style.visibility = "visible";
			
		origen_text = fromAddress;
		desti_text = toAddress;
		
	 	 gdir.load("from: " + fromAddress + ", spain" + " to: " + toAddress + ", spain", { "locale": locale });
	 	 queryroute = true;
		 return false;
    }
   function veureRuta(rutapoly)
    {
			// get tipus combustible
			form = document.getElementById("form_ruta");
			tipus_combustible = form.tcomb_ruta.value;
			fromAddress = form.origen_ruta.value;
			toAddress = form.desti_ruta.value;
			
			// alert(tipus_combustible);
			url = "/services/getxml2.cfm?tcomb=" + tipus_combustible + "&polyline=" + rutapoly + "&origen=" + fromAddress + "&destino=" + toAddress;
			// alert(url);
			// debug	
			//status=document.getElementById("status");
			//status.innerHTML = url;
			generateAltaServeiRuta(tipus_combustible, rutapoly,fromAddress,toAddress);
			downloadResults(url);
		
    }
   function showAddress(address) {
	  origen_text = address;
	  queryroute = false;
	  if (geocoder) {
        geocoder.getLatLng(address+", spain",
        function(point) {
        	if (!point) {
				UnmarckAll();
			  	MarckError("origen_punt", "textbuscador1", address + " no se ha encontrado")	
            } 
			else {
				/*Show loaders */
				loader.style.visibility = "visible";
				loader2.style.visibility = "visible";
			
				/*si el marker manager ja estat carregat... borrem tots els markers*/
				if (mgrloaded == true) {
					mgr.clearMarkers();
				}
		
			 
				map.clearOverlays();
              	map.setCenter(point, 13);
              	var marker = new GMarker(point);
              	map.addOverlay(marker);
           	 	
				// get tipus combustible
	    		form = document.getElementById("form_punt");
	    		tipus_combustible = form.tcomb_punt.value;
            
    			url = "/services/getxml2.cfm?tcomb="+ tipus_combustible +"&point=" + point.y + "," + point.x + "&origen=" + escape(address);
    			generateAltaServeiPunt(tipus_combustible,point.y,point.x,address);
			
    			downloadResults(url);
				// alert("Hola!!");
			}
          }
        );
      }
	  return false;
    }
   function downloadResults(url){
		GDownloadUrl(url, function(data){
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			var titulo = xml.documentElement.getElementsByTagName("title");
			var markarray = new Array();
			
			//Fill the markarray with the gas station data
			
			for (var i = 0; i < markers.length; i++) {
				markarray[i] = new Array();
				markarray[i].icon = markers[i].getAttribute("icon");
				markarray[i].shadow = markers[i].getAttribute("shadow");
				markarray[i].lat = markers[i].getAttribute("lat");
				markarray[i].lng = markers[i].getAttribute("lng");
				markarray[i].url = markers[i].getAttribute("url");
				markarray[i].rtl = markers[i].getAttribute("rtl");
				markarray[i].prc = markers[i].getAttribute("prc");
				markarray[i].dir = markers[i].getAttribute("dir");
				markarray[i].loc = markers[i].getAttribute("loc");
			}
			
			//Add icons and write gas tdata
			paintGasData(GXml.value(titulo[0]), markarray)
			
			
		});
	}
   function paintGasData(title, markarray){
		//$("#resultados").css("overflow-y", "scroll");
		var text = "";
		var preciodeposito
		marklist = new Array();
		pricelist = new Array();
		var opcions = "<div class='controldiposit'><input type='text' value='"+litros+"' onblur='changeDeposito(parseInt(this.value));' onkeypress='if(event.keyCode==13){changeDeposito(parseInt(this.value));this.onblur();}'><div onclick='increaseDeposito();' class='increase'> </div><div onclick='decreaseDeposito();' class='decrease'> </div></div>"
		var diferencia;
		var clase = "";
		for (var i = 0; i < markarray.length; i++) {
			marklist[i] = afegirGasolinera(markarray[i].icon,
						markarray[i].shadow,
						markarray[i].lat,
						markarray[i].lng,
						markarray[i].url,
						markarray[i].rtl,
						markarray[i].prc,
						markarray[i].dir,
						markarray[i].loc, i);
	        /*
			if(markarray[i].icon == "http://local.gas.encooche.com/includes/images/icons/green/green_"+ (i+1)+".gif") 
				var clase = "background: url(/includes/images/icons/green/green_"+ (i+1)+".gif)  no-repeat";
			else if(markarray[i].icon == "http://local.gas.encooche.com/includes/images/icons/yellow/yellow_"+(i+1)+".gif")
				var clase = "background: url(/includes/images/icons/yellow/yellow_"+ (i+1)+".gif)  no-repeat";
			else if(markarray[i].icon == "http://local.gas.encooche.com/includes/images/icons/red/red_"+(i+1)+".gif")
				var clase = "background: url(/includes/images/icons/red/red_"+ (i+1)+".gif)  no-repeat";
			*/
			if(markarray[i].icon.indexOf("yellow_dot") == -1){
				clase = "background: url("+markarray[i].icon+")  no-repeat top left;";
			}else{
				clase = "background: url("+markarray[i].icon.replace('yellow_dot', 'yellow')+")  no-repeat top left;";
			}
				
			
			pricelist[i] = parseFloat(markarray[i].prc.replace(",", "."));
			preciodeposito = pricelist[i]*litros;
			preciodeposito = preciodeposito.toFixed(2);
			preciodeposito = preciodeposito.replace(".", ",");
			
		
			
			text += "<li style='" + clase + "' class='gaselement'><span class='gasolinera' onClick='marklist["+ i +"].openInfoWindowHtml(infowindow["+i+"]);' >"+markarray[i].rtl + "</span><ul class='llistadata'><li><strong>Precio:</strong> "+ markarray[i].prc +" &euro; por litro.</li><li>"+opcions+" litros cuestan <span class='preciodeposito'>" + preciodeposito + " &euro;</span></li><li><strong>Direcci&oacute;n:</strong> " + markarray[i].dir + "<br/>" + markarray[i].loc + "</li><li> <a href='" + markarray[i].url + "'>m&aacute;s informaci&oacute;n...</a></li></ul></li>";
		 }
		 
		 
		/* text = "<div id='maxahorro'>Un depÃ³sito de "+opcions+" litros puede salirte hasta <span class='preciodeposito'>" + diferencia +"&euro;</span> mÃ¡s barato en funciÃ³n de la gasolinera que elijas. </div><ul id='llistagasolineres'>" + text;*/
		 text = altaservei +"<ul id='llistagasolineres'>" + text;
		if(queryroute)
			text = "<h3>Gasolineras entre " + origen_text + " y "+desti_text+"</h3>" + text;
		else
			text = "<h3>Gasolineras cerca de " + origen_text + "</h3>" + text;
		
		
		 text +="</ul>";
         resultats.innerHTML = text;
		 //Hide loader 2 
		 loader2.style.visibility = "hidden";
		
	 	 if(mgrloaded)
		 	 mgr.clearMarkers();
		 setTimeout("mgr.addMarkers(marklist, map.getZoom()-1);mgr.refresh(); loader.style.visibility = 'hidden';", 100);
		
		
	}    
   function afegirGasolinera(iconpic, shadowpic, lat, lng, url, rtl, prc, dir, loc, index){
			var markerOptions;
			var marker;
			var latlng = new GLatLng(parseFloat(lat), parseFloat(lng));
			
		    // icono refer mida
            icon = new GIcon(G_DEFAULT_ICON);
            icon.image = iconpic;
        
        	icon.infoWindowAnchor = new GPoint(16, 0);
			if (iconpic.indexOf("yellow_dot") == -1) {
				icon.shadow = shadowpic;
				icon.shadowSize = new GSize(59, 32);
				icon.iconSize = new GSize(34, 36);
				icon.iconAnchor = new GPoint(17, 18);
			}
			else {
				icon.shadow ="";
				icon.iconSize = new GSize(16, 16);
				icon.iconAnchor = new GPoint(8, 8);
			}
        	
            
			markerOptions = {icon:icon, zIndexProcess:orderOfCreation};
			marker = new GMarker(latlng,markerOptions);
			
			
			if(iconpic.indexOf("yellow_dot") == -1){
				var style = "background: url("+ iconpic+") no-repeat";
			}else{
				var style = "background: url("+iconpic.replace('yellow_dot', 'yellow')+")  no-repeat";
			}
			var tcomb = getCookie('tcomb');
			var opcions = "<div class='controldiposit'><input type='text' value='"+litros+"' onblur='changeDeposito(parseInt(this.value));' onkeypress='if(event.keyCode==13){changeDeposito(parseInt(this.value));this.onblur();}'><div onclick='increaseDeposito();' class='increase'> </div><div onclick='decreaseDeposito();' class='decrease'> </div></div>";
			var preciodeposito =  (parseFloat(prc.replace(",", "."))*litros).toFixed(2);	
			infowindow[index] = "<div class='gaspopup'><h3 style='" + style + "'><a href='" + url + "'>" + rtl + "</a></h3><br/> Precio: <span class='preciolitro'>" + prc +  "</span> &euro; por litro<br/>"+opcions+"  litros cuestan <span class='preciodeposito'>"+preciodeposito+" &euro;</span><br/><br/>" + dir + "<br/>" + loc+ "<br/><a href='/handlers.cfm?event=user.altaServei&tcomb="+tcomb+"&point="+parseFloat(lat).toFixed(6)+"%2C"+parseFloat(lng).toFixed(6)+"&origen="+escape(loc.split(",")[0])+"'>AvÃ­same cada semana con los nuevos precios</a></div>";
			GEvent.addListener(marker, "click", function() {
		        marker.openInfoWindowHtml(infowindow[index]);
        	});

		
			 
			return marker;
	}
   function afegirGasolinera2(iconpic, shadowpic, lat, lng, url, rtl, prcBIO, prcG95, 
			prcG98, prcG97, prcGA, prcNGA, prcGB, prcGC, dir, loc, index){
			var markerOptions;
			var marker;
			var latlng = new GLatLng(parseFloat(lat), parseFloat(lng));
			
			
			// icono refer mida
            icon = new GIcon(G_DEFAULT_ICON);
            icon.image = iconpic;
        
        	icon.infoWindowAnchor = new GPoint(16, 0);
			if (iconpic.indexOf("yellow_dot") == -1) {
				icon.shadow = shadowpic;
				icon.shadowSize = new GSize(59, 32);
				icon.iconSize = new GSize(34, 36);
				icon.iconAnchor = new GPoint(17, 18);
			}
			else {
				icon.shadow ="";
				icon.iconSize = new GSize(16, 16);
				icon.iconAnchor = new GPoint(8, 8);
			}
        	
			
			markerOptions = {icon:icon, zIndexProcess:orderOfCreation};
			marker = new GMarker(latlng,markerOptions);
			
			
			if(iconpic.indexOf("yellow_dot") == -1){
				var style = "background: url("+ iconpic+") no-repeat";
			}else{
				var style = "background: url("+iconpic.replace('yellow_dot', 'yellow')+")  no-repeat";
			}
				
			infowindow[index] = "<div class='gaspopup'><h3 style='" + style + "'><a href='" + url + "'>" + rtl + "</a></h3><u>Precios:</u><br/>";
				
			if(prcG95 != "")
				infowindow[index] = infowindow[index] +=  "<strong>Gasolina 95:</strong> " + prcG95+  " &euro;<br/>";
			if(prcG98 != "")
				infowindow[index] = infowindow[index] +=  "<strong>Gasolina 98:</strong> " + prcG98 +  " &euro;<br/>"
			if(prcGA != "")
				infowindow[index] = infowindow[index] +=  "<strong>Di&eacute;sel:</strong> " + prcGA +  " &euro;<br/>";	
			if(prcNGA != "")
				infowindow[index] = infowindow[index] +=  "<strong>Di&eacute;sel mejorado:</strong> " + prcNGA +  " &euro;<br/>";
			if(prcGB != "")
				infowindow[index] = infowindow[index] +=  "<strong>Gasoleo B:</strong> " + prcGB +  " &euro;<br/>";
			if(prcGC != "")
				infowindow[index] = infowindow[index] +=  "<strong>Gasoleo C:</strong> " + prcGC +  " &euro;<br/>";
			if(prcG97 != "")
				infowindow[index] = infowindow[index] +=  "<strong>Gasolina 97:</strong> " + prcG97 +  " &euro;<br/>";
			if(prcBIO != "")
				infowindow[index] = infowindow[index] +=  "<strong>Biodi&eacute;sel:</strong> " + prcBIO +  " &euro;<br/>";
			
		
			infowindow[index ] += "<br/>" + dir + "<br/>" + loc + "</div>";
			GEvent.addListener(marker, "click", function() {
		        marker.openInfoWindowHtml(infowindow[index]);
        	});

			 
			return marker;
	}
	function orderOfCreation(marker,b) { 
        icon = marker.getIcon();
		if(icon.image.indexOf("green") != -1)
			return 4;
		else if(icon.image.indexOf("red") != -1)
			return 3;
		else if(icon.image.indexOf("yellow_dot") != -1)
			return 1;
		else
			return 2;
    } 
   function generateAltaServeiPunt(tcomb,y,x,origen){
		if(IdUsuari == 0) {
				altaservei = "<div class='alertbox'><p class='aviso'>Te avisamos cada semana con los nuevos precios: <form action='/handlers.cfm' method='get' class='formail'><input class='textf' onfocus='this.value=\"\";' type='text' name='email' value='tu@email.com'><input class='button' type='submit' value='Aceptar'>"
				altaservei += "<input type='hidden' name='jscheck' value='correcte'>";
				altaservei += "<input type='hidden' name='tcomb' value='" + tcomb + "'>";
				altaservei += "<input type='hidden' name='point' value='" + y + "," + x + "'>";
				altaservei += "<input type='hidden' name='origen' value='" + origen + "'>";
				altaservei += "<input type='hidden' name='event' value='user.altaServei'>";
				altaservei += "</form><br/>";
				//altaservei += "Tambi&eacute;n puedes <a class='fb_button fb_button_medium' onclick='javascript: fblogin();' href='#'><span class='fb_button_text'>Conectar con Facebook</span></a><br/><br/></p></div>";
		}else{
				altaservei = "<div class='alertbox2'><form action='/handlers.cfm' method='get' class='formail' id='altaform'><p class='aviso'><a onclick='document.getElementById(\"altaform\").submit(); return false;' href='#'>Recibir alerta en tu email</a>";
				altaservei += "<input type='hidden' name='tcomb' value='" + tcomb + "'>";
				altaservei += "<input type='hidden' name='point' value='" + y + "," + x + "'>";
				altaservei += "<input type='hidden' name='origen' value='" + origen + "'>";
				altaservei += "<input type='hidden' name='event' value='user.altaServei'>";
				altaservei += "<input type='hidden' name='jscheck' value='correcte'>";
				altaservei += "</p></form></div>";
		}
			
	}
	function fblogin(){
		top.location.href='https://www.facebook.com/dialog/oauth?client_id=217573474923286&scope=email,user_birthday,user_location,publish_stream&redirect_uri=http%3A%2F%2Fwww%2Eencooche%2Ecom%2Findex%2Ecfm%3Fevent%3Duser%2EfbRegister'; 
		return true
	}
   function generateAltaServeiRuta(tcomb,rutapoly,origen,desti){
		if(IdUsuari == 0) {
				altaservei = "<div class='alertbox'><p class='aviso'>Te avisamos cada semana con los nuevos precios: <form action='/handlers.cfm' method='get' class='formail'><input onfocus='this.value=\"\";' type='text' name='email' value='tu@email.com'><input class='button' type='submit' value='Aceptar'>"
				altaservei += "<input type='hidden' name='jscheck' value='correcte'>";
				altaservei += "<input type='hidden' name='tcomb' value='" + tcomb + "'>";
				altaservei += "<input type='hidden' name='polyline' value='" + rutapoly + "'>";
				altaservei += "<input type='hidden' name='origen' value='" + origen + "'>";
				altaservei += "<input type='hidden' name='destino' value='" + desti + "'>";
				altaservei += "<input type='hidden' name='event' value='user.altaServei'>";
				altaservei += "</form></p></div>";
			}else{
				altaservei = "<div class='alertbox2'><form action='/handlers.cfm' method='get' class='formail' id='altaform'><p class='aviso'><a onclick='document.getElementById(\"altaform\").submit(); return false;' href='#'>Recibir alerta en tu email</a>";
				altaservei += "<input type='hidden' name='tcomb' value='" + tcomb + "'>";
				altaservei += "<input type='hidden' name='polyline' value='" + rutapoly + "'>";
				altaservei += "<input type='hidden' name='origen' value='" + origen + "'>";
				altaservei += "<input type='hidden' name='destino' value='" + desti + "'>";
				altaservei += "<input type='hidden' name='event' value='user.altaServei'>";
				altaservei += "<input type='hidden' name='jscheck' value='correcte'>";
				altaservei += "</p></form></div>";
		}
			
	}
	

/* ------------ Funcionalitats del dipÃ²sit de combustible --------*/
   function increaseDeposito(){
	if (litros < 995) {
		litros = litros + 5;
		updateDeposito(litros);
	}
   }
   function decreaseDeposito(){
	if(litros > 5) {
		litros = litros - 5;
		updateDeposito(litros);
	}
   }
   function changeDeposito(valor){
	if((valor >0)&&(valor <1000)){
		litros = valor;
	}
	updateDeposito(litros);
   }
   function updateDeposito(valor){
	// Change the cookie
	setCookie("litresdiposit", valor, 365);
	
	// Update tools resultats
	/*
	var opcionsresultats = document.getElementById('opcionsresultats');
	if((typeof(opcionsresultats) != 'undefined')&&(opcionsresultats != null)){
		var input_opcionsresultats = opcionsresultats.getElementsByTagName('input');
		input_opcionsresultats[0].value = litros;
	}
	*/
	// Update open popups
	var div_gmap = document.getElementById('gmap');
	if ((typeof(div_gmap) != 'undefined') && (div_gmap != null)) {
		var inputs_gmap = div_gmap.getElementsByTagName('input');
		if (typeof(inputs_gmap[0]) != 'undefined') {
			inputs_gmap[0].value = litros;
			var popup_gmap = inputs_gmap[0].parentNode.parentNode;
			var spans_popup_gmap = popup_gmap.getElementsByTagName('span');
			var span_preciodeposito_gmap;
			var preciolitro_gmap
			for (i = 0; i < spans_popup_gmap.length; i++) {
				if (spans_popup_gmap[i].className == 'preciolitro') {
					preciolitro_gmap = parseFloat(spans_popup_gmap[i].innerHTML.replace(",", "."));
				}
				else 
					if (spans_popup_gmap[i].className == 'preciodeposito') {
						span_preciodeposito_gmap = spans_popup_gmap[i];
					}
			}
			span_preciodeposito_gmap.innerHTML = (preciolitro_gmap * litros).toFixed(2).replace(".", ",") + " &euro;";
		}
	}
	// Update max ahorro
	/*
	var maxahorro = document.getElementById('maxahorro');
	if ((typeof(maxahorro) != 'undefined') && (maxahorro != null)) {
		var span_maxahorro = maxahorro.getElementsByTagName('span');
		var input_span_maxahorro = maxahorro.getElementsByTagName('input');
		input_span_maxahorro[0].value = litros;
		for (j = 0; j < span_maxahorro.length; j++) {
			if (span_maxahorro[j].className == 'preciodeposito') {
				span_maxahorro[j].innerHTML = ((pricelist[pricelist.length - 1] * valor) - (pricelist[0] * valor)).toFixed(2).replace(".", ",") + " &euro;";
			}
		}
	}
	*/
	// Update llista resultats
	var llista = document.getElementById('llistagasolineres');
	if ((typeof(llista) != 'undefined') && (llista != null)) {
		var li_llista = llista.getElementsByTagName('li');
		var span_li_llista;
		var input_li_llista;
		var gasnum = 0;
		for (i = 0; i < li_llista.length; i++) {
			if (li_llista[i].className == 'gaselement') {
				span_li_llista = li_llista[i].getElementsByTagName('span');
				input_li_llista = li_llista[i].getElementsByTagName('input');
				if (typeof(input_li_llista[0]) != 'undefined') 
					input_li_llista[0].value = litros;
				for (j = 0; j < span_li_llista.length; j++) {
					if (span_li_llista[j].className == 'preciodeposito') {
						span_li_llista[j].innerHTML = (pricelist[gasnum] * valor).toFixed(2).replace(".", ",") + " &euro;";
					}
				}
				gasnum++;
			}
		}
	}
	// Update infowindows
	var input_infowindow;
	var span_infowindows;
	var part, part2;
	var flag= false;
	for(i=0;i<infowindow.length;i++){
		infowindow[i] = infowindow[i].replace(/<input type='text' value='.*' onblur=/, "<input type='text' value='"+litros+"' onblur=");
		infowindow[i] = infowindow[i].replace(/<span class='preciodeposito'>.* &euro;/, "<span class='preciodeposito'>"+(pricelist[i] * litros).toFixed(2).replace(".", ",")+" &euro;");
	}

	// Update preus gasolina a fitxa gasolinera
	var preusgasolinera = document.getElementById("preusgasolinera");
	if ((typeof(preusgasolinera) != 'undefined') && (preusgasolinera != null)) {
		var li_preusgasolinera = preusgasolinera.getElementsByTagName("li");
		var span_li_preusgasolinera;
		var input_li_preusgasolinera;
		var preciolitro_preusgasolinera;
		var span_preciodeposito_preusgasolinera;
		for (i = 0; i < li_preusgasolinera.length; i++) {
			input_li_preusgasolinera =  li_preusgasolinera[i].getElementsByTagName("input");
			input_li_preusgasolinera[0].value = litros;
			span_li_preusgasolinera = li_preusgasolinera[i].getElementsByTagName("span");
			for(j = 0; j< span_li_preusgasolinera.length;j++){
				if (span_li_preusgasolinera[j].className == 'preciolitro') {
					preciolitro_preusgasolinera = parseFloat(span_li_preusgasolinera[j].innerHTML.replace(",", "."));
				}
				else if (span_li_preusgasolinera[j].className == 'preciodeposito') {
					span_preciodeposito_preusgasolinera = span_li_preusgasolinera[j];
				}
			}
			span_preciodeposito_preusgasolinera.innerHTML = (preciolitro_preusgasolinera*litros).toFixed(2).replace(".", ",") + " &euro;";
		}
	}
	
	/* Update controls de formulari */
	var controllitres = document.getElementById("controllitres");
	if ((typeof(controllitres) != 'undefined') && (controllitres != null)) {
		var input_litres = controllitres.getElementsByTagName("input");
		input_litres[0].value = litros;
	}	
	
   }
/*------- HANDLERS ------------------------------*/
   function onGMapsLoad(){
 
		if(mgrloaded==false){
			var mgrOptions = { borderPadding: 50, maxZoom: 15, trackMarkers: true };
			mgr = new MarkerManager(map, mgrOptions);
			mgrloaded=true;
		}
		
	}
   function onGDirectionsLoad(){
		// Use this function to access information about the latest load()
		// results.
		
		//if (query != "ruta") { //if it is an external consult don't parse polyline
		//alert("onGdirectionsLoad")
		
		rutapoly ="";
		resultats.innerHTML = "";
		if(mgrloaded)
		 	 mgr.clearMarkers();
			 	
		poly = gdir.getPolyline();
		if (poly.getVertexCount() < 1000) {
			step = 10;
		}
		else {
			step = Math.round(poly.getVertexCount() / 100);
		}
		
		for (i = 0; i * step < poly.getVertexCount(); i++) {
			vertex = poly.getVertex(step * i);
			// status.innerHTML = status.innerHTML + vertex.toUrlValue() + "<br/>";
			rutapoly = rutapoly + vertex.toUrlValue() + ",";
		}
		
		rutapoly = rutapoly + (poly.getVertex(poly.getVertexCount() - 1)).toUrlValue();
		
		//status.innerHTML = status.innerHTML + "POST poly: " + rutapoly;
		
		veureRuta(rutapoly);
	}
	/*Handler de errors de google maps */
   function handleErrors(){
		UnmarckAll();
		loader.style.visibility = "hidden";
	  	loader2.style.visibility = "hidden";
		
		if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
			MarckError("origen_ruta", "textbuscador2", "");
			MarckError("desti_ruta", "textbuscador2", "No se ha podido encontrar una de las dos direcciones.")
			//Fill the webpage with default information in case you come from the outside
			if(mgrloaded== false){
				setonInitialState();
			}
				
		}else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
			MarckError("", "textbuscador2", "Error de Google Maps. IntÃ©ntalo de nuevo mÃ¡s tarde.")
		}else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
			//alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
			MarckError("origen_ruta", "textbuscador2", "");
			MarckError("desti_ruta", "textbuscador2", "No se ha podido completar la bÃºsqueda. Por favor, rellena los campos vacÃ­os.");
		}else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
			//alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
			MarckError("", "textbuscador2", "Error de Google Maps. IntÃ©ntalo de nuevo mas tarde.");			
		}else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
			//alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
			MarckError("origen_ruta", "textbuscador2", "");
			MarckError("desti_ruta", "textbuscador2", "No se ha podido encontrar la direcciÃ³n escrita. Vuelve a intentarlo con una combinaciÃ³n diferente.");

		}else {
			MarckError("", "textbuscador2", "Error desconocido. Int&eacute;ntelo de nuevo mÃ¡s tarde.");			
		}
	}
 
/*------- Eines Ãºtils ---------------------------*/
   function setCookie(c_name,value,expiredays)
	{
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +escape(value)+ ";path=/"+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	}
   function getCookie(c_name)
	{
		if (document.cookie.length>0)
  		{
  			c_start=document.cookie.indexOf(c_name + "=");
  			if (c_start!=-1)
    		{
    			c_start=c_start + c_name.length+1;
    			c_end=document.cookie.indexOf(";",c_start);
    			if (c_end==-1) c_end=document.cookie.length;
    				return unescape(document.cookie.substring(c_start,c_end));
    		}
  		}
		return "";
	}
   function isdefined( variable)
	{
	    return (typeof(window[variable]) == "undefined")?  false: true;
	}
   function adjustNavigatorHeight(){
		try {
		var navegador = document.getElementById("navegador");
			navegador.style.height = (getHeight() - 160) + "px";
		} 
		catch (err) {
			
		}
	}
   function getHeight() {
  		var myWidth = 0, myHeight = 0;
  		if( typeof( window.innerWidth ) == 'number' ) {
   		 //Non-IE
  			  myWidth = window.innerWidth;
  			  myHeight = window.innerHeight;
  		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
 		   //IE 6+ in 'standards compliant mode'
 		   myWidth = document.documentElement.clientWidth;
  		  myHeight = document.documentElement.clientHeight;
 		 } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
  		  //IE 4 compatible
  		  myWidth = document.body.clientWidth;
  		  myHeight = document.body.clientHeight;
  		}
  		return myHeight;
	}
 

