/*
================================================================================
                  BIBLIOTECA DE FUNCOES JAVASCRIPT - VEGA IT
--------------------------------------------------------------------------------
Autor: Vários
--------------------------------------------------------------------------------
Ultima Alteracao: 29/03/06             |  Autor: Rafael <rafaelc@vegait.com.br>
--------------------------------------------------------------------------------
Funcoes disponiveis:
> datediff			: retorna a diferenca entre duas datas
> validacnpj		: faz validacao de tamanho e digito verificador de CNPJ
> validacpf			: faz validacao de tamanho e digito verificador de CPF
> fmtPrice			: formata um numero em um formato especificado
> currencyFormat	: mascara para digitacao de valores monetarios
> sonumero			: garante utilizacao somente de numeros em um determinado
					  campo
> PhoneCheck		: permite utilizacao de numeros, tracos e espaco para
					  telefone
> CheckLength		: verifica quantidade de caracteres digitados num campo
> validaemail		: faz validacao de formato de email
> DateFormat		: mascara para digitacao de datas
> dateValid			: faz validacao de formato de datas
> LeapYear			: verifica se e' ano bissexto
> trim				: remove espacos no inicio e no final de uma string
> IsEmpty			: verifica se um campo ou textarea esta vazio
> ConfirmaLimpaForm : pede confirmacao sobre limpeza de formulario
> ValidaURL			: verifica se um endereco URL e valido
> MascaraHora		: cria mascara de digitacao de hora (HH:MM)
> ValidaHora		: faz validacao de formato de hora (HH:MM)
> hideElement		: oculta elementos
> showElement		: mostra elementos
> sleep				: aguarda por um numero determinado de segundos
> smnuTOut			: função que controla os submenus
> getQueryVariable	: acessa o valor de uma variavel query string
================================================================================
*/


/*
Retorna a diferença entre duas datas
per formato
*/
function datediff(per,d1,d2) {

	d1 = new Date(d1)
	d2 = new Date(d2)

	var d = (d2.getTime() - d1.getTime())/1000

	switch (per) {
		case "yyyy": d/=12
		case "m": d*=12*7/365.25
		case "ww": d/=7
		case "d": d/=24
		case "h": d/=60
		case "n": d/=60
	}
	return Math.round(d);
}


function validacnpj(field){
/*
Chamada: <input type="text" name="qualquernome" onblur="return validacnpj(this);">
*/
    if (field.value.length == 0) {
		sim=false;
	}
	else if (field.value.length != 14) {
       sim=false;
       field.select();
       field.focus();
       alert ("Tamanho Inválido de CNPJ");
    }
    else {sim=true;}
    if (sim){  // verifica se e numero
       for (i=0;((i<=(field.value.length-1))&& sim); i++){
           val=field.value.charAt(i);
           // alert (val)
           if ((val!="9")&&(val!="0")&&(val!="1")&&(val!="2")&&(val!="3")&&(val!="4") &&
              (val!="5")&&(val!="6")&&(val!="7")&&(val!="8")) {sim=false;}
       }
       if (sim){  // se for numero continua
          m2=2;
          soma1=0;
          soma2=0;
          for (i=11;i>=0;i--){
              val=eval(field.value.charAt(i));
              // alert ("Valor do Val: "+val)
              m1=m2;
              if (m2<9) {m2=m2+1;}
              else {m2=2;}
              soma1=soma1+(val*m1);
              soma2=soma2+(val*m2);
          }  // fim do for de soma
          soma1 = soma1 % 11;
          if (soma1<2) {d1=0;}
          else {d1=11-soma1;}
          soma2=(soma2+(2*d1))%11;
          if (soma2<2) {d2=0;}
          else {d2=11-soma2;}
           //alert (d1)
           //alert (d2)
          if ((d1==field.value.charAt(12))&&(d2==field.value.charAt(13))){sim=false;}
          else{
            field.select();
            field.focus();
            alert("Valor inválido de CNPJ");
          }
       }
	   else{
            field.select();
            field.focus();
			alert("Valor inválido de CNPJ");
	   }
    }
}


function validacpf(field){
/*
Chamada: <input type="text" name="qualquernome" onblur="return validacpf(this);">
*/
         var i;
         s = field.value;
         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){
            alert("CPF Invalido")
            field.select();
            field.focus();
            return false;
         }
         d1 = 11 - (d1 % 11);
         if (d1 > 9) d1 = 0;
         if (dv.charAt(0) != d1){
            alert("CPF Invalido")
            field.select();
            field.focus();
            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){
            alert("CPF Invalido")
            field.select();
            field.focus();
            return false;
         }
         return false;
}


/**
 * Formata um numero para apresentacao
 *
 * @return	string				o valor formatado
 * @param	mixed	valor:		string ou numero a ser formatado
 * @param	string	milSep:		separador de milhares
 * @param	string	decSep:		separador decimal
 */
function fmtPrice (valor, milSep, decSep)
{
	var valor		= new String (valor);	// desse modo aceita strings ou floats
	var aux			= "";

	// Divide o numero original
	arrValor		= valor.split (".");
	arrValor [0]    = parseInt (arrValor [0]);

	// Uma string vazia de origem deve ser considerada como zero
	if (!arrValor [0])
		arrValor [0]	= 0;

	// Valores inteiros tornam arrValor [1] indefinido,
	// portanto e' necessario corrigi-lo
	if (!arrValor [1])
		arrValor [1]	= "00";

	// Arredonda as decimais para duas casas
	if (arrValor [1].length > 2) {
		arrValor [1] = Math.round (arrValor [1] / Math.pow (10, arrValor [1].length - 2));

		if (parseInt (arrValor [1]) < 10)
		    arrValor [1] = "0" + arrValor [1];
 	}
 	else {
	   	if (arrValor [1].length < 2)
		    arrValor [1] = arrValor [1] + "0";
	}
	    
	if (parseInt (arrValor [1]) > 99) {
	    arrValor [1] = "00";
	    arrValor [0] += 1;
 	}

	// Aplica o separador de milhares
	num				= new String (arrValor [0]);
	
	for (i = 0; i < num.length; i++) {
		j = num.length - 1 - i;

		if ((j % 3 == 0) && (i < num.length - 1))
			aux += num.charAt (i) + milSep;
		else
			aux += num.charAt (i);
	}

	arrValor [0] = aux;

	return (arrValor.join (decSep));
}


/**
 * Realiza formatacao de valores monetarios.
 * Alteracao realizada em 11/07/2005 por Rafael <rafaelc@vegait.com.br>,
 * para permitir compatibilidade com Gecko (Firefox, Mozilla).
 * Chamada: <input onKeyPress="return (currencyFormat (this, '', '.', event))">
 *
 * @return	boolean
 *
 * @param	object		fld:	campo a ser verificado
 * @param	char		milSep:	caracter separador de milhares
 * @param	char		decSep: caracter separador de decimais
 * @param	object		e: event (usar event e nao window.event, para
 *		compatibilidade com gecko)
 * @param	boolean		negative: informa se aceita numeros negativos
 *
 */
function currencyFormat(fld, milSep, decSep, e, negative)
{
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event ? e.which : e.keyCode);
	var isNegative = false;		// indica se o numero e' negativo
	
	if (whichCode <= 31)
		return true;
	
	key = String.fromCharCode (whichCode);

	if (fld.value.indexOf('-') > -1)
		isNegative = true;

	if (negative && (key == '-')) {
		isNegative = true;
		fld.value = '-' + fld.value.replace ('-', '');
	}

	if (strCheck.indexOf(key) == -1)
		return false;
	
	len = fld.value.length;
	
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep))
			break;
	
	aux = '';
	
	for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1)
			aux += fld.value.charAt(i);
	
	aux += key;
	len = aux.length;
	
	if (len == 0)
		fld.value = '';
	
	if (len == 1)
		fld.value = '0'+ decSep + '0' + aux;
	
	if (len == 2)
		fld.value = '0'+ decSep + aux;
	
	if (len > 2) {
		aux2 = '';
		
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		
		fld.value = '';
		len2 = aux2.length;
		
		for (i = len2 - 1; i >= 0; i--)
			fld.value += aux2.charAt(i);
		
		fld.value += decSep + aux.substr(len - 2, len);
	}

	if (negative && isNegative)
		fld.value = '-' + fld.value.replace ('-', '');

	return false;
}


/**
 * Permite somente a digitacao de numeros no campo em questao.
 * Chamada: <input name="name" onKeyPress="return (sonumero (event))">
 *
 * @bugs: no firefox/win2000, as setas direcionais nao funcionam, pois sao
 *		mapeadas com o mesmo charcode das entidade 37-40. Tecla DEL tambem
 *		nao
 *
 * @param	object	e: event (usar event e nao window.event, para
 *		compatibilidade com gecko)
 */
function sonumero (e)
{
	// So aceita numeros
	expReg	= new RegExp (/^[0-9]$/);

	if (e.keyCode)
		tecla	= e.keyCode;	// internet explorer
	else
		tecla	= e.which;		// gecko

	// So aceita os digitos 0-9 e teclas especiais (TAB, ENTER, etc)
	if (expReg.test (String.fromCharCode (tecla)) || (tecla <= 31))
		return (true);
	else
		return (false);
}


// Permite so a digitacao de numeros, espaco ou traco na caixa de texto
/*
Chamada <input name="qualquernome" onKeyPress="return PhoneCheck (this, window.event)">
*/

// Autor: Rafael <rafaelc@vegait.com.br> - 18/11/2004
function PhoneCheck (myfield, e)
{
	var keycode;
    	
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;
	else
		return true;
	if (((keycode > 47) && (keycode < 58))  || 
            ((keycode == 8) || (keycode == 32) || (keycode == 45))) {
		return true;
	}
	else {	
/*
        // Removidos os dois comandos abaixo porque geram
        // problema de loop infinito de alerts quando
        // há mais de um campo utilizando a função

        field.select();
        field.focus();
*/
		return false;
	}
}


/*
Chamada: <input type="text" name="qualquernome" 
    onblur="return CheckLength(this, 'Descricao', 3, '=');">
*/

// Autor: Rafael <rafaelc@vegait.com.br> - 19/11/2004
function CheckLength (field, nomecampo, tamanho, condicao)
{
    // 'field' e o name do campo.
    // 'nomecampo' e a descricao do campo.
    // 'tamanho' e o tamanho desejado (maior que zero).
    // 'condicao' informa se e maior, menor, igual, maior ou igual,
    // menor ou igual ou diferente
    //      Valores válidos, respectivamente (usar as aspas simples):
    //          '>'
    //          '<'
    //          '=='
    //          '>='
    //          '<='
    //          '!='

    var msgErro;

    if (tamanho < 0) {
        window.alert ("[SCRIPT ERROR] Parâmetro tamanho deve ser maior ou igual a zero!");
        return (false);
    }

    switch (condicao)
    {
        case '>':
            if (field.value.length > tamanho)
                return (true);
            else
                msgErro = "tamanho maior que";
            break;
        case '<':
            if (field.value.length < tamanho)
                return (true);
            else
                msgErro = "tamanho menor que";
            break;
        case '==':
            if (field.value.length == tamanho)
                return (true);
            else
                msgErro = "tamanho igual a";
            break;
        case '>=':
            if (field.value.length >= tamanho)
                return (true);
            else
                msgErro = "tamanho maior ou igual a";
            break;
        case '<=':
            if (field.value.length <= tamanho)
                return (true);
            else
                msgErro = "tamanho menor ou igual a";
            break;
        case '!=':
            if (field.value.length != tamanho)
                return (true);
            else
                msgErro = "tamanho diferente de";
            break;
        default:
            window.alert ("[SCRIPT ERROR] Verifique parâmetro condição!");
            return (false);
    }

    window.alert ("O campo \"" + nomecampo + "\" deve ter " + msgErro + " " + tamanho + " caracteres!");

/*
    // Removidos os dois comandos abaixo porque geram
    // problema de loop infinito de alerts quando
    // há mais de um campo utilizando a função

    field.select();
    field.focus();
*/    
    return (false);
}


function validaemail(field)
{
/*
Chamada: <input type="text" name="qualquernome" onblur="return validaemail(this);">
*/
    if (field.value.length == 0){
        return (true);
    }

    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(field.value)){
        return (true);
    }
    alert("Endereço de email inválido");
    field.select();
    field.focus();

    return (false);
}


// Remove espacos no inicio e no final de uma string
function trim (inputString) {
	// Removes leading and trailing spaces from the passed string. Also removes
	// consecutive spaces and replaces it with one space. If something besides
	// a string is passed in (null, custom object, etc.) then return the input.
	if (typeof inputString != "string") {
		return inputString;
	}
	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	while (ch == " ") { // Check for spaces at the beginning of the string
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	ch = retValue.substring(retValue.length-1, retValue.length);
	while (ch == " ") { // Check for spaces at the end of the string
		retValue = retValue.substring(0, retValue.length-1);
		ch = retValue.substring(retValue.length-1, retValue.length);
	}
	while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
		retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
	}
	return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function


// Verifica se um campo ou textarea esta vazio
function IsEmpty (inputString)
{
    // inputString no formato 'window.frmName.textarea.value' ou 
    // 'window.frmName.txtCampo.value'
	if ((inputString == null) || (trim (inputString).length == 0))
		return true;
	return false;
}


// Pede confirmacao para a limpeza de formulario
// Autor: Rafael <rafaelc@vegait.com.br> - 19/11/2004

// Uso: <input type="reset" name="btnReset" onClick="return ConfirmaLimpaForm()">
function ConfirmaLimpaForm ()
{
    if (window.confirm ("Tem certeza que deseja limpar o formulário?"))
        return (true);
    else
        return (false);

    return (false);
}


// Verifica se um endereco URL e' valido
// Autor: Rafael <rafaelc@vegait.com.br> - 22/11/2004
/*
Parametros:
> strURL: 
> reqProt: se valor igual a 1, obriga a digitacao do
           protocolo antes (http://, ftp://, file://, etc);
           se igual a 0, e opcional;
           se igual a -1, e obrigatorio a nao digitacao do protocolo;
           qualquer outro valor assume como em 0.
> httpOnly: se valor igual a 1, aceita somente o protocolo http/https
> showOKMsg: indica se manda mensagem de URL valida

Chamada em um input:
<input type="text" name="field"
    onBlur="if (!ValidaURL (this.value, 0, 0)) this.focus;">
*/
function ValidaURL (strURL, reqProt, httpOnly, showOKMsg)
{
    switch (reqProt) {
        case 1:
            if (!httpOnly)
                expReg = /^(http|ftp|file):\/\/([a-z0-9]+[-]?[a-z0-9]+\.)+[a-z]{2,3}(\.[a-z]{2})?\/?$/;
            else
                expReg = /^http:\/\/([a-z0-9]+[-]?[a-z0-9]+\.)+[a-z]{2,3}(\.[a-z]{2})?\/?$/;
            break;
        case 0:
            if (!httpOnly)
                expReg = /^((http|ftp|file):\/\/)?([a-z0-9]+[-]?[a-z0-9]+\.)+[a-z]{2,3}(\.[a-z]{2})?\/?$/;
            else
                expReg = /^(http:\/\/)?([a-z0-9]+[-]?[a-z0-9]+\.)+[a-z]{2,3}(\.[a-z]{2})?\/?$/;
            break;
        case -1:
            expReg = /^([a-z0-9]+[-]?[a-z0-9]+\.)+[a-z]{2,3}(\.[a-z]{2})?\/?$/;
            break;
    }
    
    if (expReg.test (strURL)) {
        if (showOKMsg)
            window.alert ("URL válida!");
        return (true);
    }
    else {
        window.alert ("URL inválida!");
        return (false);
    }
}


// Cria mascara de digitacao para um horario
// Cria mascara de digitacao para um horario
// Deve ser usado em conjunto com ValidaHora
// Autor: Rafael <rafaelc@vegait.com.br> - 13/01/2005

// Uso: <input type="text" onKeyPress="MascaraHora (this, event)" onBlur="ValidaHora (this)">
function MascaraHora(objeto, e)
{

	campo = eval(objeto);

	if (e.keyCode)
		tecla	= e.keyCode;	// internet explorer
	else
		tecla	= e.which;		// gecko

	var c = String.fromCharCode (tecla);
	
	// So aceita numeros
	expReg	= new RegExp (/^[0-9]$/);
	
	if (expReg.test (c) || (tecla <= 31)){
		if((campo.value.length == 1) && (tecla !=8)) {
			campo.value = campo.value + c + ':';
			return false;
		}
		else if((campo.value.length == 2) && (tecla !=8)) {
			campo.value = campo.value + ':' + c;
			return false;
		}
	}
	else {
		//e.returnValue = false;
		return false;
	}
}


// Valida uma hora digitada
// Deve ser usado em conjunto com MascaraHora
// Autor: Rafael <rafaelc@vegait.com.br> - 13/01/2005

// Uso: <input type="text" onKeyPress="MascaraHora (this)" onBlur="ValidaHora (this)">
function ValidaHora (field)
{
	if (!field.value.length)
		return;
	
	expReg = /^((0|1)[0-9]|[2][0-3]):[0-5][0-9]$/;

	if (!expReg.test (field.value)) {
		window.alert ("Hora informada inválida!")
		field.select ();
		field.focus ();
	}
}


// Oculta elementos como tabelas, linhas, inputs, etc 
// Autor: Desconhecido 

// Uso: 
//      <input type="text" id="elemento" name="campo_elemento">
//      hideElement("elemento");
function hideElement (elementId)
{
	if (window.opera && document.getElementById)
		document.getElementById(elementId).style.visibility = 'hidden';
	else if (document.all)
		document.all[elementId].style.display = 'none';
	else if (document.getElementById)
	document.getElementById(elementId).style.display = 'none';
}


// Mostra os elementos ocultados pela funcao hideElement 
// Autor: Desconhecido 

// Uso: 
//      <input type="text" id="elemento" name="campo_elemento">
//      showElement("elemento");
function showElement (elementId)
{
	if (window.opera && document.getElementById)
		document.getElementById(elementId).style.visibility = 'inherit';
	else if (document.all)
		document.all[elementId].style.display = '';
	else if (document.getElementById)
		document.getElementById(elementId).style.display = '';
}


// Aguarda por um numero determinado de segundos

// Uso: <script>sleep (5)</script>
function sleep (intervalo)
{
	var then, now;	

	then	= new Date().getTime();
	now		= then;

	// E' calculado em milissegundos
	while ((now - then) < (intervalo * 1000))
		now = new Date().getTime();
}


//função que controla os submenus
function smnuTOut( div, acao ){
	var DivRef = document.getElementById(div);
	if(acao == 'over'){
		DivRef.style.display = "block";
	}
	else if( acao == 'out' ){
		DivRef.style.display = "none";
   }
}


// Busca uma variavel de query string via javascript
// Autor: Pete Freitag <pete@cfdev.com>
// URL: http://www.activsoftware.com/code_samples/code.cfm/CodeID/59/JavaScript/Get_Query_String_variables_in_JavaScript
function getQueryVariable (variable)
{
	var query	= window.location.search.substring (1);
	var vars	= query.split ("&");
	
	for (var i=0; i < vars.length; i++) {
		var pair = vars[i].split("=");

		if (pair[0] == variable)
			return pair[1];
	} 
}

//<input name="qualquernome" onKeyUp="javascript:JumpField(this);" maxlength="2">
// Pula de uma Campo a Outro Automático
function JumpField(fields) {
    if (fields.value.length == fields.maxLength)
    {
          for (var i = 0; i < fields.form.length; i++)
          {
               if (fields.form[i] == fields && fields.form[(i + 1)] && fields.form[(i + 1)].type != "hidden")
               {
                    fields.form[(i + 1)].focus();
                    break;
               }
          }
    }
}


/*
================================================================================
							ALTERACOES ANTERIORES
================================================================================
Data Alteracao: 29/03/06              |  Autor: Rafael <rafaelc@vegait.com.br>
--------------------------------------------------------------------------------
	*	Correcao de fmtPrice()
--------------------------------------------------------------------------------
Data Alteracao: 14/10/05              |  Autor: Rafael <rafaelc@vegait.com.br>
--------------------------------------------------------------------------------
	*	Alteracao de currencyFormat(), de modo a permitir numeros negativos,
	conforme parametro
--------------------------------------------------------------------------------
Data Alteracao: 01/12/05              |  Autor: Ana Elena <ana@vegait.com.br>
--------------------------------------------------------------------------------
	*	Alteracao de validaemail, permitindo sair do campo quando ele for vazio
--------------------------------------------------------------------------------
Data Alteracao: 14/10/05              |  Autor: Rafael <rafaelc@vegait.com.br>
--------------------------------------------------------------------------------
	*	Alteracao de currencyFormat(), de modo a permitir numeros negativos,
	conforme parametro
--------------------------------------------------------------------------------
Data Alteracao: 15/09/05              |  Autor: Ana Elena <ana@vegait.com.br>
--------------------------------------------------------------------------------
	*	Adaptacao da funcao MascaraHora para Firefox
--------------------------------------------------------------------------------
Data Alteracao: 23/08/05              |  Autor: Rafael <rafaelc@vegait.com.br>
--------------------------------------------------------------------------------
	*	Alteracao de fmtPrice(), permitindo escolha do formato do dado
--------------------------------------------------------------------------------
Data Alteracao: 23/08/05              |  Autor: Ana Elena <ana@vegait.com.br>
--------------------------------------------------------------------------------
	*	validacnpj(): verificacao de letras e permissao de campo em branco
--------------------------------------------------------------------------------
================================================================================
*/
