/*
================================================================================
                  BIBLIOTECA DE FUNCOES JAVASCRIPT - VEGA IT
--------------------------------------------------------------------------------
Autor: Vários
--------------------------------------------------------------------------------
Ultima Alteracao: 30/06/05             |  Autor: Rafael <rafaelc@vegait.com.br>
--------------------------------------------------------------------------------
Funcoes disponiveis:
> datediff			: retorna a diferenca entre duas datas
> fmtPrice			: ?
> validacnpj		: faz validacao de tamanho e digito verificador de CNPJ
> validacpf			: faz validacao de tamanho e digito verificador de CPF
> 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
> ErroForm			: manda mensagem sobre a necessidade de preenchimento de
					  campo
> 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
================================================================================
*/

/*
 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 fmtPrice(value)
{
    var result = Math.floor(value) + ".";
    var cents = 100*(value - Math.floor(value))+0.5;
    result += Math.floor(cents/10);
    result += Math.floor(cents%10);
    return result;
}



function validacnpj(field){
/*
Chamada: <input type="text" name="qualquernome" onblur="return validacnpj(this);">
*/
    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");
          }
       }
    }
}

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;
}


/**
 * 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)
 *
 */
function currencyFormat(fld, milSep, decSep, e)
{
	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);
	
	if (whichCode <= 31)
		return true;
	
	key = String.fromCharCode (whichCode);
	
	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);
	}

	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 (/^\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);
}

/* Controle de Datas: mascara, formato, validacao

<input name="qualquernome" size="12" maxlength="10"
       onFocus="javascript:vDateType='3'"
       onKeyUp="DateFormat(this,this.value,event,false,'3')"
       onBlur="DateFormat(this,this.value,event,true,'3')">
*/
var isNav4 = false, isNav5 = false, isIE4 = false
var strSeperator = "/";
var vDateType = 3; // Global value for type of date format
//                1 = mm/dd/yyyy
//                2 = yyyy/dd/mm  (Unable to do date check at this time)
//                3 = dd/mm/yyyy
var vYearType = 4; //Set to 2 or 4 for number of digits in the year for Netscape
var vYearLength = 2; // Set to 4 if you want to force the user to enter 4 digits for the year before validating.
var err = 0; // Set the error code to a default of zero
if(navigator.appName == "Netscape") {
if (navigator.appVersion < "5") {
isNav4 = true;
isNav5 = false;
}else
if (navigator.appVersion > "4") {
isNav4 = false;
isNav5 = true;
}}else{
isIE4 = true;
}
function DateFormat(vDateName, vDateValue, e, dateCheck, dateType) {
vDateType = dateType;
// vDateName = object name
// vDateValue = value in the field being checked
// e = event
// dateCheck
// True  = Verify that the vDateValue is a valid date
// False = Format values being entered into vDateValue only vDateType
//Enter a tilde sign for the first number and you can check the variable information.
if (vDateValue == "~") {
alert("AppVersion = "+navigator.appVersion+" Nav. 4 Version = "+isNav4+" Nav. 5 Version = "+isNav5+" IE Version = "+isIE4+" Year Type = "+vYearType+" Date Type = "+vDateType+" Separator = "+strSeperator);
vDateName.value = "";
vDateName.focus();
return true;}
var whichCode = (window.Event) ? e.which : e.keyCode;
// Check to see if a seperator is already present.
// bypass the date if a seperator is present and the length greater than 8
if (vDateValue.length > 8 && isNav4) {
if ((vDateValue.indexOf("-") >= 1) || (vDateValue.indexOf("/") >= 1))
return true;}
//Eliminate all the ASCII codes that are not valid
var alphaCheck = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-";
if (alphaCheck.indexOf(vDateValue) >= 1) {
if (isNav4) {
vDateName.value = "";
vDateName.focus();
vDateName.select();
return false;
}
else {
vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
return false;
   }
}
if (whichCode == 8) //Ignore the Netscape value for backspace. IE has no value
return false;
else {
//Create numeric string values for 0123456789/
//The codes provided include both keyboard and keypad values
var strCheck = '47,48,49,50,51,52,53,54,55,56,57,58,59,95,96,97,98,99,100,101,102,103,104,105';
if (strCheck.indexOf(whichCode) != -1) {
if (isNav4) {
if (((vDateValue.length < 6 && dateCheck) || (vDateValue.length == 7 && dateCheck)) && (vDateValue.length >=1)) {
alert("Data informada incorreta. O formato padrão é dd/mm/aaaa");
vDateName.value = "";
vDateName.focus();
vDateName.select();
return false;
}
if (vDateValue.length == 6 && dateCheck) {
var mDay = vDateName.value.substr(2,2);
var mMonth = vDateName.value.substr(0,2);
var mYear = vDateName.value.substr(4,4)
//Turn a two digit year into a 4 digit year
if (mYear.length == 2 && vYearType == 4) {
var mToday = new Date();
//If the year is greater than 30 years from now use 19, otherwise use 20
var checkYear = mToday.getFullYear() + 30;
var mCheckYear = '20' + mYear;
if (mCheckYear >= checkYear)
mYear = '19' + mYear;
else
mYear = '20' + mYear;
}
var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
if (!dateValid(vDateValueCheck)) {
alert("Data informada incorreta. O formato padrão é dd/mm/aaaa");
vDateName.value = "";
vDateName.focus();
vDateName.select();
return false;
}
return true;
}
else {
// Reformat the date for validation and set date type to a 1
if (vDateValue.length >= 8  && dateCheck) {
if (vDateType == 1) // mmddyyyy
{
var mDay = vDateName.value.substr(2,2);
var mMonth = vDateName.value.substr(0,2);
var mYear = vDateName.value.substr(4,4)
vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
}
if (vDateType == 2) // yyyymmdd
{
var mYear = vDateName.value.substr(0,4)
var mMonth = vDateName.value.substr(4,2);
var mDay = vDateName.value.substr(6,2);
vDateName.value = mYear+strSeperator+mMonth+strSeperator+mDay;
}
if (vDateType == 3) // ddmmyyyy
{
var mMonth = vDateName.value.substr(2,2);
var mDay = vDateName.value.substr(0,2);
var mYear = vDateName.value.substr(4,4)
vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
}
//Create a temporary variable for storing the DateType and change
//the DateType to a 1 for validation.
var vDateTypeTemp = vDateType;
vDateType = 1;
var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
if (!dateValid(vDateValueCheck)) {
alert("Data informada incorreta. O formato padrão é dd/mm/aaaa");
vDateType = vDateTypeTemp;
vDateName.value = "";
vDateName.focus();
vDateName.select();
return false;
}
vDateType = vDateTypeTemp;
return true;
}
else {
if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >=1)) {
alert("Data informada incorreta. O formato padrão é dd/mm/aaaa");
vDateName.value = "";
vDateName.focus();
vDateName.select();
return false;
         }
      }
   }
}
else {
// Non isNav Check
if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >=1)) {
alert("Data informada incorreta. O formato padrão é dd/mm/aaaa");
vDateName.value = "";
vDateName.focus();
return true;
}
// Reformat date to format that can be validated. mm/dd/yyyy
if (vDateValue.length >= 8 && dateCheck) {
// Additional date formats can be entered here and parsed out to
// a valid date format that the validation routine will recognize.
if (vDateType == 1) // mm/dd/yyyy
{
var mMonth = vDateName.value.substr(0,2);
var mDay = vDateName.value.substr(3,2);
var mYear = vDateName.value.substr(6,4)
}
if (vDateType == 2) // yyyy/mm/dd
{
var mYear = vDateName.value.substr(0,4)
var mMonth = vDateName.value.substr(5,2);
var mDay = vDateName.value.substr(8,2);
}
if (vDateType == 3) // dd/mm/yyyy
{
var mDay = vDateName.value.substr(0,2);
var mMonth = vDateName.value.substr(3,2);
var mYear = vDateName.value.substr(6,4)
}
if (vYearLength == 4) {
if (mYear.length < 4) {
alert("Data informada incorreta. O formato padrão é dd/mm/aaaa");
vDateName.value = "";
vDateName.focus();
return true;
   }
}
// Create temp. variable for storing the current vDateType
var vDateTypeTemp = vDateType;
// Change vDateType to a 1 for standard date format for validation
// Type will be changed back when validation is completed.
vDateType = 1;
// Store reformatted date to new variable for validation.
var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
if (mYear.length == 2 && vYearType == 4 && dateCheck) {
//Turn a two digit year into a 4 digit year
var mToday = new Date();
//If the year is greater than 30 years from now use 19, otherwise use 20
var checkYear = mToday.getFullYear() + 30;
var mCheckYear = '20' + mYear;
if (mCheckYear >= checkYear)
mYear = '19' + mYear;
else
mYear = '20' + mYear;
vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
// Store the new value back to the field.  This function will
// not work with date type of 2 since the year is entered first.
if (vDateTypeTemp == 1) // mm/dd/yyyy
vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
if (vDateTypeTemp == 3) // dd/mm/yyyy
vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
}
if (!dateValid(vDateValueCheck)) {
alert("Data informada incorreta. O formato padrão é dd/mm/aaaa");
vDateType = vDateTypeTemp;
vDateName.value = "";
vDateName.focus();
return true;
}
vDateType = vDateTypeTemp;
return true;
}
else {
if (vDateType == 1) {
if (vDateValue.length == 2) {
vDateName.value = vDateValue+strSeperator;
}
if (vDateValue.length == 5) {
vDateName.value = vDateValue+strSeperator;
   }
}
if (vDateType == 2) {
if (vDateValue.length == 4) {
vDateName.value = vDateValue+strSeperator;
}
if (vDateValue.length == 7) {
vDateName.value = vDateValue+strSeperator;
   }
}
if (vDateType == 3) {
if (vDateValue.length == 2) {
vDateName.value = vDateValue+strSeperator;
}
if (vDateValue.length == 5) {
vDateName.value = vDateValue+strSeperator;
   }
}
return true;
   }
}
if (vDateValue.length == 10&& dateCheck) {
if (!dateValid(vDateName)) {
// Un-comment the next line of code for debugging the dateValid() function error messages
//alert(err);
alert("Data informada incorreta. O formato padrão é dd/mm/aaaa");
vDateName.focus();
vDateName.select();
   }
}
return false;
}
else {
// If the value is not in the string return the string minus the last
// key entered.
if (isNav4) {
vDateName.value = "";
vDateName.focus();
vDateName.select();
return false;
}
else
{
vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
return false;
         }
      }
   }
}

function dateValid(objName) {
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
// var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "Jan";
strMonthArray[1] = "Fev";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Abr";
strMonthArray[4] = "Mai";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Ago";
strMonthArray[8] = "Set";
strMonthArray[9] = "Out";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dez";
//strDate = datefield.value;
strDate = objName;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
   }
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
}
//Adjustment for short years entered
if (strYear.length == 2) {
strYear = '20' + strYear;
}
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
   }
}
else {
if (intday > 28) {
err = 10;
return false;
      }
   }
}
return true;
}

function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
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;
}

// Manda mensagem sobre a necessidade de preenchimento de campo obrigatorio
// (util para utilizacao em funcoes de validacao de formulario)
function ErroForm (nome, campo)
{
	window.alert ("O campo \"" + nome + "\" deve ser preenchido!");
	campo.focus();
}

// 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
// Deve ser usado em conjunto com ValidaHora
// Autor: Rafael <rafaelc@vegait.com.br> - 13/01/2005

// Uso: <input type="text" onKeyPress="MascaraHora (this)" onBlur="ValidaHora (this)">
function MascaraHora(objeto)
{
	campo = eval(objeto);

	try {
		caracteres = '0123456789';
		var c = String.fromCharCode (event.keyCode);

		if (campo.value.length < 5) {
			if (c == "." || c == "^" || c == "$" || c == "|")
				throw e;
			
			if (event.returnValue = (caracteres.search (String.fromCharCode (event.keyCode))!=-1)) {
				if((campo.value.length == 1)) {
					campo.value = campo.value + c + ':';
					event.returnValue = false;
				}
				else if(campo.value.length == 2) {
					campo.value = campo.value + ':' + c;
					event.returnValue = false;
				}
			}
		}
		else {
			event.returnValue = false;
		}
	}
	
	catch (e) {
		event.returnValue = false;
		return;
	}
}


// 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";
   }
}