function cambioRegion(nombreForm) {
    var selectRegion = document.getElementById(nombreForm + '_region_id');
    var selectPoblacion = document.getElementById(nombreForm + '_poblacion_id');
    
    selectPoblacion.disabled = true;  
    selectPoblacion.value = "";  
    if (selectRegion.value != "") {        
	    ajaxParam('/ajax/poblaciones', 
	              {region_id: selectRegion.value, textoEspecial: ' -- elige localidad -- ', valorEspecial: ''},
	               '',
	               '',
	               function (respuesta, lienzo){
	                   actualizarSelect(nombreForm + '_poblacion_id', respuesta['argumentos_js']['opciones']);
	                   selectPoblacion.disabled = false;
	               });
	}
}

var timeout_limpieza;
var textoValoraciones = ['Debe mejorar', 'No es gran cosa', 'Es aceptable', 'Muy buen centro', '¡Excelente!'];

function encenderVotoCentro(numero) {
    establecerVotacionCentro(numero);
    document.getElementById('numVotosCentro').innerHTML = textoValoraciones[numero -1];
}

function establecerVotacionCentro(numero) {
    clearTimeout(timeout_limpieza);
    var entero = parseInt(numero);
    var medio = numero > entero;
    for (var i = 1; i <= entero; i++) {
        document.getElementById('voto_centro_' + i).src = "/images/voto_on.png";
    }
    if (medio) {
        document.getElementById('voto_centro_' + (entero + 1)).src = "/images/voto_half.png";
        for (i = entero + 2; i <= 5; i++) {
            document.getElementById('voto_centro_' + i).src = "/images/voto_off.png";
        }
    } else {
        for (i = entero + 1; i <= 5; i++) {
            document.getElementById('voto_centro_' + i).src = "/images/voto_off.png";
        }
    }
}

function limpiarVotosCentro() {
    timeout_limpieza = setTimeout(function(){_limpiarVotosCentro();}, 300);
}

function _limpiarVotosCentro() {
    establecerVotacionCentro(argumentosJs['votacionCentro']);
    mostrarVotosCentro();
}

function votarCentro(puntuacion) {
    document.forms['formVotarCentro'].elements['valor'].value = puntuacion;
    clearTimeout(timeout_limpieza);
    var fExito = function(respuesta, lienzo) {
                    for (var i = 1; i <= 5; i++) {
                        var voto = document.getElementById('voto_centro_' + i);
                        voto.onclick = function(){};
                        voto.onmouseover = function(){};
                        voto.onmouseout = function(){};
                        voto.style.cursor = 'default';
                    }
                    document.getElementById('numVotosCentro').innerHTML = 'Votación realizada';
                 };
    document.getElementById('numVotosCentro').innerHTML = 'Realizando votación...';
    return ajaxForm('', 'formVotarCentro', '', 'votarCentro', fExito);
}

function repetirVotoCentro() {
    document.getElementById('numVotosCentro').innerHTML = 'Ya valoraste este centro';
}

function mostrarVotosCentro() {
    var textoVoto = ' votos';
    if (argumentosJs['numVotos'] == 1) {
        textoVoto = ' voto';
    }
    document.getElementById('numVotosCentro').innerHTML = argumentosJs['numVotos'] + textoVoto;
}

//TODO: Cambiar esto cuando tengamos un autocompletar que funcione
peticionActivaCP = false;
function cambioCP(accion) {
    var cp = document.getElementById('form' + accion.charAt(0).toUpperCase() + accion.slice(1, accion.length) + '_CP');
    var ubicaciones = document.getElementById('form' + accion.charAt(0).toUpperCase() + accion.slice(1, accion.length) + '_ubicacion_id');
    var errorCP = document.getElementById('error_' + accion + '_cp');
    var cpOK = document.getElementById('cpOK');
    
    if (cp.value.length == 5) {
        if(!peticionActivaCP){
            peticionActivaCP = true;
            ajaxParam('/ajax/ubicaciones', 
                      {cp: cp.value, pintarSelect: false},
                       '',
                       'formNuevoCentro_submit',
                       function (respuesta, lienzo){
                           ocultar('error_' + accion + '_cp');
                           ocultar('error_' + accion + '_ubicacion_id');
                           var options = respuesta['argumentos_js']['opciones'];
                            //nos llega una opcion vacia, que no contamos
                           if (options.length > 1){
                               actualizarSelect('form' + accion.charAt(0).toUpperCase() + accion.slice(1, accion.length) + '_ubicacion_id', options);
                               if (options.length > 2) {
                                    //hay mas de una opcion, asi que mostramos el select para elegir
                                    mostrar('trLocalidad');
                               }
                               cpOK.innerHTML = '<img src="/images/check_pequeno.png" />';
                           } else {
                               resaltarErroresFormulario('form' + accion.charAt(0).toUpperCase() + accion.slice(1, accion.length), respuesta['errores']['formulario']);
                               cpOK.innerHTML = '<img src="/images/wrong_pequeno.png" />';
                           }
                           peticionActivaCP = false;
                       });
        }
    } else {
        ocultar('trLocalidad');
        actualizarSelect('form' + accion.charAt(0).toUpperCase() + accion.slice(1, accion.length) + '_ubicacion_id', [{'value': '', 'texto': 'Introduce un cp válido'}]);
        cpOK.innerHTML = '<img src="/images/wrong_pequeno.png" />';
    }
}

function actualizarDatosCentro(boton) {    
    return ajaxForm(boton, 'formEditar_datosCentro', '', 'submit_editar_datosCentro');
}

function actualizarDatosInstalacion(boton, instalacion_id) {
    return ajaxForm(boton, 'formEditar_instalacionCentro_' + instalacion_id, '', 'submit_editar_instalacionCentro_' + instalacion_id);
}

function nuevaInstalacionCentro(boton) {
    return ajaxForm(boton, 'formNueva_instalacionCentro', 'bloqueInstalacionesCentro', 'submit_nueva_instalacionCentro');
}

function actualizarAtributoInstalacion(boton, instalacionXatributoInstalacion_id) {
    return ajaxForm(boton, 'formEditar_atributo_instalacionCentro_' + instalacionXatributoInstalacion_id, '', '');
}

function nuevoAtributoInstalacion(boton, instalacion_id) {
    return ajaxForm(boton, 'formNuevo_atributo_instalacionCentro_' + instalacion_id, 'edicionInstalacion_' + instalacion_id, 'submit_nuevo_atributo_instalacionCentro' + instalacion_id);
}


