var geocoder;
var map="";
var Icons=new Array();
var markers= new Array();
var top_map=-1;
var bottom_map=-1;
var left_map=-1;
var right_map=-1;
var boundSW;
var boundNE;

function inicializa_xhr() {
  if (window.XMLHttpRequest) {
    return new XMLHttpRequest(); 
  } else if (window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP"); 
  } 
}

function cargaMunicipios() {
  document.getElementById("municipioslayer").style.display="none";
  document.getElementById("cargando").style.display="";
  var lista = document.getElementById("Provincia");
  var provinciaV = lista.options[lista.selectedIndex].value;
  provincia = provinciaV.split("_");
  if(!isNaN(provincia[0])) {
    peticion = inicializa_xhr();
    if (peticion) {
      peticion.onreadystatechange = muestraMunicipios;
      peticion.open("POST", "/cargaMunicipiosRun.php", true);
      peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      peticion.send("provincia=" + provincia[0]);
    }
  }
}

function muestraMunicipios() {
	  if (peticion.readyState == 4) {
	    if (peticion.status == 200) {
	      var lista = document.getElementById("Municipio");
	      var municipios = eval('(' + peticion.responseText + ')');
	      lista.options.length = 0;
	      var i=0;
	      for(var codigo in municipios) {
	        lista.options[i] = new Option(municipios[codigo], codigo+"_"+municipios[codigo]);
	        i++;
	      }
	      document.getElementById("cargando").style.display="none";
		  document.getElementById("municipioslayer").style.display="";
	    }
	  }
}

function cargaMunicipiosList() {
  var lista = document.getElementById("Provincia");
  var provinciaV = lista.options[lista.selectedIndex].value;
  provincia = provinciaV.substring(1);
  if(!isNaN(provincia)) {
    peticion = inicializa_xhr();
    if (peticion) {
      peticion.onreadystatechange = muestraMunicipiosList;
      peticion.open("POST", "/cargaMunicipiosRun.php", true);
      peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      peticion.send("provincia=" + provincia);
    }
  }
}

function muestraMunicipiosList() {
	  if (peticion.readyState == 4) {
	    if (peticion.status == 200) {
	      var lista = document.getElementById("Poblacion");
	      var municipios = eval('(' + peticion.responseText + ')');
	      lista.options.length = 0;
	      var i=0;
	      lista.options[i] = new Option("Todos", "-1");
	      i++;
	      for(var codigo in municipios) {
	        lista.options[i] = new Option(municipios[codigo], codigo);
	        i++;
	      }
	    }
	  }
}

function cargaSectores() {
  var lista = document.getElementById("Grupo");
  var grupo = lista.options[lista.selectedIndex].value;
  if(!isNaN(grupo)) {
    peticion = inicializa_xhr();
    if (peticion) {
      peticion.onreadystatechange = muestraSectores;
      peticion.open("POST", "/cargaSectoresRun.php", true);
      peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      peticion.send("grupo=" + grupo);
    }
  }
}

function muestraSectores() {
	  if (peticion.readyState == 4) {
	    if (peticion.status == 200) {
	      var lista = document.getElementById("Sector");
	      var sectores = eval('(' + peticion.responseText + ')');
	      lista.options.length = 0;
	      var i=0;
	      lista.options[i] = new Option("Todos", "-1");
	      i++;
	      for(var codigo in sectores) {
	        lista.options[i] = new Option(sectores[codigo], codigo);
	        i++;
	      }
	    }
	  }
}

// Inicializar tiny
function InicializarTiny(){
	tinyMCE.init({
		mode : "exact",
		elements : "ComentarioGeneral , Description , DireccionContacto, Descripcion, Texto",
		theme : "advanced", 
		plugins : "safari,paste",
		relative_urls : false,
		entity_encoding : "raw",
		theme_advanced_buttons1 : "code,link,unlink,separator,bold,italic,underline,separator,bullist,numlist", 
		theme_advanced_buttons2 : "", 
		theme_advanced_buttons3 : "", 
		theme_advanced_toolbar_location : "top", 
		theme_advanced_toolbar_align : "left",
		theme_advanced_default_font : "[arial|16]"
	});	
}

function validarNewEmpresa(frm) {
	var arroba_found=false;var punto_found=false;var i=0;
	while((i < frm.Email.value.length)&&(!arroba_found)){if(frm.Email.value.charAt(i)=="@"){arroba_found=true;}else{i++;}}
	if((i==0)||(!arroba_found)){alert("El formato de tu e-mail es incorrecto, comprueba que contenga los caracteres @ y .");frm.Email.focus();return false;}
	while((i < frm.Email.value.length)&&(!punto_found)){if(frm.Email.value.charAt(i)=="."){punto_found=true;}else{i++;}}		
	if((i>frm.Email.value.length-3)||(!arroba_found)){alert("El dominio de tu e-mail es incorrecto. Tiene que aparecer un . seguido de al menos dos caracteres.");frm.Email.focus();return false;}										
	
	if(frm.Pass.value.length<1) { alert("Debes introducir una contraseña"); frm.Pass.focus(); return false; }
	if(frm.Pass2.value.length<1) { alert("Debe repetir la contraseña"); frm.Pass2.focus(); return false; }
	
	if(frm.NombreEmpresa.value.length<1) { alert("Debes introducir el nombre de la empresa"); frm.NombreEmpresa.focus(); return false; }
	if(frm.Provincia.value<0) { alert("Selecciona una provincia"); frm.Provincia.focus(); return false; }
	if(frm.Municipio.value<0) { alert("Selecciona una población"); frm.Municipio.focus(); return false; }
	if(frm.Direccion.value.length<3) { alert("Indica una dirección"); frm.Direccion.focus(); return false; }
	if(frm.CP.value.length<3) { alert("Indica el código postal"); frm.CP.focus(); return false; }
	tinyMCE.triggerSave();
	if(frm.Descripcion.value.length<200) { alert("La descripción de la empresa debe contener como mínimo 200 car√°cteres"); return false;}
	if(frm.Persona.value.length<1) { alert("Indica una persona de contacto"); frm.Persona.focus(); return false; }
	
	
	if(frm.Telefono.value.length<8) { alert("Introduce un télefono válido"); frm.Telefono.focus(); return false; }
	
	var sectores = frm.Sector;
	var i=0;
	var Sectorsel = false;
	for (i=0;i < sectores.length;i++){
       if (sectores[i].checked) {
           Sectorsel = true;
           break;
       }
    }
    
    if(Sectorsel==false) {alert("Debe seleccionar un sector para su empresa"); return false; }
	
	return true;
}

function validarModifEmpresa(frm){
	if(frm.NombreEmpresa.value.length<1) { alert("Debes introducir el nombre de la empresa"); frm.NombreEmpresa.focus(); return false; }
	tinyMCE.triggerSave();
	if(frm.Pass.value.length<1) { alert("Debes introducir una contraseña"); frm.Pass.focus(); return false; }
	if(frm.Pass2.value.length<1) { alert("Debe repetir la contraseña"); frm.Pass2.focus(); return false; }
	if(frm.Pass.value!=frm.Pass2.value) { alert("Debe repetir la contraseña correctamente"); frm.Pass2.focus(); return false; }
	if(frm.Descripcion.value.length<200) { alert("La descripción de la empresa debe contener como mínimo 200 carácteres"); return false;}
	if(frm.Persona.value.length<1) { alert("Indica una persona de contacto"); frm.Persona.focus(); return false; }
	
	var arroba_found=false;var punto_found=false;var i=0;
	while((i < frm.Email.value.length)&&(!arroba_found)){if(frm.Email.value.charAt(i)=="@"){arroba_found=true;}else{i++;}}
	if((i==0)||(!arroba_found)){alert("El formato de tu e-mail es incorrecto, comprueba que contenga los caracteres @ y .");frm.Email.focus();return false;}
	while((i < frm.Email.value.length)&&(!punto_found)){if(frm.Email.value.charAt(i)=="."){punto_found=true;}else{i++;}}		
	if((i>frm.Email.value.length-3)||(!arroba_found)){alert("El dominio de tu e-mail es incorrecto. Tiene que aparecer un . seguido de al menos dos caracteres.");frm.Email.focus();return false;}										
	
	if(frm.Telefono.value.length<8) { alert("Introduce un télefono válido"); frm.Telefono.focus(); return false; }
	
	return true;

}

function iniciarMapa(longitud, latitud, direccion, ciudad, cp, provincia, pais) {
	
	geocoder = new GClientGeocoder();
	
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		//map.addControl(new GLargeMapControl());
		
		
		if(longitud!='' && latitud!='') {
			var point = new GLatLng(latitud, longitud);
			 map.setCenter(point, 10);
			 marker = new GMarker(point);
			 GShow('',marker.getPoint().lat(),marker.getPoint().lng(),14);
			
		} else {
			var address = showAddress(direccion,ciudad, cp, provincia, pais);
			geocoder.getLatLng(
				address,
				function(point) {
				  if (!point) {
					 //alert(address + " no encontrado");
				  } else {
					 map.setCenter(point, 10);
					 marker = new GMarker(point);
							
					 GShow(address,marker.getPoint().lat(),marker.getPoint().lng(),16);
					 
				  }
				}
			 );
		}
	}
}

function GShow(direccion,latitud,longitud,zoom) {
	var point = new GLatLng(latitud, longitud); 
	map.setCenter(point, zoom);
	marker = new GMarker(point,{draggable: true});
	marker.enableDragging();	        
	
	map.addOverlay(marker);
	
	
}

function iniciarMapa2(longitud, latitud, direccion, ciudad, cp, provincia, pais) {
	
	geocoder = new GClientGeocoder();
	
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.addControl(new GLargeMapControl());
		
		
		if(longitud!='' && latitud!='') {
			var point = new GLatLng(latitud, longitud);
			 map.setCenter(point, 10);
			 marker = new GMarker(point);
			 GShow2('',marker.getPoint().lat(),marker.getPoint().lng(),16);
			
		} else {
			var address = showAddress(direccion,ciudad, cp, provincia, pais);
			geocoder.getLatLng(
				address,
				function(point) {
				  if (!point) {
					 //alert(address + " no encontrado");
				  } else {
					 map.setCenter(point, 10);
					 marker = new GMarker(point);
							
					 GShow2(address,marker.getPoint().lat(),marker.getPoint().lng(),16);
					 
				  }
				}
			 );
		}
	}
}

function GShow2(direccion,latitud,longitud,zoom) {
	var point = new GLatLng(latitud, longitud); 
	map.setCenter(point, zoom);
	marker = new GMarker(point,{draggable: true});
	marker.enableDragging();
	GEvent.addListener(marker, "dragend", function() {
			form = document.getElementById('frmAddEmpresa');
			form.Latitud.value=marker.getPoint().lat();
			form.Longitud.value=marker.getPoint().lng();
		}
	);	
	map.addOverlay(marker);
}        

function showAddress(direccion, poblacion, codigo_postal, provincia, pais) {
	direccionCompletatmp = "";
	if(direccion != ""){
		for (i = 0; i < direccion.length; i++) {
			 c = direccion.charAt(i);
			if (c >= '0' && c <= '9' || c == ',') {
				indiceNumero = i;
				break;
			}
		}
		direccion_limpia = direccion.substr(0,i);
		direccionCompletatmp = direccionCompletatmp.concat(direccion_limpia);
	}		

	if (poblacion != ""){
			direccionCompletatmp =direccionCompletatmp.concat(",");
			direccionCompletatmp =direccionCompletatmp.concat(poblacion);
	}	
	if (codigo_postal != ""){
			direccionCompletatmp =direccionCompletatmp.concat(",");                                        
			direccionCompletatmp =direccionCompletatmp.concat(codigo_postal);
	}
	if (provincia != ""){                                        
			direccionCompletatmp =direccionCompletatmp.concat(",");                                        
			direccionCompletatmp =direccionCompletatmp.concat(provincia);       
	}
	if (pais != ""){                                        
			direccionCompletatmp =direccionCompletatmp.concat(",");  
			direccionCompletatmp =direccionCompletatmp.concat(pais);                                      
				   
	}   		
	return direccionCompletatmp;
}

function showDiv(capa) {
	if(document.getElementById(capa).style.display=='none') {
		document.getElementById(capa).style.display='';
	} else {
		document.getElementById(capa).style.display='none';
	}

}

// GOOGLE MAPS

function cargaKLM(Prov,Grup,Sec,Pobl,NumPage,TemasPagina) {
	if (GBrowserIsCompatible()) {
		runMap();
		
		map = new GMap2(document.getElementById("map_canvas"));
        map.addControl(new GLargeMapControl());
        //map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng('40.416706','-3.70327'),5);
        downloadUrl("/emp-KLM.php?Provincia="+Prov+"&Grupo="+Grup+"&Sector="+Sec+"&Poblacion="+Pobl+"&NumPage="+NumPage+"&TemasPagina="+TemasPagina, function(data) { 
        var markers = data.documentElement.getElementsByTagName("marker"); 
        var LoadedMarkers=new Array();
        var z=0;
        for (var i=markers.length-1; i >= 0; i--) { 
        	longi = markers[i].getAttribute("longitud");
        	lati = markers[i].getAttribute("latitud");
	        var point = new GLatLng(parseFloat(lati),parseFloat(longi));   
	        var marker = createMarker(point,i+1);                     
	        LoadedMarkers[z]=marker;
	        
	        ylatitud=parseFloat(lati);
	        xlongitude=parseFloat(longi);
	                            
	        if (top_map==-1) {
	        	top_map=ylatitud;
	       		bottom_map=ylatitud;
	            left_map=xlongitude;
	            right_map=xlongitude;
	        }
	                             
	        if(top_map>ylatitud) {top_map=ylatitud;}
	        if(bottom_map < ylatitud) { bottom_map=ylatitud;}
	        if(left_map > xlongitude) { left_map=xlongitude;}
	        if(right_map < xlongitude) { right_map=xlongitude;}
	        z++;
        }
        
        boundSW=new GLatLng(bottom_map,left_map);
		boundNE=new GLatLng(top_map,right_map);
		
		bounds=new GLatLngBounds(boundSW,boundNE);
		ZoomLevel=map.getBoundsZoomLevel(bounds);
		map.setCenter(bounds.getCenter(),ZoomLevel);
		
        addMarkers(LoadedMarkers,0); 
         
        }); 
	}
}

function createMarker(point,id) {
	var markerOptions = {icon:Icons[id], zIndexProcess:importanceOrder};
    var marker = new GMarker(point,markerOptions);
	marker.importance = 1;
	markers[id]=marker;
	return marker;   
}

function importanceOrder (marker,b) {
    return marker.importance;
}

function runMap() {
	geocoder = new GClientGeocoder();
		
      baseIcon2 = new GIcon();
      baseIcon2.iconSize = new GSize(27,27);
      baseIcon2.iconAnchor = new GPoint(20, 20);
      baseIcon2.infoWindowAnchor = new GPoint(9, 2);
      baseIcon2.infoShadowAnchor = new GPoint(18, 25);    	
		
	for(i=1;i<11;i++) {
        Icons[i]=new GIcon(baseIcon2);
        Icons[i].image = "/iconos/"+(i)+".png";
    }
}

function addMarkers(markers,i) {    
   	for (i = 0; i < markers.length; i++) {
		map.addOverlay(markers[i]);
	}  
}

function changeBusc(tipo){

	if(tipo=="1") {
		document.busc.Grupo.value = "-1";
		document.busc.Sector.value = "-1";
		document.busc.Poblacion.value = "-1";
	} else if(tipo=="2") {
		document.busc.Sector.value = "-1";
		document.busc.Poblacion.value = "-1";
	} else if(tipo=="3") {
		document.busc.Poblacion.value = "-1";
	}
	
	document.busc.submit();

}

//--------------------------------------------------------
//--------------------------------------------------------
/**
* Returns an XMLHttp instance to use for asynchronous
* downloading. This method will never throw an exception, but will
* return NULL if the browser does not support XmlHttp for any reason.
* @return {XMLHttpRequest|Null}
*/
function createXmlHttpRequest() {
 try {
   if (typeof ActiveXObject != 'undefined') {
     return new ActiveXObject('Microsoft.XMLHTTP');
   } else if (window["XMLHttpRequest"]) {
     return new XMLHttpRequest();
   }
 } catch (e) {
   changeStatus(e);
 }
 return null;
};

/**
* This functions wraps XMLHttpRequest open/send function.
* It lets you specify a URL and will call the callback if
* it gets a status code of 200.
* @param {String} url The URL to retrieve
* @param {Function} callback The function to call once retrieved.
*/
function downloadUrl(url, callback) {
 var status = -1;
 var request = createXmlHttpRequest();
 if (!request) {
   return false;
 }

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     try {
       status = request.status;
     } catch (e) {
       // Usually indicates request timed out in FF.
     }
     if (status == 200) {
       callback(request.responseXML, request.status);
       request.onreadystatechange = function() {};
     }
   }
 }
 request.open('GET', url, true);
 try {
   request.send(null);
 } catch (e) {
   changeStatus(e);
 }
};

/**
 * Parses the given XML string and returns the parsed document in a
 * DOM data structure. This function will return an empty DOM node if
 * XML parsing is not supported in this browser.
 * @param {string} str XML string.
 * @return {Element|Document} DOM.
 */
function xmlParse(str) {
  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }

  if (typeof DOMParser != 'undefined') {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }

  return createElement('div', null);
}

/**
 * Appends a JavaScript file to the page.
 * @param {string} url
 */
function downloadScript(url) {
  var script = document.createElement('script');
  script.src = url;
  document.body.appendChild(script);
}


// show calendar
function show_cal(el) {

	if (cal_obj2) return;

var text_field = document.getElementById("Fecha");

	cal_obj2 = new RichCalendar();
	cal_obj2.start_week_day = 1;
	cal_obj2.language = 'es';
	
	cal_obj2.user_onchange_handler = cal2_on_change;
	cal_obj2.user_onclose_handler = cal2_on_close;
	cal_obj2.user_onautoclose_handler = cal2_on_autoclose;
	cal_obj2.parse_date(text_field.value, format);
	
	cal_obj2.show_at_element(text_field, "adj_right-bottom");
	cal_obj2.change_skin('alt');
	
	

}

// user defined onchange handler
function cal2_on_change(cal, object_code) {
	if (object_code == 'day') {
		document.getElementById("Fecha").value = cal.get_formatted_date(format);
		document.getElementById("FechaFormat").value = cal.get_formatted_date(format2);
		cal.hide();
		cal_obj2 = null;
	}
}

// user defined onclose handler
function cal2_on_close(cal) {
		cal.hide();
		cal_obj2 = null;
}

// user defined onclose handler (used in pop-up mode - when auto_close is true)
function cal2_on_autoclose(cal) {
	cal_obj2 = null;
}
