/*
* author: diegomrp
* date: 19/09/2007
* copyright: INDITEX S.A. - All rights reserved
*/

function findText(value){
	if(value==""){
		viewWorld();
		return;
	}
	var geoClient=new GClientGeocoder();
	geoClient.setViewport(map.getBounds());
	var b=geoClient.getViewport();
	geoClient.getLocations(value, findMarkersByValue);
}

function findMarkersByValue(response) {
	viewCargando();
	if(response.Placemark!=null){
		vaciarValores();
		/*
		* Si tenemos un resultado solo, nos posicionamos en el.
		* En caso de tener varios resultados, mostramos una lista para seleccionar
		*/
		if(response.Placemark.length>1){
			var list=new Array();
			for(i=0;i<response.Placemark.length;i++) {
				var r=response.Placemark[i];
				list[i]=r.address;
			}
			loadListByFindText(list);
		} else {
			loadMarkerByGoogleResponse(response.Placemark[0]);
		}
	}
	hideCargando();
}

function loadMarkerByGoogleResponse(r){
	switch(r.AddressDetails.Accuracy){
		case 1:
			var jSonPais=findCountryByGoogleResponse(r.AddressDetails.Country.CountryNameCode);
			if(jSonPais!=null){
				loadCountry(jSonPais.pais.idPais,jSonPais.pais.descripcion,jSonPais.num);
			} else {
				document.getElementById('texto').innerHTML="";
				noResult();
				viewWorld();
			}
			break;
		case 2:
			var jSonPais=findCountryByGoogleResponse(r.AddressDetails.Country.CountryNameCode);
			if(jSonPais!=null) {
				loadCountry(jSonPais.pais.idPais,jSonPais.pais.descripcion,jSonPais.num);
			} else {
				document.getElementById('texto').innerHTML="";
				noResult();
				viewWorld();
			}
			break;
		case 3:
			// sin definir
			//alert(r.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName);
			break;
		case 4:
			/*
			* La busqueda de la localidad depende en gran medida de la estructura del pais
			* Google estructura los paises de diferentes formas, dependiendo de si tiene
			* AdministrativeArea y SubAdministrativeArea o si por el contrario aparecen las localidades
			* sin divisiones en areas
			*/
			//loadLocaliByGoogleResponse(r,false);
			findMultipleInformationByGoogleResponse(r);
			break;
		case 6:
			/*map.setCenter(new GLatLng(r.Point.coordinates[1],r.Point.coordinates[0]), 17);
			loadLocaliByGoogleResponse(r,true);*/
			findMultipleInformationByGoogleResponse(r);
			break;
		case 8:
			/*map.setCenter(new GLatLng(r.Point.coordinates[1],r.Point.coordinates[0]), 17);
			loadLocaliByGoogleResponse(r,true);*/
			findMultipleInformationByGoogleResponse(r);
			break;
		default:
			break;
	}
}

function loadCountryAndContinent(r){
	// cargamos en el menuIzq el span de continente y pais
	var jSonPais=findCountryByGoogleResponse(r.AddressDetails.Country.CountryNameCode);
	if(jSonPais!=null) {
		loadContinentByCountry(jSonPais.pais.idPais);
		changeSpanCountry(jSonPais);
		if(jSonPais.pais.idPais==11){
			loadUniqueRegionMenuIzqByGoogleResponse(r.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName);
		}
	} else {
		noResult();
		viewWorld();
	}
	// fin de la carga de los spans
}

function findCountryByGoogleResponse(paisIso) {
	info=GXmlHttp.create();
	info.open("POST", '/map_home/findCountryByGoogleResponseAction.do?id='+paisIso, false);
	info.send(null);
	var jSonPais=eval("(" +info.responseText + ")");
	return jSonPais;
}

function vaciarValores() {
	continenteSel=null;
	paisSel=null;
	provinciaSel=null;
	localiSel=null;
	hideSpan("continente"); hideSpan("pais"); hideSpan("provincia"); hideSpan("localidad");
}

function findCountriesByText(value) {
	info=GXmlHttp.create();
	info.open("POST", '/map_home/storeFindAction.do?id='+value+'&prop=pais', true);
	info.onreadystatechange=function() {
		if(info.readyState==4) {
			if(info.status==200) {
				var jSonList=eval("(" +info.responseText + ")");
				loadCountry(jSonList[0].pais.id,jSonList[0].pais.nombre,jSonList[0].num);
				hideCargando();
			}
		} else {
			viewCargando();
		}
	}
	info.send(null);
}

function loadListByFindText(list){
	var div=document.getElementById("texto");
	var html="";

	document.getElementById("listado").className="listaLocations";

	for(i=0; i<list.length;i++){
		html=html+"<span class=\"locations\">"+
		"<a class=\"resultLocations\" href=\"#\" onClick=\"findText('"+list[i]+"');\">"+
		"<span class=\"titulo\">"+list[i]+"</span>"+
		"</a>"+"</span>";
	}

	div.innerHTML=html;

	// hace aparecer o desaparecer el scroll
	changeHeight();
	// fin de scroll
}

function verifyLocali(nombre){
	info=GXmlHttp.create();
	info.open("POST", '/map_home/infoLatLngByCityAction.do?nombre='+convertUtf8(nombre), false);
	info.send(null);
	var jSonLatLng=eval("(" +info.responseText + ")");
	if(jSonLatLng[0]==null){
		return false;
	} else {
		return true;
	}
}

function loadUniqueRegionMenuIzqByGoogleResponse(nombre){
	info=GXmlHttp.create();
	info.open("POST", '/map_home/loadRegionByNameAction.do?nombre='+convertUtf8(nombre), false);
	info.send(null);
	var jSonRegion=eval("(" +info.responseText + ")");
	changeSpanRegion(jSonRegion);
}

function loadLocaliByGoogleResponse(r,posicionar) {
	var localiName;

	loadCountryAndContinent(r);

	if(r.AddressDetails.Country.AdministrativeArea!=null){
		if(r.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea==null){
			localiName=r.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
		} else {
			localiName=r.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
		}
	} else {
		localiName=r.AddressDetails.Country.Locality.LocalityName;
	}
	if(verifyLocali(localiName)== true){
		loadCity(localiName.toUpperCase(),posicionar);
	} else {
		loadCitiesByRegionName(r);
	}
}

function loadCitiesByRegionName(r) {
	var nombre="";
	if(r.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea==null){
		nombre=r.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
	} else {
		nombre=r.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
	}
	info=GXmlHttp.create();
	info.open("POST", '/map_home/loadRegionByNameAction.do?nombre='+convertUtf8(nombre), false);
	info.send(null);
	var jSonRegion=eval("(" +info.responseText + ")");
	if(jSonRegion!=null){
		loadRegion(jSonRegion.provincia.idProvincia,null,null);
	} else {
		var jSonPais=findCountryByGoogleResponse(r.AddressDetails.Country.CountryNameCode);
		if(jSonPais!=null){
			loadCountry(jSonPais.pais.idPais,jSonPais.pais.descripcion,jSonPais.num);
		}
	}
}

function noResult() {
	info=GXmlHttp.create();
	info.open("POST", '/map_home/noResultAction.do', false);
	info.send(null);
	alert(info.responseText);
}

function findMultipleInformationByGoogleResponse(r) {
	// encontrar toda la informacion del menuIzq sin saturar de consultas el servidor
	var countryCode=null;
	var subAdministrativeArea=null;
	var localityName=null;

	countryCode=r.AddressDetails.Country.CountryNameCode;
	if(r.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea==null){
		localityName=r.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
	} else {
		subAdministrativeArea=r.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
		localityName=r.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
	}

	info=GXmlHttp.create();
	info.open("POST", '/map_home/loadMultipleInformationByGoogleAction.do?countryCode='+countryCode+
	'&subAdministrativeArea='+convertUtf8(subAdministrativeArea)+'&localityName='+convertUtf8(localityName), false);
	info.send(null);
	var jSonMultiInfo=eval("(" +info.responseText + ")");

	// cargamos todos los datos
	if(jSonMultiInfo!=null) {
		var zoom=map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(jSonMultiInfo.latLng[0],jSonMultiInfo.latLng[3]),new GLatLng(jSonMultiInfo.latLng[1],jSonMultiInfo.latLng[2])));
		map.setCenter(new GLatLng(((jSonMultiInfo.latLng[0]+jSonMultiInfo.latLng[1])/2),((jSonMultiInfo.latLng[2]+jSonMultiInfo.latLng[3])/2)),zoom);
		changeSpanContinent(jSonMultiInfo.continenteNum);
		continenteSel=jSonMultiInfo.continenteNum.continente.idZonaGeografica;
		if(jSonMultiInfo.regionNum!=null) {
			changeSpanRegion(jSonMultiInfo.regionNum);
		}
		if(jSonMultiInfo.listaTiendas!=null){
			changeSpanLocalidad(jSonMultiInfo.listaTiendas);
			loadMenuIzqMarkers(jSonMultiInfo.listaTiendas);
		}
		if(jSonMultiInfo.accionAjax=='loadTiendas'){
			loadOverlay(jSonMultiInfo.listaTiendas);
		} else if(jSonMultiInfo.accionAjax=='loadStores') {
			if(jSonMultiInfo.regionNum!=null){
				clearVars(jSonMultiInfo.continenteNum.continente.idZonaGeografica,jSonMultiInfo.paisNum.pais.idPais,jSonMultiInfo.regionNum.provincia.idProvincia);
			}
			loadStores();
		} else if(jSonMultiInfo.accionAjax=='loadCountry') {
			loadCountry(jSonMultiInfo.paisNum.pais.idPais,jSonMultiInfo.paisNum.pais.descripcion,jSonMultiInfo.paisNum.num);
		}
	}
}