jQuery(document).ready(function(){

    jQuery("#sair").mouseover(function(){
        jQuery("#sair").css("height","47px");
    });

    jQuery("#sair").mouseout(function(){
        jQuery("#sair").css("height","50px");
    });

    alertas();
    
    mascaras();
});

function mascaras() {
    jQuery("#cnpj").mask("99.999.999/9999-99");
    jQuery("#cpf").mask("999.999.999-99");
    jQuery("#cep").mask("99999-999");
    jQuery("#celular, #telefone").mask("(99) 9999-9999");
    jQuery("#data_nascimento").mask("99/99/9999").datepicker({
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true,
        showOn: 'button',
        buttonImage: '../imagens/date.png',
        buttonImageOnly: true
    });

}

function post(URL, PARAMS) {
    var temp=document.createElement("form");
    temp.action=URL;
    temp.method="POST";
    temp.style.display="none";
    for(var x in PARAMS) {
        var opt=document.createElement("textarea");
        opt.name=x;
        opt.value=PARAMS[x];
        temp.appendChild(opt);
    }
    document.body.appendChild(temp);
    temp.submit();
    return temp;
}

function esconderLegenda() {
    jQuery('#legenda').slideUp(300);
    jQuery.ajax({
        type        : "POST",
        url         : "../no_help.php"
    });
}

function alertas()
{
    var html = "";
    html += "<div id=\"alert\" onclick=\"hidealert()\"></div>";
    jQuery("body").append(html);
}

function alertErro(msg) {
    jQuery("#alert").css("background-color", "#AA0000");

    var erro = '<img src="../imagens/error.png" align="left" />';

    jQuery("#alert").html(erro + msg);
    jQuery("#alert").fadeIn(300);
    setTimeout("hidealert()", 5000);
}

function alertSucesso(msg){
    jQuery("#alert").css("background-color", "#006600");
    jQuery("#alert").html(msg);
    jQuery("#alert").fadeIn(300);
    setTimeout("hidealert()", 5000);
}

function testarFormSenha() {
    if (!testarCampoVazio("antiga_senha", "Favor preencher a senha antiga.")) return false;
    if (!testarCampoVazio("nova_senha", "Favor preencher a nova senha.")) return false;
    if (!testarCampoVazio("confirmacao_senha", "Favor preencher a confirmação da senha.")) return false;

    if (jQuery("#nova_senha").val() == jQuery("#confirmacao_senha").val()) {
        jQuery("#formSenha").submit();
        return true;
    } else {
        alertErro("Confirmação de senha inválida!");
        return false;
    }
}

/**
 *  Função faz máscara para CPF ou CNPJ dependendo do valor informado
 *  caso a quantidade de caracteres não se enquadre em um cpf ou cnpj a função
 *  dispara uma exceção e apaga o camp.
 *  @param objeto Valor a ser formatado.
 *  @return cpf ou cnpj
 *  @throws Quantidade de caracteres inválida!
 *  @example makemask(00011133344) => 000.111.333-44
 **/
function makemask(objeto){

    var cpfcnpj = objeto.value;
    var novo = cpfcnpj;
    if (cpfcnpj.length==11){
        novo = cpfcnpj.substr(0, 3)+"."+cpfcnpj.substr(3, 3)+"."+cpfcnpj.substr(6, 3)+"-"+cpfcnpj.substr(9, 2);
    }else if (cpfcnpj.length==14){
        if (cpfcnpj.substr(3, 1)!=".")
            novo = cpfcnpj.substr(0, 2)+"."+cpfcnpj.substr(2, 3)+"."+cpfcnpj.substr(5, 3)+"/"+cpfcnpj.substr(8, 4)+"-"+cpfcnpj.substr(12, 2);
    }

    if ((novo.length!= 14) && (novo.length!= 18)){
        alertErro("Quantidade de caracteres inválida!");
        jQuery("#"+objeto.id).val("");
    }else {
        jQuery("#"+objeto.id).val(novo);
    }
}

/**
 *  Esconder o alert
 **/
function hidealert(){
    jQuery("#alert").fadeOut(300);
}

/**
 *  Função para verificar se está sendo clicando na tecla ENTER
 *  @param e Event
 *  @param fn Function callback
 *  @example onkeyup="enterPress(event, "enviarFormulario");"
 */
function enterPress(e, fn)
{
    var key = e.keyCode||e.charCode;
    if (key == 13) {
        fn.call();
    }
}

function mudarTAcesso(valor) {
    jQuery("#tAcesso").html((valor==1) ? "Email:" : "Matr&iacute;cula:");

}

/**
 *  Verifica se o arquivo enviado é uma imagem através da extensão do arquivo.
 *  @param obj Object
 *  @return boolean
 */
function isImage(obj) {
    if (obj.value != "") {
        var extensoes_permitidas = new Array(".gif", ".jpg", ".png");
        var msg = "";

        var extensao = (obj.value.substring(obj.value.lastIndexOf("."))).toLowerCase();
        var permitida = false;
        for (var i = 0; i < extensoes_permitidas.length; i++) {
            if (extensoes_permitidas[i] == extensao) {
                permitida = true;
                break;
            }
        }

        if (!permitida) {
            msg = "S&oacute; &eacute; poss&iacute;vel enviar arquivos com extens&otilde;es: " + extensoes_permitidas.join();
            alertErro(msg);
            return false;
        }else{
            return true;
        }
    }
    return false;
}

function relatorio(modulo){
    var tipo = 'pdf';
    for (var i=1;i<=4;i++){
        if (jQuery("#tiporelatorio"+i).attr("checked")==true){
            tipo = jQuery("#tiporelatorio"+i).val();
            break;
        }
    }

    var relatorio = '1';
    for (var y=1;y<=10;y++){
        if (jQuery("#relatorio"+y).attr("checked")==true){
            relatorio = jQuery("#relatorio"+y).val();
            break;
        }
    }

    var filtros = "action=relatorio";
    filtros += "&tipo="+tipo;
    filtros += "&relatorio="+relatorio;
    filtros += "&tipofiltro1="+jQuery("#tipofiltro1").val();
    filtros += "&tipofiltro2="+jQuery("#tipofiltro2").val();

    var url = modulo+"?"+filtros;
    popupWindow(url, "relatorio", 800, 600);
}

function changeStylesheet(stylesheet){
    jQuery.ajax({
        type        : "POST",
        url         : "../control/ColaboradorCtrl.php",
        data        : "action=mudarEstilo&stylesheet="+stylesheet,
        dataType    : "text",
        beforeSend : function(){
            jQuery("#overlay").show();

            jQuery("#stylesheetLayout").attr("href", "../css/layout/layout"+stylesheet+".css");
            jQuery("#stylesheetStyle").attr("href", "../css/style/style"+stylesheet+".css");
            jQuery("#stylesheetMenu").attr("href", "../css/menu/menu"+stylesheet+".css");
            jQuery("#miliseconds").attr("src", "../imagens/miliseconds"+(stylesheet==4 ? '4' : '')+".png");
        },
        success: function(text){
            jQuery("#overlay").hide();
            if (text!=1) {
                alertErro("Ocorreu um erro ao tentar salvar o seu estilo.<br />Favor tentar novamente.");
            }
        },
        complete : function () {
            jQuery("#overlay").hide();
        },
        error : function (){
            alertErro("Não possivel salvar sua escolha de estilo.<br />Favor escolher novamente.");
        }
    });
}

function pesquisarCep(cep, load)
{
    var cepValue = jQuery("#"+cep).val();

    var parametros = "cep="+cepValue;
    jQuery.ajax({
        type : "POST",
        url : "../CepServiceServlet",
        data : parametros,
        dataType : "xml",
        beforeSend : function (){
            jQuery("#"+load).html('<img src="../imagens/loading.gif" />');
        },
        complete : function (){
            jQuery("#"+load).empty();
        },
        success: function(xml){

            jQuery(xml).find("service").each(function(){
                var tipo = jQuery(this).find("tipo_logradouro").text();
                var logradouro = jQuery(this).find("logradouro").text();
                var bairro = jQuery(this).find("bairro").text();
                var cidade = jQuery(this).find("cidade").text();
                var estado = jQuery(this).find("estado").text();

                jQuery("#endereco").val(tipo + " " + logradouro);
                jQuery("#bairro").val(bairro);
                jQuery("#cidade").val(cidade);
                jQuery("#estado").val(estado);
            });

        },
        error : function (){
            alertErro("Erro ao processar a informação");
            jQuery("#endereco, #bairro, #cidade, #estado").val("");
        }
    });
}

function menorQue(objeto, limit){

    if (parseFloat(objeto.value) > limit){
        alertErro("Favor informar um valor menor ou igual a "+limit);
        objeto.value = 0;
    }
}

function restConfirm()
{
    if (confirm('Deseja realmente remover todo conteúdo da caixa de texto?'))
        return true;
    return false;
}

function deleteConfirm()
{
    if (confirm('Deseja realmente excluir esse registro?'))
        return true;
    return false;
}

function newConfirm()
{
    if (confirm('Deseja realmente iniciar um novo registro?'))
        return true;
    return false;
}

function cancelarConfirm(){
    if (confirm('Deseja realmente cancelar a edição desse registro?'))
        return true;
    return false;
}

function popupWindow(url, janela, largura, altura)
{
    var top = (screen.height-(altura + 110))/2;
    var left = (screen.width-largura)/2;

    var parametros = 'width='+ largura +',height='+ altura +',scrollbars=1,resizable=1,left=' + left  + ',screenX=' + left + ',top=' + top  + ',screenY=' + top + ',menubar=1,toolbar=1';
    window.open(url, janela, parametros).focus();
}

function windowLocation(url)
{
    window.location = url;
}

function setaAction(seta)
{
    jQuery("#seta"+seta).attr("src", "../imagens/portal/setaAction.gif");
}

function setaNoAction(seta)
{
    jQuery("#seta"+seta).attr("src", "../imagens/portal/setaNoAction.gif");
}

function blocTexto(obj, maxChar)
{
    var total = obj.value.length;
    if(total <= maxChar){
        var resto = maxChar - total;
        jQuery("#cont").html(resto);
    }else{
        obj.value = obj.value.substr(0,maxChar);
    }
}

function verificarSenha(senha1, senha2)
{
    senha1 = senha1.trim();
    senha2 = senha2.trim();

    if ( (senha2 == senha1) && (!empty(senha2)) ){
        return true;
    }else{
        alertErro("Senhas de valores incompatíveis!");
        return false;
    }
}

function isEmpty(campo, titulo){
    if (empty(jQuery("#"+campo).val())){
        alertErro("Favor preencha o campo "+titulo+".");
        jQuery("#"+campo).focus();
        return true;
    }
    return false;
}

function onlyNumber(obj)
{
    var er = /\D/g;
    obj.value = obj.value.replace(er, "");
}


function setZeroIfNull(obj)
{
    var vl = obj.value;
    vl = vl.trim();
    if (vl == "")
        obj.value = 0;
}

function setOneIfNull(obj) {
    var vl = obj.value;
    vl = vl.trim();
    if ((vl == "") || (vl == "0"))
        obj.value = 1;
}

// FUNCTION TRIM
String.prototype.trim = function()
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

/**
 *  Passa o dinheiro para o formato de Float
 *  @paramn money String
 *  @return Float
 **/
function moneyToFloat(money)
{
    var tam = money.length;
    for(var i=0;i<tam;i++) money = money.replace(".", "");
    money = money.replace("R$ ","").replace(",",".");
    return parseFloat(money);
}

// funç?o apra formtar dinheiro apenas de entrada direta via javascript
Number.prototype.formatMoney = function(c, d, t){ //Serve para formatar um number em formato dinheiro
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t,
    i = parseInt(n = (+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
    + (c ? d + (n - i).toFixed(c).slice(2) : "");
};

/**
 *  Função para testar se campo está vazio ou não.
 *  @return boolean
 **/
function empty(valor)
{
    valor = valor.trim();
    return (valor=="") ? true : false;
}

/**
 *  Função para teste do campo igual a vazio. Em caso de campo vazio será emitido
 *  uma mensagem para o span definido por id no parametro erro.
 *  @paramn obj Objeto XHTML que deseja testar
 *  @paramn erro Span onde será mostrado o erro
 **/
function testarCampoVazio(obj, msg)
{
    if(!msg)msg = "Esse campo n&atilde;o pode estar vazio.";
    obj = "#"+obj;

    if ( empty(jQuery(obj).val()) ){
        alertErro(msg);
        jQuery(obj).focus();
        return false;
    }
    return true;
}

/**
 *  Função para teste do campo igual a vazio. Em caso de campo vazio será emitido
 *  uma mensagem para o span definido por id no parametro erro.
 *  @paramn obj Objeto XHTML que deseja testar
 *  @paramn erro Span onde será mostrado o erro
 **/
function testarCampoData(obj, msg)
{
    if(!msg)msg = "Esse campo n&atilde;o pode estar vazio.";
    obj = "#"+obj;

    if ( empty(jQuery(obj).val()) ){
        alertErro(msg);
        jQuery(obj).focus();
        return false;
    }

    if (validaData(jQuery(obj).val())!=""){
        alertErro("Data inválida.");
        jQuery(obj).focus();
        return false;
    }
    return true;
}

// VALIDAR CPF
function validaCPF(s){

    var i;

    // DESFORMATANDO CPF;
    s = s.replace('.','');
    s = s.replace('.','');
    s = s.replace('.','');
    s = s.replace('-','');

    var c = s.substr(0,9);
    var dv = s.substr(9,2);

    var d1 = 0;

    for (i = 0; i < 9; i++){
        d1 += c.charAt(i)*(10-i);
    }

    if (d1 == 0){
        return false;
    }

    d1 = 11 - (d1 % 11);

    if (d1 > 9)
        d1 = 0;

    if (dv.charAt(0) != d1){
        return false;
    }


    d1 *= 2;

    for (i = 0; i < 9; i++){
        d1 += c.charAt(i)*(11-i);
    }

    d1 = 11 - (d1 % 11);

    if (d1 > 9)
        d1 = 0;

    if (dv.charAt(1) != d1){
        return false;
    }

    return true;

}


// >> begin FUNCTION CNPJ

function isNUMB(c)
{
    if((cx=c.indexOf(","))!=-1) {
        c = c.substring(0,cx)+"."+c.substring(cx+1);
    }
    if((parseFloat(c) / c != 1)) {
        if(parseFloat(c) * c == 0) {
            return(1);
        } else {
            return(0);
        }
    } else {
        return(1);
    }
}

function LIMP(c)
{
    while((cx=c.indexOf("-"))!=-1) {
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf("/"))!=-1) {
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf(","))!=-1) {
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf("."))!=-1) {
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf("("))!=-1) {
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf(")"))!=-1) {
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf(" "))!=-1) {
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    return(c);
}

function validaCPNJ(CNPJ)
{
    CNPJ = LIMP(CNPJ);
    if(isNUMB(CNPJ) != 1) {
        return(0);
    } else {
        if(CNPJ == 0) {
            return(0);
        } else {
            g=CNPJ.length-2;
            if(RealTestaCNPJ(CNPJ,g) == 1) {
                g=CNPJ.length-1;
                if(RealTestaCNPJ(CNPJ,g) == 1) {
                    return(1);
                } else {
                    return(0);
                }
            } else {
                return(0);
            }
        }
    }
}
function RealTestaCNPJ(CNPJ,g)
{
    var VerCNPJ=0;
    var ind=2;
    var tam;
    for(f=g;f>0;f--) {
        VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind;
        if(ind>8) {
            ind=2;
        }else {
            ind++;
        }
    }
    VerCNPJ%=11;
    if(VerCNPJ==0 || VerCNPJ==1) {
        VerCNPJ=0;
    } else {
        VerCNPJ=11-VerCNPJ;
    }
    if(VerCNPJ!=parseInt(CNPJ.charAt(g))) {
        return(0);
    } else {
        return(1);
    }
}// se retornar 1 ok caso contrario false

// << end FUNCTION CNPJ



function validarEmail(email)
{
    var str = email;
    var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return (filter.test(str)) ? true : false;
}

function validaURL(url)
{
    var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    return (RegExp.test(url)) ? true : false;
}

function validaData(dtd)
{
    if (dtd!=''){
        var dts = new Date();
        var sdia = dts.getDate();
        var smes = dts.getMonth()+1;
        var sano = dts.getFullYear();
        var dia = dtd.substring(0,2);
        var mes = dtd.substring(3,5);
        var ano = dtd.substring(6,10);

        if (dia<=31 && dia>0){
            if (mes<=12 && mes>0) {
                if (ano<=sano){
                    if((mes==4 && dia > 30) || (mes==6 && dia > 30) || (mes==9 && dia > 30) || (mes==11 && dia > 30)) {
                        return "O mês digitado contém no máximo 30 dias.";
                    }
                    if(ano%4!=0 && mes==2 && dia>28) {
                        return "O mês digitado contém no máximo 28 dias.";
                    }
                    if(ano%4==0 && mes==2 && dia>29) {
                        return "O mês digitado contém no máximo 29 dias.";
                    }
                }
            }else {
                return "O mês deve ser maior que zero e menor que 13.";
            }
        }else {
            return "O dia deve ser maior que zero e menor que 31.";
        }
        return "";
    }
    return "";
}


/*
Descrição.: formata um campo do formulário de
acordo com a máscara informada...
Parâmetros: - objForm (o Objeto Form)
- strField (string contendo o nome do textbox)

* - sMask (mascara que define o
* formato que o dado será apresentado,
* usando o algarismo "9" para
* definir números e o símbolo "!" para
* qualquer caracter...
* - evtKeyPress (evento)
* Uso.......: <input type="textbox"
* name="xxx".....
* onkeypress="return txtBoxFormat('str_cep', '99999-999', event);">
* Observação: As máscaras podem ser representadas como os exemplos abaixo:
* CEP -> 99.999-999
* CPF -> 999.999.999-99
* CNPJ -> 99.999.999/9999-99
* Data -> 99/99/9999
* Tel Resid -> (99) 999-9999
* Tel Cel -> (99) 9999-9999
* Processo -> 99.999999999/999-99
* C/C -> 999999-!
* E por aí vai...
***/
function txtBoxFormat(strField, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

    if(document.all) { // Internet Explorer
        nTecla = evtKeyPress.keyCode;
    } else if(document.layers) { // Nestcape
        nTecla = evtKeyPress.which;
    } else {
        nTecla = evtKeyPress.which;
        if (nTecla == 8) {
            return true;
        }
    }

    sValue = jQuery("#"+strField).val();
    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    // toString().replace [transforma em sring e troca elementos por ""]
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
        bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ":") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
        bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " ") || (sMask.charAt(i) == "."))

        //Se for true utiliza elementos especiais aumenta a máscara
        if (bolMask) {
            sCod += sMask.charAt(i);
            mskLen++;
        //Caso false mostra o sValue(o q foi digitado)
        } else {
            sCod += sValue.charAt(nCount);
            nCount++;
        }
        i++;
    }

    jQuery("#"+strField).val(sCod);
    if (nTecla != 8) { // backspace
        if (sMask.charAt(i-1) == "9") { // apenas números...
            return ((nTecla > 47) && (nTecla < 58));
        } // números de 0 a 9
        else { // qualquer caracter...
            return true;
        }
    } else {
        return true;
    }
}

/**
 *  Função para converter data do formato de ISO para PtBR
 *  @param datas JSON [0] => nome do objeto [1] => valor do objeto
 */
function parseDate(datas) {

    for (var obj in datas) {
        if (datas[obj] == "") continue;

        var justData = datas[obj].toString().split(" ");
        var data = justData[0].split("-");
        jQuery("#"+obj).val(data[2]+"/"+data[1]+"/"+data[0]);
    }    
}

function writeData(isoData) {
    if (isoData == "") return;
    
    var justData = isoData.split(" ");
    var data = justData[0].split("-");
    document.write(data[2]+"/"+data[1]+"/"+data[0]);
}

function removeNL(s){
    return s.replace(/[\n\r\t]/g,"");
}


function subString(str, start, length) {
    document.write(str.substr(start, length));
}
