jQuery.noConflict( )

switch (location.hostname) {
	
	/*case 'www.tiendasenliquidacion.com':
		var GM_KEY = new String("ABQIAAAAt43tA9Bpyvf2LCItwoHZjhSk_x8sRY5Fmf1-fQBsEvAfO7BSrBSWXLR1cUH-0aSR16Cf0SUZ47V69g");
		break;*/
	case 'www.tiendasenliquidacion.com':
		var GM_KEY = new String("ABQIAAAAt43tA9Bpyvf2LCItwoHZjhTmMPRsd5uSU39mMo3vks3KBn_mXxTB8j9ynjk6vUh1Wy5K45GfDBGS3g");
		break;
	default:
		var GM_KEY = new String("ABQIAAAAt43tA9Bpyvf2LCItwoHZjhTmMPRsd5uSU39mMo3vks3KBn_mXxTB8j9ynjk6vUh1Wy5K45GfDBGS3g");
		break;
}

/*
Variables globales
*/
var GM_lang = "es";
var GM_location = "";
var GM_charset = "iso-8859-1";
var GM_address;
var GM_zip;
var GM_city;
var GM_province;
var GM_country;
var GM_city_ID;
var GM_province_ID;
var GM_country_ID;
var map = null;
var geocoder = null;
var GM_BIG_ZOOM = 15;
var GM_SMALL_ZOOM = 5;
var GM_ADDRESS = "Spain";
var GM_latitude;
var GM_longitude;
var GM_country_lat;
var GM_country_long;
var GM_address_norm;
var GM_Category;
var GM_Title;
var GM_IDLargo;
var GM_Empresa;


                            
var center = null;
var maxLat = null;
var minLat = null;
var maxLong = null;
var minLong = null;
var ArrayMakers = new Array;
var defaultMaker = null;


document.write('<script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&amp;ie=' + GM_charset + '&amp;hl=' + GM_lang + '&amp;key=' + GM_KEY + '"></script>');


/* 
Inicializa gmaps
@params void;*/
function InicializaMapa() {
	//Inicialización de mapa
	if (GBrowserIsCompatible()) {
		// Para mapa
		if (document.getElementById("googleMap")){
			map = new GMap2(document.getElementById("googleMap"));
			map.setCenter(new GLatLng(GM_country_lat,GM_country_long),GM_SMALL_ZOOM);
		}
		if (document.getElementById("googleMapBoxList")){
			 map = new GMap2(document.getElementById("googleMapList"));
			 map.setCenter(new GLatLng(GM_country_lat,GM_country_long),GM_BIG_ZOOM);
		}
		
		geocoder = new GClientGeocoder();
		
		// Para get Direcction
		gdir = new GDirections(map, document.getElementById("directions"));
      		GEvent.addListener(gdir, "load", onGDirectionsLoad);
      		GEvent.addListener(gdir, "error", setDirectionsErrors);
	
		// Inclusión de botones
		if (document.getElementById("googleMap")){
			map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(3, 3)));
			map.addControl(new GLargeMapControl());
		}
		else{
			map.addControl(new GSmallMapControl());
		}
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		
		//var adsManager = new GAdsManager(map, "pub-0805091709214217",{"maxAdsOnMap":5, "minZoomLevel": 2, "channel":""});
		var adsManager = new GAdsManager(map, "pub-0805091709214217");
        	adsManager.enable();
		
		return true;
		
	} else return false;
}

/*
Inicia proceso para gmaps*/
function LoadGMaps() {
	var Localizacion = new String('');	
	if (document.getElementById('googleMapBox')){
	 	if (document.getElementById('googleMapBox').style.display == 'none') document.getElementById('googleMapBox').style.display = '';
	}
	
	// Inicializacimos mapa
	InicializaMapa();
	// Normalizamos los datos para la correcta localización
	GM_province=GM_province.split('/')[0];
	GM_city=GM_city.split('/')[0];
	GM_country=GM_country.split('/')[0];
	// damos formato a location para  geocoder.getLatLng
	Localizacion += (GM_address != '') ? GM_normalizeAddress(GM_address) + ", " : "";
	Localizacion += (GM_zip != '') ? GM_zip + ", " : "";
	Localizacion += (GM_city != '') ? GM_city + ", " : "";
	Localizacion += (GM_province != '') ? GM_province + ", " : "";
	Localizacion += (GM_country != '') ? GM_country : "";
	
	GM_location=Localizacion;
	// Si el anuncio tiene coordenadas, situamos estas directamente en el mapa
	if (GM_latitude !='' && GM_longitude !=''){
		// Creamos el marcador
		var point = new GLatLng(GM_latitude,GM_longitude);
		CreaMaker(point);
		// Buscamos tiendas cercanas y las mostramos en el mapa
		TiendasCercanas(map);
		// Añadimos evento para moverse por el mapa, buscando mas tiendas
		GEvent.addListener(map, "moveend", function() {TiendasCercanas(map);});
	}
	else{
	// Si el anuncio no tiene coordenadas, las pedimos mediante la funcion geocoder.getLatLng
		if (Localizacion){
			geocoder.getLatLng(
    				Localizacion,
    				function(point) {
	      				if (!point) {
	      					map.setCenter(new GLatLng(GM_country_lat,GM_country_long),GM_SMALL_ZOOM);		
      					} else {
      						// Creamos el marcador
      						if (document.getElementById('googleMapBox')){
      							CreaMaker(point);
							// Buscamos tiendas cercanas y las mostramos en el mapa
							TiendasCercanas(map);
							// Añadimos evento para moverse por el mapa, buscando mas tiendas
							GEvent.addListener(map, "moveend", function() {TiendasCercanas(map);});
						}
						if (document.getElementById('googleMapBoxList')){
								if (GM_city != '') map.setCenter(point,7);
								else map.setCenter(point,9);
								
								jQuery("input[@name='Lat']").each(function() { 
									if (this.value != ''){
										var id= this.id.split('_')[1];
										
										NewPoint = new GLatLng(jQuery('#Lat_'+id).val(),jQuery('#Lng_'+id).val());
										var marker = new GMarker(NewPoint);
										
										marker.name=jQuery('#Emp_'+id).val();
										marker.url=jQuery('#Url_'+id).val();
										marker.categoria=jQuery('#Cat_'+id).val();
										CreaMaker(NewPoint,marker);
										
									}
                						}); 
						}
      						
      					}
    				}
  			)
  		}
  		else{
  			
  		 	map.setCenter(new GLatLng(GM_country_lat,GM_country_long),GM_BIG_ZOOM);
  		 	
  		}
	}
	return true;
}
/*
Parsea JSON con tiendas devueltas
@parametros: objeto json
@parametros: marcador original*/
function handleMasTiendas(req){	
	
	var Tiendas  = eval("(" + req.responseText + ")");
	// Defino iconos
	var TenLIcon = new GIcon(G_DEFAULT_ICON);
	var SizeIcon = new GSize(18, 33);
	var Destacadas=0;
	var PosMaker = 0;

	TenLIcon.image = "http://www.tiendasenliquidacion.com/Images/iconoG.png";
	TenLIcon.iconSize = SizeIcon;
	// Inicializamos capas del mapa
	jQuery("#paginacion").hide();
	jQuery("#Legend").html("");
	
	//Eliminamos los makers del mapa
	ArrayMakers = jQuery.map(ArrayMakers, function(maker){map.removeOverlay(maker);});
	var markerOptions = {icon:TenLIcon};
	
	if (Tiendas.coordenadas.total_anuncios!='0'){
		//jQuery("#Legend").html('<img src="http://www.tiendasenliquidacion.com/Images/iconoGpeq.png"/>&nbsp;<span style="background-color:#fff;padding:2px;"><strong>'+Tiendas.coordenadas.total_anuncios_sql+' tiendas de '+Tiendas.coordenadas.categoria+' en la zona</strong></span><br/><br/>');
		for (var i=0;i<Tiendas.ListadoTiendas.length; i++){	
			var point = new GLatLng(Tiendas.ListadoTiendas[i].lat,Tiendas.ListadoTiendas[i].long);
			if (Tiendas.ListadoTiendas[i].id != defaultMaker){
				if (Tiendas.ListadoTiendas[i].destacado=='S'){
					TenLIcon.image = "http://www.tiendasenliquidacion.com/Images/iconoGdestacado.png";
					var markerOptions = { icon:TenLIcon };
					var marker = new GMarker(point,markerOptions);
					var WindowInfo = new String('');
					Destacadas=Destacadas+1;
					
				}else{
					TenLIcon.image = "http://www.tiendasenliquidacion.com/Images/iconoG.png";
					var markerOptions = { icon:TenLIcon };
					var marker = new GMarker(point,markerOptions);
					var WindowInfo = new String('');
				}
				// Defino carateristicas del marcador
				marker.ID=Tiendas.ListadoTiendas[i].id;
				marker.Nombre=Tiendas.ListadoTiendas[i].nombre;
				marker.Categoria=Tiendas.ListadoTiendas[i].categoria;
				marker.Destacado=Tiendas.ListadoTiendas[i].destacado;
				marker.TipoTienda=Tiendas.ListadoTiendas[i].tipotienda;
				marker.Marcas=Tiendas.ListadoTiendas[i].marcas.substring(0,60);
				marker.Desc=Tiendas.ListadoTiendas[i].descripcion;
				marker.Direccion=Tiendas.ListadoTiendas[i].direccion;
				marker.Url=Tiendas.ListadoTiendas[i].url_liq;
				marker.Imagen=Tiendas.ListadoTiendas[i].imagen;
				marker.Pixels=point;
				// Situo el marcador en el mapa
        	        	map.addOverlay(marker);
        	        	// Guardamos los makers en array
        	        	ArrayMakers.push(marker); 	
        	        	// Añado eventos al marcador
                		GEvent.addListener(marker, "click", function() {document.location.href = this.Url;});
                		GEvent.addListener(marker, "mouseover", function() {ShowInfoMaker(map,this)});
                		GEvent.addListener(marker, "mouseout", function() {HideInfoMaker();}); 
                		
                		jQuery("#Legend").append('<div class="MoreTiendas"  id="MakerList_'+marker.ID+'"><span style="color:#ccc;font-weight:bold;">>></span> <a onmouseover="ShowInfoMaker(map,ArrayMakers['+PosMaker+']);" onmouseout="HideInfoMaker();" href="'+marker.Url+'">'+marker.Nombre+'</a><p style="color:#6E6358;margin-left:20px;font-weight:normal;">'+marker.Direccion+'</p></div>');	
                		PosMaker++;
                	}
		}
		
		if (Tiendas.paginacion.length>1){
			var Paginacion = new String('');
			var Paginacion = '<div style="margin:0px auto 0px auto;width:410px;border:0px solid red;">';
			for (var j=0;j<Tiendas.paginacion.length; j++){
				if (Tiendas.paginacion[j].actual=='si'){
					Paginacion += '<span style=";margin-left:5px;color:#000;font-weight:bold;" id="Pag'+j+'" onclick="TiendasCercanas(map,\''+Tiendas.paginacion[j].url_text+'\');return false;">'+Tiendas.paginacion[j].url+'</span>';
				}
				else Paginacion += '<a href="#" style="margin-left:5px;" id="Pag'+j+'" onclick="TiendasCercanas(map,\''+Tiendas.paginacion[j].url_text+'\');return false;">'+Tiendas.paginacion[j].url+'</a>';
				
			}
			Paginacion+='</div>';
			jQuery("#paginacion").show();
			jQuery("#paginacion").html(Paginacion);
		} 
		
		
		
	}
}
/*
Crea un marcador en el mapa
@parametros: punto cardinal*/
function CreaMaker(point,options){	
	// Defino variables estilo de marcador
	var TenLIcon = new GIcon(G_DEFAULT_ICON);	
	var SizeIcon = new GSize(18,33);
	var markerOptions;
	// Doy valores a propiedades marcador
	TenLIcon.image = "http://www.tiendasenliquidacion.com/Images/iconoGselect.png";
	TenLIcon.iconSize = SizeIcon;
	markerOptions = {icon:TenLIcon};
	
	if (!options){
	
		defaultMaker=GM_IDLargo;
		// Creo marcador
		var marker = new GMarker(point,markerOptions);
		// Atributos maker
		marker.Nombre=GM_Empresa+' '+GM_Title;
		marker.Pixels=point;
		marker.Categoria='';
		marker.TipoTienda='';
		marker.Marcas='';
		marker.Imagen='';
		// Posiciono marcador
		map.setCenter(point,GM_BIG_ZOOM);
		map.addOverlay(marker);
		// Añado eventos
		GEvent.addListener(marker, "mouseover", function() {ShowInfoMaker(map,this,'LEFT')});
	}
	else{
		var marker = new GMarker(point,markerOptions);
		marker.Nombre=options.name;
		marker.Pixels=point;
		marker.Url=options.url;
		marker.Categoria=options.categoria;
		marker.TipoTienda='';
		marker.Marcas='';
		marker.Imagen='';
		// Posiciono marcador
		map.addOverlay(marker);
		GEvent.addListener(marker, "click", function() {document.location.href = this.Url;});
		GEvent.addListener(marker, "mouseover", function() {ShowInfoMaker(map,this,'RIGHT')});
		
		
	}
	
        GEvent.addListener(marker, "mouseout", function() {HideInfoMaker();}); 
	return true;
}

/*  	
muestra información adicional al marcados
@par	ametros: objeto map,maker*/
function ShowInfoMaker(map,maker,position){
	if (position=='RIGHT'){
		var posx = map.fromLatLngToContainerPixel(maker.Pixels).x-205;
    		var posy = map.fromLatLngToContainerPixel(maker.Pixels).y;
	}
	else{
		var posx = map.fromLatLngToContainerPixel(maker.Pixels).x-205;
    		var posy = map.fromLatLngToContainerPixel(maker.Pixels).y;
    	}
    	
    	var messaje = new String('');
    	
    	message = '<div class="MakerInfo" style="position:absolute;left:'+posx+'px;top:'+posy+'px;z-index:100;display:visible;width:242px;">';
    	message+='<div class="InfoMakerTop">&nbsp;</div>';
    	message+='<div class="InfoMaker">';
    	if (maker.Nombre.length >1) message+='<strong>'+maker.Nombre+'</strong>';
    	if (maker.Categoria.length >1) message+='<br/><span style="color:#DCAC18;font-weight:bold;">'+maker.Categoria+'</span>';
    	if (maker.TipoTienda.length >1) message+='<br/>'+maker.TipoTienda;
    	if (maker.Marcas.length >1) message+='<br/><br/><strong>Marcas:</strong><br/>'+maker.Marcas;
    	if (maker.Imagen != "0") message+='<br/><br/><img src="http://www.tiendasenliquidacion.com/Fotos/'+maker.Imagen+'"/>';
    	message+='</div>';
    	message+='<div class="InfoMakerBottom">&nbsp;</div>';
    	message+='</div>';
    	
    	if (document.getElementById('googleMapBox'))jQuery("#googleMapBox").append(message);
			if (document.getElementById('googleMapBoxList'))jQuery("#googleMapBoxList").append(message);
	
    	return true;
}   

/*  	
esconde información adicional al marcados
@par	ametros: objeto map,maker*/
function HideInfoMaker(){
	jQuery(".MakerInfo").hide();
	return true;
}

/*  	
Fija las coordenas para delimitar el area de busqueda
@parametros: objeto map*/
function FijarCoordenadas(map){	
	center = map.getCenter();
	maxLat = map.getBounds().getNorthEast().lat();
	minLat = map.getBounds().getSouthWest().lat();
	maxLong = map.getBounds().getSouthWest().lng();
	minLong = map.getBounds().getNorthEast().lng();
	return true;
}

/*
Peticion para tiendas cercanas
@parametros: objeto map*/
function TiendasCercanas(map,params){

	
	var post = new String('');
	// Fijo las coordenadas par hacer un rectangulo de busqueda
	FijarCoordenadas(map);
	post += 'MAX_LAT=' +maxLat;
	post += '&MIN_LAT=' +minLat;
	post += '&MAX_LONG=' +maxLong;
	post += '&MIN_LONG=' +minLong;
	post += '&ID1=' +GM_Category;
	
	if (params) post +='&'+params.split('&')[0];
	
	// hacemos llamada a otras tiendas en mismo lugar
	sendRequest("http://www.tiendasenliquidacion.com/ListadoTiendasJson.xsql",handleMasTiendas,post);
	return true;
}


/*
Hace peticion a gmaps para encontar ruta a una direccion
Requiere onGDirectionsLoad y setDirectionsErrors
@params: void;*/
function setDirections() {
     
      jQuery("#directions").show();
      jQuery("#directionsError").show();
    
      var toAddress=GM_address_norm;
      var fromAddress=document.getElementById("toAddress").value;  
	  
      var locale='es';
      gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": locale });
     return true;
}

/*Hace vacia peticion a gmaps para eliminar la ruta
Requiere onGDirectionsLoad y setDirectionsErrors
@params: void;*/
function clearDirections(){
	
      jQuery("#directions").hide();
      jQuery("#directionsError").hide();
      jQuery("#toAddress").val("");
	
      var toAddress='';
      var fromAddress='';  
      var locale='es';
      
      gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": locale });
      return true;  
}
/*
No uso esta funcion
@params: void;*/
function onGDirectionsLoad(){ 
     	return true;
}

/*
Devuelve codigo de Error en la petición setDirections
@params: void;*/
function setDirectionsErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	    jQuery("#directionsError").html(">> La ubicación geográfica no  podido ser encontrada por una de las direcciones especificadas. Esto puede deberse al hecho de que la dirección es relativamente nueva, o puede ser incorrecta.");
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     jQuery("#directionsError").html(">> Una de códigos geográficos o las indicaciones solicitud no pudo ser procesado con éxito.\n Error code: ");
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     jQuery("#directionsError").html(">> No se ha introducido ninguna dirección.");
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     jQuery("#directionsError").html(">> La clave está dado, ya sea inválida o no coincide con el dominio para el que fue dado.");

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     jQuery("#directionsError").html("");
	    
	   else jQuery("#directionsError").html(""); 
}
/**/

/*
Normaliza direcciones
@param: direccion*/
function GM_normalizeAddress(direccion) {
	direccion=String(direccion);
	//Eliminamos caracteres y palabras inecesarios.
	direccion_temp=direccion.split(" No."); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split(" no."); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("c/"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("C/"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("."); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split(","); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("-"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("/"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("nº"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Nº"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("º"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("ª"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("BIS"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("S/N"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("s/n"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("S/n"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Calle"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("calle"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("carrer"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Carrer"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("pl "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Pl "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Pº"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("pº"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("paseo"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Paseo"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Paseig"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("paseig"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Passeig"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("passeig"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Av "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Adireccion_temp "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("av "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("avd "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Avd "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Adireccion_tempD "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Avenida"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("avenida"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("Avinguda"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("avinguda"); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("    "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("  "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("  "); direccion=direccion_temp.join(" ");
	direccion_temp=direccion.split("  "); direccion=direccion_temp.join(" ");
	// Cuando encuentra un numero elimina todo lo que queda.
	for (conti=0; direccion.charAt(conti); conti++ ) 
	{
		if ((direccion.charAt(conti)==parseInt(direccion.charAt(conti)))&&(direccion.charAt(conti+1)==' '))
		{
		direccion = direccion.substring(0,conti+1);
		break;
		}
	}	
	
	return direccion;
}


/*
Incluye mensge de aviso, al final del mapa
@param: msg*/
function GM_displayMessage(msg) {
	if (document.getElementById("googleMapMessage")) {
		document.getElementById("googleMapMessage").innerHTML = '<p>' + msg + '</p>';
	}
	else if (document.getElementById("googleMapText")) {
		var elem = document.getElementById("googleMapText");
		var p = document.createElement("p");
		Element.extend(p);
		p.setAttribute("id", "googleMapMessage");
		// elem.appendChild(p);
		document.getElementById("googleMapText").insertBefore(p, document.getElementById("googleMapText").firstChild);
		p.innerHTML = msg;	
	}
	else {
		alert(msg);
	}
	return true;
}

/*
Envia a gmap, con url montada
@param: void*/
function GM_gotoGoogle() {
	var linksArray = document.getElementById("googleMap").getElementsByTagName("a");
	for (var i = 0; i < linksArray.length; i++){
		var linksString = linksArray[i].toString();		
		var dividido = linksString.split('&');	
		for (var k = 0; k < dividido.length; k++){
			if (dividido[k].match('key')){
				var llave = dividido[k];	
				var trozo = llave.split('=');
				var mikey = trozo[1];
			 if (mikey == GM_KEY){
			 window.open(linksArray[i].getAttribute("href") + "&q=" + GM_location, "_blank");	
			 return undefined;
				}
			}
		}
		
	}
	
	window.open("http://maps.google.com", "_blank");
	return undefined;
}
