jQuery.noConflict( )
switch (location.hostname) {
	
	case 'www.nucleo-canguroencasa.com':
		var GM_KEY = new String("ABQIAAAAt43tA9Bpyvf2LCItwoHZjhR8RNSvnTLZtv20MRUUkri5WpIu7BRpqZekQZ7Up9zXSAo1k_IMNC-UKQ");
		break;
	case 'www.canguroencasa.com':
		var GM_KEY = new String("ABQIAAAAt43tA9Bpyvf2LCItwoHZjhRN8n9MHyHLnpQARlJXWcoBTILiVhRO14Or1R47KS9j0avV8iOOeiF6fA");
		break;
	default:
		var GM_KEY = new String("ABQIAAAAt43tA9Bpyvf2LCItwoHZjhRN8n9MHyHLnpQARlJXWcoBTILiVhRO14Or1R47KS9j0avV8iOOeiF6fA");
		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
		map = new GMap2(document.getElementById("googleMap"));
		map.setCenter(new GLatLng(GM_country_lat,GM_country_long),GM_SMALL_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
		map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(3, 3)));
		//map.addControl(new GSmallMapControl());
		map.addControl(new GLargeMapControl());
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		/* PUBLICIDAD DE TIENDAS */ 
		//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').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
      						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{
  		 	map.setCenter(new GLatLng(GM_country_lat,GM_country_long),GM_SMALL_ZOOM);
  		}
	}
	return true;
}

/*
Crea un marcador en el mapa
@parametros: punto cardinal*/
function CreaMaker(point){
	// 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.iconSize = SizeIcon;
	markerOptions = {icon:TenLIcon};
	defaultMaker=GM_IDLargo;
	// Creo marcador
	var marker = new GMarker(point,markerOptions);
	// Atributos maker
	marker.Nombre=GM_Empresa+' '+GM_Title;
	marker.Pixels=point;
	marker.Categoria=GM_Category;
	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)});
    GEvent.addListener(marker, "mouseout", function() {HideInfoMaker();}); 
	return true;
}

/*  	
muestra información adicional al marcados
@par	ametros: objeto map,maker*/
function ShowInfoMaker(map,maker){
	
		var posx = map.fromLatLngToContainerPixel(maker.Pixels).x-210;
    	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:#CA0315;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.canguroencasa.com/Fotos/'+maker.Imagen+'"/>';
    	message+='</div>';
    	message+='<div class="InfoMakerBottom">&nbsp;</div>';
    	message+='</div>';
    	jQuery("#googleMapBox").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;
}


/*
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;
}
