//<![CDATA[
var requestData;
var responseXML;
var ListOfPoints = new Array(); // array of point
var gmap; //Map of Google
var gNewUserMarker; //New User Mark
var gmarker;
var gmarkerSelected = null;
var gIdSelected = -1;
var ggroupSelected = null;
var page;
var totalRegister;
var totalPages;
var nLocationsByPage = 50;

var photoOnClick = "";
var widthPhotoOnClick = 0;
var heightPhotoOnClick = 0;

var myPoints = false;

/*Variables de categoria seleccionadas*/
var gCategories = new Array(1,2,3,4,5); // array of categorias

var placeId = -1;
var gDateSelected = null;
var userId = -1;
var userSessionId = -1;

// variables para comentarios

var requestDataComments;
var responseXMLComments;
var pageComments;
var totalPagesComments;

// precarga de imágenes

img1=new Image();
img1.src="img/ico_1_off.jpg";
img2=new Image();
img2.src="img/ico_1_on.jpg";

img3=new Image();
img3.src="img/ico_2_off.jpg";
img4=new Image();
img4.src="img/ico_2_on.jpg";

img5=new Image();
img5.src="img/ico_3_off.jpg";
img6=new Image();
img6.src="img/ico_3_on.jpg";

img7=new Image();
img7.src="img/ico_4_off.jpg";
img8=new Image();
img8.src="img/ico_4_on.jpg";

img9=new Image();
img9.src="img/ico_5_off.jpg";
img10=new Image();
img10.src="img/ico_5_on.jpg";

img11=new Image();
img11.src="img/my_points_off.png";

function setLocationsByPage(i) {
	if (i<0)
		nLocationsByPage = 10000;
	else
		nLocationsByPage = i;
	idSelected = "item_page_" + i;
	
	if (i<0) idSelected = "item_page_todos";
	
	document.getElementById("item_page_25").className = "item_page_off";
	document.getElementById("item_page_50").className = "item_page_off";
	document.getElementById("item_page_100").className = "item_page_off";
	document.getElementById("item_page_todos").className = "item_page_off";
	
	document.getElementById(idSelected).className = "item_page_on";
	
	GetPointsInViewMap();
}

function unSelectedPOI() {
	if ( gmarkerSelected != null) {
		gmarkerSelected.setImage("img/mark" + ggroupSelected + "_off.png");
		gmarkerSelected.disableDragging();		
		gmarkerSelected = null;
		GetPointsInViewMap();
	}
	gIdSelected = -1;
}

function sendTwitter( ){
	window.open ("http://twitter.com/home/?status=http://www.dondereciclar.com/?id=" + document.getElementById("location_id").value,"_blank");
}

function sendFacebook( ){
	window.open ("http://www.facebook.com/share.php?u=http://www.dondereciclar.com/?id=" + document.getElementById("location_id").value,"_blank");
}

function showURL( ){
	prompt("URL para enlazar directamente", "http://www.dondereciclar.com/?id=" + document.getElementById("location_id").value);
}

function getParamUrl( name ){
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp ( regexS );
	var tmpURL = window.location.href;
	var results = regex.exec( tmpURL );
	if( results == null )
		return "";
	else
		return results[1];
}


function writeMsg( msg ){
	if (msg == 1) {
		alert("Clave actual no válida");
	} else if (msg == 2) {
		alert("Las dos claves no son iguales");
	} else if (msg == 3) {
		alert("El usuario no está conectado");
	} else if (msg == 4) {
		alert("Clave modificada correctamente");
	} else if (msg == 5) {
		alert("Datos de usuario modificados correctamente");
	} else if (msg == 6) {
		alert("El usuario no existe. Por favor inténtelo de nuevo");
	}
}

function changeImageUpload( image ){
	var imgDiv = document.getElementById("image_location");
	out = "<input type=\"hidden\" id=\"form_image\" value=\"" + image + "\" />";
	out += "<br/><img src=\"photos/" + image + "\" height=\"80px\" />";
	out += "<div align=\"center\"><a href=\"#\" onclick=\"changeButtonUpload();\">Eliminar imagen</a></div>";
	imgDiv.innerHTML = out;
}

function changeButtonUpload() {
	var imgDiv = document.getElementById("image_location");
	out = "<input type=\"hidden\" id=\"form_image\" value=\"\" />";
	out += "<a href=\"#\" onclick=\"MOOdalBox.open('upload_window.php', '', '600 250');\"><img src=\"img/btn_upload_image.png\" border=\"0\" /></a>";
	imgDiv.innerHTML = out;
}

//--------------------------------------------
//----------------- GUI ----------------------
//--------------------------------------------

function openPhoto() {
	if (photoOnClick != "") {
		w = 0;
		h = 0;
		if (widthPhotoOnClick>heightPhotoOnClick) {
			w = 600;
			h = parseInt((600*heightPhotoOnClick)/widthPhotoOnClick);
		} else {
			h = 600;
			w = parseInt((600*widthPhotoOnClick)/heightPhotoOnClick);
		}

		MOOdalBox.open('photo.php?photo=' + photoOnClick, '', (w+20) + ' ' + (h+20));
	}
}

function ChangeColorcategorie(cat) {
	var c = document.getElementById("menu_"+cat);
	var icon = document.getElementById("icon_menu_active_"+cat);
	if (c.className == "button_menu") {
		icon.className = "icon_menu_active_" + cat;
		c.className = "button_menu_active_" + cat;
		c.getElementsByTagName("img")[0].src = "img/ico_" + cat + "_on.jpg";
	}
	else {
		icon.className = "icon_menu_active_off";
		c.className = "button_menu";
		c.getElementsByTagName("img")[0].src = "img/ico_" + cat + "_off.jpg";
	}
}

function setUserId(id){
	userId = id;
}

function setUserSessionId(id){
	userSessionId = id;
}

function setDate(date){
	gDateSelected = date;
}

function setPlace(pl){
	placeId = pl;
	loadXMLPlace();
}

var requestDataPlace;
var responseXMLPlace;

function loadXMLPlace () {
  url = "api_place.php?id="+placeId;
  if (window.XMLHttpRequest) {
    requestDataPlace = new XMLHttpRequest();
	requestDataPlace.onreadystatechange = processChangeXMLPlace;
	requestDataPlace.open("GET", url, true);
	requestDataPlace.send(null);
  } else if (window.ActiveXObject) {
    requestDataPlace = new ActiveXObject("Microsoft.XMLHTTP");
	if (requestDataPlace) {
	  requestDataPlace.onreadystatechange = processChangeXMLPlace;
	  requestDataPlace.open("GET", url, true);
	  requestDataPlace.send();
	}
  }
}

function processChangeXMLPlace(){
  if (requestDataPlace.readyState == 4) {
    if (requestDataPlace.status == 200) {      
      responseXMLPlace = null;
      responseXMLPlace = requestDataPlace.responseXML.documentElement;
      if (responseXMLPlace) {  
		var location = responseXMLPlace.getElementsByTagName("location");
		if ( location.length == 1 ) { //Existe el lugar pasado por parametro
			gmap.setCenter(new GLatLng(location[0].getAttribute("latitude"), location[0].getAttribute("longitude")), parseInt(location[0].getAttribute("zoomlevel")));
		}
		GetPointsInViewMap();
      }
    } else {
      alert("There was a problem retrieving the XML data:\n" + responseXML.statusText);
    }
  }
}

function deleteFilters(){
	placeId = -1;
	gDateSelected = null;
	userId = -1;
	var msg_filter = $('msg_filter');
	msg_filter.fade(0);
	GetPointsInViewMap();
}

function selectedCategoryInNewPOI(cat){
	var txt = document.getElementById("type_poi");
	var img = document.getElementById("img_new_1");
	var form = document.getElementById("form_group");
	form.value = cat;
	
	if (cat==1) {
		txt.innerHTML = "Punto Limpio";
		img.className = "icon_new_active_1";
		img.src = "img/ico_1_on.jpg";
	} else {
		img.className = "icon_new";
		img.src = "img/ico_1_off.jpg";
	}
	
	var img = document.getElementById("img_new_2");
	if (cat==2) {
		txt.innerHTML = "Pilas";
		img.className = "icon_new_active_2";
		img.src = "img/ico_2_on.jpg";
	} else {
		img.className = "icon_new";
		img.src = "img/ico_2_off.jpg";
	}
	
	var img = document.getElementById("img_new_3");
	if (cat==3) {
		txt.innerHTML = "Denuncia";
		img.className = "icon_new_active_3";
		img.src = "img/ico_3_on.jpg";
	} else {
		img.className = "icon_new";
		img.src = "img/ico_3_off.jpg";
	}
	
	var img = document.getElementById("img_new_4");
	if (cat==4) {
		txt.innerHTML = "Ropa";
		img.className = "icon_new_active_4";
		img.src = "img/ico_4_on.jpg";
	} else {
		img.className = "icon_new";
		img.src = "img/ico_4_off.jpg";
	}
	
	var img = document.getElementById("img_new_5");
	if (cat==5) {
		txt.innerHTML = "Otro";
		img.className = "icon_new_active_5";
		img.src = "img/ico_5_on.jpg";
	} else {
		img.className = "icon_new";
		img.src = "img/ico_5_off.jpg";
	}
}

function selectOnlyCategory(cat){
	//alert("seleccionar sólo categoría: " + cat); 
	gCategories[0] = 0;
	gCategories[1] = 0;
	gCategories[2] = 0;
	gCategories[3] = 0;
	gCategories[4] = 0;

	var c = document.getElementById("menu_1");
	c.className = "button_menu";
	c.getElementsByTagName("img")[0].src = "img/ico_1_off.jpg";
	var icon = document.getElementById("icon_menu_active_1");
	icon.className = "icon_menu_active_off";

	var c = document.getElementById("menu_2");
	c.className = "button_menu";
	c.getElementsByTagName("img")[0].src = "img/ico_2_off.jpg";
	var icon = document.getElementById("icon_menu_active_2");
	icon.className = "icon_menu_active_off";

	var c = document.getElementById("menu_3");
	c.className = "button_menu";
	c.getElementsByTagName("img")[0].src = "img/ico_3_off.jpg";
	var icon = document.getElementById("icon_menu_active_3");
	icon.className = "icon_menu_active_off";

	var c = document.getElementById("menu_4");
	c.className = "button_menu";
	c.getElementsByTagName("img")[0].src = "img/ico_4_off.jpg";
	var icon = document.getElementById("icon_menu_active_4");
	icon.className = "icon_menu_active_off";

	var c = document.getElementById("menu_5");
	c.className = "button_menu";
	c.getElementsByTagName("img")[0].src = "img/ico_5_off.jpg";
	var icon = document.getElementById("icon_menu_active_5");
	icon.className = "icon_menu_active_off";

	selectCategory(cat);
}

function selectCategory(cat) {
	if ( gCategories[cat-1] == 0 ){
		gCategories[cat-1] = cat;
		ChangeColorcategorie(cat);
	} else {
		gCategories[cat-1] = 0;
		/* Comprobamos que no se hallan quedado todas las categorias sin marcar */
		if ( gCategories == "0,0,0,0,0" ) {
			gCategories[cat-1] = cat;
			alert("Como mínimo debe haber una categoría seleccionada");
		} else {
			ChangeColorcategorie(cat);
		}
	}	
	/* Consultamos los puntos de las categorias seleccionadas */	
	GetPointsInViewMap();
}

function CancelNewUserMark() {	
	if ( gNewUserMarker ) {
		gmap.removeOverlay(gNewUserMarker);
		gNewUserMarker = null;
	}	
	showMenu();
	AddAllListenersForEditMarker(gmarkerSelected, gIdSelected, ggroupSelected);
}

function showMenu() {
					
	var menuButtons = $('menu_buttons');
	menuButtons.style.display = "block";
	menuButtons.fade(1);
	
	var menuInfo = $('menu_info');
	menuInfo.style.display = "block";
	menuInfo.fade(1);
	
	var menuData = $('menu_data');
	menuData.style.display = "none";
	menuData.fade(0);
	
	var menuComments = $('menu_comments');
	menuComments.style.display = "none";
	menuComments.fade(0);
	
	var menuNewpoi = $('menu_newpoi');
	menuNewpoi.style.display = "none";
	menuNewpoi.fade(0);

	/* Quitamos la seleccion del posible punto activo*/
	if ( gmarkerSelected != null) {
		gmarkerSelected.setImage("img/mark" + ggroupSelected + "_off.png");
		gmarkerSelected.disableDragging();		
		gmarkerSelected = null;
	        GetPointsInViewMap();
	}
	gIdSelected = -1;
}

function showDataFromTab() {
	showData();
	loadXMLDataLocation('web_info_location.php?id=' + gIdSelected, gmarker);
}

function showData() {
	
	document.getElementById("btn_inappropriate").style.display = "none";
	document.getElementById("btn_edit").style.display = "none";
	document.getElementById("btn_delete").style.display = "none";
	
	var menuButtons = $('menu_buttons');
	menuButtons.style.display = "none";
	menuButtons.fade(0);

	var menuInfo = $('menu_info');
	menuInfo.style.display = "none";
	menuInfo.fade(0);
	
	var menuData = $('menu_data');
	menuData.style.display = "block";
	menuData.fade(1);
	
	var menuComments = $('menu_comments');
	menuComments.style.display = "none";
	menuComments.fade(0);
	
	var menuNewpoi = $('menu_newpoi');
	menuNewpoi.style.display = "none";
	menuNewpoi.fade(0);
}

function showComments() {
	if (gIdSelected>0) {
		pageComments = 0;
		loadXMLCommentsLocation("api_comments.php?id="+gIdSelected);
		
		document.getElementById("btn_inappropriate").style.display = "block";
		document.getElementById("btn_edit").style.display = "none";
		document.getElementById("btn_delete").style.display = "none";
		
		var menuButtons = $('menu_buttons');
		menuButtons.style.display = "none";
		menuButtons.fade(0);
	
		var menuInfo = $('menu_info');
		menuInfo.style.display = "none";
		menuInfo.fade(0);
		
		var menuData = $('menu_data');
		menuData.style.display = "none";
		menuData.fade(0);
		
		var menuComments = $('menu_comments');
		menuComments.style.display = "block";
		menuComments.fade(1);
		
		var menuNewpoi = $('menu_newpoi');
		menuNewpoi.style.display = "none";
		menuNewpoi.fade(0);
	}
}

function onClickAddressComment() {
	if (document.getElementById("form_address_comment").value == "Comentario a la dirección") {
		document.getElementById("form_address_comment").value = "";
		document.getElementById("form_address_comment").className = "";
	}
}

function onKeyUpAddressComment() {
	if (document.getElementById("form_address_comment").value == "") {
		document.getElementById("form_address_comment").value = "Comentario a la dirección";
		document.getElementById("form_address_comment").className = "empty";
		document.getElementById("form_description").focus();
	}
}

function showNewPoi() {
		
	document.getElementById("form_location_id").value = "";
	document.getElementById("form_description").value = "";
	document.getElementById("form_address").value = "";
	document.getElementById("form_address_comment").value = "Comentario a la dirección";
	document.getElementById("form_address_comment").className = "empty";
	document.getElementById("form_contact").value = "";
	document.getElementById("form_latitud").value = "";
	document.getElementById("form_longitud").value = "";
	document.getElementById("form_group").value = "";
	document.getElementById("form_more_details").value = "";
	document.getElementById("form_group").selectedIndex = 0;
	changeButtonUpload();
	
	var menuButtons = $('menu_buttons');
	menuButtons.style.display = "none";
	menuButtons.fade(0);

	var menuInfo = $('menu_info');
	menuInfo.style.display = "none";
	menuInfo.fade(0);
	
	var menuData = $('menu_data');
	menuData.style.display = "none";
	menuData.fade(0);
	
	var menuComments = $('menu_comments');
	menuComments.style.display = "none";
	menuComments.fade(0);
	
	var menuNewpoi = $('menu_newpoi');
	menuNewpoi.style.display = "block";
	menuNewpoi.fade(1);
}

function ClearAllListenersForEditMarker(pMarker) {
	GEvent.clearListeners(gmap, "moveend");	
	GEvent.clearListeners(pMarker, "click");
}

function AddAllListenersForEditMarker(pMarker, pid, pgroup) {
	GEvent.addListener(gmap, "moveend", GetPointsInViewMap);
	GEvent.addListener(pMarker, "click", function () {ShowMarkerInfo(pMarker, pid, pgroup) } );
}

function showEditPoi() {		
	if ( gmarkerSelected != null) {
		gmarkerSelected.enableDragging();
		gmap.openInfoWindowHtml(gmarkerSelected.getLatLng(),
							'<table><tr><td width="10"><img src="/img/information.png"></td><td align="left"><b>Informaci&oacute;n</b></td></tr><tr><td colspan="2">Puedes moverme para modificar</td></tr><tr><td colspan="2">la posición del punto</td></tr><tr><td colspan="2">&nbsp;</td></tr></table>');
		GEvent.addListener(gmarkerSelected,  "mouseup", function () {fillDataNewMarker(gmarkerSelected) } );
		// Desactivamos los eventos del mapa y de la marca seleccionada para que no se pierda la edicion cunado lo mueva
		ClearAllListenersForEditMarker(gmarkerSelected);	
	}	
	showNewPoi();
	url = "api_edit_location.php?id=" + document.getElementById("location_id").value;
	
  	if (window.XMLHttpRequest) {
  		requestData = new XMLHttpRequest();
  		requestData.onreadystatechange = processEditPoi;
  		requestData.open("GET", url, true);
  		requestData.send(null);
  	}
  	else 
  		if (window.ActiveXObject) {
  			requestData = new ActiveXObject("Microsoft.XMLHTTP");
  			if (requestData) {
  				requestData.onreadystatechange = processEditPoi;
  				requestData.open("GET", url, true);
  				requestData.send();
  			}
  		}
}

function processEditPoi(){  
  if (requestData.readyState == 4) {
    if (requestData.status == 200) {   
      responseXML = null;
      responseXML = requestData.responseXML.documentElement;
      if (responseXML) {
		var resp = responseXML.getElementsByTagName("location");
		
		document.getElementById("form_location_id").value = resp[0].getAttribute("id");
		
		var description = responseXML.getElementsByTagName("description");
		document.getElementById("form_description").value = description[0].firstChild.data;
		
		var address = responseXML.getElementsByTagName("address");
		document.getElementById("form_address").value = address[0].firstChild.data;
		document.getElementById("form_text_address").innerHTML = address[0].firstChild.data;		
		
		var comment_address = responseXML.getElementsByTagName("comment-address");
		if (comment_address[0].firstChild.data == "") {
			document.getElementById("form_address_comment").value = "Comentario a la dirección";
			document.getElementById("form_address_comment").className = "empty";
		} else {
			document.getElementById("form_address_comment").value = comment_address[0].firstChild.data;
			document.getElementById("form_address_comment").className = "";
		}
		
		var contact = responseXML.getElementsByTagName("contact");
		document.getElementById("form_contact").value = contact[0].firstChild.data;
		
		document.getElementById("form_latitud").value = resp[0].getAttribute("latitude");
		//document.getElementById("form_text_latitud").innerHTML = resp[0].getAttribute("latitude");
		
		document.getElementById("form_longitud").value = resp[0].getAttribute("longitude");
		//document.getElementById("form_text_longitud").innerHTML = resp[0].getAttribute("longitude");
		
		var more_details = responseXML.getElementsByTagName("more-details");		
		document.getElementById("form_more_details").value = more_details[0].firstChild.data;
		
		document.getElementById("form_group").value = resp[0].getAttribute("group");
		
		selectedCategoryInNewPOI(parseInt(resp[0].getAttribute("group")));
		
		var image = responseXML.getElementsByTagName("image");
		if (image.length>0) {
			changeImageUpload(image[0].firstChild.data);
		} else {
			changeButtonUpload();
		}
		
      }
    } else {
      alert("There was a problem retrieving the XML data:\n" + responseXML.statusText);
    }
  }
}

//--------------------------------------------
//----------------- END GUI ------------------
//--------------------------------------------

//--------------------------------------------
//---------Object point ----------------------
//--------------------------------------------

function point(latitude, longitude, group, id) {
  this.latitude = latitude;
  this.longitude = longitude;
  this.group = group;
  this.id = id;
  this.AddToMap = AddToMap;
}

function AddToMap() {
  var point = new GPoint(this.longitude, this.latitude);
  var marker = createInfoMarker(point, this.group, this.id);  
  gmap.addOverlay(marker); 
}

function SwapMyPoints(){
	myPoints = !myPoints;
	if (myPoints) {
		document.getElementById("img_my_points").src = "img/my_points_on.png";
	} else {
		document.getElementById("img_my_points").src = "img/my_points_off.png";
	}
	GetPointsInViewMap();
}

function NewUserMarker () {  	
  var licon = new GIcon();
  licon.image = "img/new_mark.png";
  licon.shadow = "img/markshadow.png";
  licon.iconSize = new GSize(30, 30);
  licon.shadowSize = new GSize(52, 28);
  licon.iconAnchor = new GPoint(15, 30);
  licon.infoWindowAnchor = new GPoint(15, 0);
  var options = { 
    draggable: true,
    bounceGravity: 0.8,
    dragCrossMove: true,
	icon: licon,
	autoPan: true
  };

  if ( gNewUserMarker ) {
    alert('Existen un punto pendiente de guardar. Guardelo antes de crear otro');
  } else {
    /* Desactivamos el posible punto que puede estar seleccionado */
    if ( gmarkerSelected != null) {
      gmarkerSelected.setImage("img/mark" + ggroupSelected + "_off.png");
      gmarkerSelected.disableDragging();      
      gmarkerSelected = null;
      GetPointsInViewMap(); 
    }
    gIdSelected = -1;

    var UserMarker = new GMarker(gmap.getCenter(), options);
    gmap.addOverlay(UserMarker);
    gNewUserMarker = UserMarker;

	GEvent.addListener(UserMarker, 
	                   "mouseup",  
		               function () {fillDataNewMarker(UserMarker) } );
	
	gmap.openInfoWindowHtml(gmap.getCenter(),
							'<table><tr><td width="10"><img src="/img/information.png"></td><td align="left"><b>Informaci&oacute;n</b></td></tr><tr><td colspan="2">Arrastrame hasta el lugar exacto donde se encuentre el punto</td></tr><tr><td colspan="2">y rellena los datos de la localizaci&oacute;n en la parte derecha</td></tr><tr><td colspan="2">&nbsp;</td></tr></table>');							 
	showNewPoi();
	selectedCategoryInNewPOI(1);
	/* Rellenamos la posición de la marca en los campos del formulario */ 
	fillDataNewMarker(UserMarker);
  }  
}

function fillDataNewMarker (pmarker) {
	document.getElementById("form_latitud").value = pmarker.getLatLng().lat();
	document.getElementById("form_longitud").value = pmarker.getLatLng().lng();
	//document.getElementById("form_text_latitud").innerHTML = pmarker.getLatLng().lat();
	//document.getElementById("form_text_longitud").innerHTML = pmarker.getLatLng().lng();
	/* Dirección a partir de las coordenadas */
	var geocoder = null;
	geocoder = new GClientGeocoder();
	geocoder.getLocations(pmarker.getLatLng(), function(addresses) {
          if(addresses.Status.code != 200) {
		  	document.getElementById("form_text_address").innerHTML = "";
            document.getElementById("form_address").value = "";
          }
          else {
            laddress = addresses.Placemark[0];
			document.getElementById("form_text_address").innerHTML = laddress.address;
			document.getElementById("form_address").value = laddress.address;
          }
        });
}

function createInfoMarker(point, pgroup, pid) {
  var icon = new GIcon();
  if ( gIdSelected == pid ) {  /* esta seleccionado */
    icon.image = "img/mark" + pgroup + "_on.png";
  } else { /* no esta seleccionado */
    icon.image = "img/mark" + pgroup + "_off.png";
  }
  icon.shadow = "img/markshadow.png";
  icon.iconSize = new GSize(30, 30);
  icon.shadowSize = new GSize(52, 28);
  icon.iconAnchor = new GPoint(15, 30);
  icon.infoWindowAnchor = new GPoint(15, 0);

  var options = { 
    draggable: true,
    bounceGravity: 0.8,
    dragCrossMove: true,
	icon: icon,
	autoPan: true
  };
  
  //var marker = new GMarker(point, icon);
  var marker = new GMarker(point, options);
  marker.disableDragging();
  if ( gIdSelected == pid ) {  /* esta seleccionado */
    gmarkerSelected = marker;
    //aShowMarkerInfo(marker, pid, pgroup);
  }
  GEvent.addListener(marker, 
                    "click",  
                     function () {ShowMarkerInfo(marker, pid, pgroup) } );
                  
  return marker;
} 

function ShowMarkerInfo(pmarker, pid, pgroup){
  if ( gNewUserMarker )  {
    alert('Existen un nuevo punto en edición. Guárdelo o cancélelo antes de ver la información de otro');
  } else {
    /* Cambiamos el icono de la marca que esta editando para que se sepa cual es*/  
    if ( gmarkerSelected != null) {
      gmarkerSelected.setImage("img/mark" + ggroupSelected + "_off.png");
    }
    gmarkerSelected = pmarker;
    ggroupSelected = pgroup;
    pmarker.setImage("img/mark" + pgroup + "_on.png");  
    gIdSelected = pid;
  
    showData();    
    loadXMLDataLocation('web_info_location.php?id=' + pid, pmarker);  
  }
}

//--------------------------------------------
//---------End Object point ------------------
//--------------------------------------------


/********************************
 *
 *  ENVIAR CORREO
 * 
 **********************************/

var requestDataEmailInappropiateContent;
var responseXMLEmailInappropiateContent;

function sendXMLEmailInappropiateContent() 
{
	if (gIdSelected > 0) {
		url = "inappropriate_content_send_email.php?";
		data = "form_inappropriate_location_id=" + escape(gIdSelected);
		data += "&form_inappropriate_name=" + escape(document.getElementById("form_inappropriate_name").value);
		data += "&form_inappropriate_email=" + escape(document.getElementById("form_inappropriate_email").value);
		data += "&form_inappropriate_text=" + escape(document.getElementById("form_inappropriate_text").value);
		
		if (window.XMLHttpRequest) {
			requestDataEmailInappropiateContent = new XMLHttpRequest();
			requestDataEmailInappropiateContent.onreadystatechange = processChangeRequestInappropiateContent;
			requestDataEmailInappropiateContent.overrideMimeType("text/xml; charset=ISO-8859-1");
			requestDataEmailInappropiateContent.open("POST", url, true);
			requestDataEmailInappropiateContent.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			requestDataEmailInappropiateContent.setRequestHeader("Content-length", data.length);
			requestDataEmailInappropiateContent.setRequestHeader("Connection", "close");
			requestDataEmailInappropiateContent.send(data);
		}
		else 
			if (window.ActiveXObject) {
				requestDataEmailInappropiateContent = new ActiveXObject("Microsoft.XMLHTTP");
				if (requestDataEmailInappropiateContent) {
					requestDataEmailInappropiateContent.onreadystatechange = processChangeRequestInappropiateContent;
					requestDataEmailInappropiateContent.open("POST", url, true);
					requestDataEmailInappropiateContent.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					requestDataEmailInappropiateContent.setRequestHeader("Content-length", data.length);
					requestDataEmailInappropiateContent.setRequestHeader("Connection", "close");
					requestDataEmailInappropiateContent.send(data);
				}
			}
	}
}

function processChangeRequestInappropiateContent()
{
	// Sólo se procesa si la solicitud esta completada
	if (requestDataEmailInappropiateContent.readyState == 4) {
		// Sólo si se ha procesado correctamente
		if (requestDataEmailInappropiateContent.status == 200) {
			// Obtenemos el documento XML que devuelve script php
			responseXMLEmailInappropiateContent = requestDataEmailInappropiateContent.responseXML.documentElement;
			
			if (responseXMLEmailInappropiateContent) {
							
				var items = responseXMLEmailInappropiateContent.getElementsByTagName("reponse");
				var item = items[0];
			
				if (item.getAttribute("send")=="true") {
					MOOdalBox.close();
					alert("El correo se ha enviado satisfactoriamente");
				} else {
					MOOdalBox.close();
					alert("Se ha producido un problema al enviar el correo. Inténtelo más tarde o envíe un correo al administrador");
				}
			
			} else {
				alert("No existe 'response'");
			}

		} else {
			alert("There was a problem retrieving the XML data:\n" + responseList.statusText);
		}
	}
}

//--------------------------------------------
//--------- SAVE COMMENT ---------------------
//--------------------------------------------

function saveComment() {
	if (gIdSelected>0) {
		url = "web_save_comment.php?";
		data = "location_id=" + escape(gIdSelected);
		data += "&comment=" + escape(document.getElementById("form_comment_text").value);
	
		if (window.XMLHttpRequest) {
			requestData = new XMLHttpRequest();
			requestData.onreadystatechange = processSaveComment;
			requestData.overrideMimeType("text/xml; charset=ISO-8859-1");
			requestData.open("POST", url, true);
			requestData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			requestData.setRequestHeader("Content-length", data.length);
			requestData.setRequestHeader("Connection", "close");
			requestData.send(data);
		}
		else 
			if (window.ActiveXObject) {
				requestData = new ActiveXObject("Microsoft.XMLHTTP");
				if (requestData) {
					requestData.onreadystatechange = processSaveComment;
					requestData.open("POST", url, true);
					requestData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					requestData.setRequestHeader("Content-length", data.length);
					requestData.setRequestHeader("Connection", "close");
					requestData.send(data);
				}
			}
	}
	
}

function processSaveComment(){  
if (requestData.readyState == 4) {
  if (requestData.status == 200) {   
    responseXML = null;
    responseXML = requestData.responseXML.documentElement;
    if (responseXML) {
      var resp = responseXML.getElementsByTagName("response");
		if (resp[0].getAttribute("save")=="true") {
			MOOdalBox.close();
			loadXMLCommentsLocation("api_comments.php?id="+gIdSelected);
		} else {
			alert("Ha habido un problema al guardar el comentario. Intentelo más tarde. Si el problema persiste póngase en contacto con el administrador");
		}
    }
  } else {
    alert("There was a problem retrieving the XML data:\n" + responseXML.statusText);
  }
}
}


//--------------------------------------------
//--------- DELETE POI -------------------------
//--------------------------------------------

function deletePOI() {

  if (confirm("¿Esta seguro que quiere borrar este POI?")) {
  
  	url = "web_deletepoi.php?id=" + document.getElementById("location_id").value;
  	
  	if (window.XMLHttpRequest) {
  		requestData = new XMLHttpRequest();
  		requestData.onreadystatechange = processDeletePoi;
  		requestData.open("GET", url, true);
  		requestData.send(null);
  	}
  	else 
  		if (window.ActiveXObject) {
  			requestData = new ActiveXObject("Microsoft.XMLHTTP");
  			if (requestData) {
  				requestData.onreadystatechange = processDeletePoi;
  				requestData.open("GET", url, true);
  				requestData.send();
  			}
  		}
  	
  }
}

function processDeletePoi(){  
  if (requestData.readyState == 4) {
    if (requestData.status == 200) {   
      responseXML = null;
      responseXML = requestData.responseXML.documentElement;
      if (responseXML) {
        var resp = responseXML.getElementsByTagName("response");
		if (resp[0].getAttribute("save")=="true") {
			alert("El POI se ha borrado correctamente");			
			GetPointsInViewMap();
			showMenu();
		} else {
			alert("Ha habido un problema al borrar el POI. Intentelo más tarde. Si el problema persiste póngase en contacto con el administrador");
		}
      }
    } else {
      alert("There was a problem retrieving the XML data:\n" + responseXML.statusText);
    }
  }
}

//--------------------------------------------
//--------- SAVE POI -------------------------
//--------------------------------------------

function savePOI() {
  var todoSave = true;
  
  if (document.getElementById("form_group").value=="1") {
	  if (confirm("Te dispones a introducir un Punto Limpio en el sistema. Por favor recuerda que estos son puntos que coordinan los ayuntamientos para la recogida de todo tipo de materiales.\n\nSi estás seguro sigue adelante, si tienes alguna duda, por favor lee la información del menú anterior. Gracias.") ) {
		  todoSave = true;
	  } else {
		  todoSave = false;
	  }
  }

  if (todoSave) {
	  url = "web_savepoi.php";
	  data = "form_description=" + escape(document.getElementById("form_description").value);
	  data += "&form_address=" + escape(document.getElementById("form_address").value);
	  data += "&form_address_comment=" + escape(document.getElementById("form_address_comment").value);
	  data += "&form_contact=" + escape(document.getElementById("form_contact").value);
	  data += "&form_latitud=" + escape(document.getElementById("form_latitud").value);
	  data += "&form_longitud=" + escape(document.getElementById("form_longitud").value);
	  data += "&form_group=" + escape(document.getElementById("form_group").value);
	  data += "&form_more_details=" + escape(document.getElementById("form_more_details").value);
	  data += "&form_location_id=" + escape(document.getElementById("form_location_id").value);
	  data += "&form_image=" + escape(document.getElementById("form_image").value);
	
	  if (window.XMLHttpRequest) {
	   requestData = new XMLHttpRequest();
		 requestData.onreadystatechange = processSavePoi;
		 requestData.overrideMimeType("text/xml; charset=ISO-8859-1");
		 requestData.open("POST", url, true);
		 requestData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		 requestData.setRequestHeader("Content-length", data.length);
		 requestData.setRequestHeader("Connection", "close");
		 requestData.send(data);
	  } else if (window.ActiveXObject) {
		  requestData = new ActiveXObject("Microsoft.XMLHTTP");
		  if (requestData) {
			requestData.onreadystatechange = processSavePoi;
			requestData.open("POST", url, true);
			requestData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			requestData.setRequestHeader("Content-length", data.length);
			requestData.setRequestHeader("Connection", "close");
			requestData.send(data);
		  }
	  }
  }
}

function processSavePoi(){  
  if (requestData.readyState == 4) {
    if (requestData.status == 200) {   
      responseXML = null;
      responseXML = requestData.responseXML.documentElement;
      if (responseXML) {
        var resp = responseXML.getElementsByTagName("response");
		if (resp[0].getAttribute("save")=="true") {
			alert("El POI se ha guardado correctamente");			
			if ( gNewUserMarker ) {								
				gmap.removeOverlay(gNewUserMarker);
				AddAllListenersForEditMarker(gNewUserMarker, gIdSelected, ggroupSelected);
				gNewUserMarker = null;
			} else {
				AddAllListenersForEditMarker(gmarkerSelected, gIdSelected, ggroupSelected);		
			}
			GetPointsInViewMap();
			showMenu();
		} else {
			alert("Ha habido un problema al grabar el POI. Intentelo más tarde. Si el problema persiste póngase en contacto con el administrador");
		}
      }
    } else {
      alert("There was a problem retrieving the XML data:\n" + responseXML.statusText);
    }
  }
}

//--------------------------------------------
//--------- Cargar Comentarios ---------------
//--------------------------------------------

function loadXMLCommentsLocation(url) {
	if (window.XMLHttpRequest) {
		requestDataComments = new XMLHttpRequest();
		requestDataComments.onreadystatechange = processChangeCommentsLocation;
		requestDataComments.open("GET", url, true);
		requestDataComments.send(null);
	} else if (window.ActiveXObject) {
		requestDataComments = new ActiveXObject("Microsoft.XMLHTTP");
		if (requestDataComments) {
			requestDataComments.onreadystatechange = processChangeCommentsLocation;
			requestDataComments.open("GET", url, true);
			requestDataComments.send();
		}
	}
}

function processChangeCommentsLocation(){  
	  if (requestDataComments.readyState == 4) {
		    if (requestDataComments.status == 200) {   
				responseXMLComments = null;
				responseXMLComments = requestDataComments.responseXML.documentElement;
								
				if (responseXMLComments) {
					
					var nodeComments = responseXMLComments.getElementsByTagName("comments");
					totalPagesComments = parseInt(nodeComments[0].getAttribute("total-pages"));
					page = parseInt(nodeComments[0].getAttribute("page"));
					
					document.getElementById("total_comments_comments").innerHTML = "<span></span>Comentarios (" + nodeComments[0].getAttribute("total") + ")";
					
					var out = "";
					var comments = responseXMLComments.getElementsByTagName("comment");
					for (i = 0; i < comments.length; i++) {
						out += "<div class=\"comment\">";
						out += "<div class=\"comment_say\">";
						out += comments[i].getAttribute("nick") + " dice:";
						out += "</div>";
						out += "<div class=\"comment_text\">";
						out += comments[i].firstChild.data;
						out += "</div>";
						out += "</div>";
					}
					if (totalPagesComments>1) {
						out += "<div class=\"pagination_comment\">";
						out += "<a href=\"#\" onclick=\"PreviousPageComments();\"><img src=\"img/btn_left.png\" align=\"absmiddle\" border=\"0\" hspace=\"7\" alt=\"Anterior\" /></a> ";
						out += "<span id=\"found\">" + (page+1) + "/" + totalPagesComments + "</span> ";
						out += "<a href=\"#\" onclick=\"NextPageComments();\"><img src=\"img/btn_right.png\" align=\"absmiddle\" border=\"0\" hspace=\"7\" alt=\"Anterior\" /></a>";
						out += "</div>";
					}
					
					if (out!="")
						document.getElementById("comments").innerHTML = out;
					else
						document.getElementById("comments").innerHTML = "<br/><br/>No existen comentarios por el momento.<br/><br/>Si deseas hacer alguna aclaración sobre este punto, puedes hacerlo ahora.";
				}
		    }
	  }
}

function PreviousPageComments() {
  if (gIdSelected>0) {
	  if (pageComments>0) {
		  pageComments--;
		  loadXMLCommentsLocation("api_comments.php?id="+gIdSelected+"&page="+pageComments);
	  }
  }
}

function NextPageComments() {
  if (gIdSelected>0) {
	  if (pageComments<totalPagesComments-1) {
		  pageComments++;
		  loadXMLCommentsLocation("api_comments.php?id="+gIdSelected+"&page="+pageComments);
	  }
  }
}

//--------------------------------------------
//--------- Cargar datos ---------------------
//--------------------------------------------

function loadXMLDataLocation(url, pmarker) {  
  gmarker = pmarker;
  if (window.XMLHttpRequest) {
   requestData = new XMLHttpRequest();
	 requestData.onreadystatechange = processChangeDataLocation;
	 requestData.open("GET", url, true);
	 requestData.send(null);
  } else if (window.ActiveXObject) {
	  requestData = new ActiveXObject("Microsoft.XMLHTTP");
	  if (requestData) {
	    requestData.onreadystatechange = processChangeDataLocation;
		  requestData.open("GET", url, true);
		  requestData.send();
	  }
  }
}

function processChangeDataLocation(){  
  if (requestData.readyState == 4) {
    if (requestData.status == 200) {   
      responseXML = null;
      responseXML = requestData.responseXML.documentElement;
      if (responseXML) {
        var loc = responseXML.getElementsByTagName("location");
        
        document.getElementById("total_comments_data").innerHTML = "<span></span>Comentarios (" + loc[0].getAttribute("total-comments") + ")";
        
		document.getElementById("info_loc_group").innerHTML = loc[0].getAttribute("group");
		var address = responseXML.getElementsByTagName("address");
		document.getElementById("info_loc_address").innerHTML = address[0].firstChild.data;
		var description = responseXML.getElementsByTagName("description");
		if (description[0].firstChild.data=="")
			document.getElementById("info_loc_desc").innerHTML = "Sin información";
		else
			document.getElementById("info_loc_desc").innerHTML = description[0].firstChild.data;
			
		document.getElementById("location_id").value = loc[0].getAttribute("id");
		
		document.getElementById("info_author").innerHTML = "Creado por " + loc[0].getAttribute("author") + "<br/>" + loc[0].getAttribute("date");
		
		if (loc[0].getAttribute("user-id") == userSessionId) {
			document.getElementById("btn_inappropriate").style.display = "none";
			document.getElementById("btn_edit").style.display = "block";
			document.getElementById("btn_delete").style.display = "block";
		} else {
			document.getElementById("btn_inappropriate").style.display = "block";
			document.getElementById("btn_edit").style.display = "none";
			document.getElementById("btn_delete").style.display = "none";
		}
		
		var image = responseXML.getElementsByTagName("image");
		if (image.length>0) {
			photoOnClick = "photos/" + image[0].firstChild.data;
			widthPhotoOnClick = parseInt(image[0].getAttribute("width"));
			heightPhotoOnClick = parseInt(image[0].getAttribute("height"));
			w = 0;
			h = 0;
			if (widthPhotoOnClick>heightPhotoOnClick) {
				w = 200;
				h = (200*heightPhotoOnClick)/widthPhotoOnClick;
			} else {
				h = 200;
				w = (200*widthPhotoOnClick)/heightPhotoOnClick;
			}
			
			document.getElementById("info_image").style.display = "block";
			document.getElementById("info_image_src").src = photoOnClick;
			document.getElementById("info_image_src").width = w;
			document.getElementById("info_image_src").height = h;
		} else {
			document.getElementById("info_image").style.display = "none";
			photoOnClick = "";
		}
		
      }
    } else {
      alert("There was a problem retrieving the XML data:\n" + responseXML.statusText);
    }
  }
}

//--------------------------------------------
//--------- END Cargar datos -----------------
//--------------------------------------------


function getAddress(platitude, plongitude) {
  lpoint = new GLatLng(platitude, plongitude);
  if (lpoint != null) {
    var geocoder = new GClientGeocoder();
    address = lpoint;
    geocoder.getLocations(lpoint, showAddress);
  }
} 

function showAddress(presponse) {
  if ( presponse.Status.code == 200 ) {  
    var lplace = presponse.Placemark[0];
    alert(lplace.address);  
	}
}

function CreateMap(pcontainer) {
  if (GBrowserIsCompatible()) {   
    //map = new GMap2(document.getElementById(pcontainer)); //Only on FireFox and Chrome
    var map = new google.maps.Map2(document.getElementById(pcontainer));
    gmap = map;
    lat = 40.407;
    long = -3.68;
    zoom = 6;
    gmap.setCenter(new GLatLng(lat,long), zoom);
    gmap.addControl(new GLargeMapControl3D());
    gmap.addControl(new GMapTypeControl());
    gmap.addControl(new GOverviewMapControl());
    gmap.enableScrollWheelZoom();	
    gmap.addControl(new GScaleControl());
    //gmap.addControl(new GMenuMapTypeControl());
    //gmap.addControl(new google.maps.LocalSearch(),new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0,-30)));

    //-----------------------------------------------------------------//
    //--------------------------- Events Map---------------------------//
    //-----------------------------------------------------------------//
	GEvent.addListener(gmap, "moveend", GetPointsInViewMap);
  }
}

function GetPointsInViewMap() {
  if (!gmap) {
    CreateMap('map');
  }
  
  var lBound = gmap.getBounds(); 
	lcat = "(" + gCategories + ")";
	lparameters = '?itemsbypage=' + nLocationsByPage + '&latitude1=' + lBound.getNorthEast().lat() + '&latitude2=' + lBound.getSouthWest().lat() + 
              '&longitude1=' + lBound.getNorthEast().lng() + '&longitude2=' + lBound.getSouthWest().lng() + '&categories=' + lcat;
	if (gDateSelected!=null) lparameters += '&date=' + gDateSelected;
	if (placeId>0) lparameters += '&idplace=' + placeId;
	if (userId > 0) {
		lparameters += '&user_id=' + userId;
	}
	else {
		if (userSessionId > 0 && myPoints) 
			lparameters += '&user_id=' + userSessionId;
	}
	loadXMLData('api_locations.php' + lparameters, 'map');
}

function FindOnePointInMap(pid) {  
  lparameters = '?id=' + pid;  
  loadXMLData_FindOnePointInMap('api_locations.php' + lparameters, 'map');
}

function loadXMLData(url, pmap_object) {
  if (!gmap) {
    CreateMap(pmap_object);
  }
  if (window.XMLHttpRequest) {
    requestData = new XMLHttpRequest();
	requestData.onreadystatechange = processChangeData;
	requestData.open("GET", url, true);
	requestData.send(null);
  } else if (window.ActiveXObject) {
    requestData = new ActiveXObject("Microsoft.XMLHTTP");
	if (requestData) {
	  requestData.onreadystatechange = processChangeData;
	  requestData.open("GET", url, true);
	  requestData.send();
	}
  }
}

function loadXMLData_FindOnePointInMap(url, pmap_object) {
  if (!gmap) {
    CreateMap(pmap_object);
  }
  if (window.XMLHttpRequest) {
    requestData = new XMLHttpRequest();
	requestData.onreadystatechange = processChangeData_FindOnePointInMap;
	requestData.open("GET", url, true);
	requestData.send(null);
  } else if (window.ActiveXObject) {
    requestData = new ActiveXObject("Microsoft.XMLHTTP");
	if (requestData) {
	  requestData.onreadystatechange = processChangeData_FindOnePointInMap;
	  requestData.open("GET", url, true);
	  requestData.send();
	}
  }
}

function processChangeData(){
  if (requestData.readyState == 4) {
    if (requestData.status == 200) {      
      responseXML = null;
      responseXML = requestData.responseXML.documentElement;
      if (responseXML) {
        CreatePoints(responseXML);												
      }
    } else {
      alert("There was a problem retrieving the XML data:\n" + responseXML.statusText);
    }
  }
}

function processChangeData_FindOnePointInMap(){
  if (requestData.readyState == 4) {
    if (requestData.status == 200) {      
      responseXML = null;
      responseXML = requestData.responseXML.documentElement;
      if (responseXML) {  
	var location = responseXML.getElementsByTagName("location");
	if ( location.length == 1 ) { //Existe el punto pasado por parametro
		gmap.setCenter(new GLatLng(location[0].getAttribute("latitude"), location[0].getAttribute("longitude")), 13);  
		gIdSelected = location[0].getAttribute("id");          
		gmarkerSelected = new point(location[0].getAttribute("latitude"), location[0].getAttribute("longitude"), location[0].getAttribute("group"), gIdSelected);	  
	}
	GetPointsInViewMap();
      }
    } else {
      alert("There was a problem retrieving the XML data:\n" + responseXML.statusText);
    }
  }
}

function CreatePoints(presponseXML) {
  var location = presponseXML.getElementsByTagName("locations");
  page = parseInt(location[0].getAttribute("page")); 
  totalRegister = parseInt(location[0].getAttribute("total")); 
  
  var found = document.getElementById("found");
  found.innerHTML = totalRegister + " encontrados";
  
  var page_of = document.getElementById("page_of");
  
  if (totalRegister%nLocationsByPage==0) {
  	totalPages = parseInt(totalRegister/nLocationsByPage);
  } else {
  	totalPages = parseInt(totalRegister/nLocationsByPage)+1;
  }
  var npage = page+1;
  page_of.innerHTML = "Página " + npage + " de " + totalPages;
	
  var locations = presponseXML.getElementsByTagName("location");
  gmap.clearOverlays (); //Remove all points
  var lfindselected = false;
  for (i = 0; i < locations.length; i++) {	  
    llatitude = locations[i].getAttribute("latitude"); 
    llongitude = locations[i].getAttribute("longitude");
    lgroup =  locations[i].getAttribute("group");
    lid = locations[i].getAttribute("id");
	if ( lid == gIdSelected) {
	    lfindselected = true;
	}
    ListOfPoints[i] = new point(llatitude, llongitude, lgroup, lid);
    ListOfPoints[i].AddToMap();
    if ( lid == gIdSelected) {
      ShowMarkerInfo(gmarkerSelected, lid, lgroup); //Simulamos el click sobre la marca para que salga la información.
    }
  }
  /* Si la marca es nula y hay seleccionado un id quiere decir que el usuario
     selecciono una marca, ha movido el mapa y no ha devuleto entre los puntos 
	 el que el selecciono, con lo que nosotros la creamos  */
  if ( (gmarkerSelected != null) && ( gIdSelected != -1 ) && (lfindselected == false) ) {
    var icon = new GIcon();
    icon.image = "img/mark" + ggroupSelected + "_on.png";
    icon.shadow = "img/markshadow.png";
    icon.iconSize = new GSize(30, 30);
    icon.shadowSize = new GSize(52, 28);
    icon.iconAnchor = new GPoint(15, 30);
    icon.infoWindowAnchor = new GPoint(15, 0);
    var options = { 
    draggable: true,
    bounceGravity: 0.8,
    dragCrossMove: true,
	icon: icon,
	autoPan: true
    };  
    var marker = new GMarker(gmarkerSelected.getLatLng(), options);
    marker.disableDragging();
    GEvent.addListener(marker, 
                      "click",  
                       function () {ShowMarkerInfo(marker, 11, ggroupSelected) } );
    gmap.addOverlay(marker); 
    gmarkerSelected = marker;
  
  }
  /* Nueva marca*/
  if ( gNewUserMarker != null) {
    gmap.addOverlay(gNewUserMarker);
  }
}

function SearchCheckEnter(e){
	var characterCode;

	if(e && e.which){
		e = e;
		characterCode = e.which; 
	} else{
		e = event;
		characterCode = e.keyCode;
	}
	if(characterCode == 13){
		SearchInMap(document.getElementById('txtSearchMap').value);
		return false;
	} else {
		return true;
	}
}


function SearchInMap(paddress) {
  var geocoder = new GClientGeocoder();
  geocoder.getLocations('* ' + paddress + ' *', ShowResults);
}

function ShowResults(presponse) {
  ldiv = document.getElementById("results_search");
  ldiv.style.visibility = "visible";
  
  outHTML = "<b>Resultados de la búsqueda</b><br/><br/>";
 
  if ( presponse.Status.code == 200 ) {  
    if ( presponse.Placemark.length > 1 ) {  
      for (i=0; i < presponse.Placemark.length; i++) {
        var lplace = presponse.Placemark[i];
  	    lLink = '<a href="javascript:SetPositionMap(' + lplace.Point.coordinates[1] + ',' + lplace.Point.coordinates[0] + ');">' + lplace.address + '</a>';
   	    outHTML += lLink + "<br/>";
      }  
    } else if ( presponse.Placemark.length == 1 ) {
      var lplace = presponse.Placemark[0];
      SetPositionMap(lplace.Point.coordinates[1], lplace.Point.coordinates[0]);
	  lLink = '<a href="javascript:SetPositionMap(' + lplace.Point.coordinates[1] + ',' + lplace.Point.coordinates[0] + ');">' + lplace.address + '</a>';
	  outHTML += lLink + "<br/>";
	}
  } else if (presponse.Status.code == 602) { // No results
	outHTML = "No se han encontrado resultados<br/>";
  }
  outHTML += "<br/>" + "<a href=\"javascript:HideResults();\">cerrar</a>";
  ldiv.innerHTML = outHTML;

  //--------------STRUCT RESPONSE XML ---------------------
/*<kml>
  <Response>
     <name>821 Mohawk St, Columbus, OH</name>
     <Status>
        <code>200</code>
        <request>geocode</request>
     </Status>
     <Placemark>
        <address>821 Mohawk St, Columbus, OH 43206, USA</address>
        <AddressDetails>
           <Country>
              <CountryNameCode>US</CountryNameCode>
              <AdministrativeArea>
                 <AdministrativeAreaName>OH</AdministrativeAreaName>
                 <SubAdministrativeArea>
                    <SubAdministrativeAreaName>Franklin</SubAdministrativeAreaName>
                    <Locality>
                       <LocalityName>Columbus</LocalityName>
                       <Thoroughfare>
                          <ThoroughfareName>821 Mohawk St</ThoroughfareName>
                       </Thoroughfare>
                       <PostalCode>
                          <PostalCodeNumber>43206</PostalCodeNumber>
                       </PostalCode>
                    </Locality>
                 </SubAdministrativeArea>
              </AdministrativeArea>
           </Country>
        </AddressDetails>
        <Point>
           <coordinates>-82.992942,39.945728,0</coordinates>
        </Point>
     </Placemark>
  </Response>
 </kml>
 */
 //--------------END STRUCT RESPONSE XML ---------------------
}

function HideResults(){
  ldiv = document.getElementById("results_search");
  ldiv.style.visibility = "hidden";
}

function SetPositionMap(platitude, plongitude) {
  lpoint = new GLatLng(platitude, plongitude);
  gmap.setCenter(lpoint, 10);
}
/*
function loadXMLDataTabs(url, pmarker) {  
  gmarker = pmarker;
  if (window.XMLHttpRequest) {
   requestData = new XMLHttpRequest();
	 requestData.onreadystatechange = processChangeDataTabs;
	 requestData.open("GET", url, true);
	 requestData.send(null);
  } else if (window.ActiveXObject) {
	  requestData = new ActiveXObject("Microsoft.XMLHTTP");
	  if (requestData) {
	    requestData.onreadystatechange = processChangeDataTabs;
		  requestData.open("GET", url, true);
		  requestData.send();
	  }
  }
}

function processChangeDataTabs(){  
  if (requestData.readyState == 4) {
    if (requestData.status == 200) {      
      responseXML = null;
      responseXML = requestData.responseXML.documentElement;
      if (responseXML) {
        LoadHTMLTabs(responseXML);
      }
    } else {
      alert("There was a problem retrieving the XML data:\n" + responseXML.statusText);
    }
  }
}

function LoadHTMLTabs(presponseXML) {  
  var tabs = presponseXML.getElementsByTagName("tab");
  //-----------TAB 1 ---------------  
  lTitleTab1 = tabs[0].getAttribute("name");
  lHTMLTab1 = tabs[0].firstChild.data;
  //-----------TAB 2 ---------------
  lTitleTab2 = tabs[1].getAttribute("name");
  lHTMLTab2 = tabs[1].firstChild.data;
  //-----------TAB 3 ---------------
  lTitleTab3 = tabs[2].getAttribute("name");
  lHTMLTab3 = tabs[2].firstChild.data;
  gmarker.openInfoWindowTabsHtml([new GInfoWindowTab(lTitleTab1, lHTMLTab1), 
	                              new GInfoWindowTab(lTitleTab2, lHTMLTab2),
                                  new GInfoWindowTab(lTitleTab3, lHTMLTab3)]);
}
*/
function PreviousPage() {
  lcat = "(" + gCategories + ")";
  if (page>0) {
	var lBound = gmap.getBounds();  
	lparameters = '?itemsbypage=' + nLocationsByPage + '&latitude1=' + lBound.getNorthEast().lat() + '&latitude2=' + lBound.getSouthWest().lat() + 
	           '&longitude1=' + lBound.getNorthEast().lng() + '&longitude2=' + lBound.getSouthWest().lng()
			   + '&page=' + (page-1) + '&categories=' + lcat;
	if (myPoints) lparameters += '&user_id=' + userSessionId;
	loadXMLData('api_locations.php' + lparameters, 'map');
  }
}

function NextPage() {
  lcat = "(" + gCategories + ")";
  if (page < totalPages - 1) {
	var lBound = gmap.getBounds();  
	lparameters = '?itemsbypage=' + nLocationsByPage + '&latitude1=' + lBound.getNorthEast().lat() + '&latitude2=' + lBound.getSouthWest().lat() + 
	           '&longitude1=' + lBound.getNorthEast().lng() + '&longitude2=' + lBound.getSouthWest().lng()
			   + '&page=' + (page+1) + '&categories=' + lcat;
	if (userId > 0) {
		lparameters += '&user_id=' + userId;
	}
	else {
		if (userSessionId > 0 && myPoints) 
			lparameters += '&user_id=' + userSessionId;
	}
	loadXMLData('api_locations.php' + lparameters, 'map');
  }
}

//]]>
