function validarMenu() {
	if (!document.getElementById("usuario").value) {
		alert("Debe indicar su Usuario");
		document.getElementById("usuario").focus();
		return false;
	}
	else if (!document.getElementById("password").value) {
		alert("Debe indicar su Clave de Acceso");
		document.getElementById("password").focus();
		return false;
	}
	return true;
}

function agregarFavoritos(){
	var url="http://www.grupoopcion.com" 
	var titulo="GrupoOpcion.com - El Grupo del sector lider en España -"
	if ((window.sidebar) && (window.sidebar.addPanel)){
		window.sidebar.addPanel(titulo, url,"");
	}
	else {
		window.external.AddFavorite(url, titulo) // IE;
	}
}

function nuevoAjax(){ 
	var xmlhttp=false;
	try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");}
	catch(e){
		try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
		catch(E){if (!xmlhttp && typeof XMLHttpRequest!='undefined') xmlhttp=new XMLHttpRequest();}
	}
	return xmlhttp; 
}

function cambiaProvincia(){
	ajax=nuevoAjax();
	ajax.open("POST", "cambia-provincia-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	document.getElementById("municipio").length = 1;
	document.getElementById("municipio").options[0].text="Cargando...";
	ajax.send("provincia=" + document.getElementById("prov").value + "&funcion=cambiaMunicipio()");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("municipio").parentNode.innerHTML=ajax.responseText;
			cambiaMunicipio();
		}
	}
}

function cambiaProvinciaFormulario(){
	ajax=nuevoAjax();
	ajax.open("POST", "../cambia-provincia-todo-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	document.getElementById("municipio").length = 1;
	document.getElementById("municipio").options[0].text="Cargando...";
	document.getElementById("pedania").length = 1;
	document.getElementById("pedania").options[0].text="Cargando...";
	ajax.send("provincia=" + document.getElementById("provincia").value + "&indiferente=no&funcion=cambiaMunicipioFormulario()");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("municipio").parentNode.innerHTML=ajax.responseText;
			cambiaMunicipioFormulario();
		}
	}
}
function cambiaProvinciaAltaCliente(){
	ajax=nuevoAjax();
	ajax.open("POST", "cambia-provincia-todo-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	document.getElementById("municipio").length = 1;
	document.getElementById("municipio").options[0].text="Cargando...";
	document.getElementById("pedania").length = 1;
	document.getElementById("pedania").options[0].text="Cargando...";
	ajax.send("provincia=" + document.getElementById("provincia").value + "&indiferente=no&funcion=cambiaMunicipioAltaCliente()");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("municipio").parentNode.innerHTML=ajax.responseText;
			cambiaMunicipioAltaCliente();
		}
	}
}

function cambiaProvinciaEmpresas(){
	ajax=nuevoAjax();
	ajax.open("POST", "cambia-provincia-empresas-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	document.getElementById("municipio").length = 1;
	document.getElementById("municipio").options[0].text="Cargando...";
	ajax.send("provincia=" + document.getElementById("prov").value);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("municipio").parentNode.innerHTML=ajax.responseText;
		}
	}
}

function cambiaProvinciaDestacado(){
	ajax=nuevoAjax();
	ajax.open("POST", "../cambia-provincia-todo-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	document.getElementById("municipio").length = 1;
	document.getElementById("municipio").options[0].text="Cargando...";
	ajax.send("provincia=" + document.getElementById("provincia").value + "&funcion=cambiaMunicipioDestacado()");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("municipio").parentNode.innerHTML=ajax.responseText;
			cambiaMunicipioDestacado();
		}
	}
}

function cambiaMunicipio(){
	ajax=nuevoAjax();
	ajax.open("POST", "cambia-municipio-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	document.getElementById("pedania").length = 1;
	document.getElementById("pedania").options[0].text="Cargando...";
	ajax.send("provincia=" + document.getElementById("prov").value + "&municipio=" + document.getElementById("municipio").value + "&indiferente=si");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("pedania").parentNode.innerHTML=ajax.responseText;
		}
	}
}

function cambiaMunicipioFormulario(){
	ajax=nuevoAjax();
	ajax.open("POST", "../cambia-municipio-todo-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	document.getElementById("pedania").length = 1;
	document.getElementById("pedania").options[0].text="Cargando...";
	ajax.send("provincia=" + document.getElementById("provincia").value + "&municipio=" + document.getElementById("municipio").value + "&indiferente=no");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("pedania").parentNode.innerHTML=ajax.responseText;
		}
	}
}
function cambiaMunicipioAltaCliente(){
	ajax=nuevoAjax();
	ajax.open("POST", "cambia-municipio-todo-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	document.getElementById("pedania").length = 1;
	document.getElementById("pedania").options[0].text="Cargando...";
	ajax.send("provincia=" + document.getElementById("provincia").value + "&municipio=" + document.getElementById("municipio").value + "&indiferente=no");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("pedania").parentNode.innerHTML=ajax.responseText;
		}
	}
}

function cambiaMunicipioDestacado(){
	ajax=nuevoAjax();
	ajax.open("POST", "../cambia-municipio-todo-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	document.getElementById("pedania").length = 1;
	document.getElementById("pedania").options[0].text="Cargando...";
	ajax.send("provincia=" + document.getElementById("provincia").value + "&municipio=" + document.getElementById("municipio").value + "&indiferente=si");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("pedania").parentNode.innerHTML=ajax.responseText;
		}
	}
}

function calculaHipoteca(){
	ajax=nuevoAjax();
	ajax.open("POST", "calcula-hipoteca-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("cantidad=" + document.getElementById("cantidad").value + "&entrada=" + document.getElementById("entrada").value + "&interes=" + document.getElementById("interes").value + "&anos=" + document.getElementById("anos").value);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("resultadoHipoteca").innerHTML=ajax.responseText;
		}
	}
}

function enviarContacto() {
	if (!document.getElementById("nombre").value) {
		document.getElementById("nombre").focus();
		alert("Debe indicar su Nombre");
	}
	else if (!document.getElementById("telefono").value) {
		document.getElementById("telefono").focus();
		alert("Debe indicar un Teléfono para el contacto");
	}
	else if (!validaEmail(document.getElementById("email").value)) {
		document.getElementById("email").focus();
		alert("Debe indicar una cuenta de Correo válida para el contacto");
	}
	else { 
		ajax=nuevoAjax();
		ajax.open("POST", "enviar-contacto-ajax.php", true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send("nombre=" + document.getElementById("nombre").value + "&direccion=" + document.getElementById("direccion").value + "&email=" + document.getElementById("email").value + "&telefono=" + document.getElementById("telefono").value + "&mensaje=" + document.getElementById("mensaje").value);
		ajax.onreadystatechange=function() {
			if (ajax.readyState==4) {
				document.getElementById("nombre").value = "";
				document.getElementById("direccion").value = "";
				document.getElementById("telefono").value = "";
				document.getElementById("email").value = "";
				document.getElementById("mensaje").value = "";
				alert(ajax.responseText);
			}
		}
	}
}

function enviarMasInfo() {
	if (!document.getElementById("nombre").value) {
		document.getElementById("nombre").focus();
		alert("Debe indicar su NOMBRE de Contacto");
		return false;
	}
	else if (!validaEmail(document.getElementById("email").value)) {
		alert("Debe indicar una cuenta de Correo válida");
		document.getElementById("email").focus();
		return false;
	}  
	else if (document.getElementById("telefono").value.length < 9) {
		alert("El número de TELÉFONO no es válido");
		document.getElementById("telefono").focus();
		return false;
	} 
	else { 
		ajax=nuevoAjax();
		ajax.open("POST", "enviar-mensaje-mas-info-ajax.php", true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send("nombre=" + document.getElementById("nombre").value + "&referencia=" + document.getElementById("referencia").value + "&email=" + document.getElementById("email").value + "&telefono=" + document.getElementById("telefono").value + "&mensaje=" + document.getElementById("mensaje").value + "&id=" + document.getElementById("id").value + "&emailEmpresa=" + document.getElementById("emailEmpresa").value);
		ajax.onreadystatechange=function() {
			if (ajax.readyState==4) {
				document.getElementById("nombre").value = "";
				document.getElementById("telefono").value = "";
				document.getElementById("email").value = "";
				document.getElementById("mensaje").value = "";
				alert(ajax.responseText);
			}
		}
	}
}

function validaEmail(email){
	var re  = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	if (!re.test(email)) {
		return false;
	}
	return true;
}

function verInmueble(id){
	document.location='fichageneral1.php?ident='+id;
}

function borrarTexto(objeto){
	objeto.value = "";
}

function comprobar(ruta){
	if (ruta=="#") {
		alert("Se ha superado el límite");
	}
}

function nuevoCampoImagen(){
	var formulario = document.getElementById("formulario");
	var vacio=false;
	var n=1;
	for (i=0; i<formulario.length; i++){
		var img = document.getElementById("file"+i);
		if (img!=null){	
			n++;
			if (img.value=="") vacio=true; 
		}
	}

	if (vacio){
		alert("Rellene todos los campos de imagen antes de insertar uno nuevo");
	}
	else {
		var contenedor = document.getElementById("imagenes");
		var objeto = document.createElement("input");
		objeto.setAttribute("type", "file");
		objeto.setAttribute("name", "file"+n);
		objeto.setAttribute("id", "file"+n);
		objeto.setAttribute("class", "campos");
		objeto.setAttribute("size", "32");
		contenedor.appendChild(objeto); 
		document.getElementById("numFotos").value = n;
	}
}

function validarEntero(valor){
	valor = parseInt(valor)
	if (isNaN(valor)) {
		return "";
	}else{
		return valor;
	}
} 

function isNumeric (num, vacio) {
	reNumeric = /^\d+$/;
	if (reNumeric.test(num)) {
		return true;
	}
	else if (vacio && num==""){
		return true;
	}
	else return false;
}

function validarAltaInmueble() {
	if ((document.getElementById("habitaciones").value=="") && ((document.getElementById("propiedad").value=="Piso/Apartamento") || (document.getElementById("propiedad").value=="Ático") || (document.getElementById("propiedad").value=="Casa/Chalet Independiente") || (document.getElementById("propiedad").value=="Adosado/Pareado/Bungalow"))){
		alert("El número de Habitaciones no puede ser Indiferente");
		document.getElementById("habitaciones").focus();
		return false;
	} 
	else if ((document.getElementById("banios").value=="") && ((document.getElementById("propiedad").value=="Piso/Apartamento") || (document.getElementById("propiedad").value=="Ático") || (document.getElementById("propiedad").value=="Casa/Chalet Independiente") || (document.getElementById("propiedad").value=="Adosado/Pareado/Bungalow"))){
		alert("El número de Baños no puede ser Indiferente");
		document.getElementById("banios").focus();
		return false;
	} 
	else if(!isNumeric(document.getElementById("precio").value, true)){
		alert ("Debe rellenar el campo PRECIO con un valor numérico válido, sin puntos ni comas.");
		document.getElementById("precio").value.focus();
		return false;
	} 
	else if (document.getElementById("referencia").value=="") {
		alert("Debe rellenar el campo REFERENCIA");
		document.getElementById("referencia").focus();
		return false;
	} 
	else if (document.getElementById("descripcion").value=="") {
		alert("Debe rellenar el campo DESCRIPCION");
		document.getElementById("descripcion").focus();
		return false;
	} 
	else if(!isNumeric(document.getElementById("metros").value, true)){
		alert ("Debe rellenar el campo METROS con un valor numérico válido, sin puntos ni comas.");
		document.getElementById("metros").focus();
		return false;
	} 
	else {
		extensiones_permitidas = new Array(".gif", ".jpg", ".bmp");
		for (i=0; i<document.getElementById("formulario").length; i++){
			var img = document.getElementById("file"+i);
			if (img!=null){
				if (img.value!=""){
					extension = (img.value.substring(img.value.lastIndexOf("."))).toLowerCase();
					var permitida = false;
					for (var j = 0; j < extensiones_permitidas.length; j++) {
						if (extensiones_permitidas[j] == extension) {
							permitida = true;
							break;
						}
					}
					if (!permitida) {
						alert("Compruebe las extensiones de los archivos a subir. \nSólo se visualizaran archivos con extensiones: " + extensiones_permitidas.join());
						img.focus();
						return false;
					}
				}
			}
		}
		return true;
	}// Fin else
}// Fin function validar

function comprobarLongitud(campo) {
	if (campo.value.length > 40) campo.value = campo.value.substring(0, 40);
}

function eliminarInmueble(){
	if (window.confirm('¿Desea Realmente Eliminar el Inmueble?')){
		return true;
	}
	else {
		return false;
	}
}

function validarFormularioCliente() {
	if (document.getElementById("telefono").value.length < 9) {
		alert("El número de TELÉFONO no es válido");
		document.getElementById("telefono").focus();
		return false;
	} 
	else if (document.getElementById("clave").value != document.getElementById("clave2").value) {
		alert("Los campos PASSWORD deben ser Iguales");
		document.getElementById("clave2").focus();
		return false;
	} 
	else if (!document.getElementById("clave").value) {
		alert("Debe elegir un PASSWORD");
		document.getElementById("clave").focus();
		return false;
	} 
	else if (!document.getElementById("empresa").value) {
		alert("Debe rellenar el campo EMPRESA");
		document.getElementById("empresa").focus();
		return false;
	} 
	else if (!document.getElementById("direccion").value) {
		alert("Debe rellenar el campo DIRECCIÓN");
		document.getElementById("direccion").focus();
		return false;
	}
	return true;
}

function validarAltaCliente() {
	var q=document.getElementById("usuarioCliente").value;
	for (i=0; i<q.length; i++) {   
		if (q.charAt(i) == " ") {   
			alert("El Campo USUARIO no admite espacios en blanco");
			document.getElementById("usuarioCliente").focus();
			return false;
		}   
	}  
	if (document.getElementById("provincia").value=="Seleccione Provincia") {
		alert("Debe seleccionar una PROVINCIA y una LOCALIDAD");
		document.getElementById("provincia").focus();
		return false;
	}
	else if (document.getElementById("telefono").value.length < 9) {
		alert("El número de TELÉFONO no es válido");
		document.getElementById("telefono").focus();
		return false;
	} 
	else if (!document.getElementById("usuarioCliente").value) {
		alert("Debe rellenar el campo USUARIO");
		document.getElementById("usuarioCliente").focus();
		return false;
	} 
	else if (document.getElementById("clave").value != document.getElementById("clave2").value) {
		alert("Los campos PASSWORD deben ser Iguales");
		document.getElementById("clave2").focus();
		return false;
	} 
	else if (!document.getElementById("clave").value) {
		alert("Debe elegir un PASSWORD");
		document.getElementById("clave").focus();
		return false;
	} 
	else if (!validaEmail(document.getElementById("email").value)) {
		alert("Debe indicar una cuenta de Correo válida");
		document.getElementById("email").focus();
		return false;
	} 
	else if (!document.getElementById("empresa").value) {
		alert("Debe rellenar el campo EMPRESA");
		document.getElementById("empresa").focus();
		return false;
	} 
	else if (!document.getElementById("direccion").value) {
		alert("Debe rellenar el campo DIRECCIÓN");
		document.getElementById("direccion").focus();
		return false;
	}
	return true;
}

function guardarDestacado(boton){
	var texto = boton.name.split("-");
	ajax=nuevoAjax();
	ajax.open("POST", "guardar-destacado-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("id=" + texto[1] + "&inmueble=" + document.getElementById(texto[1]).value);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			alert(ajax.responseText);
		}
	}
}

function reservarDestacado(){
	ajax=nuevoAjax();
	ajax.open("POST", "reservar-destacado-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("provincia=" + document.getElementById("provincia").value + "&localidad=" + document.getElementById("municipio").value + "&pedania=" + document.getElementById("pedania").value + "&tipo=" + document.getElementById("tipo").value + "&oferta=" + document.getElementById("oferta").value + "&precio=" + document.getElementById("precio").value + "&habitaciones=" + document.getElementById("habitaciones").value + "&banios=" + document.getElementById("banios").value + "&obranueva=" + document.getElementById("obranueva").value + "&garaje=" + document.getElementById("garaje").value + "&trastero=" + document.getElementById("trastero").value + "&ascensor=" + document.getElementById("ascensor").value);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			alert(ajax.responseText);
		}
	}
}

function insertarNoticia(){
	ajax=nuevoAjax();
	ajax.open("POST", "insertar-noticia-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("titulo=" + document.getElementById("titulo").value + "&texto=" + document.getElementById("texto").value + "&fecha=" + document.getElementById("fecha").value);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.getElementById("titulo").value = "";
			document.getElementById("texto").value = "";
			window.location = "noticias.php";
			alert("Noticia Insertada Correctamente");
		}
	}
}
function guardarNoticia(identificador){
	ajax=nuevoAjax();
	ajax.open("POST", "guardar-noticia-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("id=" + identificador + "&titulo=" + document.getElementById("titulo_"+identificador).value + "&texto=" + document.getElementById("texto_"+identificador).value + "&fecha=" + document.getElementById("fecha_"+identificador).value);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			window.location = "noticias.php";
			alert("Noticia Guardada Correctamente");
		}
	}
}
function eliminarNoticia(identificador){
	ajax=nuevoAjax();
	ajax.open("POST", "eliminar-noticia-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("id=" + identificador);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			window.location = "noticias.php";
			alert("Noticia Eliminada Correctamente");
		}
	}
}

var nuevoMarcador, map = null;
function cargarMapa(lugar) {
	if (GBrowserIsCompatible()) { 
		map = new GMap2(document.getElementById("map")); 
		map.addControl(new GSmallMapControl()); 
		map.addControl(new GMapTypeControl()); 
		geocoder = new GClientGeocoder();
		geocoder.getLatLng(lugar,
			function(point) {
				if (point) {
					map.setCenter(point, 13); 
				}
				else {
					map.setCenter(new GLatLng(38.05117, -1.215085), 13); 
				}
			}
		);

		nuevoMarcador = null;
		GEvent.addListener(map, "click", function(marcador, punto) {
			if (!marcador){
				if (nuevoMarcador){
					map.removeOverlay(nuevoMarcador);
				}
				nuevoMarcador = new GMarker(punto);
				map.addOverlay(nuevoMarcador);
				document.getElementById("latitud").value = nuevoMarcador.getPoint().lat();
				document.getElementById("longitud").value = nuevoMarcador.getPoint().lng();
//					nuevoMarcador.openInfoWindowHtml("Lat: " + nuevoMarcador.getPoint().lat() + "<br/>Lon: " + nuevoMarcador.getPoint().lng() );
			}
		});
	}//Fin if es compatible
}

function cargarMapaModificar(latitud, longitud) {
	if (GBrowserIsCompatible()) { 
		map = new GMap2(document.getElementById("map")); 
		map.addControl(new GSmallMapControl()); 
		map.addControl(new GMapTypeControl()); 
		map.setCenter(new GLatLng(latitud, longitud), 13); 

		nuevoMarcador = new GMarker(new GLatLng(latitud, longitud));
		map.addOverlay(nuevoMarcador);

		GEvent.addListener(map, "click", function(marcador, punto) {
			if (!marcador){
				if (nuevoMarcador){
					map.removeOverlay(nuevoMarcador);
				}
				nuevoMarcador = new GMarker(punto);
				map.addOverlay(nuevoMarcador);
				document.getElementById("latitud").value = nuevoMarcador.getPoint().lat();
				document.getElementById("longitud").value = nuevoMarcador.getPoint().lng();
			}
		});
	}//Fin if es compatible
}//Fin load

function cargarMapaVer(latitud, longitud) {
	if (GBrowserIsCompatible()) { 
		map = new GMap2(document.getElementById("map")); 
		map.addControl(new GSmallMapControl()); 
		map.addControl(new GMapTypeControl()); 
		map.setCenter(new GLatLng(latitud, longitud), 13); 
		nuevoMarcador = new GMarker(new GLatLng(latitud, longitud));
		map.addOverlay(nuevoMarcador);
	}//Fin if es compatible
}//Fin load

function quitarMarcador(){
	if (nuevoMarcador){
		map.removeOverlay(nuevoMarcador);
		document.getElementById("latitud").value = "";
		document.getElementById("longitud").value = "";
	}
}