var alertaSesionEterna = true;

function getXmlHttpObject() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        // IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("Tu navegador no soporta Ajax.\nAlgunas funcionalidades de nuestra web pueden no funcionar correctamente en tu navegador.");
    }
    return xmlhttp;
}


function pintarLienzo(contenido, lienzo) {
    if (lienzo != undefined){
        if (typeof lienzo == 'string') {
            lienzo = document.getElementById(lienzo);
        }
        lienzo.innerHTML = contenido;
    }
}


function dictToPost(diccionario) {
    var post = '';
    for (param in diccionario){
        if(diccionario[param] != null){
            if (typeof diccionario[param] == "object") {
                for (var i=0; i<diccionario[param].length; i++) {
                    post += (post == '' ? '' : '&') + param + '=' + encodeURIComponent(diccionario[param][i]);
                }
            } else {
                post += (post == '' ? '' : '&') + param + '=' + encodeURIComponent(diccionario[param]);
            }
        } else {
            post += (post == '' ? '' : '&') + param + '=' + '';
        }
    }
    return post;
}


function ajaxParam(url, parametros, idLienzo, idCarga, fExito, fError, fCarga) {
    var idLienzo = (idLienzo != null) ? idLienzo : '';
    var idCarga = (idCarga != null) ? idCarga : '';
    var fExito = (fExito != null) ? fExito : function(respuesta, lienzo){pintarLienzo(respuesta['respuesta'], lienzo);};
    var fError = (fError != null) ? fError : function(error) { 
                                                    var errores = getEstructuraErrores();
                                                    errores['sistema']['ajax'] = {'codigo': 1, 'mensaje':error};
                                                    actualizarNotificaciones(errores, []);
                                                    }
    var fCarga = (fCarga != null) ? fCarga : function(lienzo){pintarLienzo('<img alt="cargando" title="cargando" src="/images/loading.gif" />', lienzo);};
    var xmlhttp = getXmlHttpObject();
    var lienzo = document.getElementById(idLienzo);
    var carga = document.getElementById(idCarga);
    if (carga != null){
        var cargaBackup = carga.innerHTML;
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 0) {
            
        }
        if (xmlhttp.readyState == 1) {
            if (carga != null){
                fCarga(carga);
            }
        }
        if (xmlhttp.readyState == 2) {
           
        }
        if (xmlhttp.readyState == 4) {                        
            if (xmlhttp.status == 200) {
               pintarLienzo(cargaBackup, carga);
               try {
                    var dict = JSON.parse(xmlhttp.responseText);
                } catch (error) {
                    //Por algun motivo no nos llega una respuesta en JSON                    
                    fError('Ha ocurrido un error inesperado. Inténtelo más adelante.');
                    return;
                }
                actualizarNotificaciones(dict['errores'], dict['notificaciones']);
                actualizarValidacion(dict['validacion']);
                //declaramos globales los argumentos_js recibidos
                actualizarArgumentosJs(dict['argumentos_js']);
                fExito(dict, lienzo);
            } else if (xmlhttp.status >= 300 && (xmlhttp.status <= 400)) {
                if (carga != null){
                    pintarLienzo(cargaBackup, carga);
                }
                fError('Ha ocurrido un error inesperado. Inténtelo más adelante.');
            } else if (xmlhttp.status > 400 && (xmlhttp.status < 500)) {
                if (carga != null){
                    pintarLienzo(cargaBackup, carga);
                }
                if (xmlhttp.status == 401) {
                    fError('No tienes permisos para realizar esta acción.');
                } else if (xmlhttp.status == 403) {
                    fError('Debes iniciar sesión para realizar esta acción.');
                } else {
                    fError('Puede que tu cuenta no tenga permisos suficientes para realizar la acción');
                }
            } else if (xmlhttp.status >= 500 && (xmlhttp.status < 600)) {
                if (carga != null){
                    pintarLienzo(cargaBackup, carga);
                }
                fError('Ha ocurrido un error inesperado. Inténtelo más adelante.');
            }
        }
    };
    xmlhttp.open("POST",url,true);
    xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
    xmlhttp.send(dictToPost(parametros));
}


function ajaxForm(boton, formulario, idLienzo, idCarga, fExito, fError, fCarga){
    var id = setTimeout(function(){_ajaxForm(boton, formulario, idLienzo, idCarga, fExito, fError, fCarga);}, 10);
    return false;
}


function _ajaxForm(boton, formulario, idLienzo, idCarga, fExito, fError, fCarga) {
    var fExito = (fExito != null) ? fExito : function(respuesta, lienzo){pintarLienzo(respuesta['respuesta'], lienzo);};
    var fError = (fError != null) ? fError : function(error) { 
                                                    var errores = getEstructuraErrores();
                                                    errores['sistema']['ajax'] = {'codigo': 1, 'mensaje':error};
                                                    actualizarNotificaciones(errores, []);
                                                    }
    
    var valueBackup = '';
    //Asi podemos llamar a ajaxForm sin tener que pulsar ningun boton
    if (boton) {
        valueBackup = boton.value;
        boton.value = 'enviando..';
        boton.disabled = 'disabled';
    }
    var funTimeoutError = function(){ terminarEspera(boton, valueBackup, '', false); };
    var funTimeout = function(){ terminarEspera(boton, valueBackup, false, false); };
    var idError = setTimeout(funTimeoutError, 5000);
    var form = document.forms[formulario];
    var camposValid = getListaValidacionForm(form);
    ocultarErroresFormularios();
    if(validarCampos(form, camposValid)){
	    parametros = {}
	    for(i=0; i<camposValid.length; i++){
	        var campoValid  = camposValid[i];
	        var nombreCampo = campoValid['nombre'];
	        var campoForm   = form.elements[nombreCampo];
	        if (campoForm){
	            valorCampo = campoForm.value;
	            if (valorCampo == undefined) {
	                //el campo es un checkbox multiple
	                valorCampo = checkboxToArray(campoForm);
	            } else if (campoForm.type == 'checkbox' && !campoForm.checked) {
	                valorCampo = '';
	            }
	            if (campoValid['privado']) {
	                nombreCampo = 'p_' + nombreCampo;
	            }
	            parametros[nombreCampo] = valorCampo;
	        }
	    }
	    //Parche para compensar que nombreForm no esta nunca en las listas de validacion
	    var nombreForm = form.elements['nombreForm'];
	    if (nombreForm){
	        parametros['nombreForm'] = nombreForm.value;
	    }
	    //Generamos un id aleatorio para el boton, ya que la referencia this se perdera si empleamos una 
        //funcion de carga que sobrescriba el html del boton
        var boton_id = 'botonAjaxForm_' + idError;
        if (boton) {
            boton.id = boton_id;
        }
	    var fExitoTimeout = function(contenido, lienzo){
	                            clearTimeout(idError);
	                            terminarEsperaId(boton_id, valueBackup, false, false);
	                            fExito(contenido, lienzo);
	                        };
	    var fErrorTimeout = function(mensaje){
	                            clearTimeout(idError);
	                            terminarEsperaId(boton_id, valueBackup, false);
	                            fError(mensaje);
	                        };
	    ajaxParam(form.action, parametros, idLienzo, idCarga, fExitoTimeout, fErrorTimeout, fCarga);
	} else {
	    //Si no se ha validado correctamente, forzamos la reactivacion
	    clearTimeout(idError);
	    var id = setTimeout(funTimeout, 100);
	}
	return false;
}


function notificarErrores(errores){
/*
    var errores = getEstructuraErrores();
    errores['sistema']['ajax'] = {codigo:1, mensaje: error};
    actualizarNotificaciones(errores, []);
*/
    var contenido = '';
    var total = 0;
   //Si usas el IE6 asqueroso, te quedaste sin mensajitos
    var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
    if (!IE6) {
        for (var i in errores) {
            contenido += '<div>' + errores[i] + '</div>';
            total += 1;
        }
        if (total){          
            document.getElementById('barraError').innerHTML = contenido;
            $("#barraError").fadeIn(1500, function(){setTimeout(function(){$("#barraError").fadeOut(1500);}, 3500);});
        }
    }
}


function notificarError(error){
    notificarErrores([error]);
}


function notificarExitos(mensajes){
/*
    var errores = getEstructuraErrores();
    errores['sistema']['ajax'] = {codigo:1, mensaje: error};
    actualizarNotificaciones(errores, []);
*/
    var contenido = '';
    var total = 0;
    //Si usas el IE6 asqueroso, te quedaste sin mensajitos
    var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
    if (!IE6) {
        for (var i in mensajes) {
            contenido += '<div>' + mensajes[i] + '</div>';
            total += 1;
        }
        if (total){
            document.getElementById('barraNotificacion').innerHTML = contenido;
            $("#barraNotificacion").fadeIn(1500, function(){setTimeout(function(){$("#barraNotificacion").fadeOut(1500);}, 3500);});
        }
    }
}


function notificarExito(mensaje){
    notificarExitos([mensaje]);
}


function getEstructuraErrores(){
    return {sistema: {}, formulario:{accion: '', huboErrores: false}};
}


function actualizarNotificaciones(errores, notificaciones){
    var contenido ='';
    var divError = '';
    var mensajeError = '';
    var editable = false;
    var clases = [];
    var mensajesError = [];
    var numErrores = 0;
    var contenidoResumen = '';
    if (notificaciones.length > 0){
        contenido += '<h3>Tienes las siguientes notificaciones:</h3><ul>';
        
        for (var i=0; i < notificaciones.length; i++){
            contenido += '<li class="notificacion">' + notificaciones[i] + '</li>';
        }
        contenido += '</ul>';
    }
    var huboError = false;
    
    for (var key in errores['sistema']){
        if (!huboError && errores['sistema'][key]['codigo']){
            contenido += '<h3>Se han producido los siguientes errores:</h3><ul>';
            huboError = true;
        }
        if (errores['sistema'][key]['codigo']){
            contenido += '<li class="error">' + errores['sistema'][key]['mensaje'] + '</li>';
            mensajesError.push(errores['sistema'][key]['mensaje']);
            numErrores += 1;
        }
    }
    if (huboError){
        contenido += '</ul>';
    }
    for (var key in errores['formulario']){
        if (!huboError && key != 'accion' && key != 'huboErrores' && errores['formulario'][key]['codigo']){
            contenido += '<h3>Se han producido los siguientes errores:</h3><ul>';
            huboError = true;
        }
        if (key != 'accion' && key != 'huboErrores'){
            if (errores['formulario'][key]['codigo']){
                //se ha producido un error, ahora comprobamos si existe un mensaje de error por defecto
                numErrores += 1;
                mensajeError = errores['formulario'][key]['mensaje'];
                divError = document.getElementById('error_' + errores['formulario']['accion']  + '_' + key);
                if (divError) {
                    clases = divError.className.split(' ');
	                editable = true;
	                for (var j = 0; j < clases.length; j++){
	                    if (clases[j] == 'noeditable'){
	                        editable = false;
	                        break;
	                    }
	                }
	                if (!editable && divError.innerHTML != ""){
	                    mensajeError = divError.innerHTML;
	                    divError.style.display = '';
	                } else {
	                    divError.innerHTML = mensajeError;
	                    divError.style.display = '';
	                }
                }
                contenido += '<li class="error">' + mensajeError + '</li>';
                mensajesError.push(mensajeError);
            }
        }
    }
    if (huboError){
        contenido += '</ul>';
    }
    
    if (contenido != ''){
        document.getElementById('contenidoNotificaciones').innerHTML = contenido;
        if (numErrores) {
            contenidoResumen += '<span class="error">' + numErrores +'</span><img src="/images/error_pequeno.png" />';
        }
        if (notificaciones.length) {
            contenidoResumen += '<span class="notificacion">' + notificaciones.length +'</span><img src="/images/informacion_pequeno.png" />';
        }
        document.getElementById('resumenErroresNotificaciones').innerHTML = contenidoResumen;
        if (document.getElementById('notificaciones').style.display == 'none') {
            mostrar('notificaciones');
        } 
    } else {
        if (document.getElementById('contenidoNotificaciones').style.display != 'none') {
            minimizarNotificaciones();
        }
        if (document.getElementById('notificaciones').style.display != 'none') {
            ocultar('notificaciones');
        }
        document.getElementById('contenidoNotificaciones').innerHTML = contenido;
    }
    notificarErrores(mensajesError);
    notificarExitos(notificaciones);
}


function huboErrores(errores) {
    var error = false;
    if (errores['formulario']['huboErrores']) {
        error = true;
    }
    
    if (!error) {
        for (var key in errores['sistema']){
            if (errores['sistema'][key]['codigo']){
                error = true;
                break;
            }
        }
    }
    
    return error;
}

function actualizarValidacion(nuevasValidaciones) {
    if (typeof validacion == 'undefined'){
        validacion = {};
    }
    for (var key in nuevasValidaciones){
        validacion[key] = nuevasValidaciones[key];
    }
}


function actualizarArgumentosJs(nuevosArgumentos) {
    if (typeof argumentosJs == 'undefined'){
        argumentosJs = {};
    }
    for (var key in nuevosArgumentos){
        argumentosJs[key] = nuevosArgumentos[key];
    }
}


function intercambiar(elem1, elem2) {
    mostrarOcultar(elem1);
    mostrarOcultar(elem2);
}


function mostrarOcultar(elemento) {
    if (typeof elemento == 'string') {
        elemento = document.getElementById(elemento);
    }
    if (elemento != null) {
        elemento.style.display = (elemento.style.display == 'none') ? '' : 'none';
    }
}


function mostrar(elemento) {
    if (typeof elemento == 'string') {
        elemento = document.getElementById(elemento);
    }
    if (elemento != null) {
        elemento.style.display = '';
    }
}


function ocultar(elemento) {
    if (typeof elemento == 'string') {
        elemento = document.getElementById(elemento);
    }
    if (elemento != null) {
        elemento.style.display = 'none';
    }
}


function cambioHoras(id) {
    var horas = document.getElementById(id + '_horas');
    var minutos = document.getElementById(id + '_minutos');
    var time_input = document.getElementById(id);
    if (horas.value == '-1'){
        minutos.value = '-1';
        time_input.value = ''; 
    } else {
        if (minutos.value == '-1'){
            minutos.value = '00';
        }
        time_input.value = horas.value + ':' + minutos.value;
    }
}


function cambioMinutos(id) {
    var horas = document.getElementById(id + '_horas');
    var minutos = document.getElementById(id + '_minutos');
    var time_input = document.getElementById(id);
    if (minutos.value == '-1'){
        horas.value = '-1';
        time_input.value = ''; 
    } else {
        if (horas.value == '-1'){
            horas.value = '00';
        }
        time_input.value = horas.value + ':' + minutos.value;
    }
}


function habilitarDeshabilitar(elemento) {
    if (typeof elemento == 'string') {
        elemento = document.getElementById(elemento);
    }
    if (elemento != null) {
        elemento.style.display = (elemento.style.display == 'none') ? '' : 'none';
    }
}


function habilitar(elemento) {
    if (typeof elemento == 'string') {
        elemento = document.getElementById(elemento);
    }
    if (elemento != null) {
        elemento.disabled = false;
    }
}


function deshabilitar(elemento) {
    if (typeof elemento == 'string') {
        elemento = document.getElementById(elemento);
    }
    if (elemento != null) {
        elemento.disabled = true;
    }
}


function cambiarAtributo(elemento, atributo, valor) {
    if (typeof elemento == 'string') {
        elemento = document.getElementById(elemento);
    }
    if (elemento != null) {
        elemento.setAttribute(atributo,valor);
    }
}


function diasDelMes(mes, ano) {
    //Espera los meses en un rango del 1 al 12
	return 32 - new Date(ano, mes -1, 32).getDate();
}


function actualizarSelect(select, contenido) {
    //Espera una lista de diccionarios del tipo [{'texto': xx, 'value': yy', 'selected': bool}]
    if (typeof select == 'string') {
        select = document.getElementById(select);
    }
    select.innerHTML = "";
    var opt = "";
    var opt_txt = "";
    for(var i = 0; i < contenido.length; i++) {
        opt = document.createElement("option");
        opt_txt = document.createTextNode(contenido[i]['texto']);
		opt.appendChild(opt_txt);
		opt.setAttribute("value", contenido[i]['value']);
		if (contenido[i]['selected']) {
		    opt.setAttribute("selected", "selected");
		}
		select.appendChild(opt);
	}
}


function actualizarSelectDias(idSelect, dias) {
    //Actualiza las opciones de un select al numero de dias que se pasan
    //Si el dia elegido previamente esta fuera de rango, elige el ultimo dia del rango
    var select = document.getElementById(idSelect);
    var elegido = select.value;
    var opciones = [];
    for (var i=0; i<dias; i++){
        opciones.push({'texto': i + 1, 'value': i + 1});
    }
    actualizarSelect(idSelect, opciones);
    if(elegido <= dias){
        select.value = elegido;
    } else {
        select.value = dias;
    }
}


function expandirDatos(boton, id) {
    //Para las cajas de datos (edicion de perfil, etc)
    boton.src = "/images/boton_bajar.png";
    boton.onclick = function() {contraerDatos(boton, id); return false;};
    document.getElementById(id).style.display = "block";
    //$("#" + id).slideToggle("slow");
}


function contraerDatos(boton, id) {
    //Para las cajas de datos (edicion de perfil, etc)
    boton.src = "/images/boton_derecha.png";
    boton.onclick = function() {expandirDatos(boton, id); return false;};
    document.getElementById(id).style.display = "none";
    //$("#" + id).slideToggle("slow");
}


function intercambiarHTML(id1, id2) {
    var temp = document.getElementById(id1).innerHTML;
    document.getElementById(id1).innerHTML = document.getElementById(id2).innerHTML;
    document.getElementById(id2).innerHTML = temp;    
}


function minimizarNotificaciones() {
    var boton = document.getElementById('botonInteriorNotificaciones');
    boton.src = "/images/boton_bajar.png";
    boton.onclick = function() {maximizarNotificaciones();};
    
    $("#contenidoNotificaciones").slideToggle(500, function(){
        $("#interiorNotificaciones").animate({
            width: "100px"
        }, 500 );});
    
    /*
    $("#contenidoNotificaciones").slideToggle(1500);
    */
}


function maximizarNotificaciones() {
    var boton = document.getElementById('botonInteriorNotificaciones');
    boton.src = "/images/boton_subir.png";
    boton.onclick = function() {minimizarNotificaciones();};
    
    $("#interiorNotificaciones").animate({
        width: "400px"
    }, 500, null, function() {
        $("#contenidoNotificaciones").slideToggle(500);});
    /*
    $("#contenidoNotificaciones").slideToggle(1500);
    */
}


function swapBuscadorSuperior(opcion) {
    if (opcion.value == 'eventos') {
        ocultar('buscadorSuperiorUsuarios');
        mostrar('buscadorSuperiorEventos');
    } else if (opcion.value == 'usuarios') {
        ocultar('buscadorSuperiorEventos');
        mostrar('buscadorSuperiorUsuarios');
    }
}

/*prueba de concepto para futuras transiciones de estilos*/
/*transita el color de fondo de un elemento, de un color a otro en unos pasos definidos durante un tiempo definido*/
function colorear(elementoId, rgbInicial, rgbFinal, pasos, duracionMs) {
    for (paso=0;paso<=pasos;paso++){
        setTimeout("document.getElementById('" + elementoId + "').style.backgroundColor = 'rgb(" + Math.floor(rgbInicial[0]+(rgbFinal[0]-rgbInicial[0])*paso/pasos) + "," + Math.floor(rgbInicial[1]+(rgbFinal[1]-rgbInicial[1])*paso/pasos) + "," + Math.floor(rgbInicial[2]+(rgbFinal[2]-rgbInicial[2])*paso/pasos) + ")'", duracionMs/pasos * paso);
    }
}


function mensajeRecordarme(input) {
    if (input.checked && alertaSesionEterna) {
        alertaSesionEterna = false;
        if (confirm('¿Estás seguro/a de que quieres que se te recuerde en este equipo?\n Si hay más personas con acceso a este equipo, recomendamos encarecidamente NO marcar la casilla')) {
            return;
        } else {
            input.checked = false;
        }
    } else {
        return;
    }
}
