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 && lienzo != null){
        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 dictToGet(diccionario) {
    //Transforma un dicionario en una cadena con formato de llamada GET
    var get = '';
    for (param in diccionario){
        if(diccionario[param] != null){
            if (typeof diccionario[param] == "object") {
                for (var i=0; i<diccionario[param].length; i++) {
                    get += (get == '' ? '?' : '&') + param + '=' + encodeURIComponent(diccionario[param][i]);
                }
            } else {
                get += (get == '' ? '?' : '&') + param + '=' + encodeURIComponent(diccionario[param]);
            }
        } else {
            get += (get == '' ? '?' : '&') + param + '=' + '';
        }
    }
    return get;
}


function ajaxParam(url, parametros, lienzo, carga, fExito) {
    if (typeof lienzo == 'string') {
        lienzo = document.getElementById(lienzo);
    }
    if (typeof carga == 'string') {
        carga = document.getElementById(carga);
    }
    var fExito = (fExito != null) ? fExito : function(respuesta, lienzo){pintarLienzo(respuesta, lienzo);};
    
    var fCarga = function(lienzo){pintarLienzo('<img alt="cargando" title="cargando" src="/img/loading.gif" />', lienzo);};
    var xmlhttp = getXmlHttpObject();
    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) {
                var dict = xmlhttp.responseText;
                pintarLienzo(cargaBackup, carga);
                fExito(dict, lienzo);
            }
        }
    };
    xmlhttp.open("POST",url,true);
    xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
    //Indicamos en la peticion que se trata de una llamada AJAX
    xmlhttp.send(dictToPost(parametros));
    return false;
}

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 limpiarInput(input, texto) {
    if (input.value == texto) {
        input.value = "";
    }
}

function restaurarInput(input, texto) {
    if (input.value == "") {
        input.value = texto;
    }
}

function get_destacado(id, solicitud) {
    var args = {};
    args['data[id_actual]'] = id;
    args['data[solicitud]'] = solicitud;
    return ajaxParam('/get_destacado', args, 'articuloDestacado', 'cargaArticulo');
}

function recuperarEstilo(inmediato) {
    if (inmediato) {
        clearTimeout(_timeEstilo);
        _recuperarEstilo();
    } else {
        _timeEstilo = setTimeout("_recuperarEstilo();", 400);
    }
}

function _recuperarEstilo() {
    mostrarEstilo(_estiloActivo);
}

var _timeEstilo = '';

function mostrarEstilo(estilo) {
    clearTimeout(_timeEstilo);
    document.getElementById('contenedor').className =  estilo;
    document.getElementById('footer').className =  estilo;
}

function setEstilo(estilo, divEstilo) {
    _estiloActivo = estilo;
    document.getElementById('contenedor').className =  estilo;
    document.getElementById('footer').className =  estilo;
    recuperarEstilo(true);
    var args = {};
    args['data[estilo]'] = estilo;
    if (divEstilo) {
        document.getElementById('selectorEstilo').style.display = 'none';
        window.location = '#arriba';
    }
    var estilos = ['inspiracion', 'vitalidad', 'pasion'];
    for (var i = 0; i < estilos.length; i ++) {
         document.getElementById('menu_sup_' + estilos[i]).className = '';
    }
    document.getElementById('menu_sup_' + estilo).className = 'seleccionado';
    return ajaxParam('/set_estilo', args, '');
}

function contacto() {
    var args = {};
    var fExito = function(respuesta, lienzo) {
        document.forms['contactoLayout'].reset();
        document.getElementById('contactoFooter').innerHTML = '<h3>¡Muchas gracias por su mensaje!</h3>';
    };
    args['data[nombre]'] = document.forms['contactoLayout'].elements['nombre'].value;
    args['data[apellidos]'] = document.forms['contactoLayout'].elements['apellidos'].value;
    args['data[email]'] = document.forms['contactoLayout'].elements['email'].value;
    args['data[comentario]'] = document.forms['contactoLayout'].elements['comentario'].value;
    return ajaxParam('/contacto', args, '', 'enviarFormularioContacto', fExito);
}

