/******************************************************************

				OPERAÇÕES COM FORMULÁRIOS
				-------------------------
				Triares Informática e Tecnologia
				http://www.triares.com.br	

*******************************************************************/

function addEventLis(obj, evType, fn){
    if (obj.addEventListener)
		obj.addEventListener(evType, fn, true);
	if (obj.attachEvent)
		obj.attachEvent("on"+evType, fn);
}

/******************************************************************
*****************************  MÁSCARAS  **************************
*******************************************************************/

/** ============================================================================================
	Permite inserir um caracter em uma string em uma posio especifica 
*/
function InsChar( str, charr, pos ) {
	var aux = '';
	var tmp = new String( str );
	var auxstr = tmp.split('');
	for( i=0; i < auxstr.length; i++ ) {
		if( (pos == i) && ( auxstr[i] != charr ) ) {
			aux = aux + charr;
		}
		aux = aux + auxstr[i];
	}
	return aux;
}

/** ============================================================================================
	Retorna apenas os digitos numericos de uma string 
*/
function GetNum( str, sinal ) {
	if( typeof( sinal ) == "undefined" ) {
		sinal = false;
	}
	var aux = '';
	var firstNum = false;
	var tmp = new String( str );
	var arr = tmp.split('');
	for( i=0; i < arr.length; i++ ) {
		if( (!isNaN( arr[i] ) && (arr[i] != ' ')) || ((arr[i] != '-') && (sinal))) {
			aux = aux + arr[i];
		}
	}
	return aux;
}
// -----------------------------------------------------------------------------------------
function isNegativo( str ) {
    var valor_str = new String( str );
    var valor_array = valor_str.split("");
    if( valor_array.length > 1 ) {
        return ( valor_array[0] == '-' );
    } else {
        return false;
    }
}
// -----------------------------------------------------------------------------------------
function getEvent( args_array ) {
	if( args_array.length > 0 ) {
		return args_array[0];
	} else {
		return false;
	}
}
// -----------------------------------------------------------------------------------------
function getElement( args_array, obj ) {
	var element = null;
	if( args_array.length == 1 ) {
		e = args_array[0];
		if (typeof(e)=='undefined'){var e=window.event;}
		source=e.target?e.target:e.srcElement;
		if(source.nodeType == 3)source = source.parentNode;
		element = source;
		element.evento_obj = e;
	} else {
		element = obj;
		element.evento_obj = null;
	}
	return element;
}
// -----------------------------------------------------------------------------------------
function strData() {
	var dt_obj = new Date();
	var ano = dt_obj.getFullYear();
	var mes = dt_obj.getMonth() + 1;
	var dia = dt_obj.getDate();
	var dt_str = "";
	if( dia < 10 ) {
		dt_str = dt_str + "0" + dia;
	} else {
		dt_str = dt_str + "" + dia;
	}
	if( mes < 10 ) {
		dt_str = dt_str + "/0" + mes;
	} else {
		dt_str = dt_str + "/" + mes;
	}
	dt_str = dt_str + "/" + ano;
	return dt_str;
}

function $( id ){
	return document.getElementById( id );
}

function getDocCoords() {
	var L = document.documentElement.scrollLeft;
	var T = document.documentElement.scrollTop;
	var W = document.documentElement.clientWidth;
	var H = document.documentElement.clientHeight;
	return { L:L, T:T, W:W, H:H };
}

function centrar( obj ){
	var pos = getDocCoords();
	if( typeof( obj ) == "string" )
		obj = $(obj);
	var x = pos.L + parseInt((pos.W - obj.offsetWidth)/2);
	var y = pos.T + parseInt((pos.H - obj.offsetHeight)/2);
	obj.style.left = x + "px";
	obj.style.top = y + "px";
}

function getTargetCoords( obj ){
	var x = obj.offsetLeft;
	var y = obj.offsetTop;
	var xb = 0;
	var yb = 0;
	var t = 1; 
	if( obj.clientTop && (t>0) ){
		yb = yb + obj.clientTop;
		xb = xb + obj.clientLeft;
		t = 2;
	}
	var pai = obj.offsetParent;
	while( pai ){
		if( pai.clientTop && (t>0) ){
			yb = yb + pai.clientTop;
			xb = xb + pai.clientLeft;
		}
		x = x + pai.offsetLeft;
		y = y + pai.offsetTop;
		pai = pai.offsetParent;
	}
	if( t == 2 ){
		xb = xb - 2;
		yb = xb - 2;
	}
	return { left: x + xb, top: y + yb, height: obj.offsetHeight, width: obj.offsetWidth }
}

function ev(e) {
	
	var self = this;
	if( typeof(e) != 'undefined' ) {
		this.e = e;
	} else {
		this.e = window.event;
	}
	if( !this.e.target ) {
		this.e.target = e.srcElement;
	}
	// this.e.target = (e.target)?(e.target):(e.srcElement);
	if( this.e.target.nodeType == 3 ) {
		this.e.target.parentNode;
	}
	
	this.element = this.e.target;
	
	this.getDocumentMouseCoords = function(){
		if( self.e.pageX || self.e.pageY){
			return {x:self.e.pageX, y:self.e.pageY};
		}
		return {
			x:self.e.clientX + document.body.scrollLeft - document.body.clientLeft,
			y:self.e.clientY + document.body.scrollTop  - document.body.clientTop
		};
	}
	
	this.getTargetCoords = function(){
		var left = 0;
		var top  = 0;
		var e = self.e.target;
	
		while (e.offsetParent){
			left += e.offsetLeft;
			top  += e.offsetTop;
			e     = e.offsetParent;
		}
	
		left += e.offsetLeft;
		top  += e.offsetTop;
	
		return {x:left, y:top};
	}
	
	this.getTargetMouseCoords = function(){
		var docPos    = self.getTargetCoords();
		var mousePos  = self.getDocumentMouseCoords();
		return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
	}
	
	this.bloquear = function(){
		if( self.e.preventDefault ) {
			self.e.preventDefault();
		} else {
			self.e.returnValue = false;
		}	
	}
	
	this.keyCode = function() {
		return (self.e.keyCode)?(self.e.keyCode):(self.e.which);
	}
}
/** ============================================================================================
*/
function InverteString( str ) {
	var aux1 = new String( str );
	var aux = aux1.split("");
	var tmp = '';
	for( i=0; i < aux.length; i++ ) {
		tmp = aux[i] + tmp;
	}
	return tmp;
}

// ##### Mascara para formatao de data #####################################################
function mskData( input_obj, preencher_bool ) {
	if( typeof( preencher_bool ) == "undefined" ) {
		preencher_bool = true;
	}
	input_obj.preencher_bool = preencher_bool;
	input_obj.style.textAlign = "right";
	input_obj.setAttribute( "maxlength", 10 );
	input_obj.setAttribute( "size", 10 );
	// ---------------------------------------------------------------------------------------
	input_obj.formatar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var valor_str = new String( Element.value );
		if( (valor_str.length == 0) || (valor_str == "0000-00-00") ) {

			if( Element.preencher_bool ) {
				Element.value = strData();
			} else {
				Element.value = "";
			}
		} else {
			if( valor_str.length == 10 ) {
				if( valor_str.indexOf( "-" ) > -1 ) {
					var data_array = valor_str.split("-");
					if( valor_str.indexOf("-") == 4 ) {
						var dia_str = data_array[2];
						var mes_str = data_array[1];
						var ano_str = data_array[0];
					} else {
						var dia_str = data_array[0];
						var mes_str = data_array[1];
						var ano_str = data_array[2];
					}
					Element.value = dia_str + "/" + mes_str + "/" + ano_str;
				}
			}
		}
	}
	// ---------------------------------------------------------------------------------------
	input_obj.formatar();
	// ---------------------------------------------------------------------------------------
	input_obj.verificar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var valor_str = new String( InsChar( GetNum( Element.value ), '/', 2 ) );
		var erro_int = 0;
		valor_str = valor_str.substring( 0, 10 );
		valor_str = InsChar( valor_str, '/', 5 );
		if( valor_str.length == 10 ) {
			var data_array = valor_str.split("/");
			var dia_str = parseFloat( data_array[0] );
			if( (dia_str > 31) || (dia_str < 1)) {
				erro_int = 1
			} else {
				var mes_str = parseFloat( data_array[1] );
				if( (mes_str>12) || (mes_str<1) ) {
					erro_int = 2;
				} else {
					var ano_str = parseFloat( data_array[2] );
					switch ( mes_str ) {
						case 4:
						case 6:
						case 9:
						case 11:
							if( dia_str > 30 ) {
								erro_int = 3;
							}
						break;
						case 2:
							if( (ano_str % 4) == 0 ) {
								if( dia_str > 29 ) {
									erro_int = 4;
								}
							} else {
								if( dia_str > 28 ) {
									erro_int = 5;
								}
							}
						break;
					} // end switch
				} // end else
			} // end else
		} // end else
		Element.value = valor_str.substring( 0, 10 );
		return erro_int;
	}
	// ---------------------------------------------------------------------------------------
	input_obj.corrigir = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var err = Element.verificar();
		if( err > 0 ) {
			alert("Data invalida!");
		}
	}
	// ---------------------------------------------------------------------------------------
	input_obj.voltar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		if( Element.verificar() > 0 ) {
			Element.focus();
			return false;
		} else {
			return true;
		}
	}
	// ---------------------------------------------------------------------------------------
	input_obj.converter = function() {
		var valor_str = new String( this.value );
		var dt = valor_str.split("/");
		return ( dt[2] + '-' + dt[1] + '-' + dt[0]);
	}
	// ---------------------------------------------------------------------------------------
	addEventLis( input_obj, "keyup", input_obj.corrigir );
	addEventLis( input_obj, "blur", input_obj.voltar );
}


// ##### Mascara para formatao de nmero ###################################################
function mskNumero( input_obj, cd_int ) {
	// ---------------------------------------------------------------------------------------
	input_obj.casasDecimais = cd_int;
	input_obj.converter_bool = true;
	// input_obj.style.textAlign = 'right';
	// ---------------------------------------------------------------------------------------
	input_obj.converter = function() {
		var convertido_str = "";
		var valor_str = new String( this.value );
		var valor_array = valor_str.split("");
		if( valor_array.length > 0 ) {
			for( i=0; i < valor_array.length; i++ ) {
				if( (!isNaN( valor_array[i] )) || (valor_array[i] == ",")) {
					if( valor_array[i] == "," ) {
						convertido_str = convertido_str + ".";
					} else {
						convertido_str = convertido_str + "" + valor_array[i];
					}
				}
			}
			if( isNegativo( valor_str ) ) {
				convertido_str = "-" + convertido_str;
			}
		} else {
			convertido_str = "0";
		}
		return parseFloat( convertido_str );
	}
	// ---------------------------------------------------------------------------------------
	input_obj.isNumber = function() {
		
	}
	// ---------------------------------------------------------------------------------------
	/**
	 * 
	 */
	input_obj.formatar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var aux_num = new Number();
		
		
		
		
		var valor_str = new String( Element.value );
		if( valor_str == "" ) { valor_str = "0"; } 
		var casas_array = valor_str.split(".");
		var NumeroNovo_str = 0;
		if( this.casasDecimais > 0 ) {
            NumeroNovo_str = NumeroNovo_str + ",";
            for(i=0; i < this.casasDecimais; i++ ) {
                NumeroNovo_str = NumeroNovo_str + "0";
            }
		}
		if( (casas_array.length > 0) && (valor_str != "") ) {
			var inteiro_str = new String( casas_array[0] );
			var inteiro_array = inteiro_str.split("");
			var inteiroNovo_str = "";
			var ponto_int = 0;
			var j = null;
			for( i=inteiro_array.length-1; i >= 0; i-- ) {
				if( (ponto_int == 3) && (inteiro_array[i] != "-") ) {
					inteiroNovo_str = inteiro_array[i] + "." + inteiroNovo_str;
					ponto_int = 0;
				} else {
				    inteiroNovo_str = inteiro_array[i] + inteiroNovo_str;
				}
			    ponto_int++;
			}
			NumeroNovo_str = inteiroNovo_str;
			if( Element.casasDecimais > 0 ) {
                if( casas_array.length > 1 ) {
                    var decimal_str = new String( casas_array[1] );
                } else {
                    var decimal_str = new String( "" );
                }
                for( i=decimal_str.length; i < Element.casasDecimais; i++ ) {
                    decimal_str = decimal_str + "0";
                }
                NumeroNovo_str = NumeroNovo_str + "," + decimal_str;
			}
		}
		Element.value = NumeroNovo_str;
	}
	// -----------------------------------------------------------------------------------------
	input_obj.formatar();
	// -----------------------------------------------------------------------------------------
    input_obj.corrigir = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var sinal = "";
        if( isNegativo( Element.value ) ) {
			sinal = "-";
		}
		if( (CrossBrowse.ObjEvento.keyCode == 109) || (CrossBrowse.ObjEvento.keyCode == 189)) {
			sinal = '-';
		}
		if( (CrossBrowse.ObjEvento.keyCode == 107) || (CrossBrowse.ObjEvento.keyCode == 187)) {
			sinal = '';
		}
        var valor_str = new String( GetNum( Element.value ) );
		if( valor_str == "" ) { valor_str = "0"; } 
		var valor_array = valor_str.split("");
		var formatado_str = "";
		if( typeof( Element.casasDecimais ) == "undefined" ) {
			Element.casasDecimais = 0;
		}
		if( valor_array.length != 0 ) {
			var valor_int = parseFloat( valor_str );
			var divisor_int = Math.pow(10,Element.casasDecimais);
			var inteiro_str = new String( Math.floor( valor_int / divisor_int ) );
			var inteiro_array = inteiro_str.split("");
			var ponto_int = 0;
			for( var i=inteiro_array.length-1; i >= 0; i-- ) {
				if( ponto_int == 3 ) {
					formatado_str = inteiro_array[i] + "." + formatado_str;
					ponto_int = 0;
				} else {
				    formatado_str = inteiro_array[i] + formatado_str;
				}
			    ponto_int++;
			}
			if( Element.casasDecimais > 0 ) {
				var decimal_str = "";
				for( i=0; i < Element.casasDecimais; i++ ) {
					j = valor_array.length-i-1;
					var vlr = valor_array[j];
					if (typeof(vlr) == "undefined")
						decimal_str = "0" + decimal_str;
					else
						decimal_str = valor_array[j] + decimal_str;
				}
				formatado_str = formatado_str + "," + decimal_str;
			}
		} else {
			formatado_str = "0";
			if( Element.casasDecimais > 0 ) {
				formatado_str = formatado_str + ",";
				for( i=0; i < Element.casasDecimais; i++ ) {
					formatado_str = formatado_str + "0";
				}
			}
		}		
		Element.value = sinal + formatado_str;
	}
	// -----------------------------------------------------------------------------------------
	input_obj.voltar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
	   //alert("Voltar: "+Element.casasDecimais);
	}
	// -----------------------------------------------------------------------------------------
	addEventLis( input_obj, "keyup", input_obj.corrigir );
	addEventLis( input_obj, "blur", input_obj.voltar );
}

// ##### Mascara para formatao de telefone ##################################################
function mskTelefone( input_obj ) {
	// -----------------------------------------------------------------------------------------
	
	input_obj.setAttribute( "maxlength", 14 );
	input_obj.setAttribute( "size", 14 );
	input_obj.corrigir = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var valor_str = new String( GetNum( Element.value ) );
		var valor_array = valor_str.split("");
		var telefone_str = "";
		for( i=0; i < valor_array.length; i++ ) {
			if( i==0 ) { telefone_str = telefone_str + "(";	}
			if( i==2 ) { telefone_str = telefone_str + ") ";	}
			if( i==6 ) { telefone_str = telefone_str + ".";	}
			telefone_str = telefone_str + valor_array[i];
		}
		Element.value = telefone_str;
	}
	// -----------------------------------------------------------------------------------------
	addEventLis( input_obj, "keyup", input_obj.corrigir );
}

// ##### Mascara para formatao de texto simples ############################################
function mskTexto( input_obj ) {
	// -----------------------------------------------------------------------------------------
	input_obj.maxlength = 255;
	input_obj.verificar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var valor_str = new String( Element.value );
		var valor_array = valor_str.slice("");
		if( valor_array.length > 0 ) {
			var repeticoes_int = 0;
			var ultimoChar_str = null;
			for(i=0; (i < valor_array.length) && (repeticoes_int < 2); i++ ) {
				if( ultimoChar_str != valor_array[i] ) {
					repeticoes_int = 0;
				} else {
					repeticoes_int++;
				}
				ultimoChar_str = valor_array[i];
			}
			return (repeticoes_int < 2);
		} else {
			return !Element.requerido_bool;
		}
	}
	// -----------------------------------------------------------------------------------------
	input_obj.corrigir = function() {		
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}		
		if (Element.value.length >= Element.maxlength) {
			Element.value = Element.value.substring(0, Element.maxlength);
		}
//		if( (Element.value != "") && ( Element.verificar() )) {
//			alert("Este texto possui mais de 2 caracteres repetidos em sequencia");
//		}
	}
	// -----------------------------------------------------------------------------------------
	input_obj.voltar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		if( (Element.value == "") && ( Element.requerido_bool ) && ( Element.verificar() )) {
			alert("Este texto possui mais de 2 caracteres repetidos em sequencia");
		}		
	}
	// -----------------------------------------------------------------------------------------
	addEventLis( input_obj, "keyup", input_obj.corrigir );
	addEventLis( input_obj, "blur", input_obj.voltar );
}

/******************************************************************
********************** FIM DAS MÁSCARAS  **************************
*******************************************************************/

//Permite digitao de nmeros apenas com aviso
function permitirNumero(e,  div){
	var tecla=(window.event)?event.keyCode:e.which;	
    if((tecla > 47 && tecla < 58)){
		if (typeof(div) != "undefined")
			document.getElementById(div).innerHTML = "";
		return true;
	}else{
		//return(tecla != 8 && tecla !=13 && tecla != 0)?false:true;
    	if (tecla != 8 && tecla !=13 && tecla != 0){ 
			if (typeof(div) != "undefined")
				document.getElementById(div).innerHTML = "digite somente n&uacute;meros";
			return false;
		}else{
			if (typeof(div) != "undefined")
				document.getElementById(div).innerHTML = "";
			return true;
		}
	} 
}

function maxLength(obj, limit) {
	if (obj.value.length >= limit) {
		obj.value = obj.value.substring(0, limit-1);
	}
}

function validarEmail(email){
	var bolReturn = false;
	var oRegEmail = /^[a-z0-9\._\-]+\@[a-z0-9\._\-]+\.[a-z]{2,3}$/i;
	bolReturn = oRegEmail.test(email);
	
	if(!bolReturn){
		return false;
	}
	return true;
}

/* ====================================================================================== */

/**
 * @author Márcio d'Ávila
 * @version 1.03, 2004-2008
 *
 * Este script foi retirado de:
 * http://www.mhavila.com.br/topicos/web/cpf_cnpj.html
 *
 * Licenciado sob os termos da licença Creative Commons,
 * Atribuição - Compartilhamento pela mesma licença 2.5:
 * http://creativecommons.org/licenses/by-sa/2.5/br/
 * Qualquer outra forma de uso requer autorização expressa do autor.
 *
 * PROTÓTIPOS:
 * método String.lpad(int pSize, char pCharPad)
 * método String.trim()
 *
 * String unformatNumber(String pNum)
 * String formatCpfCnpj(String pCpfCnpj, boolean pUseSepar, boolean pIsCnpj)
 * String dvCpfCnpj(String pEfetivo, boolean pIsCnpj)
 * boolean isCpf(String pCpf)
 * boolean isCnpj(String pCnpj)
 * boolean isCpfCnpj(String pCpfCnpj)
 */


NUM_DIGITOS_CPF  = 11;
NUM_DIGITOS_CNPJ = 14;
NUM_DGT_CNPJ_BASE = 8;


/**
 * Adiciona método lpad() à classe String.
 * Preenche a String à esquerda com o caractere fornecido,
 * até que ela atinja o tamanho especificado.
 */
String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif>0; dif--) str = ch + str;
	return (str);
} //String.lpad


/**
 * Adiciona método trim() à classe String.
 * Elimina brancos no início e fim da String.
 */
String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim


/**
 * Elimina caracteres de formatação e zeros à esquerda da string
 * de número fornecida.
 * @param String pNum
 * 	String de número fornecida para ser desformatada.
 * @return String de número desformatada.
 */
function unformatNumber(pNum)
{
	return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
} //unformatNumber


/**
 * Formata a string fornecida como CNPJ ou CPF, adicionando zeros
 * à esquerda se necessário e caracteres separadores, conforme solicitado.
 * @param String pCpfCnpj
 * 	String fornecida para ser formatada.
 * @param boolean pUseSepar
 * 	Indica se devem ser usados caracteres separadores (. - /).
 * @param boolean pIsCnpj
 * 	Indica se a string fornecida é um CNPJ.
 * 	Caso contrário, é CPF. Default = false (CPF).
 * @return String de CPF ou CNPJ devidamente formatada.
 */
function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	if (pUseSepar==null) pUseSepar = true;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var numero = unformatNumber(pCpfCnpj);

	numero = numero.lpad(maxDigitos, '0');

	if (!pUseSepar) return numero;

	if (pIsCnpj)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		numero = numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return numero;
} //formatCpfCnpj


/**
 * Calcula os 2 dígitos verificadores para o número-efetivo pEfetivo de
 * CNPJ (12 dígitos) ou CPF (9 dígitos) fornecido. pIsCnpj é booleano e
 * informa se o número-efetivo fornecido é CNPJ (default = false).
 * @param String pEfetivo
 * 	String do número-efetivo (SEM dígitos verificadores) de CNPJ ou CPF.
 * @param boolean pIsCnpj
 * 	Indica se a string fornecida é de um CNPJ.
 * 	Caso contrário, é CPF. Default = false (CPF).
 * @return String com os dois dígitos verificadores.
 */
function dvCpfCnpj(pEfetivo, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? NUM_DGT_CNPJ_BASE: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pEfetivo + "00", false, pIsCnpj);
	calculado = calculado.substring(0, maxDigitos-2);
	var result = "";

	for (j = 1; j <= 2; j++)
	{
		k = 2;
		soma = 0;

		for (i = calculado.length-1; i >= 0; i--)
		{
			soma += (calculado.charAt(i) - '0') * k;
			k = (k-1) % cicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) dv = 0;
		calculado += dv;
		result += dv
	}

	return result;
} //dvCpfCnpj


/**
 * Testa se a String pCpf fornecida é um CPF válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCpf
 * 	String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF válido.
 */
function isCpf(pCpf)
{
	var numero = formatCpfCnpj(pCpf, false, false);
	if (numero.length > NUM_DIGITOS_CPF) return false;

	var base = numero.substring(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	// Valida dígitos verificadores
	if (numero != "" + base + digitos) return false;

	/* Não serão considerados válidos os seguintes CPF:
	 * 000.000.000-00, 111.111.111-11, 222.222.222-22, 333.333.333-33, 444.444.444-44,
	 * 555.555.555-55, 666.666.666-66, 777.777.777-77, 888.888.888-88, 999.999.999-99.
	 */
	algUnico = true;
	for (var i=1; algUnico && i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isCpf


/**
 * Testa se a String pCnpj fornecida é um CNPJ válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCnpj
 * 	String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CNPJ válido.
 */
function isCnpj(pCnpj)
{
	var numero = formatCpfCnpj(pCnpj, false, true);
	if (numero.length > NUM_DIGITOS_CNPJ) return false;

	var base = numero.substring(0, NUM_DGT_CNPJ_BASE);
	var ordem = numero.substring(NUM_DGT_CNPJ_BASE, 12);
	var digitos = dvCpfCnpj(base + ordem, true);
	var algUnico;

	// Valida dígitos verificadores
	if (numero != "" + base + ordem + digitos) return false;

	/* Não serão considerados válidos os CNPJ com os seguintes números BÁSICOS:
	 * 11.111.111, 22.222.222, 33.333.333, 44.444.444, 55.555.555,
	 * 66.666.666, 77.777.777, 88.888.888, 99.999.999.
	 */
	algUnico = numero.charAt(0) != '0';
	for (var i=1; algUnico && i<NUM_DGT_CNPJ_BASE; i++)
	{
		algUnico = (numero.charAt(i-1) == numero.charAt(i));
	}
	if (algUnico) return false;

	/* Não será considerado válido CNPJ com número de ORDEM igual a 0000.
	 * Não será considerado válido CNPJ com número de ORDEM maior do que 0300
	 * e com as três primeiras posições do número BÁSICO com 000 (zeros).
	 * Esta crítica não será feita quando o no BÁSICO do CNPJ for igual a 00.000.000.
	 */
	if (ordem == "0000") return false;
	return (base == "00000000"
		|| parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
} //isCnpj


/**
 * Testa se a String pCpfCnpj fornecida é um CPF ou CNPJ válido.
 * Se a String tiver uma quantidade de dígitos igual ou inferior
 * a 11, valida como CPF. Se for maior que 11, valida como CNPJ.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCpfCnpj
 * 	String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF ou CNPJ válido.
 */
function isCpfCnpj(pCpfCnpj)
{
	var numero = pCpfCnpj.replace(/\D/g, "");
	if (numero.length > NUM_DIGITOS_CPF)
		return isCnpj(pCpfCnpj)
	else
		return isCpf(pCpfCnpj);
} //isCpfCnpj


/* ====================================================================================== */


function validarForm( form ) {
	for(i=0; i < form.elements.length; i++) {	
		if(typeof(form.elements[i].name) != "undefined") {
			if(form.elements[i].getAttribute("class") != null ) {
				if(form.elements[i].getAttribute("class").indexOf("requerido") != -1 && form.elements[i].value == "") {
					alert("Preencha todos os campos obrigatórios");
					form.elements[i].focus();
					return false;
				}
			}
			if(form.elements[i].name.indexOf("email") != -1 && form.elements[i].value != "") {	
				if(!validarEmail(form.elements[i].value)) {
					alert("E-mail Inválido");
					form.elements[i].focus();
					return false;
				}
			}			
			if(form.elements[i].name.indexOf("cpf") != -1 && form.elements[i].value != "") {
				var cpf = form.elements[i];
				if(!isCpf(form.elements[i].value)) {
					alert("CPF Inválido");
					cpf.focus();
					return false;
				}
			}
			if(form.elements[i].name.indexOf("cnpj") != -1 && form.elements[i].value != "") {
				if( !isCnpj(form.elements[i].value) ) {
					alert('CNPJ Inválido');
					form.elements[i].focus();
					return false;
				}
			}
		}
	}
	return true;
	
}

function formatar() {
	var inputs = document.getElementsByTagName("input");
	for( var i=0; i < inputs.length; i++ ){
		switch( inputs[i].type ){
			case "button":
			case "submit":
				inputs[i].className = "botao";
			break;
			case "radio":
			case "checkbox":
				inputs[i].style.border = "none 0px";
			break;
			case "text":
				if( inputs[i].name.indexOf( "dt_" ) == 0 )
					mskData( inputs[i], false );
				if( inputs[i].name.indexOf( "celular" ) > -1 || inputs[i].name.indexOf( "telefone" ) > -1 ) 
					mskTelefone( inputs[i] );
			break;
		}		
	}
}

addEventLis( window, "load", function(e){
	formatar();
});