
var roundHundreds = function(num){
    return Math.round(num/100)*100
}
var roundThousands = function(num){
    return Math.round(num/1000)*1000
}

var loadLocationName = function(){	
    var param_string = window.location.href.split('?')[1];
    if (param_string != undefined) {
        var params = param_string.toQueryParams()
        var location = params.query
        if (location != undefined) {
            $("query").setValue(location.gsub('\\+',' '));
        }
    }
}


function str_replace(cadena, cambia_esto, por_esto) {
    return cadena.split(cambia_esto).join(por_esto);
}


function new_search(form){
    var particular = document.getElementById('particular').checked;
    var profesional = document.getElementById('profesional').checked;
	

    var rooms = document.getElementById('id_rooms').value;

    var bathrooms = document.getElementById('id_bathrooms').value;
    
    var max = document.getElementById('id_price_to').value;
    if (max){
        max = parseInt(max);
		
        if (isNaN(max)){
            max = 0;
        }
    }else{
        max = 0;
    }
    var min = document.getElementById('id_price_from').value;
    if (min){
        min = parseInt(min);

        if (isNaN(min)){
            min = 0;
        }
    }else{
        min = 0;
    }

    var m2from = document.getElementById('id_m2_from').value;
    if (m2from){
        m2from = parseInt(m2from);

        if (isNaN(m2from)){
            m2from = 0;
        }
    }else{
        m2from = 0;
    }

    var m2to = document.getElementById('id_m2_to').value;
    if (m2to){
        m2to = parseInt(m2to);

        if (isNaN(m2to)){
            m2to = 0;
        }
    }else{
        m2to = 0;
    }
    var modality = document.getElementById('search_tabs').className.split('value_')[1];
    var type = form.id_type.value;
    if (type.length == 0){
        tipo = 0;
    }else{
        tipo = type;
    }
    var status_disable = document.getElementById('id_status');
	
	
    if (!status_disable.disabled){
        name_status = status_disable.value;
    }else{
        name_status = 0;
    }
    var province = form.id_province.value;
    if (province.length == 0){
        province = 0;
    }
    var municipality_disable = document.getElementById('id_municipality');
	
    if (!municipality_disable.disabled){
        var municipality = municipality_disable.value;
        name_municipality = municipality;
    }else{
        name_municipality = 0;
    }
	
    var id_name = document.getElementById('query').value;
	
    if (id_name.length != 0){
        name = id_name;
    }else {
        name = 'none';
    }
    if (!modality){
        modality = 0;
    }
    if(name_status.length == 0){
        name_status = 0;
    }
    if (name_municipality.length == 0){
        name_municipality = 0;
    }
    if (type.length == 0){
        tipo = 0;
    //type = 0;
    }
    if (province.length == 0){
        province = 0;
    }
    name = escape(name);
    name = str_replace(name, '%20', '_');
    name = str_replace(name, '%E1', 'á');
    name = str_replace(name, '%E9', 'é');
    name = str_replace(name, '%ED', 'í');
    name = str_replace(name, '%F3', 'ó');
    name = str_replace(name, '%FA', 'ú');
    name = str_replace(name, '%F1', 'ñ');
	
	
    url_type = '/know_type/'+ modality +'/'+tipo +'/'+name_status+'/'+province+'/'+name_municipality +'/';
	
    var response;
    new Ajax.Request(url_type,
    {
        method:'post',
        onSuccess: function(transport){
            response = transport.responseText || "no response text";
			    
            //alert("Success! \n\n" + response );
            new_response = str_replace(response, '"', '');
			    
            if (name != 'none'){
                new_response1  = new_response + '?q='+name;
            }else{
                new_response1 = new_response + '?q=none';
            }
            
            if (max){
                new_response1 = new_response1+'&max='+max;
            }
            if (min){
                new_response1 = new_response1+'&min='+min;
            }
            if (m2from){
                new_response1 = new_response1+'&m2from='+m2from;
            }
            if (m2to){
                new_response1 = new_response1 + '&m2to='+m2to;
            }
            if (particular == true){
                new_response1 = new_response1 + '&part='+particular;
            }
            if (profesional == true){
                new_response1 = new_response1 + '&prof='+profesional;
            }
            if (rooms){
               new_response1 = new_response1 + '&rooms='+rooms;
            }
            if (bathrooms){
                new_response1 = new_response1 + '&bathrooms=' + bathrooms;
            }
            location.href = new_response1;
        },
        onFailure: function(transport){
        //alert(transport.value);alert('Something went wrong...')
        }
    });
	
    //alert(response);
    return false;
}

function validarEmail(valor) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
        //alert(”La dirección de email ” + valor + ” es correcta.”)
        return (true)
    } else {
        //alert(”La dirección de email es incorrecta.”);
        return (false);
    }
}


function comprueba_demanda(form){
    
    var errores = new Array();
    var i = 0;

    var tipo = document.getElementById('id_type').value;
    if (tipo.length == 0 || tipo == null){
        errores[i] = "Seleccione un tipo";
        i++;
    }

    var status = document.getElementById('id_status').value;
    if (status.length == 0 || status == null){
        errores[i] = "Seleccione un estado";
        i++;
    }
     var title = document.getElementById('title').value;
    if (title.length == 0 || title == null){
        errores[i] = "Inserte un título";
        i++;
    }

     var desc = document.getElementById('description').value;
    if (desc.length == 0 || desc == null){
        errores[i] = "Inserte una descripción";
        i++;
    }

    var errores_str = errores.toString();

    if (errores == '' || errores == null){

        return true;

    }else{
        alert(str_replace(errores_str, ',','\n'));
        return false;
    }
}
//Comprobaremos que todos los campos del formulario afiliacion estan completos
function comprobar_formulario(form){
            
    var errores = new Array();
    var i = 0;
    if (form.group2 == null){
        //alert("Seleccione usuario registrado o Nuevo usuario");
        errores[i] = "Seleccione usuario registrado o Nuevo usuario";
        //return false;
        i++;
    }
	   
	    
    var email = document.getElementById('id_email').value;
    if (email.length == 0 || email == null){
        errores[i] = "Introduzca su email";
        i++;
    //resultado = false;
    }else{
        var correcto = validarEmail(email);
        if (correcto == false){
            errores[i] = "Introduzca un email correcto";
            i++;
        //resultado = false;
        }
    }
    if (form.group2[0].checked){ //Usuario registrado
        var password = document.getElementById('id_password').value;
        if (password.length == 0 || password == null){
            errores[i] = "Introduzca su contraseña";
            i++;
        //	resultado = false;
        }
    }else{
        var name = document.getElementById('id_name').value;
        if (name.length == 0 || name == null){
            errores[i] = "Introduzca su nombre";
            i++;
        //resultado = false;
        }
    }
	    	
    var errores_str = errores.toString();
	    
    if (errores == '' || errores == null){
	    	
        return true;
	    
    }else{
        alert(str_replace(errores_str, ',','\n'));
        return false;
    }


}
	

function toggleInmobliarias(form){
    var valor = form.value;
    var div = document.getElementById('archivo');

    if (valor == 'Archivo XML'){
        div.style.display = 'block';
    }else{
        div.style.display = 'none';
    }
}

function toggleRegister(form) {
		
    document.getElementById('password').style.display;
    document.getElementById('new_name').style.display;
		
		
    valor = form.value;
    if (valor == 'Registrado') {
        document.getElementById('password').style.display = 'block';
        document.getElementById('new_name').style.display = 'none';
    } else {
        document.getElementById('password').style.display = 'none';
        document.getElementById('new_name').style.display = 'block';
    }
}

	
function togglesupplyRegister(form){
    var valor = form.value;
    if (valor == 'noregistro'){
        document.getElementById('telephone').style.display = 'block';
        document.getElementById('email').style.display = 'none';
    }else{
        document.getElementById('telephone').style.display = 'none';
        document.getElementById('email').style.display = 'block';
                    
    }
}

function valida_formulario(form){
    var errores = new Array();
    var i = 0;


    if (form.persona.value.length == 0 || form.persona == null){
        errores[i] = "Introduzca su nombre";
        i++;
    }
    if (form.email.value == null || form.email.value.length == 0){
        errores[i] = "Introduzca un email";
        i++;
    }else{
        var correcto = validarEmail(form.email.value);
        if (correcto == false){
            errores[i] = "Introduzca un email correcto";
            i++;
        }
    }

 if (form.telefono.value.length == 0 || form.telefono == null){
        errores[i] = "Introduzca su telefono";
        i++;
    }
     if (form.comentario.value.length == 0 || form.comentario == null){
        errores[i] = "Introduzca un mensaje";
        i++;
    }
    var errores_str = errores.toString();

    if (errores == '' || errores == null){
        return true;

    }else{
        alert(str_replace(errores_str, ',','\n'));
        return false;
    }
}

function valida_xml_upload(form){
    var errores = new Array();
    var i = 0;
    if (form.email.value == null || form.email.value.length == 0){
        errores[i] = "Introduzca un email";
        i++;
    }else{
        var correcto = validarEmail(form.email.value);
        if (correcto == false){
            errores[i] = "Introduzca un email correcto";
            i++;
        }
    }
    
    var errores_str = errores.toString();

    if (errores == '' || errores == null){
        return true;

    }else{
        alert(str_replace(errores_str, ',','\n'));
        return false;
    }
}

//Comprobaremos que todos los campos del formulario de publicar inmobiliarios estan completos
function  valida_inmobiliarias(form){
    var errores = new Array();
    var i = 0;
    if (form.publicacion == null ){
        errores[i] = "Selecciona una forma de publicación";
        i++;
    }else{

        if (form.publicacion[0].checked){
            var archivo = document.getElementById('file_id').value;
            if (archivo.length == 0 || archivo == null){
                errores[i] = "Adjunte un archivo";
                i++;
            }
        }

    }


    var empresa = document.getElementById('id_empresa').value;
    if (empresa.length == 0 || empresa == null){
        errores[i] = "Introduzca el nombre de su empresa";
        i++;
    }

    var email = document.getElementById('id_email').value;
    if (email.length == 0 || email == null){
        errores[i] = "Introduzca un email";
        i++;
    }else{
        var correcto = validarEmail(email);
        if (correcto == false){
            errores[i] = "Introduzca un email correcto";
            i++;
        }
    }

    var telefono = document.getElementById('id_telefono').value;
    if (telefono.length == 0 || telefono == null){
        errores[i] = "Introduzca un número de teléfono";
        i++;
    }

    var titulo = document.getElementById('id_titulo').value;
    if (titulo.length == 0 || titulo == null){
        errores[i] = "Introduzca una persona de contacto";
        i++;
    }


    var errores_str = errores.toString();

    if (errores == '' || errores == null){
        return true;

    }else{
        alert(str_replace(errores_str, ',','\n'));
        return false;
    }
}

//Comprobaremos que todos los campos del formulario anuncio popular estan completos
function valida_anuncio_popular(form){

    var errores = new Array();
    var i = 0;
    if (form.pago == null){
        errores[i] = "Seleccione forma de pago";
        i++;
    }


    var nombre = document.getElementById('id_nombre').value;
    if (nombre.length == 0 || nombre == null){
        errores[i] = "Introduzca su nombre";
        i++;
    }
    var email = document.getElementById('id_email').value;
    if (email.length == 0 || email == null){
        errores[i] = "Introduzca un email";
        i++;
    }else{
        var correcto = validarEmail(email);
        if (correcto == false){
            errores[i] = "Introduzca un email correcto";
            i++;
        }
    }

    var telefono = document.getElementById('id_telefono').value;

    if (telefono.length == 0 || telefono == null){
        errores[i] = "Introduzca un número de teléfono";
        i++;
    }
    var titulo = document.getElementById('id_titulo').value;
    if (titulo.length == 0 || titulo == null){
        errores[i] = "Introduzca el título del anuncio que desea popularizar";
        i++;
    }

    var errores_str = errores.toString();

    if (errores == '' || errores == null){
        return true;

    }else{
        alert(str_replace(errores_str, ',','\n'));
        return false;
    }
}


function confirm_anuncio(){
    if (confirm('¿Són correctos los datos del anuncio a publicar?')){
        return true;
    }else{
        return false;
    }
}

function enviar_anuncio(){
    var phone = document.getElementById("telephone");
    var field = document.getElementById("id_telephone").value;



    var errores = new Array();
    var i = 0;

    var modo = document.getElementById('id_modality').value;
    if (modo.length == 0 || modo == null){
        errores[i] = "Introduzca una modalidad";
        i++;
    }else{
        if (modo != 5){
            var stado = document.getElementById('id_status').value;
            if (stado.length == 0 || stado == null){
                errores[i] = "Introduzca un estado";
                i++;
            }

        }
    }

    var tipo = document.getElementById('id_type').value;
    if (tipo.length == 0 || tipo == null){

        errores[i] = "Introduzca un tipo";
        i++;
    }

    var province = document.getElementById('id_province').value;
    if (province.length == 0 || province == null){
        errores[i] = "Introduzca una provincia";
        i++;
    }

    var municipality = document.getElementById('id_municipality').value;
    if (municipality.length == 0 || municipality == null){
        errores[i] = "Introduzca un municipio";
        i++;
    }

    var title = document.getElementById('id_title').value;
    if (title.length == 0 || title == null){
        errores[i] = "Introduzca un titulo";
        i++;
    }

    var desc = document.getElementById('id_description').value;
    if (desc.length == 0 || desc == null){
        errores[i] = "Introduzca una descripción";
        i++;
    }

    var errores_str = errores.toString();

    if (errores == '' || errores == null){
    //return true;

    }else{
        alert(str_replace(errores_str, ',','\n'));
        return false;
    }


    if (phone.style.display == "block"){
        if (field.length == 0 || field == null){
            alert("Introduzca un teléfono");
            return false;
        };
        if (confirm_anuncio()){
            document.formulario.submit();
        /*if (confirm("Su anuncio está en proceso de revisión. En breve será publicado. \n\n Consiga que su anuncio sea visitado por miles de usuarios interesados. \n Active el Servicio ANUNCIO POPULAR\n\n Pulse Aceptar para más información")){
        location.href='/anuncio_popular/';
    }*/
        }
    }
    else{
        var eml = document.getElementById('id_email').value;
        if (eml.length == 0 || eml == null){
            alert("Introduzca un email");
            return false;
        }else{
           
            document.formulario.submit();
        }

    /*	if (confirm("Esta acción tiene un coste de "+1+" créditos, ¿desea continuar?")){
                    document.formulario.submit();
                };*/
        
	
    }
    
}

function mostrar(id){
    document.getElementById('c_inmobiliario').style.display = 'none';
    document.getElementById('q_hacer').style.display = 'none';
    document.getElementById('c_funciona').style.display = 'none';
    document.getElementById(id).style.display = 'block';
}
