/*
Biblioteca iDesk de Funcionalidades jQuery
*/

/*********************************************************
 * CONFIGURAÇOES INICIAIS
 *********************************************************/

//INÍCIO - FillSelect
$.fn.clearSelect = function() {
    return this.each(function() {
        if (this.tagName == 'SELECT')
            this.options.length = 0;
    });
}

$.fn.fillSelect = function(data) {
    return this.clearSelect().each(function() {
        if (this.tagName == 'SELECT')
        {
            var dropdownList = this;
            $.each(data, function(index, optionData) {
                var option = new Option(optionData.Text, optionData.Value);

                if ($.browser.msie)
                {
                    dropdownList.add(option);
                }
                else
                {
                    dropdownList.add(option, null);
                }
            });
        }
    });
}
//FIM - FillSelect

/*********************************************************
 * ROTINAS DE VALIDAÇÃO
 *********************************************************/

function validaCPF(value, element) {

    if (value != "___.___.___-__")
    {
        var cpf = value.replace(/\D/g, "");

        if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
            return false;
        add = 0;
        for (i = 0; i < 9; i++)
            add += parseInt(cpf.charAt(i)) * (10 - i);
        rev = 11 - (add % 11);
        if (rev == 10 || rev == 11)
            rev = 0;
        if (rev != parseInt(cpf.charAt(9)))
            return false;
        add = 0;
        for (i = 0; i < 10; i++)
            add += parseInt(cpf.charAt(i)) * (11 - i);
        rev = 11 - (add % 11);
        if (rev == 10 || rev == 11)
            rev = 0;
        if (rev != parseInt(cpf.charAt(10)))
            return false;

        return true;
    }
}

function validaCNPJ(value, element)
{
    var cnpj = value.replace(/\D/g,"");
    
    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
    
    digitos_iguais = 1;
    if (cnpj.length < 14 && cnpj.length < 15)
        return false;
    for (i = 0; i < cnpj.length - 1; i++)
        if (cnpj.charAt(i) != cnpj.charAt(i + 1))
        {
            digitos_iguais = 0;
            break;
        }
    if (!digitos_iguais)
    {
        tamanho = cnpj.length - 2
        numeros = cnpj.substring(0,tamanho);
        digitos = cnpj.substring(tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--)
        {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                pos = 9;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        
        if (resultado != digitos.charAt(0))
              return false;
              
        tamanho = tamanho + 1;
        numeros = cnpj.substring(0,tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--)
        {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                pos = 9;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1))
              return false;

        return true;
    }
    else
        return false;
} 

function validaData(value, element)
{
  var expReg = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/(19|20)?\d{2}$/;
  var aRet = true;
  if (value.match(expReg) && (value != ''))
  {
      var dia = value.substring(0, 2);
      var mes = value.substring(3, 5);
      var ano = value.substring(6, 10);
      if ((mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia > 30)
          aRet = false;
      else
          if ((ano % 4) != 0 && mes == 2 && dia > 28)
          aRet = false;
      else
          if ((ano % 4) == 0 && mes == 2 && dia > 29)
          aRet = false;
  }
  else if (value == '__/__/____' || value == "")
      aRet = true;
  else
      aRet = false;  
        
  return aRet;
}

function validaDuracaoMultiplo5(value, element){
    return this.optional(element) || (value % 5 == 0);
}

function validaDuracaoRange(value, element){
    if (value > 240)
        return false;
    else if (value < 0)
        return false;
    else
        return true        
}


$.validator.addMethod("cpf",validaCPF,"CPF Inválido");
$.validator.addMethod("cnpj",validaCNPJ,"CNPJ Inválido");
$.validator.addMethod("data",validaData,"Data Inválida");
$.validator.addMethod("duracaoMultiplo", validaDuracaoMultiplo5, "<br />DURAÇÃO deve ser múltipla de 5 (5, 10, 15, 20, 25 etc.)" );
$.validator.addMethod("duracaoRange", validaDuracaoRange, "DURAÇÃO deve ser maior ou igual a 0 e menor ou igual a 240");
$.validator.addClassRules("duracao", { duracaoMultiplo: true, duracaoRange: true });  
   
   

            
            

/*********************************************************
 * ROTINAS DE USO GERAL
 *********************************************************/

//atualizaCampo: além de setar um valor, indica que o campo mudou através
//de uma animação. Utilizada para padronização da interface

//Atualiza o valor de um campo com animação
$.fn.atualizaCampo = function(valor) {
        $(this) 
            .val(valor)
            .animate({backgroundColor: "#8addff"},900)
            .animate({backgroundColor: "#ffffff"},900);
}

//Atualiza o texto de um campo com animação
$.fn.atualizaTexto = function(valor) {
    $(this) 
        .text(valor)
        .animate({backgroundColor: "#8addff"},900)
        .animate({backgroundColor: "#ffffff"},900);
}
 
//Ajusta foco com animação
$.fn.ajustaFoco = function() {
    // Animação ao colocar o foco na caixa de texto (input text) - Colocar este efeito na biblioteca
    $(this).focus(function() {
        $(this).animate({backgroundColor: "#fffdd9"},500);
    })

    // Animação ao tirar o foco da caixa de texto (input text) - Colocar este efeito na biblioteca
    $(this).blur(function() {
        $(this).animate({ backgroundColor: "#ffffff" }, 500);
    })

}

//Limpa campos de formulário
$.fn.clearForm = function() {
   
    return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input',this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};
