var map;
var dragZoom;
var mapCenter = new GLatLng(40,-3.703551);
var mapZoom = 6;
var markerMgr;
var codPostalMostradoActivo = null;

////////////////////////////////////////////
// Variables usadas para el calculo de rutas
var gdir;
var puntosCercanos = null;
var geocoder = null;
var addressMarker;
//////////////////////////////////////////

///////////////////////////////
//Objeto para el calculo de distancias
var calculoDistanciasOBJ = null;
//Objeto para usar las utilizades
var utilidadesOBJ = null;
//Objeto que controla las variables globales
var variablesGlobalesOBJ = null;
///////////////////////////////

var marcadoresProvincia = [];

var windowTabs = null;
var windowTabsToolTip = null;
var objetoVentana = null;
var objetoVentanaToolTip = null;
var windowWeb = null;
var ventanaUsosMultiples = null;
var ventanaMiniSites = null;
var	myPanorama = null;
var	myPanoramaw2 = null;
var menuIniciado = null;
var resizeObjeto = null;
var kaWinMan = null;
var streetViewHandler = null;
var ventanaStreetView = null;
var iconoStreeView = null;
var streeViewOverlay = null;
var ventanaPolPriv = windowPolPriv = null;

/*
    var greenMarkers = [];
    
    var greenMarkers = [
      {"name":"Central Park Zoo",              "lat":40.7677, "lng":-3.9715},
      {"name":"Central Park Boat House",       "lat":40.7754, "lng":-3.9688},
      {"name":"Jacqueline Onassis Reservoir",  "lat":40.7848, "lng":-3.9616},
      {"name":"Museum of Natural History",     "lat":40.7811, "lng":-3.9738},
      {"name":"Mount Sinai Hospital",          "lat":40.7893, "lng":-3.9538},
      {"name":"CUNY Hunter College",           "lat":40.7684, "lng":-3.9649},
      {"name":"Metropolitan Museum",           "lat":40.7791, "lng":-3.9629}
    ]
*/
		
    var clusterIcon = new GIcon(G_DEFAULT_ICON);
    clusterIcon.image = "./images/LP/cluster.png"; 
		clusterIcon.shadow = "./images/LP/icoCluster_s.png";
		clusterIcon.iconSize = new GSize(30, 30);
		clusterIcon.shadowSize = new GSize(45, 30);
		clusterIcon.iconAnchor = new GPoint(9, 34);
		clusterIcon.printImage = "./images/LP/icoCluster.png";
		//clusterIcon.infoWindowAnchor = new GPoint(9, 2);
	
		var tiendaIcon = new GIcon(G_DEFAULT_ICON);
    tiendaIcon.image = "./images/LP/visor.png"; 
    tiendaIcon.shadow = "./images/LP/icoTienda_s.png";
    tiendaIcon.iconSize = new GSize(16, 16);
    tiendaIcon.shadowSize = new GSize(25, 16);
    tiendaIcon.iconAnchor = new GPoint(8, 8);
    tiendaIcon.printImage = "./images/LP/visor.png"; 
    //tiendaIcon.infoWindowAnchor = new GPoint(5, 1);
    
    var tiendaIconOver = new GIcon(G_DEFAULT_ICON);
    tiendaIconOver.image = rutaImagenes+"icoTiendaOver.png";
    tiendaIconOver.shadow = rutaImagenes+"icoTiendaOver_s.png";
    tiendaIconOver.iconSize = new GSize(25, 25);
    tiendaIconOver.shadowSize = new GSize(38, 25);
    tiendaIconOver.iconAnchor = new GPoint(11, 13);
    tiendaIconOver.printImage = rutaImagenes+"icoTiendaOver.png";
    //tiendaIconOver.infoWindowAnchor = new GPoint(5, 1);
    
    var iconoSalida = new GIcon(G_DEFAULT_ICON);
    iconoSalida.image = "./images/LP/punto-a.png";
		iconoSalida.shadow = "./images/LP/punto-s2.png";
		iconoSalida.iconSize = new GSize(25, 35); // Ancho y Alto
		iconoSalida.shadowSize = new GSize(45, 41);
		iconoSalida.iconAnchor = new GPoint(12, 34);
		iconoSalida.printImage = "./images/LP/punto-a2.png";
		//iconoSalida.infoWindowAnchor = new GPoint(9, 2);
		
		var iconoLlegada = new GIcon(G_DEFAULT_ICON);
    iconoLlegada.image = "./images/LP/punto-b.png";
		iconoLlegada.shadow = "./images/LP/punto-s2.png";
		iconoLlegada.iconSize = new GSize(25, 35);
		iconoLlegada.shadowSize = new GSize(45, 41);
		iconoLlegada.iconAnchor = new GPoint(12, 34);
		iconoLlegada.printImage = "./images/LP/punto-b2.png";
		//iconoLlegada.infoWindowAnchor = new GPoint(9, 2);
		
		var iconoStreeViewPoint = new GIcon(G_DEFAULT_ICON);
    iconoStreeViewPoint.image = "./images/LP/streetview.png";
    iconoStreeViewPoint.shadow = "./images/LP/streetview-s.png";
    iconoStreeViewPoint.iconSize = new GSize(40, 40);
    iconoStreeViewPoint.shadowSize = new GSize(45, 41);
    iconoStreeViewPoint.iconAnchor = new GPoint(24, 40);
    iconoStreeViewPoint.printImage = "./images/LP/streetview.png";

$(document).ready(function(){ 
    if (GBrowserIsCompatible()) {
    	/*
    	//Creamos los DIVīs de carga de aplicacion
    	$("BODY").append(
		  	'<div id="controladorDeCarga">' +
		  		'<div id="cargandoBarraInferior">' +
          	'<span>Cargando...</span>' +
          '</div>' +
		  	'</div>');
			*/
			
			//Creo el objeto que controla las variables globales
			variablesGlobalesOBJ = new variablesGlobales();
			
      // create the map
      map = new GMap2(document.getElementById("map"));
      //map.addControl(new GLargeMapControl());
      //map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(40,-3.703551), 6);
      map.enableScrollWheelZoom();
			
			//Creamos el objeto para calcular Dist. Minimas
		  calculoDistanciasOBJ = new puntosCernanos();
		  //Creamos el objeto para usar las utilidades
		  utilidadesOBJ = new utilidades();
		   
		  agregarBackgroundControl(map);
		  agregarMapTypeControl(map);
			agregarZoomControl(map);
			
			//Ventana de Pestaņas -Menu-  
			var pestanas = new Array(null,'C&oacute;mo llegar','Cont&aacute;ctanos'); 
			//pestanas[2] = 'Ay&uacute;danos';
			kaWinMan = new kaWinManager('map');
			windowTabs = kaWinMan.createWin('ventanaPestanas');
			objetoVentana = windowTabs.setValues('Menu','Grupo Gali' ,0,27,300,300,false,false,pestanas); 
			windowTabs.pushContent(getRawObject('data'));
			$("#ventanaPestanas").css("left","-300px");
			
			//Ventana de Pestaņas -ToolTip- 
			pestanas = ["Informaci&oacute;n","C&oacute;mo llegar","Vista Calle"]; 
			windowTabsToolTip = kaWinMan.createWin('ventanaPestanasToolTip');
			objetoVentanaToolTip = windowTabsToolTip.setValues('ToolTip','Grupo Gali',400,27,370,207,false,false,pestanas); 
			windowTabsToolTip.pushContent(getRawObject('dataToolTipTabWindow'));
			windowTabsToolTip.domObj.style.display = 'none';
			
			//Ventana de Web -windowWeb- 
			pestanas = ["M&aacute;s Info.",null, "Vista Calle", null]; 
			windowWeb = kaWinMan.createWin('VentanaWeb');
			ventanaMiniSites = windowWeb.setValues('VentanaWeb','Entorno Web',0,27,1000,187,false,false,pestanas);
			windowWeb.pushContent(getRawObject('dataVentanaWeb'));
			windowWeb.domObj.style.display = 'none';
			
			//Ventana Usos Multiples -eMail, imprimir, ...
			var windowMultiple = kaWinMan.createWin('ventanaMultiple');
			ventanaUsosMultiples = windowMultiple.setValues('ventanaMultiple','Enviar e-Mail',360,87,450,300,false,true,null);
			windowMultiple.pushContent(getRawObject('formularioEmail'));
			windowMultiple.domObj.style.display = 'none';
			
			//Ventana Street-View
			var windowStreetView = kaWinMan.createWin('streetView');
			ventanaStreetView = windowStreetView.setValues('streetView','Vista de Calle',360,87,500,340,false,false,null);
			windowStreetView.pushContent(getRawObject('streeViewPanel'));
			windowStreetView.domObj.style.display = 'none';
			
			//Politica Privacidad
			pestanas = ["Pol. Privacidad",null, null, null]; 
			windowPolPriv = kaWinMan.createWin('ventanaPolPriv');
			ventanaPolPriv = windowPolPriv.setValues('ventanaPolPriv','Pol&iacute;tica de Privacidad -Grupo Gali-',360,87,450,300,false,true,null);
			windowPolPriv.pushContent(getRawObject('politicaPrivacidad'));
			ventanaPolPriv.domObj.style.display='none';
			
			//Desactivamos el eventos sobre la ventana de resultados de las tiendas
			$("#dataToolTipTabWindow").dblclick(function(ev){  
				try{ev.stopPropagation()}catch(ev){event.cancelBubble=true}; 
			});
			$("#dataToolTipTabWindow").mousedown(function(ev){  
				try{ev.stopPropagation()}catch(ev){event.cancelBubble=true}; 
			});
			
			var boxStyleOpts = {
				nOpacity:.2,
				sBorder:"2px solid red"
      }

      /* second set of options is for everything else */
      
      var otherOpts = {
          buttonHTML: "<img src='images/px.gif' class='barra-zoom1' />",
          buttonZoomingHTML: "<img src='images/px.gif' class='barra-zoom2' />",
          buttonStartingStyle: {width: '20px', height: '20px', position: 'absolute', left: '-175px', top:'2px'},
          backButtonEnabled: true, 
          overlayRemoveTime: 1500
      };
      
      /* third set of options specifies callbacks */
      var callbacks = {
          //buttonclick: function(){GLog.write("Looks like you activated DragZoom!")},
          //dragstart: function(){GLog.write("Started to Drag . . .")},
          //dragging: function(x1,y1,x2,y2){GLog.write("Dragging, currently x="+x2+",y="+y2)},
          //dragend: function(nw,ne,se,sw,nwpx,nepx,sepx,swpx){GLog.write("Zoom! NE="+ne+";SW="+sw)}
      };
  
  		//alert($('#btnCerca').css('left') );
  
      map.addControl(dragZoom = new DragZoomControl(boxStyleOpts, otherOpts, callbacks),  new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(205,1)));
      
      ////////////////////////////////////////////////////////
      // Para el calculo de rutas
      ////La salida del metodo gdir.load la introducimos en el div "directions"
        gdir = new GDirections(map, document.getElementById("directions"));  
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay);
        
      // Fin calculo de rutas
			///////////////////////////////////////////////////////
		  
				GEvent.addListener(map, "mouseover", function() {
				  if(!menuIniciado){
				  	menuIniciado = true;
				  	document.getElementById("tab1Menu").style.display = "block";
				  	$("#menu").click();
				  	objetoVentana.tab3.onclick(); 
				  }
				});
				
				GEvent.addListener(map, "moveend", function() { 
				  apantallaNavegador(false);
				  
				  if(cambiaPestana){
						objetoVentana.tab2.onclick();
					}
					
					cambiaPestana = false;
				});
				
				GEvent.addListener(map, "zoomend", function (antiguoZoom, nuevoZoom){
		         
		         if ((nuevoZoom < 7) && (nuevoZoom > 4) && (!variablesGlobalesOBJ.tiendaSeleccionada[0])){
		         		
		         		map.closeInfoWindow();
		         		//Limpiamos los marcadores de provincias
		         		if (marcadoresProvincia)
							    for (var z = 0; z < marcadoresProvincia.length; z++)
							    	map.removeOverlay(marcadoresProvincia[z]);	
				    		
				    		var codPostalMostradoActivo = null;
				    		
				    		//Reseteamos las rutas dibujadas
				    		utilidadesOBJ.reseteaRutas();
				    		
				    		//Borramos los contorno de las provincia
				    		if(utilidadesOBJ.contornoPoblacion){
					    		map.removeOverlay(utilidadesOBJ.contornoPoblacion);
					    		utilidadesOBJ.contornoPoblacion=null;
				    		}
				    		//Restauramos el icono del cluster pulsado
				    		if (variablesGlobalesOBJ.iconoClusterPulsado){
				    			map.addOverlay(variablesGlobalesOBJ.iconoClusterPulsado);
				    			variablesGlobalesOBJ.iconoClusterPulsado = null;
				    		}
				    		//Ocultamos la ventana de informacion de tienda
				    		windowTabsToolTip.domObj.style.display='none';
				    		
		         } else if (nuevoZoom < 5){
		         		map.setZoom(antiguoZoom); 
		         		alert("No es posible disminuir el valor del Zoom.");
		         } else if (nuevoZoom > 10){
		         		if(utilidadesOBJ.contornoPoblacion){
		         			//utilidadesOBJ.contornoPoblacion.hide();
		         			map.removeOverlay(utilidadesOBJ.contornoPoblacion);
					    		utilidadesOBJ.contornoPoblacion=null;
								}
		        }
		        /*
		        if (nuevoZoom < 11 && nuevoZoom > 7){
		        	if(utilidadesOBJ.contornoPoblacion)
									utilidadesOBJ.contornoPoblacion.show();
		        }
		        */
		        if (streeViewOverlay != null && nuevoZoom < 15){
		        	//Reseteamos la ventana de StreetView
		        	ventanaStreetView.headerButton1.onclick();
		        }
		        
		        repintarZooms(map);
    		}); 
    		
    		cargaClusterTiendas(function(){
			  	var timer = setInterval(function(){
	    			clearInterval(timer); 
				    //$("#cargandoBarraInferior").css({display: 'none'});
			  		$("#controladorDeCarga").remove();
			  		 
			  		$("#selectProvincia").selectOptions("40", true);
			  		cargaPoblacion('cp', 40);
			  		
	      	}, 1000);  
	      	
	      	var demo = setInterval(function(){
	    			if(document.getElementById('resultado_0')){
		    			clearInterval(demo); 
					    document.getElementById('resultado_0').onclick();
							map.panBy(new GSize(0, 40));
							
							if ($("#provpob"))
								$("#provpob").remove();
								
						$("#cont2").append("<div id='provpob' class='provincias'><div class='barra-posicion' onclick='cargaPoblacion(null,"+$("#selectProvincia").selectedValues('digito')+")'><a href='#'>"+$("#selectProvincia").selectedValues()+"</a></div><div class='barra-posicion'>Nueva Segovia</div></div>");
						}
	      	}, 1000);  
			  });

		} else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
});

// A function to create the marker and set up the event window
function createMarker(point,tipoTienda,html,zoom, tipoIcono, cp, poblacion, direccionCompleta, fotos, datosTienda) {
     
   var marker = new GMarker(point, tipoIcono);
   
   GEvent.addListener(marker, "click", function() { 
   		
   		//Cierro ventana de Stree-View
   		if(streeViewOverlay != null)
		    ventanaStreetView.headerButton1.onclick();
      
	   	if (tipoTienda == 'iconoProvincia'){
	   		
	   		//Maquetamos la informacion de la tienda seleccionada
	   		var htmlTienda = "<p class='flecha'>Direcci&oacute;n:</p><p class='direccion' style='width:190px;overflow:hidden;'>"+datosTienda[1]+"<br>" + datosTienda[2] + " " + datosTienda[3] + "</p><p class='flecha'>Tel&eacute;fono: 921 43 82 54</p><p class='flecha'>Fax: 921 43 46 85</p><p class='flecha' style='width:190px;overflow:hidden;'>"+ datosTienda[6] + "</p>";
	   		
		    marker.openToolTip(tipoTienda, htmlTienda, windowTabsToolTip.domObj, fotos);
		    posicionaVentanaInformacion(point, tipoTienda);
		    variablesGlobalesOBJ.tiendaSeleccionada = [{"direccion":direccionCompleta, "point":point, "infTienda":datosTienda}];
		    objetoVentanaToolTip.tab1.onclick();
		    
		 }
		  
		 if (tipoTienda == 'cluster'){
		 		//Cerramos la ventaba de pestaņas ToolTip si esta abierta
   			if(ToolTipInstanceTabWindow != null){ 
					$("#ventanaPestanasToolTip").fadeOut("fast", function(){map.removeOverlay(ToolTipInstanceTabWindow);ToolTipInstanceTabWindow = null;});
				}
				variablesGlobalesOBJ.tiendaSeleccionada = [];
   		
		    marker.openToolTip(tipoTienda, html, windowTabsToolTip.domObj);
		    posicionaVentanaInformacion(point, tipoTienda);
		 }
		 
   });
   
   if (tipoTienda == 'cluster'){
	   GEvent.addListener(marker, "dblclick", function() {
	   	
	   		//Cierro ventana de Stree-View
	   		if(ventanaStreetView.domObj.style.display != 'none')
		    	ventanaStreetView.headerButton1.onclick();
		    
	   	 cargaPoblacion(null, cp);
	   });
   }
   
   return marker;
}

function posicionaVentanaInformacion(point, tipoTienda){
	var pixXY = map.fromLatLngToContainerPixel(point);
	var reajusteX = 0;
	var reajusteY = 0;
	var instanciaToolTip = null;
	var ventanaPestanasVisible = parseInt($("#ventanaPestanas").css('width')) + parseInt($("#ventanaPestanas").css('left'));
					
	if (tipoTienda == 'iconoProvincia')
		instanciaToolTip = ToolTipInstanceTabWindow;
	else if (tipoTienda == 'cluster')
		instanciaToolTip = ToolTipInstance;
					
	if ((pixXY.y - instanciaToolTip.desplazamientoY) < parseInt(document.getElementById("fondoBarraHerram").style.height))
		reajusteY = instanciaToolTip.desplazamientoY + parseInt(document.getElementById("fondoBarraHerram").style.height) - pixXY.y + 5;
				
	if ((pixXY.x - instanciaToolTip.desplazamientoX) < ventanaPestanasVisible)
		reajusteX = ventanaPestanasVisible - (pixXY.x - instanciaToolTip.desplazamientoX) + 5;
					
	if ((pixXY.x + instanciaToolTip.desplazamientoX) > parseInt(document.body.offsetWidth))
		reajusteX = parseInt(document.body.offsetWidth) - (instanciaToolTip.desplazamientoX + pixXY.x) - 15;
						
	if (reajusteX != 0 || reajusteY != 0)
		map.panBy(new GSize(reajusteX, reajusteY));	
}

function muestraTiendaUnica(lat,lng, i){
	map.setCenter(new GLatLng(lat,lng),17);
	map.panBy(new GSize(0, 40));
	GEvent.trigger(marcadoresProvincia[i], "click");
}

function muestraTiendas(campo, valor, opciones){//jAlert(campo + " " + valor + " "  + opciones + " php/phpsqlajax_genxmlCluster.php?"+campo+"="+valor+"&opciones="+opciones+"&nombre_tienda="+cod_cadena);
				
  GDownloadUrl("php/phpsqlajax_genxmlCluster.php?"+campo+"="+valor+"&opciones="+opciones+"&nombre_tienda="+cod_cadena, function(data, responseCode) {
  	//jAlert("php/phpsqlajax_genxmlCluster.php?"+campo+"="+valor+"&opciones="+opciones+"&nombre_tienda="+cod_cadena,"");
				  // To ensure against HTTP errors that result in null or bad data,
				  // always check status code is equal to 200 before processing the data
				  if(responseCode == 200) {
				    var xml = GXml.parse(data);
				    
				    //para hacer un zoom a todas las tiendas de las provincias q no tenemos limites administrativos
				    var tipo_consulta = campo;
				    if (opciones)
				    	tipo_consulta = 'nombre_poblacion';
				    
				    //Limpiamos los marcadores de provincias y rutas si existen
				    for (var z = 0; z < marcadoresProvincia.length; z++)
				    	map.removeOverlay(marcadoresProvincia[z]);
				    
				    //Reseteamos las rutas dibujadas
				    utilidadesOBJ.reseteaRutas();
				    
				    // ===== Start with an empty GLatLngBounds object =====     
      			var bounds = new GLatLngBounds();
				    
				    var items = xml.documentElement.getElementsByTagName("marker");
				    var salida = "";
				    var html = "";
				    var numeroItems = items.length;
				    
				    for (var i = 0; i < numeroItems; i++) {
				    	var nom_comercial = items[i].getAttribute("name");
				      var poblacion = items[i].getAttribute("poblacion");
				      var address = items[i].getAttribute("address");
				      var lati = parseFloat(items[i].getAttribute("lat"));
				      var longi = parseFloat(items[i].getAttribute("lng"));
				      var cp = items[i].getAttribute("cp");
				      var point = new GLatLng(lati,longi);
				      var direccionCompleta = address+" ,"+cp+" ,"+poblacion;
				       
				      var fotos = new Array(2);
				      if (items[i].getAttribute("foto_ext_ver") == 'S'){
					      fotos[0] = items[i].getAttribute("foto_ext");
					      fotos[1] = items[i].getAttribute("foto_int");
				    	}
				      var telefono = items[i].getAttribute("telefono");
				      var fax = items[i].getAttribute("fax");
				      var email = "E-mail: " + items[i].getAttribute("email");
				      
							var datosTienda = new Array(nom_comercial, address, cp, poblacion, telefono, fax, email);
							
				      var marker = createMarker(point,'iconoProvincia',html,0, tiendaIcon, valor, poblacion, direccionCompleta, fotos, datosTienda);
		          map.addOverlay(marker);
		          
		          //Guardamos los marcadores de provincias
		          marcadoresProvincia[i]=marker;
		          // Sobrecarga Ralentiza IE
		          
		          salida += "<div id='resultado_"+i+"' class='resultado' onmouseover='IconoResaltadoListadoTiendas(this,"+lati+","+longi+")' onmouseout='eliminarIconoResaltado(this)' onclick='muestraTiendaUnica("+lati+","+longi+","+i+")'>"
							//salida += "<div class='resultfondo'></div>"
							salida += "<img src="+rutaImagenes+"resultado-logo.jpg alt='Logo de la empresa'>"
							salida += "<div id='tiendasProvincia' class='resultado-direccion'>"+address+",<br>"+poblacion+"</div>"
							salida += "<div class='clear'></div>"
							salida += "</div>"
									 
		          if (tipo_consulta == 'nombre_poblacion')
		          	bounds.extend(point);
				    }
				    
				    //Mostramos todas las tiendas de la provincia
				    document.getElementById("resultadosTiendasCarcanas").style.display='block';
				    var localizacion = null;
				    
				    if ($("#selectPoblacion").selectedValues() == 'Poblacion')
				    	localizacion = $("#selectProvincia").selectedValues();
				    else
				    	localizacion = $("#selectPoblacion").selectedValues() + " (" + $("#selectProvincia").selectedValues() + ")";
				  	
				  	if (numeroItems > 1)
				  		salida = "<h1>"+numeroItems+" Tiendas en "+localizacion+"</h1><div id='directionsPanel'></div>" + salida;
					else
						salida = "<h1>"+numeroItems+" Tienda en "+localizacion+"</h1><div id='directionsPanel'></div>" + salida;
				  	var panel = document.getElementById("resultadosTiendasCarcanas");
				  	panel.innerHTML  = salida; 
				  	//Fin listado de tiendas
				  	
				  	// Si opciones == 'muestraTiendasPueblo' Estamos mostrando las tiendas de un pueblo en concreto, dejamos el icono del cluster oculto
				  	if (opciones != 'muestraTiendasPueblo'){ 
			        //Restauramos el icono del cluster pulsado anteriormente
						  if (variablesGlobalesOBJ.iconoClusterPulsado){
						   	map.addOverlay(variablesGlobalesOBJ.iconoClusterPulsado);
						   	variablesGlobalesOBJ.iconoClusterPulsado = null;
						  }
							
							//Ocultamos el Icono del Cluster Pulsado
							for (var i = 0; i < variablesGlobalesOBJ.cargaInicialIconos.length; i++) {
							   if (variablesGlobalesOBJ.cargaInicialIconos[i]["cp_marker"] == valor){
							    	variablesGlobalesOBJ.iconoClusterPulsado = variablesGlobalesOBJ.cargaInicialIconos[i]["marker"];
								   	map.removeOverlay(variablesGlobalesOBJ.iconoClusterPulsado);
								 }
							}
						}
						
						if (tipo_consulta == 'nombre_poblacion'){
							// ===== determine the zoom level from the bounds =====
		          map.setZoom(map.getBoundsZoomLevel(bounds));
		
		          // ===== determine the centre from the bounds ======
		          map.setCenter(bounds.getCenter());
						}
						
					  if(ToolTipInstance != null) {
							map.removeOverlay(ToolTipInstance);
							ToolTipInstance = null;
						}	
					  
					  //objetoVentana.tab1.onclick();
 
				  } else if(responseCode == -1) {
				    alert("Data request timed out. Please try later.");
				  } else { 
				    alert("Request resulted in error. Check XML file is retrievable.");
				  }
	});
}
		
function muestraTiendasSinLimitesAdm(campo, valor){
				
  GDownloadUrl("php/phpsqlajax_genxmlCluster.php?"+campo+"="+valor+"&nombre_tienda="+cod_cadena, function(data, responseCode) {
				  // To ensure against HTTP errors that result in null or bad data,
				  // always check status code is equal to 200 before processing the data
				  if(responseCode == 200) {
				    var xml = GXml.parse(data);
				    
				    //Limpiamos los marcadores de provincias y rutas si existen
				    for (var z = 0; z < marcadoresProvincia.length; z++)
				    	map.removeOverlay(marcadoresProvincia[z]);
				    
				    var items = xml.documentElement.getElementsByTagName("marker");
				    var numeroItems = items.length;
				    var html = "";
				    
				    for (var i = 0; i < numeroItems; i++) {
				    	var nom_comercial = items[i].getAttribute("name");
				      var poblacion = items[i].getAttribute("poblacion");
				      var address = items[i].getAttribute("address");
				      var lati = parseFloat(items[i].getAttribute("lat"));
				      var longi = parseFloat(items[i].getAttribute("lng"));
				      var cp = items[i].getAttribute("cp");
				      var point = new GLatLng(lati,longi);
				      var direccionCompleta = address+" ,"+cp+" ,"+poblacion;
				      
				      var fotos = new Array(2);
				      if (items[i].getAttribute("foto_ext_ver") == 'S'){
					      fotos[0] = items[i].getAttribute("foto_ext");
					      fotos[1] = items[i].getAttribute("foto_int");
				    	}
				    	
				      var telefono = items[i].getAttribute("telefono");
				      var fax = items[i].getAttribute("fax");
				      var email = "E-mail: " + items[i].getAttribute("email");
				      
							var datosTienda = new Array(nom_comercial, address, cp, poblacion, telefono, fax, email);
							
						  var marker = createMarker(point,'iconoProvincia',html,0, tiendaIcon, valor, poblacion, direccionCompleta, fotos, datosTienda);
		          map.addOverlay(marker);
		          
		          //Guardamos los marcadores de provincias
		          marcadoresProvincia[i]=marker;
		          
				    }
				    
				     
		        //Restauramos el icono del cluster pulsado anteriormente
					  if (variablesGlobalesOBJ.iconoClusterPulsado){
					   	map.addOverlay(variablesGlobalesOBJ.iconoClusterPulsado);
					   	variablesGlobalesOBJ.iconoClusterPulsado = null;
					  }
						  
						//Ocultamos el Icono del Cluster Pulsado
						for (var i = 0; i < variablesGlobalesOBJ.cargaInicialIconos.length; i++) {
						  if (variablesGlobalesOBJ.cargaInicialIconos[i]["cp_marker"] == valor){
						   	variablesGlobalesOBJ.iconoClusterPulsado = variablesGlobalesOBJ.cargaInicialIconos[i]["marker"];
						   	map.removeOverlay(variablesGlobalesOBJ.iconoClusterPulsado);
						  }
						}
												
					  if(ToolTipInstance != null) {
							map.removeOverlay(ToolTipInstance);
							ToolTipInstance = null;
						}	
 						
 						
				  } else if(responseCode == -1) {
				    alert("Data request timed out. Please try later.");
				  } else { 
				    alert("Request resulted in error. Check XML file is retrievable.");
				  }
	});
}	
		
function variablesGlobales() {

//Controlar la carga inical de iconos
this.intervalo = null;
this.cargaInicialIconos = [];
this.numTotalIconosInicial = null;
////////////////////////////////////

this.anchoTabWindow = null;
this.altoTabWindow = null;
this.iconoClusterPulsado = null;

this.medioTransporte = 'coche';
this.tiendaSeleccionada = [];
}

/////////////////////////////////////////////////////////////////////////////////
//create the ToolTip overlay object
function ToolTip(tipoTienda,marker,html,objTabWindow,width,fotos) {
	this.html_ = html;
	this.width_ = (width ? width + 'px' : 'auto');
	this.desplazamientoX = null;
	this.desplazamientoY = null;
	this.marker_ = marker;
	this.objTabWindow_ = objTabWindow;
	this.tipoTienda_ = tipoTienda;
	this.fotos_ = fotos;
}

//ToolTip.prototype = new GOverlay();

ToolTip.prototype.initialize = function(map) {
	var div = document.createElement("div");
	div.id = 'todoboc';
	div.style.display = 'none';
	
	if (this.objTabWindow_)
		div = this.objTabWindow_;
		
	map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
	
	this.map_ = map;
	this.container_ = div;
	
	
	if (this.objTabWindow_){ 
    //Posicion Ventana del de Tiendas Especificas 
    this.desplazamientoY = parseInt($("#"+div.id).css('height'))+16; 
    this.desplazamientoX = parseInt($("#"+div.id).css('width'))/2; 
  }else { 
    //Posicion Ventana del Cluster de Tiendas 
    this.desplazamientoY = parseInt($("#"+div.id).css('height'))+ 58; 
    this.desplazamientoX = parseInt($("#"+div.id).css('width'))/2 - 4; 
  } 

}

ToolTip.prototype.remove = function() {
	this.container_.parentNode.removeChild(this.container_);
}

ToolTip.prototype.copy = function() { 
	if (this.tipoTienda_)
		return new ToolTip(this.tipoTienda_, this.html_);
	else
		return;
}

ToolTip.prototype.redraw = function(force) {//alert("this.marker_: " + this.marker_ + " tipo: " +typeof(this.marker_) );
	
	if (!force) return;
	
	var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
	
	if (!this.objTabWindow_){
		this.container_.innerHTML = this.html_;
		//Desactivamos el boton derecho del raton
		utilidadesOBJ.noContextMenu(this.container_);
	} else { 
		document.getElementById('tab1ToolTipContenidoInner').innerHTML = this.html_;
		
		if (!this.fotos_[0] && !this.fotos_[1]){ 
			document.getElementById('fotoTiendaToolTip').innerHTML = "<img style='margin-top:25px;width:140px;height:auto' src='images/sinfoto1.jpg'>";
		}else if (this.fotos_[0] && !this.fotos_[1]){
			document.getElementById('fotoTiendaToolTip').innerHTML = "<img src='images/fotos/"+this.fotos_[0]+"'></div>";
		}else if (!this.fotos_[0] && this.fotos_[1]){
			document.getElementById('fotoTiendaToolTip').innerHTML = "<img src='images/fotos/"+this.fotos_[1]+"'>";
		}else document.getElementById('fotoTiendaToolTip').innerHTML = "<div class='detalles-img'><img src='images/fotos/"+this.fotos_[0]+"'></div><div class='detalles-iz' id='miniCarruselIzqda' style='display:none' onclick='muestraFotosTienda(\""+this.fotos_[0]+"\", this.parentNode.firstChild);'></div><div id='miniCarruselDrcha' class='detalles-de' style='display:block' onclick='muestraFotosTienda(\""+this.fotos_[1]+"\", this.parentNode.firstChild);'></div>";
		
		//Street View
		var puntoX = this.marker_.getPoint().lat();
		var puntoY = this.marker_.getPoint().lng();
		var coordenadas = new GLatLng(puntoX, puntoY);																																					
		objetoVentanaToolTip.tab3.style.display='block';
		ventanaMiniSites.tab3.style.display='block';
		
		var panoramaOptions = {latlng:coordenadas,zoom:1};
		myPanorama = new GStreetviewPanorama(document.getElementById("miniStreetView"),panoramaOptions);
		
    GEvent.addListener(myPanorama, "error", function(errorCode) {
	   	if (errorCode == 603) {
	       jAlert("Su nevegador no soporta Flash.","Flash No Instalado");
	     }else if (errorCode == 600) {
	     	//No se dispone de vista de calle
	     	objetoVentanaToolTip.tab3.style.display='none';
	     	ventanaMiniSites.tab3.style.display='none';
	     }
	     return;
    });
    //Fin Street View
	}																																																																		 
	this.container_.style.position = 'absolute';
	this.container_.style.left = pixelLocation.x - this.desplazamientoX + "px";
	this.container_.style.top = pixelLocation.y - this.desplazamientoY + "px";
	/*
	this.container_.style.width = this.width_;
	this.container_.style.font = 'bold 10px/10px verdana, arial, sans';
	this.container_.style.border = '1px solid black';
	this.container_.style.background = 'yellow';
	this.container_.style.padding = '4px';
	*/
	//one line to desired width
	this.container_.style.whiteSpace = 'nowrap';
	if(this.width_ != 'auto') this.container_.style.overflow = 'hidden';
	//this.container_.style.display = 'block';
}

ToolTipInstance = null;
ToolTipInstanceTabWindow = null;

GMarker.prototype.openToolTip = function(tipoTienda, content, objTabWindow, fotos) {
	 
		//don't show the tool tip if there is acustom info window
		map.closeInfoWindow();
		if(ToolTipInstance != null) {
				map.removeOverlay(ToolTipInstance);
				ToolTipInstance = null;
		}	
		
		if(myPanorama != null)
			myPanorama.remove();
			
		if(tipoTienda == 'cluster') {
			
			objTabWindow.style.display='none'; 
			ToolTipInstance = new ToolTip(tipoTienda, this,content, null, null);
			map.addOverlay(ToolTipInstance);
			ToolTipInstance.container_.style.display = 'block';
			
		} else if(tipoTienda == 'iconoProvincia'){
			
			if(ToolTipInstanceTabWindow == null) {
				ToolTipInstanceTabWindow = new ToolTip(tipoTienda, this, content, objTabWindow, null, fotos);
				map.addOverlay(ToolTipInstanceTabWindow);
				
			} else {
				ToolTipInstanceTabWindow.html_ = content;
				ToolTipInstanceTabWindow.fotos_ = fotos;
				ToolTipInstanceTabWindow.marker_ = this;
				ToolTipInstanceTabWindow.redraw(true);
			}
			
			objTabWindow.style.display='block'; 
	}
}

GMarker.prototype.getIcon = function(opcion) {
	var icono = (opcion == 0)? iconoSalida : iconoLlegada;
	return icono;
}

function apantallaNavegador(valor){
	
	if(valor){
		$(".carga-bg").css("display","block");   
		$(".carga-bg-img").css("display","block");   
		$(".carga-imagen").css("display","block");   
		$(".carga-logo").css("display","block");   
	}else {
		$(".carga-bg").css("display","none");   
		$(".carga-bg-img").css("display","none");   
		$(".carga-imagen").css("display","none");   
		$(".carga-logo").css("display","none");   
	}

}

function eliminaToolTip(){
	if(ToolTipInstance != null) { 
			$("#todoboc").fadeOut("fast", function(){map.removeOverlay(ToolTipInstance);ToolTipInstance = null;});
	}	
			
	if(ToolTipInstanceTabWindow != null){ 
		$("#ventanaPestanasToolTip").fadeOut("fast", function(){map.removeOverlay(ToolTipInstanceTabWindow);ToolTipInstanceTabWindow = null;});
	}
	
	variablesGlobalesOBJ.tiendaSeleccionada = [];
}

function rutasDesdeHacia(obj){
	
	if (obj.id == 'v-desde1'){
	 //medioTransporteMenu=(medioTransporteMenu=='sin-autovias')? 'coche' : 'sin-autovias';
	 obj.className='ventana-activo1';
	 document.getElementById('v-hacia2').className='ventana-activo2';
	 document.getElementById('fromToAddress').value="Introduzca su Direcc. o Cod. Postal. < ORIGEN >";
	
	  
	} else if (obj.id == 'v-hacia2'){
	  //medioTransporteMenu=(medioTransporteMenu=='sin-autovias')? 'coche' : 'sin-autovias';
	  obj.className='ventana-activo1';
	  document.getElementById('v-desde1').className='ventana-activo2'
	  document.getElementById('fromToAddress').value="Introduzca su Direcc. o Cod. Postal. < DESTINO >";

		 
	} else if (obj.id == 'pista1'){
		medioTransporteMenu=(medioTransporteMenu=='sin-autovias')? 'coche' : 'sin-autovias';
		obj.className=(obj.className=='ventana-activo1')? 'ventana-activo2' : 'ventana-activo1';
		var obj2 = document.getElementById('pista301');
	  obj2.className=(obj2.className=='ventana-activo1')? 'ventana-activo2' : 'ventana-activo1'
		
	} else if (obj.id == 'pista301'){
		medioTransporteMenu=(medioTransporteMenu=='sin-autovias')? 'coche' : 'sin-autovias';
		obj.className=(obj.className=='ventana-activo1')? 'ventana-activo2' : 'ventana-activo1';
		var obj2 = document.getElementById('pista1');
		obj2.className=(obj2.className=='ventana-activo1')? 'ventana-activo2' : 'ventana-activo1';
	}
};

function toolTipDesdeHacia(){
	
	apantallaNavegador(true);
	var from = true;  //Indica q tenemos q georefenciar la direccion origen; 
	
	if(document.getElementById('v-desde1').className == 'ventana-activo1'){
		document.getElementById('fromAddress').value = document.getElementById('fromToAddress').value;
		document.getElementById('toAddress').value = variablesGlobalesOBJ.tiendaSeleccionada[0]["direccion"];
		
	} else {
		document.getElementById('fromAddress').value = variablesGlobalesOBJ.tiendaSeleccionada[0]["direccion"];
		document.getElementById('toAddress').value = document.getElementById('fromToAddress').value;
		from = false;
	} 
	calculoDistanciasOBJ.obtenerCoordCliente(document.getElementById('fromToAddress'), from, function(){objetoVentana.tab2.onclick();});
};

function muestraFotosTienda(foto, imagen){
	
	if (foto){
		imagen.firstChild.src = 'images/fotos/'+foto;
		imagen.firstChild.alt = 'Foto Exterior';
		var fotoIzqda = document.getElementById('miniCarruselIzqda');
		var fotoDrcha = document.getElementById('miniCarruselDrcha');
		fotoIzqda.style.display = (fotoIzqda.style.display=='none') ? 'block' : 'none';
		fotoDrcha.style.display = (fotoDrcha.style.display=='none') ? 'block' : 'none';
	}else
		jAlert("Imagen No Disponible","Imagen");
	 
};

function ajustaVentanas(){
	windowTabs.Agrandar(windowTabs);
	
	if (resizeObjeto)
		$.alerts._reposition(resizeObjeto, true);
		
	if(windowWeb.domObj.style.display == 'block')
		windowWeb.Agrandar(windowWeb, "pantallaCompleta");
}

function zoomTienda(){
	map.setCenter(new GLatLng(variablesGlobalesOBJ.tiendaSeleccionada[0]["point"].lat(),variablesGlobalesOBJ.tiendaSeleccionada[0]["point"].lng()), 17);
	map.panBy(new GSize(0, 40));
}
			
function cargaClusterTiendas(callback){//jAlert("php/phpsqlajax_genxmlCluster.php?nombre_tienda="+cod_cadena);
		GDownloadUrl("php/phpsqlajax_genxmlCluster.php?nombre_tienda="+cod_cadena, function(data, responseCode) {
				  // To ensure against HTTP errors that result in null or bad data,
				  // always check status code is equal to 200 before processing the data
				  if(responseCode == 200) {
				    var xml = GXml.parse(data);
				    
				    var items = xml.documentElement.getElementsByTagName("marker");
				    
				    variablesGlobalesOBJ.numTotalIconosInicial= items.length;
				    
				    for (var i = 0; i < variablesGlobalesOBJ.numTotalIconosInicial; i++) {
				      	
				      	var poblacion = items[i].getAttribute("poblacion");
		            var lng = parseFloat(items[i].getAttribute("lng"));
		            var lat = parseFloat(items[i].getAttribute("lat"));
		            var point = new GLatLng(lat,lng);
		            var cp = items[i].getAttribute("cp");
		            var tiendas = items[i].getAttribute("tiendas");
		            var html = "";
		            
		            if(tiendas > 0){ 
			            // create the marker
									html += '<div id="infoCluster" class="ventana-cabecera" style="width:110px"><h1>'+poblacion+'</h1><div id="botonCerrarBocadillo" class="ventana-cerrar1" onmouseover=this.className="ventana-cerrar2" onmouseout=this.className="ventana-cerrar1" onclick="eliminaToolTip();"></div></div>';
		            	html += '<img src="images/'+ firma +'/v-fondo.gif" class="cluster-fondo">';
									html += '<div class="ventana-base" style="top: 24px; padding: 5px"><p class="flecha">Tiendas:  '+tiendas+'</p><a href="#" class="enviar-link" onclick="cargaPoblacion(null,'+cp+');">Ir a</a></div>';
									html += '<div class="ventana-pico"></div';
						
		            	var marker = createMarker(point,'cluster',html,0, clusterIcon, cp, poblacion);
		            	//Si la provincia tiene tiendas aņado el icono del cluster en el mapa
			            map.addOverlay(marker); 
			            
			            //Guardamos los marcadores 
			          	//variablesGlobalesOBJ.cargaInicialIconos[i]=marker;
			          	var cont = variablesGlobalesOBJ.cargaInicialIconos.length; 
			          	variablesGlobalesOBJ.cargaInicialIconos[cont]={"cp_marker":cp,"marker":marker,"poblacion":poblacion};	
		          	}	          	
				    }
				    
				    ajustaVentanas();		 
				     
				    if( callback )callback(true);
									
				  } else if(responseCode == -1) {
				    alert("Data request timed out. Please try later.");
				  } else { 
				    alert("Request resulted in error. Check XML file is retrievable.");
				  }
				});
};




