/*
* author: diegomrp
* date: 10/09/2007
* copyright: INDITEX S.A. - All rights reserved
*/

var map;
var continenteSel=5;
var paisSel=null;
var provinciaSel=null;
var localiSel=null;
var action=false;
var traducc=null;

function load() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT));
		map.setCenter(new GLatLng(43.5, -2.5), 4);
		cw = new cWindow(map);
		map.addOverlay(cw);

		loadTraducc();
		loadTotalStores();
		loadContinentMenuIzq();
		loadStores();

		GEvent.addListener(map,"moveend",function(){
			if(continenteSel==null && paisSel==null &&
			provinciaSel==null && localiSel==null){
				clearOverlays();
				loadStores();
			}
		});
		GEvent.addListener(map, "click", function(marker,point) {
			if (point) cw.hide();
		});
		GEvent.addListener(map, "zoomend", function(oldLevel,newLevel) {
			if(action==false){
				continenteSel=null;
				paisSel=null;
				provinciaSel=null;
				localiSel=null;
				clearOverlays();
				loadStores();
			} else {
				action=false;
			}
		});
	}
}

function clearOverlays(){
	map.clearOverlays();
}

function loadStores(){
	var bounds=map.getBounds();
	datos= GXmlHttp.create();
	datos.open("POST", '/map_home/loadDataAction.do?latIni='+bounds.getSouthWest().lat()+
	'&latFin='+bounds.getNorthEast().lat()+'&lngIni='+bounds.getSouthWest().lng()+
	'&lngFin='+bounds.getNorthEast().lng(), false);
	datos.send(null);
	var jSonZoom=datos.responseText;

	if(continenteSel!=null){
		info=GXmlHttp.create();
		if(paisSel!=null){
			if(paisSel==11){
				if(provinciaSel!=null) {
					info.open("POST", '/map_home/loadCityByRegionAction.do?id='+provinciaSel, true);
					info.onreadystatechange=function() {
						if(info.readyState==4) {
							if(info.status==200) {
								viewCargando();
								var jSonLocalidades=eval("(" +info.responseText + ")");
								if(jSonLocalidades!=null){
									loadOverlayCities(jSonLocalidades);
									loadMenuIzqLocali(provinciaSel);
								}
								hideCargando();
							}
						} else {
							viewCargando();
						}
					}
					info.send(null);

				} else {
					info.open("POST", '/map_home/loadRegionAction.do?id='+paisSel, true);
					info.onreadystatechange=function() {
						if(info.readyState==4) {
							if(info.status==200) {
								viewCargando();
								var jSonProvincias=eval("(" +info.responseText + ")");
								if(jSonProvincias!=null){
									loadOverlayRegion(jSonProvincias);
									loadRegions(jSonProvincias);
									loadMenuIzqRegion(paisSel);
								}
								hideCargando();
							}
						} else {
							viewCargando();
						}
					}
					info.send(null);
				}
			} else {
				info.open("POST", '/map_home/loadCityAction.do?id='+paisSel, true);
				info.onreadystatechange=function() {
					if(info.readyState==4) {
						if(info.status==200) {
							viewCargando();
							var jSonLocalidades=eval("(" +info.responseText + ")");
							if(jSonLocalidades!=null){
								loadOverlayCities(jSonLocalidades);
								loadMenuIzqRegion(paisSel);
							}
							hideCargando();
						}
					} else {
						viewCargando();
					}
				}
				info.send(null);
			}
		} else {
			info.open("POST", '/map_home/loadCountriesByContinentAction.do?id='+continenteSel, true);
			info.onreadystatechange=function() {
				if(info.readyState==4) {
					if(info.status==200) {
						viewCargando();
						var jSonPaises=eval("(" +info.responseText + ")");
						if(jSonPaises!=null){
							loadOverlayPaises(jSonPaises);
							loadMenuIzqCountries(continenteSel);
							changeHeight();
						}
						hideCargando();
					}
				} else {
					viewCargando();
				}
			}
			info.send(null);
		}
	} else {
		if(jSonZoom=="continentes"){
			loadMenuIzqContinents();
		}else if(jSonZoom=="paises"){
			loadMenuIzqCountries(null);
		} else if(jSonZoom=="provincias") {
			loadMenuIzqRegion(null);
		} else if(jSonZoom=="localidad") {
			// cargamos las localidades en el menuIzq
			paisSel=loadCountryMenuIzq();
			if(paisSel==11){
				loadUniqueRegionMenuIzq();
			}
			var jSonLocalidades=loadMenuIzqLocali(null);
			// fin de la carga de las localidades en el menuIzq
			if(jSonLocalidades!=null){
				loadOverlayCities(jSonLocalidades);
			}
		} else if(jSonZoom=="puntos"){
			paisSel=loadCountryMenuIzq();
			if(paisSel==11){
				loadUniqueRegionMenuIzq();
			}
			loadTiendas();
			loadMenuIzqLocaliMarker();
		}
	}
}

function loadTiendas(){
	var bounds=map.getBounds();
	datos= GXmlHttp.create();
	datos.open("POST", '/map_home/loadJSonAction.do?latIni='+bounds.getSouthWest().lat()+
	'&latFin='+bounds.getNorthEast().lat()+'&lngIni='+bounds.getSouthWest().lng()+
	'&lngFin='+bounds.getNorthEast().lng(), true);
	datos.onreadystatechange= recuperar;
	datos.send(null);
}

function recuperar(){
	if (datos.readyState == 4){
		if(datos.status==200){
			viewCargando();
			var jSonArray=eval("(" + datos.responseText + ")");
			if(jSonArray!=null) {
				loadOverlay(jSonArray);
			}
			hideCargando();
		}
	}
}

function loadOverlay(jSonArray){
	for(i=0;i<jSonArray.length;i++){
		for(j=0;j<jSonArray[i].length;j++){
			var point = new GLatLng(jSonArray[i][j].latitud,jSonArray[i][j].longitud,false);
			var marker = createMarker(point,jSonArray[i][j]);
			map.addOverlay(marker);
		}
	}
}

function loadOverlayContinentes(jSonArray){
	for(var i=0;i<jSonArray.length;i++){
		var cL=new cLabel(map);
		map.addOverlay(cL);
		var point = new GLatLng(jSonArray[i].latitud,jSonArray[i].longitud,false);
		var html=loadHtmlContinent(jSonArray[i].continente.idZonaGeografica,jSonArray[i].continente.descripcion,jSonArray[i].num);
		cL.show(point,html);
	}
}

function loadOverlayPaises(jSonArray){
	for(var i=0;i<jSonArray.length;i++){
		var cL=new cLabel(map);
		map.addOverlay(cL);
		var point = new GLatLng(jSonArray[i].latitud,jSonArray[i].longitud,false);
		if(map.getBounds().containsLatLng(point)){
			var html=loadHtmlCountry(jSonArray[i].pais.idPais,jSonArray[i].pais.descripcion,jSonArray[i].num);
			cL.show(point,html);
		}
	}
}

function loadOverlayRegion(jSonArray){
	for(var i=0;i<jSonArray.length;i++){
		var cL=new cLabel(map);
		map.addOverlay(cL);
		var point = new GLatLng(jSonArray[i].latitud,jSonArray[i].longitud,false);
		if(map.getBounds().containsLatLng(point)){
			var html=loadHtmlRegion(jSonArray[i].idProvincia,jSonArray[i].nombre,jSonArray[i].num);
			cL.show(point,html);
		}
	}
}

function loadOverlayCities(jSonArray){
	for(var i=0;i<jSonArray.length;i++){
		var cL=new cLabel(map);
		map.addOverlay(cL);
		var point = new GLatLng(jSonArray[i].latitud,jSonArray[i].longitud,false);
		if(map.getBounds().containsLatLng(point)) {
			var html=loadHtmlCities(jSonArray[i].localidad,jSonArray[i].num);
			cL.show(point,html);
		}
	}
}

function createMarker(point,store){
	var icon = new GIcon();
	icon.image = "img/marcador_ZH.png";
	icon.iconSize = new GSize(28, 36);
	icon.iconAnchor = new GPoint(0, 28);
	icon.infoWindowAnchor = new GPoint(31,8);
	var marker = new GMarker(point,icon);
	var html=loadHtmlStore(store);
	//GEvent.addListener(marker, "click",function() { cw.openOnMarker(marker,html); });
	GEvent.addListener(marker, "click",function() { marker.openInfoWindowHtml(html); });

	return marker;
}

function loadHtmlStore(store){
	var html='<div class="infoStore">';
	html=html+'<div class="imagen"></div>';
	html=html+'<span class="direccion">'+store.calle+'</span>';
	html=html+'<div class="cplocali"><span class="cp">'+store.cp+'</span>';
	html=html+'<span class="localidad">'+store.poblacion+'</span></div>';
	html=html+'<div><span class="provincia">'+store.provincia+'</span></div>';
	html=html+'<div><span class="telefono">'+store.tlf+'</span></div>';
	html=html+'<div><span class="secciones">'+traducc.secciones+': </span>'+store.secciones+'</div></div>';
	return html;
}

function loadHtmlContinent(id,nombre,numero){
	var html;
	html='<div class="expandir"><a href="#" onClick="loadContinent(\''+id+'\',\''+nombre+'\',\''+numero+'\');"><div class="infoPais"><div class="izq"></div><div class="centro"><span class="pais">'+nombre+'</span><span class="valor">'+numero+'</span></div><div class="drcha"></div></div></a></div>';
	return html;
}

function loadHtmlCountry(id,nombre,numero){
	var html;
	html='<div class="expandir"><a href="#" onClick="loadCountry(\''+id+'\',\''+nombre+'\',\''+numero+'\');"><div class="infoPais"><div class="izq"></div><div class="centro"><span class="pais">'+nombre+'</span><span class="valor">'+numero+'</span></div><div class="drcha"></div></div></a></div>';
	return html;
}

function loadHtmlCities(nombre,numero){
	var html;
	html='<div class="expandir"><a href="#" onClick="loadCity(\''+nombre+'\',false);"><div class="infoPais"><div class="izq"></div><div class="centro"><span class="pais">'+nombre+'</span><span class="valor">'+numero+'</span></div><div class="drcha"></div></div></a></div>';
	return html;
}

function loadHtmlRegion(id,nombre,numero){
	var html;
	html='<div class="expandir"><a href="#" onClick="loadRegion(\''+id+'\',\''+nombre+'\',\''+numero+'\');"><div class="infoPais"><div class="izq"></div><div class="centro"><span class="pais">'+nombre+'</span><span class="valor">'+numero+'</span></div><div class="drcha"></div></div></a></div>';
	return html;
}

function loadContinent(id,nombre,numero){
	clearVars(id,null,null,null);
	action=true;
	/*
	* nos posicionamos en el continente seleccionado
	*/
	info=GXmlHttp.create();
	info.open("POST", '/map_home/infoLatLngByContinentAction.do?id='+id, false);
	info.send(null);
	var jSonLatLng=eval("(" +info.responseText + ")");
	if(jSonLatLng!=null){
		var zoom=map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(jSonLatLng[0],jSonLatLng[3]),new GLatLng(jSonLatLng[1],jSonLatLng[2])));
		map.setCenter(new GLatLng(((jSonLatLng[0]+jSonLatLng[1])/2),((jSonLatLng[2]+jSonLatLng[3])/2)),zoom);
		clearOverlays();

		// cargamos el span con el continente correcto
		var object=new Object();
		var continente=new Object();
		continente.idZonaGeografica=id;
		continente.descripcion=nombre;
		object.continente=continente;
		object.num=numero;
		changeSpanContinent(object);
		// fin de la carga de el span

		/*
		* seleccionamos todas las provincias / localidades del pais
		* y mostramos el total por localidad
		*/

		loadStores();
	}
	action=false;
}

function loadCountry(id,name,num){
	continenteSel=loadContinentByCountry(id);
	clearVars(continenteSel,id,null,null);
	paisSel=id;
	action=true;

	/*
	* cargamos el pais en el menu izquierdo
	* si los parametros name y num no son nulos
	*/
	if(name!=null && num!=null) {
		var object=new Object();
		var pais=new Object();
		object.num=num;
		pais.descripcion=name;
		pais.idPais=id;
		object.pais=pais;
		changeSpanCountry(object);
	}

	/*
	* nos posicionamos en el pais seleccionado
	*/
	info=GXmlHttp.create();
	info.open("POST", '/map_home/infoLatLngAction.do?id='+id, false);
	info.send(null);
	var jSonLatLng=eval("(" +info.responseText + ")");
	if(jSonLatLng!=null){
		var zoom=map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(jSonLatLng[0],jSonLatLng[3]),new GLatLng(jSonLatLng[1],jSonLatLng[2])));
		map.setCenter(new GLatLng(((jSonLatLng[0]+jSonLatLng[1])/2),((jSonLatLng[2]+jSonLatLng[3])/2)),zoom);
		clearOverlays();

		/*
		* seleccionamos todas las provincias / localidades del pais
		* y mostramos el total por localidad
		*/

		loadStores();
	}
	action=false;
}

function loadRegion(id,nombre,num){
	clearVars(continenteSel,paisSel,id,null);
	action=true;
	/*
	* nos posicionamos en la provincia seleccionada
	*/
	info=GXmlHttp.create();
	info.open("POST", '/map_home/infoLatLngByRegionAction.do?id='+id, false);
	info.send(null);
	var jSonLatLng=eval("(" +info.responseText + ")");
	if(jSonLatLng!=null){
		var zoom=map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(jSonLatLng[0],jSonLatLng[3]),new GLatLng(jSonLatLng[1],jSonLatLng[2])));
		map.setCenter(new GLatLng(((jSonLatLng[0]+jSonLatLng[1])/2),((jSonLatLng[2]+jSonLatLng[3])/2)),zoom);
		clearOverlays();

		loadStores();
	}
	action=false;
}

function loadCity(nombre,googleResponse){
	/*
	* nos posicionamos en la ciudad seleccionada
	*/
	action=true;
	info=GXmlHttp.create();
	info.open("POST", '/map_home/infoLatLngByCityAction.do?nombre='+convertUtf8(nombre), false);
	info.send(null);
	var jSonLatLng=eval("(" +info.responseText + ")");
	if(jSonLatLng!=null){
		if(googleResponse==false) {
			var zoom=map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(jSonLatLng[0],jSonLatLng[3]),new GLatLng(jSonLatLng[1],jSonLatLng[2])));
			map.setCenter(new GLatLng(((jSonLatLng[0]+jSonLatLng[1])/2),((jSonLatLng[2]+jSonLatLng[3])/2)),zoom);
			clearOverlays();

			loadTiendas();
		}

		loadMenuIzqLocaliMarker(nombre);
	}
	action=false;
}

function loadContinentByCountry(paisId) {
	info=GXmlHttp.create();
	info.open("POST", '/map_home/loadContinentByCountryAction.do?id='+paisId, false);
	info.send(null);
	var jSonContinent=eval("(" +info.responseText + ")");
	if(jSonContinent!=null) {
		// cargamos el span con el continente correcto
		var object=new Object();
		var continente=new Object();
		continente.idZonaGeografica=jSonContinent.id;
		continente.descripcion=jSonContinent.nombre;
		object.continente=continente;
		object.num=jSonContinent.num;
		changeSpanContinent(object);
		// fin de la carga de el span

		return jSonContinent.id;
	} else {
		return null;
	}
}

function loadMarker(id,latitud,longitud){
	// posicionar el mapa en la latitud y longitud indicada
	action=true;
	map.setCenter(new GLatLng(latitud,longitud), 17);
	loadTiendas();
}

function clearVars(cont,pais,prov,locali){
	continenteSel=cont;
	paisSel=pais;
	provinciaSel=prov;
	localiSel=locali;
}

function loadTraducc() {
	info=GXmlHttp.create();
	info.open("POST", '/map_home/loadTraduccAction.do', false);
	info.send(null);
	traducc=eval("(" +info.responseText + ")");
}