var map;
var geo;
var panoramio_layer=new GLayer("com.panoramio.all");
var reasons=[];
var showText = function() { this.openInfoWindowHtml(this.Texto) };
var myInterval = null;
var marcador_uposicion = null;

function gmapa_websites(cadena,campo){
	var request = GXmlHttp.create();
	var htmlinfo="";
	
	request.open("GET", "xml_websites.php?search="+cadena+"&campo="+campo, true);

	request.onreadystatechange = function(){
		if(request.readyState == 4  && request.status == 200){
			 if(request.responseXML) {
				var xmlDoc = request.responseXML;
				var markers = xmlDoc.documentElement.getElementsByTagName("location");
				var point=new GLatLng(0,0);
				var idusuario=0;
				var titulo="";
				for (var i = 0; i < markers.length; i++) {
					if(parseFloat(markers[i].getAttribute("lat"))!=0 && parseFloat(markers[i].getAttribute("lng"))!=0){
						if(markers[i].getAttribute("idu")!=idusuario){
							if(idusuario!=0){
								map.addOverlay(crear_marcatab_array(point,tabs_array));
							}
							idusuario=markers[i].getAttribute("idu");
							var tabs_array=Array();
						}

						var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));

						htmlinfo="<b><div class=\"titulo_grande\"><a href=\""+markers[i].getAttribute("url")+"\" class=\"titulo_grande\" target=\"_blank\">"+markers[i].getAttribute("titulo")+"</a></div></b><br />"+markers[i].getAttribute("descripcion");
						if(markers[i].getAttribute("idu")!=0){
							htmlinfo+="<br /><br />Propietario:"+markers[i].getAttribute("propietario");
						}
						htmlinfo+="<br />Categoría:"+markers[i].getAttribute("categoria")
												htmlinfo+='<br /><br />';
						htmlinfo+='<table width="300" border="0" cellpadding="0" cellspacing="0">';
						htmlinfo+='<tr>';
																		htmlinfo+='</tr>';
						htmlinfo+='</table>';
						
						if(markers[i].getAttribute("idu")!=0){
							titulo=markers[i].getAttribute("titulo");
							tab_actual=new GInfoWindowTab(titulo.substr(0,7)+"...", htmlinfo);
							tabs_array.push(tab_actual);
						}else{
							map.addOverlay(crear_marca_website(point,htmlinfo));
						}
					}
				}
				if(typeof(tabs_array) != "undefined"){ 
					if(tabs_array.length>0){
						map.addOverlay(crear_marcatab_array(point,tabs_array));
					}
				}
				
				/*
				GEvent.addListener(map, "zoomend", function() {
					if(map.getZoom()>=11){
						map.addOverlay(panoramio_layer);
					}else{
						map.removeOverlay(panoramio_layer);
					}
                });
                */ 

				if(cadena!='')
					alert("Se han encontrado "+markers.length+" resultados");
			}
		}
	}
	request.send(null);
}

function crear_marcatab_array(point,tabs_array) {
	var marker = new GMarker(point,gicono_website());

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowTabsHtml(tabs_array,{maxWidth:500});
	});
	return marker;
}

function crear_marca_website(point,htmlinfo) {
	var marker = new GMarker(point,gicono_website());

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(htmlinfo,{maxWidth:500});
	});
	return marker;
}

function gmapa_usuarios(cadena,idw){
	var request = GXmlHttp.create();
	var htmlinfo="";
	
	request.open("GET", "xml_usuarios.php?search="+cadena+"&idw="+idw, true);

	request.onreadystatechange = function(){
		if(request.readyState == 4  && request.status == 200){
			 if(request.responseXML) {
				var xmlDoc = request.responseXML;
				var markers = xmlDoc.documentElement.getElementsByTagName("location");			
				var points = []; 
				for (var i = 0; i < markers.length; i++) {
					if(parseFloat(markers[i].getAttribute("lat"))!=0 && parseFloat(markers[i].getAttribute("lng"))!=0){
						var marcador = new GMarker(new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng"))),gicono_usuario());
						htmlinfo='<b><a class="titulo_grande" href="http://'+markers[i].getAttribute("usuario")+'.nimaps.com/">'+markers[i].getAttribute("nombre")+'</a></b>';
						htmlinfo+='<br /><br />';
						htmlinfo+='<table width="300" border="0" cellpadding="0" cellspacing="0">';
						htmlinfo+='<tr>';
						if(idu!=markers[i].getAttribute("id")){
							htmlinfo+='<td align="center"><a href="#"><img src="images/icn_mensaje.gif" width="24" height="19" alt="Enviar mensaje al webmaster" title="Enviar mensaje al webmaster" border="0" onclick="mostrar_mensaje('+markers[i].getAttribute("id")+')" /></a></td>';
						}
						htmlinfo+="<td align=\"center\"><a href=\"#\"><img src=\"images/icn_verfoto.gif\" width=\"25\" height=\"22\" alt=\"Ver fotos\" title=\"Ver fotos\" border=\"0\" onclick=\"mostrar_fotos('usuario',"+markers[i].getAttribute("id")+")\" /></a></td>";
						htmlinfo+='</tr>';
						htmlinfo+='</table>';
						marcador.Texto = htmlinfo;
						marcador.id=markers[i].getAttribute("id");
						GEvent.addListener(marcador , 'click', showText);
						map.addOverlay(marcador);
					}
				}
				if(cadena!='')
					alert("Se han encontrado "+markers.length+" resultados");
			}
		}
	}
	request.send(null);
}

function gmapa_usuario(usuario){
	var request = GXmlHttp.create();
	var htmlinfo="";

	request.open("GET", "xml_usuario.php?usuario="+usuario, true);

	request.onreadystatechange = function(){
		if(request.readyState == 4  && request.status == 200){
			 if(request.responseXML) {
				var xmlDoc = request.responseXML;
				var markers = xmlDoc.documentElement.getElementsByTagName("location");
				var points = []; 
				for (var i = 0; i < markers.length; i++) {
					if(parseFloat(markers[i].getAttribute("lat"))!=0 && parseFloat(markers[i].getAttribute("lng"))!=0){
						var marcador = new GMarker(new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng"))),gicono_usuario());
						htmlinfo="<b><div class=\"titulo_grande\">"+markers[i].getAttribute("nombre")+"</div></b>";
						htmlinfo+='<br /><br />';
						htmlinfo+='<table width="300" border="0" cellpadding="0" cellspacing="0">';
						htmlinfo+='<tr>';
						htmlinfo+='</tr>';
						htmlinfo+='</table>';
						marcador.Texto = htmlinfo;
						marcador.id=markers[i].getAttribute("id");
						GEvent.addListener(marcador , 'click', showText);
						map.addOverlay(marcador);
						marcador_uposicion=new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
						map.setCenter(marcador_uposicion);
					}
				}
			}
		}
	}
	request.send(null);
}
function gaccion_posiciona(lat,lng){
	map.panTo(new GLatLng(parseFloat(lat), parseFloat(lng)));
}

function gaccion_marca_website(lat,lng){
	var marcador = new GMarker(new GLatLng(parseFloat(lat), parseFloat(lng)));
	map.addOverlay(marcador);
	gaccion_posiciona(lat,lng);
}

function gaccion_inicializar() {
	if (GBrowserIsCompatible()) {      
		map = new GMap2(document.getElementById("map"));
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
		var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
		map.addControl(new GLargeMapControl(),bottomRight);
		map.addControl(new GMapTypeControl());
		marcador_iniposicion=new GLatLng(40.01078714046552, -4.21875);
		map.setCenter(marcador_iniposicion);
		
		gaccion_cargadatos('','website',0,'');
	}
}

function gaccion_inicializar_perfil(usuario) {
	if (GBrowserIsCompatible()) {      
		map = new GMap2(document.getElementById("map"));
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
		map.addControl(new GSmallZoomControl());
		marcador_iniposicion=new GLatLng(40.01078714046552, -4.21875);
		map.setCenter(marcador_iniposicion);
		
		map.clearOverlays();
		map.setMapType(G_NORMAL_MAP);
		map.setZoom(6);
		gmapa_usuario(usuario);
	}
}

function gaccion_inicializar_adwebsite() {
	if (GBrowserIsCompatible()) {      
		map = new GMap2(document.getElementById("map"));
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
		map.addControl(new GSmallZoomControl());
		marcador_iniposicion=new GLatLng(40.01078714046552, -4.21875);
		map.setCenter(marcador_iniposicion);
		
		map.clearOverlays();
		map.setMapType(G_NORMAL_MAP);
		map.setZoom(6);

		if(typeof(ad_lat) != "undefined" && typeof(ad_lng) != "undefined"){ 
			if(ad_lat!="" && ad_lng!=""){
				gaccion_marca_website(ad_lat,ad_lng);
			}
		}

		GEvent.addListener(map, "click", function(overlay, point) {
          if (overlay) {
            map.removeOverlay(overlay);
          } else {
            map.clearOverlays();
            map.addOverlay(new GMarker(point));
            xajax.$('frmlat').value=point.y;
            xajax.$('frmlng').value=point.x;
          }
        });
	}
}

function gaccion_calleposicion(search) {
	geo = new GClientGeocoder();
	// ====== Array for decoding the failure codes ======
	reasons[G_GEO_SUCCESS]            = "Success";
	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
	reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";	

	// ====== Perform the Geocoding ======
	geo.getLocations(search, function (result)
	{ 
		// If that was successful
		if (result.Status.code == G_GEO_SUCCESS) {
		  // Loop through the results, placing markers
		  for (var i=0; i<result.Placemark.length; i++) {
			var p = result.Placemark[i].Point.coordinates;
			var marker = new GMarker(new GLatLng(p[1],p[0]));
			grabar_datos(marker.getLatLng().lat(),marker.getLatLng().lng());
		  }
		}else{
			// ====== Decode the error status ======
			var reason="Code "+result.Status.code;
			if (reasons[result.Status.code]) {
			reason = reasons[result.Status.code]
			} 
			grabar_datos(0,0);
		}
	});
}

function gicono_website() {
    var result = new GIcon();
    result.image = "images/icn_website.png";
    result.shadow = "images/icn_website_s.png";
    result.iconSize = new GSize(32, 32);
    result.shadowSize = new GSize(59, 32);
    result.iconAnchor = new GPoint(14, 25);
    result.infoWindowAnchor = new GPoint(10, 10);
    return result;
}

function gicono_usuario() {
    var result = new GIcon();
    result.image = "images/icn_usuario.png";
    result.shadow = "images/icn_usuario_s.png";
    result.iconSize = new GSize(16, 16);
    result.shadowSize = new GSize(30, 16);
    result.iconAnchor = new GPoint(14, 20);
    result.infoWindowAnchor = new GPoint(10, 10);
    return result;
}

function gaccion_cargadatos(cadena,tipo,idw,campo_busqueda) {
	clearTimeout(myInterval);
	map.clearOverlays();
	map.setMapType(G_NORMAL_MAP);
	if (GBrowserIsCompatible()) {      
		switch(tipo){
		case "website":
			map.setZoom(6);
			gmapa_websites(cadena,campo_busqueda);
		break;
		case "usuario":
			map.setZoom(6);
			gmapa_usuarios(cadena,idw);
		break;
		}
	}
}

function gaccion_buscar(){
	gaccion_cargadatos(xajax.$('fndBusqueda').value,"website",0,'');
}

function gaccion_buscar_avanzada(){
	if(xajax.$('frmBATipo').value=="nombre"){
		gaccion_cargadatos(xajax.$('frmBABusqueda').value,"usuario",0,'');
	}else{
		gaccion_cargadatos(xajax.$('frmBABusqueda').value,"website",0,xajax.$('frmBATipo').value);
	}
}
