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.opcioninmobiliaria.com" 
	var titulo="OpcionInmobiliaria.com - Portal Inmobiliario -"
	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() {
	var longitud = document.getElementById("telefono").value.length;
	if (!document.getElementById("nombre").value) {
		document.getElementById("nombre").focus();
		alert("Debe indicar su Nombre");
	}
	else if ((longitud<8) || (longitud>12)) {
		document.getElementById("telefono").focus();
		alert("Debe indicar un Teléfono válido");
	}
	else if (!document.getElementById("direccion").value) {
		document.getElementById("direccion").focus();
		alert("Debe indicar la Dirección");
	}
	else if (!document.getElementById("municipio").value) {
		document.getElementById("municipio").focus();
		alert("Debe indicar el Municipio");
	}
	else if (!document.getElementById("provincia").value) {
		document.getElementById("provincia").focus();
		alert("Debe indicar la Provincia");
	}
	else if (!validaEmail(document.getElementById("email").value)) {
		document.getElementById("email").focus();
		alert("Debe indicar una cuenta de Correo válida para el contacto");
	}
	else if (!document.getElementById("mensaje").value) {
		document.getElementById("mensaje").focus();
		alert("Debe indicar su Mensaje");
	}
	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 + "&municipio=" + document.getElementById("municipio").value + "&provincia=" + document.getElementById("provincia").value);
		ajax.onreadystatechange=function() {
			if (ajax.readyState==4) {
				document.getElementById("nombre").value = "";
				document.getElementById("direccion").value = "";
				document.getElementById("municipio").value = "";
				document.getElementById("provincia").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>=8) && (document.getElementById("telefono").value.length<=12)) {
		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 validaFecha(fecha){
	var re  = /^([0-9]{2})+\/([0-9]{2})\/+([0-9]{4})+$/;
	if (!re.test(fecha)) return false;
	else return true;
}
function validaCP(cp){
	var re  = /^([0-9]{5})+$/;
	if (!re.test(cp)) return false;
	else return true;
}
function validaCIF_NIF(cif_nif){
	var cif  = /^([a-zA-Z])+([0-9]{7})+([a-zA-Z0-9])+$/;
	var nif  = /^([0-9]{8})+$/;
	if (cif.test(cif_nif) || nif.test(cif_nif)) return true;
	else return false;
}
function validaPorcentaje(porcentaje){
	var re  = /^([0-9]{1,2})+$/;
	if (!re.test(porcentaje)) return false;
	else return true;
}
function dosNumeros(numero){
	var re  = /^([0-9]{2})+$/;
	if (!re.test(numero)) return false;
	else return true;
}
function cuatroNumeros(numero){
	var re  = /^([0-9]{4})+$/;
	if (!re.test(numero)) return false;
	else return true;
}
function cincoNumeros(numero){
	var re  = /^([0-9]{4})+$/;
	if (!re.test(numero)) return false;
	else return true;
}
function nueveNumeros(numero){
	var re  = /^([0-9]{9})+$/;
	if (!re.test(numero)) return false;
	else return true;
}
function diezNumeros(numero){
	var re  = /^([0-9]{10})+$/;
	if (!re.test(numero)) return false;
	else return true;
}
function validaNumero(numero){
	var re  = /^([0-9]+)+$/;
	if (!re.test(numero)) return false;
	else return true;
}
function insertarContrato(){
	if (!$("#condiciones").attr("checked")){
		alert("¡¡¡ Debe Aceptar las Condiciones del Contrato !!!");
	}
	else if ($("#contacto").val()==""){
		alert("¡¡¡ Debe indicar un persona de contacto !!!");
	}
	else if ($("#identificacion").val()==""){
		alert("¡¡¡ Debe indicar la identificación del cliente !!!");
	}
	else if ($("#direccion").val()==""){
		alert("¡¡¡ Debe indicar una dirección !!!");
	}
	else if (($("#provincia").val()=="0") || ($("#municipio").val()=="0")) {
		alert("¡¡¡ Debe indicar una Localidad y una Provincia !!!");
	}
	else if (!cincoNumeros($("#cp").val())) {
		alert("¡¡¡ Debe indicar un Código Postal válido !!!");
	}
	else if (!validaNumero($("#telefono").val())) {
		alert("¡¡¡ Debe indicar un número de Teléfono válido !!!");
	}
	else if ((!validaNumero($("#fax").val())) && ($("#fax").val()!="")) {
		alert("¡¡¡ Debe indicar un número de Fax válido !!!");
	}
	else if ((!validaNumero($("#movil").val())) && ($("#movil").val()!="")) {
		alert("¡¡¡ Debe indicar un número de Celular !!!");
	}
	else if (!validaEmail($("#email").val())) {
		alert("¡¡¡ Debe indicar una Cuenta de Correo válida !!!");
	}
	else if ($("#nombre").val()==""){
		alert("¡¡¡ Debe indicar un nombre para la empresa !!!");
	}
	else if (!validaCIF_NIF($("#cif").val())) {
		alert("¡¡¡ El D.N.I. no es válido !!!");
	}
	else if (!validaNumero($("#importe").val())) {
		alert("¡¡¡ Debe indicar un importe válido !!!");
	}
	else {
		
		var opciongest = $("#opciongest").attr("checked") ? 1 : 0;
		var opcionimage = $("#opcionimage").attr("checked") ? 1 : 0;
		var alojamiento = $("#alojamiento").attr("checked") ? 1 : 0;
		var dominio = $("#dominio").attr("checked") ? 1 : 0;
		var mantenimiento = $("#mantenimiento").attr("checked") ? 1 : 0;
		var paginaWeb = $("#paginaWeb").attr("checked") ? 1 : 0;
		var portales = $("#portales").attr("checked") ? 1 : 0;
		var destacado = $("#destacado").attr("checked") ? 1 : 0;

		var textoDestacados = "&n="+$("#contadorDestacados").val();
		for(i=1;i<=$("#contadorDestacados").val();i++){
			textoDestacados += "&provinciaDestacado_" + i +"=" + $("#provinciaDestacado_"+i).val() + "&municipioDestacado_" + i +"=" + $("#municipioDestacado_"+i).val() + "&pedaniaDestacado_" + i +"=" + $("#pedaniaDestacado_"+i).val() + "&propiedadDestacado_" + i +"=" + $("#propiedadDestacado_"+i).val() + "&ofertaDestacado_" + i +"=" + $("#ofertaDestacado_"+i).val() + "&obranuevaDestacado_" + i +"=" + $("#obranuevaDestacado_"+i).val() + "&habitacionesDestacado_" + i +"=" + $("#habitacionesDestacado_"+i).val() + "&banosDestacado_" + i +"=" + $("#banosDestacado_"+i).val() + "&precioDestacado_" + i +"=" + $("#precioDestacado_"+i).val();
		}

		$.ajax({
			type: "POST",
			url: "contrato-ajax.php",
			data: "contacto="+$("#contacto").val()+"&identificacion="+$("#identificacion").val()+"&direccion="+$("#direccion").val()+"&provincia="+$("#provincia").val()+"&municipio="+$("#municipio").val()+"&cp="+$("#cp").val()+"&telefono="+$("#telefono").val()+"&fax="+$("#fax").val()+"&movil="+$("#movil").val()+"&email="+$("#email").val()+"&web="+$("#web").val()+"&nombre="+$("#nombre").val()+"&cif="+$("#cif").val()+"&observaciones="+$("#observaciones").val()+"&importe="+$("#importe").val()+"&comercial="+$("#comercial").val()+"&opciongest="+opciongest+"&opcionimage="+opcionimage+"&alojamiento="+alojamiento+"&dominio="+dominio+"&mantenimiento="+mantenimiento+"&paginaWeb="+paginaWeb+"&portales="+portales+"&destacado="+destacado+textoDestacados+"&observacionesImporte="+$("#observacionesImporte").val(),
			success: function(datos){
				if (datos==0) alert("¡¡¡ Ha habido un problema al tramitar su contrato !!!");
				else window.open("contratos/"+datos+".pdf", "_blank", "width=800,height=700,resizable=yes");
			}
		})
	}
}

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 validarAltaParticular() {
	ajax=nuevoAjax();
	ajax.open("POST", "check-members.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("email=" + document.getElementById("email").value + "&usuario=" + document.getElementById("usuarioCliente").value)
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			if (ajax.responseText=="email"){
				alert("Ya existe un usuario con ese E-mail");
				document.getElementById("email").focus();
			}
			else if(ajax.responseText=="usuario"){
				alert("Ya existe un usuario con ese Identificador");
				document.getElementById("usuarioCliente").focus();
			}
			else {
				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();
					}   
				}  
				if (document.getElementById("provincia").value=="Seleccione la Provincia") {
					alert("Debe seleccionar una PROVINCIA y una LOCALIDAD");
					document.getElementById("provincia").focus();
				}
				else if (document.getElementById("nombre").value=="") {
					alert("Debe introducir su Nombre");
					document.getElementById("nombre").focus();
				} 
				else if (document.getElementById("telefono").value.length < 9) {
					alert("El número de TELÉFONO no es válido");
					document.getElementById("telefono").focus();
				} 
				else if (!validaEmail(document.getElementById("email").value)) {
					alert("Debe indicar una cuenta de Correo válida");
					document.getElementById("email").focus();
				} 
				else if (!document.getElementById("usuarioCliente").value) {
					alert("Debe rellenar el campo USUARIO");
					document.getElementById("usuarioCliente").focus();
				} 
				else if (document.getElementById("clave").value != document.getElementById("clave2").value) {
					alert("Los campos PASSWORD deben ser Iguales");
					document.getElementById("clave2").focus();
				} 
				else if (!document.getElementById("clave").value) {
					alert("Debe elegir un PASSWORD");
					document.getElementById("clave").focus();
					return false;
				}
				else {
					alert("Usuario Registrado Correctamente. Proceda a la carga del inmueble");
					document.getElementById("formulario").submit();
				}
			}
		}
	}
	return false;
}

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 = "";
	}
}

function realizarBusqueda(){
	ajax=nuevoAjax();
	ajax.open("POST", "crea-ruta-ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("prov=" + document.getElementById("prov").value + "&municipio=" + document.getElementById("municipio").value + "&pedania=" + document.getElementById("pedania").value + "&propiedad=" + document.getElementById("propiedad").value + "&oferta=" + document.getElementById("oferta").value + "&habitaciones=" + document.getElementById("habitaciones").value + "&ambientes=" + document.getElementById("ambientes").value + "&banos=" + document.getElementById("banos").value + "&precio=" + document.getElementById("precio").value + "&obranueva=" + document.getElementById("obranueva").value);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			document.location.href=ajax.responseText;
		}
	}
}

function cambiaOrden(objeto){
	var valorNuevo = objeto.value;
	var valorAntiguo = objeto.id;
	var objetoAntiguo = document.getElementById(valorNuevo);
	objetoAntiguo.value = valorAntiguo;
	objetoAntiguo.id = valorAntiguo;
	objeto.id = valorNuevo;
	
	ajax=nuevoAjax();
	ajax.open("POST", "guarda-orden.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("objetoAntiguo=" + objetoAntiguo.name + "&valorAntiguo=" + valorAntiguo + "&objetoNuevo=" + objeto.name + "&valorNuevo=" + valorNuevo);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
		}
	}
}

function borrarImagen(id){
	ajax=nuevoAjax();
	ajax.open("POST", "borrar-imagen.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("id=" + id);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			location.reload();
		}
	}
}
