// JavaScript Document
// Limpa o texto do campo quando este recebe o foco
function limpaTextoCampo(campo) {
    if (campo.value == campo.defaultValue) {
        campo.value = "";
    }
}

// Restaura o texto original caso não tenha sido digitado nada
function restauraTextoCampo(campo) {
    if (campo.value == "") {
        campo.value = campo.defaultValue;
    }
}


function validaBranco(campoParam) {
    var campo = document.getElementById(campoParam);

    if (campo.value == "") {
        alert("A pergunta " + campo.name + " deve ser preenchida.");
        campo.focus();
        return false;
    }
    return true;
}
function validaBranco2(campoParam) {
    var campo = document.getElementById(campoParam);

    if (campo.value == "") {
        return false;
    }
    return true;
}

//Limita a quantidade de caracteres no text area

function ismaxlength(obj) {
    var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
    if (obj.getAttribute && obj.value.length > mlength) {
        obj.value = obj.value.substring(0, mlength);
    }
}

// Valida um URL
function validaURL(campo, mensagem) {
    campo = document.getElementById(campo);

    if (campo.value.substr(0, 7) != "http://" || campo.value.length <= 12) {
        alert("O campo " + mensagem.toUpperCase() + " não contém uma URL válida.");
        campo.focus();
        return false;
    }
    return true;
}

/*function selecionaLogin(local){
if(local.value == "Username")
local.value = "";
}*/

function selecionaLogin(local) {
    if (local.value == "Username")
        local.value = "";

    if (local.value == "Usuário")
        local.value = "";
}
/*
function tiraSelecaoLogin(local){
if(!local.value)
local.value = "Username";
}*/

function NomeUsuario(localUser, localSenha, idioma) {
    if (idioma == "en-US") {
        localUser.value = "Username";
        localSenha.value = "Password";
    }
    else {
        localUser.value = "Usuário";
        localSenha.value = "Senha";
    }
}

function tiraSelecaoLogin(local, idioma) {
    if (!local.value) {
        if (idioma == "en-US")
            local.value = "Username";
        else
            local.value = "Usuário";
    }
}

function selecionaSenha() {
    getElement("senha").style.display = "inline";
    getElement("senhaVisual").style.display = "none";
    getElement("senha").focus();
}

function tiraSelecaoSenha() {
    if (!getElement("senha").value) {
        getElement("senha").style.display = "none";
        getElement("senhaVisual").style.display = "inline";
    }
}


function getElement(id) {
    return document.getElementById(id);
}


//Limita a quantidade de caracteres no text area

function ismaxlength(obj) {
    var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
    if (obj.getAttribute && obj.value.length > mlength) {
        obj.value = obj.value.substring(0, mlength);
    }
}

function valida_email(campoform) {
    var MensIdioma = "O e-mail deve ser um endereço de e-mail válido.";
    var email = campoform.value;
    if (email) {
        p = email.indexOf('@');
        pont = email.indexOf('.');
        if (p < 1 || p == (email.length - 1) || pont < 1 || pont == (email.length - 1)) {
            alert(MensIdioma);
            campoform.value = '';
            campoform.focus();
            return false;
        } else return true;
    } else {
        alert(MensIdioma);
        campoform.value = '';
        campoform.focus();
        return false;
    }
}

function valida_tel(campo) {
    var valor = '';
    var digito = false;
    a = campo.value;
    if (a) {
        num = a.length;
        for (f = 0; f < num; f++) {
            if (parseInt(a.substr(f, 1)) || a.substr(f, 1) == '0')
                if ((a.substr(f, 1) != '0') || digito) valor = valor + '' + a.substr(f, 1);
            if (parseInt(a.substr(f, 1)) && a.substr(f, 1) != '0') digito = true;
        };
        num = valor.length;
        if (num < 9 || num > 10) {
            alert('- Número de telefone inválido. \nEntre com o DDD e o número do telefone.\nExemplo: (11) 1234-5678');
            campo.value = '';
            campo.focus();
        }
        else {
            if (num == 9) valor = '(' + valor.substr(0, 2) + ') ' + valor.substr(num - 7, 3) + '-' + valor.substr(num - 4, 4);
            if (num == 10) valor = '(' + valor.substr(0, 2) + ') ' + valor.substr(num - 8, 4) + '-' + valor.substr(num - 4, 4);
            campo.value = valor;
        }
    }
}

function valida_cep(campo) {
    var valor = '';
    a = campo.value;
    if (a) {
        num = a.length;
        for (f = 0; f < num; f++) {
            if (parseInt(a.substr(f, 1)) || a.substr(f, 1) == '0')
                valor = valor + '' + a.substr(f, 1);
        };
        num = valor.length;
        if (num != 5 && num != 8) {
            alert('- CEP inválido. \nEntre com o CEP correto.\nExemplo: 12345678');
            campo.value = '';
            campo.focus();
        }
        else {
            /*if (num == 5) valor = valor.substr(0, 2) + '.' + valor.substr(num-3, 3) + '-000';
            if (num == 8) valor = valor.substr(0, 2) + '.' + valor.substr(num-6, 3) + '-' + valor.substr(num-3, 3);
            campo.value = valor;*/
        }
    }
}

function valida_cpf(campoform) {
    num_cpf = '';
    campo = campoform.value;
    if (campo == "00000000000" || campo == "11111111111" || campo == "22222222222" || campo == "33333333333" || campo == "44444444444" || campo == "55555555555" || campo == "66666666666" || campo == "77777777777" || campo == "88888888888" || campo == "99999999999") {
        alert('- CPF inválido. \nEntre com o CPF correto.');
        campoform.value = '';
        campoform.focus();
        return false;
    }
    if (campo == "000.000.000-00" || campo == "111.111.111-11" || campo == "222.222.222-22" || campo == "333.333.333-33" || campo == "444.444.444-44" || campo == "555.555.555-55" || campo == "666.666.666-66" || campo == "777.777.777-77" || campo == "888.888.888-88" || campo == "999.999.999-99") {
        alert('- CPF inválido. \nEntre com o CPF correto.');
        campoform.value = '';
        campoform.focus();
        return false;
    }
    if (!campo) return true;
    for (i = 0; i < campo.length; i++) {
        resposta = campo.charAt(i);
        num = parseFloat(resposta);
        if (resposta == '' + num) num_cpf = num_cpf + resposta;
    }
    if (num_cpf.length == 11) {
        soma = 0;
        for (i = 0; i < 9; i++) soma += parseInt(num_cpf.charAt(i)) * (10 - i);
        resto = 11 - (soma % 11);
        if (resto == 10 || resto == 11) resto = 0;
        soma = 0;
        for (i = 0; i < 10; i++) soma += parseInt(num_cpf.charAt(i)) * (11 - i);
        resto2 = 11 - (soma % 11);
        if (resto2 == 10 || resto2 == 11) resto2 = 0;
        if ((resto != parseInt(num_cpf.charAt(9))) || (resto2 != parseInt(num_cpf.charAt(10)))) {
            alert('- CPF inválido. \nEntre com o CPF correto.');
            campoform.value = '';
            campoform.focus();
            return false;
        } else {
            campoform.value = num_cpf.substring(0, 3) + '.' + num_cpf.substring(3, 6) + '.'
			+ num_cpf.substring(6, 9) + '-' + num_cpf.substring(9, 11);
            return true;
        }
    } else {
        alert('- CPF inválido. \nEntre com o CPF correto.');
        campoform.value = '';
        campoform.focus();
        return false;
    }
}

function convertCPF(num_cpf) {
    if (num_cpf.length < 12 && isNumber(num_cpf)) {
        while (num_cpf.length < 11) {
            num_cpf = "0" + num_cpf;
            //alert(11-num_cpf.length + " - " + num_cpf);
        }
        num_cpf = num_cpf.substring(0, 3) + '.' + num_cpf.substring(3, 6) + '.' + num_cpf.substring(6, 9) + '-' + num_cpf.substring(9, 11);
    }
    return num_cpf;
}

function convertData(a) {
    var valor = a.value;
    if (valor.indexOf("/") == -1) {
        if (valor.length > 2 && valor.length < 5)
            a.value = valor.substr(0, 2) + "/" + valor.substr(2, 1);
    }
    if (valor.lastIndexOf("/") < 5) {
        if (valor.length > 5)
            a.value = valor.substr(0, 5) + "/" + valor.substr(5, 1);
    }
    if (valor.length > 10)
        a.value = valor.substr(0, 10);
}

function isNumber(x) {
    var anum = /(^\d+$)|(^\d+\.\d+$)/;
    if (anum.test(x)) testresult = true;
    else testresult = false;
    return (testresult);
}


function validaData(objData) {
    var data = objData.value.toString();
    var dia = data.substr(0, 2);
    var mes = data.substr(3, 2);
    var ano = data.substr(6, 4);
    var erro = "";
    if (isNumber(dia) && isNumber(mes) && isNumber(ano) && data.length == 10) {
        try {
            dia = parseInt(dia);
            mes = parseInt(mes);
            ano = parseInt(ano);
            dataAtual = new Date();
            anoAtual = dataAtual.getFullYear();
            if (dia > 31) erro += "\n- Foi digitado um número maior que 31 para dia.";
            if (mes > 12) erro += "\n- Foi colocado um número maior que 12 para mês.";
            if (ano > (anoAtual + 50) || ano < (anoAtual - 120)) erro += "\n- O ano foi digitado incorretamente";
            if (dia == 29 && mes == 2 && !anoBissesto(ano)) erro += "\n- O ano digitado não é bissesto para ter 29 dias";
            if (dia > 29 && mes == 2) erro += "\n- O mês de fevereiro não tem mais de 29 dias.";
            if ((dia > 30 && mes == 4) || (dia > 30 && mes == 6) || (dia > 30 && mes == 4) || (dia > 30 && mes == 6) || (dia > 30 && mes == 9) || (dia > 30 && mes == 11)) erro += "\n- O mês de digitado possui no máximo 30 dias.";
            if ((dia > 31 && mes == 1) || (dia > 31 && mes == 3) || (dia > 31 && mes == 5) || (dia > 31 && mes == 7) || (dia > 31 && mes == 8) || (dia > 31 && mes == 10) || (dia > 31 && mes == 12)) erro += "\n- O mês de digitado possui no máximo 31 dias.";
        } catch (e) {
            erro += "\n- Foi digitado um caracter não-numérico na data.";
        }
    } else {
        erro += "\n- Foi digitado um caracter não-numérico na data.";
    }
    if (erro) {
        //alert("Data Inválida:\n" + erro);
        //objData.value = "";
        objData.focus();
        return false;
    }

    return true;
}

function validaLogin(form) {
    var login = document.getElementById('log').value;
    var senha = document.getElementById('senha').value;

    if ((login != null && login != "Username" && login != "Usuario") && (senha != null && senha != ""))
        form.submit();

    return false;
}

function validaPesquisa(form, idioma) {
    var pesquisa = document.getElementById('pesquisa').value;

    if (pesquisa != null && pesquisa != "") {
        var opcoesPesquisa = document.getElementsByName("opcaoPesquisa");
        var opcaoPesquisaSelecionada = false;

        for (var i = 0; i < opcoesPesquisa.length; i++) {
            if(opcoesPesquisa.item(i).checked)
                opcaoPesquisaSelecionada = true;
        }

        if (opcaoPesquisaSelecionada) {
            if (pesquisa.length < 3) {
                if (idioma == "en-US")
                    alert("The search must contain at least three (3) characters");
                else
                    alert("A pesquisa deve conter pelo menos três(3) caracteres");
            }
            else
                form.submit();
        }
        else {
            if (idioma == "en-US")
                alert("Please select one of the options available: Current Issue or Previous Editions");
            else
                if (idioma == "pt-BR")
                    alert("Por favor selecione uma das opcões disponíveis: Número Atual ou Edicões Anteriores");
        }
    }
    else {
        if (idioma == "en-US")
            alert("Write the content of your search.");
        else
            alert("Escreva o conteúdo de sua busca.");
    }

    return false;
}

function anoBissesto(ano) {
    if ((((ano % 4) == 0 && (ano % 100) != 0) || (ano % 400) == 0))
        return true;
    else
        return false;
}

function SetOption(option, idioma) {

    document.getElementById("option").value = option;

    switch (option) {
        case 1:

            var textAutores = document.getElementById('textAutores').value;
            if (textAutores.length < 3) {
                showMessageCaracters(idioma);
                return false;
            }

            break;
        case 3:

            var textFrasesNoConteudo = document.getElementById('textFrasesNoConteudo').value;
            if (textFrasesNoConteudo.length < 3) {
                showMessageCaracters(idioma);
                return false;
            }
            break;
        case 4:

            var textFrasesNoTitulo = document.getElementById('textFrasesNoTitulo').value;
            if (textFrasesNoTitulo.length < 3) {
                showMessageCaracters(idioma);
                return false;
            }
            break;
        case 6:

            var listBox = document.getElementById('idDescritor');

            var contSelecionados = 0;
            for (var i = 0; i < listBox.options.length; i++) {
                if (listBox.options[i].selected)
                    contSelecionados++;
            }

            if (contSelecionados == 0) {
                if (idioma == "en-US")
                    alert("Please, select at least one keyword.");
                else
                    alert("Por favor, selecione pelo menos uma palavra-chave.");
                return false;
            }

            break;
    }

    return true;
}

function showMessageCaracters(idioma) {
    if (idioma == "en-US") {
        alert("Please enter at least three characters.");
    }
    else {
        if (idioma == "pt-BR") {
            alert("Por favor digite pelo menos três caracteres.");
        }
    }
}

function validDate(idioma) {
    var regex = /^\d{2}\/\d{2}\/\d{4}$/;
    var dtInicial = document.getElementById("dtInicial").value;
    var dtFinal = document.getElementById("dtFinal").value;
    var now = new Date();

    if (!validaData(document.getElementById("dtInicial"))) {
        if (idioma == "en-US")
            alert("The start date is invalid.");
        else
            alert("A data inicial é inválida.");

        return false;
    }

    if (!validaData(document.getElementById("dtFinal"))) {
        if (idioma == "en-US")
            alert("The end date is invalid.");
        else
            alert("A data final é inválida.");

        return false;
    }
    
    var splitInicial = dtInicial.split('/');
    var nowInicial = new Date(splitInicial[2], splitInicial[1]-1, splitInicial[0]);

    var splitFinal = dtFinal.split('/');
    var nowFinal = new Date(splitFinal[2], splitFinal[1]-1, splitFinal[0]);

    if (nowInicial > nowFinal) {
        if (idioma == "en-US")
            alert("The start date can not be larger than the final date.");
        else
            alert("A data inicial não pode ser maior que a data final.");

        return false;
    }
    
    if ((nowFinal.getTime() > now.getTime()) || (nowInicial.getTime() > now.getTime())) {
        if (idioma == "en-US")
            alert("Some dates may be higher than typed today's date.");
        else
            alert("Alguma das datas digitadas pode estar maior que a data atual.");

        return false;
    }

    return true;
}

// jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
// http://jquery.thewikies.com/swfobject
(function (f, h, i) { function k(a, c) { var b = (a[0] || 0) - (c[0] || 0); return b > 0 || !b && a.length > 0 && k(a.slice(1), c.slice(1)) } function l(a) { if (typeof a != g) return a; var c = [], b = ""; for (var d in a) { b = typeof a[d] == g ? l(a[d]) : [d, m ? encodeURI(a[d]) : a[d]].join("="); c.push(b) } return c.join("&") } function n(a) { var c = []; for (var b in a) a[b] && c.push([b, '="', a[b], '"'].join("")); return c.join(" ") } function o(a) { var c = []; for (var b in a) c.push(['<param name="', b, '" value="', l(a[b]), '" />'].join("")); return c.join("") } var g = "object", m = true; try { var j = i.description || function () { return (new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version") } () } catch (p) { j = "Unavailable" } var e = j.match(/\d+/g) || [0]; f[h] = { available: e[0] > 0, activeX: i && !i.name, version: { original: j, array: e, string: e.join("."), major: parseInt(e[0], 10) || 0, minor: parseInt(e[1], 10) || 0, release: parseInt(e[2], 10) || 0 }, hasVersion: function (a) { a = /string|number/.test(typeof a) ? a.toString().split(".") : /object/.test(typeof a) ? [a.major, a.minor] : a || [0, 0]; return k(e, a) }, encodeParams: true, expressInstall: "expressInstall.swf", expressInstallIsActive: false, create: function (a) { if (!a.swf || this.expressInstallIsActive || !this.available && !a.hasVersionFail) return false; if (!this.hasVersion(a.hasVersion || 1)) { this.expressInstallIsActive = true; if (typeof a.hasVersionFail == "function") if (!a.hasVersionFail.apply(a)) return false; a = { swf: a.expressInstall || this.expressInstall, height: 137, width: 214, flashvars: { MMredirectURL: location.href, MMplayerType: this.activeX ? "ActiveX" : "PlugIn", MMdoctitle: document.title.slice(0, 47) + " - Flash Player Installation"}} } attrs = { data: a.swf, type: "application/x-shockwave-flash", id: a.id || "flash_" + Math.floor(Math.random() * 999999999), width: a.width || 320, height: a.height || 180, style: a.style || "" }; m = typeof a.useEncode !== "undefined" ? a.useEncode : this.encodeParams; a.movie = a.swf; a.wmode = a.wmode || "opaque"; delete a.fallback; delete a.hasVersion; delete a.hasVersionFail; delete a.height; delete a.id; delete a.swf; delete a.useEncode; delete a.width; var c = document.createElement("div"); c.innerHTML = ["<object ", n(attrs), ">", o(a), "</object>"].join(""); return c.firstChild } }; f.fn[h] = function (a) { var c = this.find(g).andSelf().filter(g); /string|object/.test(typeof a) && this.each(function () { var b = f(this), d; a = typeof a == g ? a : { swf: a }; a.fallback = this; if (d = f[h].create(a)) { b.children().remove(); b.html(d) } }); typeof a == "function" && c.each(function () { var b = this; b.jsInteractionTimeoutMs = b.jsInteractionTimeoutMs || 0; if (b.jsInteractionTimeoutMs < 660) b.clientWidth || b.clientHeight ? a.call(b) : setTimeout(function () { f(b)[h](a) }, b.jsInteractionTimeoutMs + 66) }); return c } })(jQuery, "flash", navigator.plugins["Shockwave Flash"] || window.ActiveXObject);
