// JavaScript Document

//Esta função simula a função trim para o javascript
//uma função trim elimina os espaços em branco de uma variavel
String.prototype.trim = function() {
	var x = this;
	x = x.replace(/^\s*(.*)/, "$1");
	x = x.replace(/(.*?)\s*$/, "$1");
	return x;
}


function validaEmail(campo,email){
	var reEmail1 = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	if(email != ""){
	    if (!reEmail1.test(email)) {
		
			//textos conforme idioma
			var msg = " não é um endereço de e-mail válido!";
			if(document.getElementById("idm_atual")!=null){
				switch(document.getElementById("idm_atual").value){
					case 2:
						msg = " E-mail address is not valid!";
						break;
					case 3:
						msg = " no es una dirección de e-mail válida.";
						break;
				}
			}		
            
            alert('"' + email + '"' + msg);
		    campo.value = "";
		    campo.focus();
		    return false;
	    }else{
	        return true;
	    }
    }
    return false;
}

//VALIDA QUANTIDADE DE CARACTERES DIGITADOS
function countChars(num_chars, obj_mostrador, obj_texto, msg) {
	var campo = obj_texto.value;
	obj_mostrador.value=campo.length;
	if (campo.length>parseInt(num_chars)) {
		alert(msg+" "+num_chars+" caracteres.");
		obj_texto.value=campo.substring(0,parseInt(num_chars));
		obj_mostrador.value=num_chars;
		return false;
	}
	return true;
}

//ABRE JANELA CENTRALIZADA
function PopupCentralizado(pagina,nome,width,height,parametros) {
	largura = screen.width;
	altura = screen.height;
	posX = (largura - width) / 2;
	posY = (altura - height) / 2;
	var janela = null;
	if (parametros=='') {
		janela = window.open(pagina, nome,'left='+posX+',top='+posY+',height='+height+',width='+width);
	} else {
		janela = window.open(pagina, nome,parametros+',left='+posX+',top='+posY+',height='+height+',width='+width);
	}
	janela.focus();
	return false;
}

function TeclaInteiro(e){
	var key;
	var keychar;
	var reg;
	
	if(window.event) {
		// for IE, e.keyCode or window.event.keyCode can be used
		key = e.keyCode; 
	}
	else if(e.which) {
		// netscape or firefox
		key = e.which; 
	}
	else {
		// no event, so pass through
		return true;
	}
	if((key > 47 && key < 58) || (key == 8)) // numeros de 0 a 9 OU BACKSPACE
		return true;
	else {
		return false;
	}
}


function validaData(objeto) {

	//textos conforme idioma
	var msg = "Digite uma data correta.";
	if(document.getElementById("idm_atual")!=null){
		switch(document.getElementById("idm_atual").value){
			case 2:
				msg = "Enter a valid date";
				break;
			case 3:
				msg = "Digite una fecha correcta";
				break;
		}
	}

	data = objeto.value;
	if (data == "") return true;
	if (data.length != 8 && data.length != 10) {
		alert(msg); 
		objeto.focus();
		return false;
	}

	dia = data.substring(0, 2);
	mes = data.substring(3, 5);
	
	if (data.length == 8)
		ano = data.substring(6, 8);
	else
		ano = data.substring(6, 10);
		
	objeto.value = dia + "/" + mes + "/" + ano;
	if ((retorno = isDate(objeto)) != false) {
		return true;
	} else {
		alert(msg);
		objeto.focus();
		return false;
}	}
//------------------------------------------------------------------------------------------------------------------------
function tira_barra(obj) {
	data = obj.value;
	dia = data.substr(0, 2);
	mes = data.substr(3, 2);
	if (data.length == 10)
		ano = data.substr(6, 4);
	else
		ano = data.substr(6, 2);
	data = dia + mes + ano;
	obj.value=data;
}
//------------------------------------------------------------------------------------------------------------------------
function isDate(objeto) {

//	var ano = "<%'= year(date) %>";
//	var hoje = "<%= year(date) & right("0"& month(date), 2) & right("0"& day(date), 2) %>";
	
	data = objeto.value;
	itens = data.split("/");
	if (itens[0] == "" || itens[1] == "" || itens[2] == "")
		return false;	

	if (isNaN(itens[0]) || isNaN(itens[1]) || isNaN(itens[2]))
		return false;

	/*if ((itens[2] + itens[1] + itens[0]) < strHoje)
		return "MENOR";//*/

	t0 = itens[0].length;	t1 = itens[1].length;	t2 = itens[2].length;
	if (t0 >= 3 || t1 >= 3 || t2 >= 5)
		return false;

	// valida se nunhum valor  menor que 0
	if (itens[0] <= 00 || itens[1] <= 00 || itens[2] <= 0000)
		return false;

	// valida o ano
	if (t2 <= 3) {
		if (itens[2] > 22)
			ano = "1900";
		else ano = "2000";
		aux = "";
		for (w = 0; w < 4 - t2; w++)
			aux += ano.charAt(w);
		y = 0;
		for (; w < 4; w++)
			aux += itens[2].charAt(y++);		
		itens[2] = aux;
	}

	// valida o mes
	if (itens[1] >= 13)
		return false;

	// captura o dia maximo para o mes digitado
	itens[1] = itens[1] * 1;
	if (itens[1] == 2) {
		if (itens[2]%400 == 0 || itens[2]%4 == 0 && itens[2]%100 != 0)
			vMax = 29;
		else	
			vMax = 28;
	} else
	if (itens[1] == 1 || itens[1] == 3 || itens[1] == 5 || itens[1] == 7 || itens[1] == 8 || itens[1] == 10 || itens[1] == 12)
		vMax = 31;
	else vMax = 30;
	itens[1] = "0"+ itens[1]; itens[1] = itens[1].charAt(itens[1].length - 2) + itens[1].charAt(itens[1].length - 1);

	// valida o dia do mes
	if (itens[0] > vMax)
		return false;
	itens[0] = "0"+ itens[0]; itens[0] = itens[0].charAt(itens[0].length - 2) + itens[0].charAt(itens[0].length - 1);

	objeto.value = itens[0] +"/"+ itens[1] +"/"+ itens[2];
	return true;
}


function ajaxCarregaDadosDiv(urlGet, divId){

	var xmlhttpTemplate = createHttp();
	xmlhttpTemplate.onreadystatechange = function () {
		if (xmlhttpTemplate.readyState == 4){
			if (xmlhttpTemplate.status == 404) {
				//nao encontru url
			} else {
				//resposta da query ok
				var divConteudo = document.getElementById(divId);
				divConteudo.innerHTML = xmlhttpTemplate.responseText;
			}
			delete xmlhttpTemplate;
		}
	}
	xmlhttpTemplate.open("GET", urlGet, true);
	xmlhttpTemplate.send(null);
}


function createHttp(){
	//cria objeto de conexo AJAX
	try {var xmlhttp = new XMLHttpRequest();
	} catch(ee) {
		try {var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(E) {var xmlhttp = false;}
		}
	}
	return xmlhttp;
}


function validaCNPJ(campo,cnpj){
	if(!isCnpj(cnpj)){
		alert("Número do CNPJ  inválido");
		document.getElementById(campo).value = "";
		document.getElementById(campo).focus();
		return false;
	}else{
		return true;
	}
}

function validaCPF(campo,cpf){
	if(!isCpf(cpf)){
		alert("Número do CPF  inválido");
		document.getElementById(campo).value = "";
		document.getElementById(campo).focus();
		return false;
	}else{
		return true;
	}
}


/** ===================INICIO DAS FUNCOES DE VALIDACAO DE CPF E CNPJ=======================================================================*/
/*
 * @version 1.01, 2004
 *
 * PROTTIPOS:
 * mtodo String.lpad(int pSize, char pCharPad)
 * mtodo 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 mtodo 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 mtodo trim()  classe String.
// * Elimina brancos no incio e fim da String.
// */
//String.prototype.trim = function()
//{
//	return this.replace(/^\s*/, "").replace(/\s*$/, "");
//} //String.trim


/**
 * Elimina caracteres de formatao e zeros  esquerda da string
 * de nmero fornecida.
 * @param String pNum
 * 	String de nmero fornecida para ser desformatada.
 * @return String de nmero 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 necessrio 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 contrrio,  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 dgitos verificadores para o nmero-efetivo pEfetivo de
 * CNPJ (12 dgitos) ou CPF (9 dgitos) fornecido. pIsCnpj  booleano e
 * informa se o nmero-efetivo fornecido  CNPJ (default = false).
 * @param String pEfetivo
 * 	String do nmero-efetivo (SEM dgitos verificadores) de CNPJ ou CPF.
 * @param boolean pIsCnpj
 * 	Indica se a string fornecida  de um CNPJ.
 * 	Caso contrrio,  CPF. Default = false (CPF).
 * @return String com os dois dgitos 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, false, pIsCnpj);
	calculado = calculado.substring(2, maxDigitos);
	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 vlido.
 * Qualquer formatao que no seja algarismos  desconsiderada.
 * @param String pCpf
 * 	String fornecida para ser testada.
 * @return <code>true< / code> se a String fornecida for um CPF vlido.
 */
function isCpf(pCpf)
{
	var numero = formatCpfCnpj(pCpf, false, false);
	var base = numero.substring(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	// Valida dgitos verificadores
	if (numero != base + digitos) return false;

	/* No sero considerados vlidos 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 (i=1; i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isCpf


/**
 * Testa se a String pCnpj fornecida  um CNPJ vlido.
 * Qualquer formatao que no seja algarismos  desconsiderada.
 * @param String pCnpj
 * 	String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CNPJ vlido.
 */
function isCnpj(pCnpj)
{
	var numero = formatCpfCnpj(pCnpj, false, true);
	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 dgitos verificadores
	if (numero != base + ordem + digitos) return false;

	/* No sero considerados vlidos os CNPJ com os seguintes nmeros BSICOS:
	 * 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 (i=1; i<NUM_DGT_CNPJ_BASE; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	if (algUnico) return false;

	/* No ser considerado vlido CNPJ com nmero de ORDEM igual a 0000.
	 * No ser considerado vlido CNPJ com nmero de ORDEM maior do que 0300
	 * e com as trs primeiras posies do nmero BSICO com 000 (zeros).
	 * Esta crtica no ser feita quando o no BSICO 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 vlido.
// * Se a String tiver uma quantidade de dgitos igual ou inferior
// * a 11, valida como CPF. Se for maior que 11, valida como CNPJ.
// * Qualquer formatao que no seja algarismos  desconsiderada.
// * @param String pCpfCnpj
// * 	String fornecida para ser testada.
// * @return <code>true</code> se a String fornecida for um CPF ou CNPJ vlido.
// */
//function isCpfCnpj(pCpfCnpj)
//{
//	var numero = pCpfCnpj.replace(/\D/g, "");
//	if (numero.length > NUM_DIGITOS_CPF)
//		return isCnpj(pCpfCnpj)
//	else
//		return isCpf(pCpfCnpj);
//} //isCpfCnpj

/**===========================FIM DAS FUNCOES DE VALIDACAO DE CPF E CNPJ===============================================================*/

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
  var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

  if(window.event) {
	// for IE, e.keyCode or window.event.keyCode can be used
	nTecla = evtKeyPress.keyCode; 
  }
  else if(evtKeyPress.which) {
	// netscape or firefox
	nTecla = evtKeyPress.which; 
  }
  else {
	// no event, so pass through
	return true;
  }

  /*if(document.all) { // Internet Explorer
	nTecla = evtKeyPress.keyCode;
	 }
  else if(document.layers) { // Nestcape
	nTecla = evtKeyPress.which;
  }*/
  
  sValue = objForm[strField].value;

  if (sMask == '(99) 999-9999') {
	 if (sValue.length > 12) {
		sMask = '(99) 9999-9999';
	 }
  }

  // Limpa todos os caracteres de formatao que
  // j estiverem no campo.
  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) == "/"))
	bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

	if (bolMask) {
	  sCod += sMask.charAt(i);
	  mskLen++; }
	else {
	  sCod += sValue.charAt(nCount);
	  nCount++;
	}

	i++;
  }
  
  objForm[strField].value = sCod;

  if (nTecla != 8) { // backspace
	if (sMask.charAt(i-1) == "9") { // apenas nmeros...
	  return ((nTecla > 47) && (nTecla < 58)); } // nmeros de 0 a 9
	else if (sMask.charAt(i-1) == "A") { // apenas caracteres literais (formata automaticamente para maiuscula)...
	  if(evtKeyPress.keyCode >= 97 && evtKeyPress.keyCode <= 122){ //a - z
		  evtKeyPress.keyCode = evtKeyPress.keyCode - 32;
	  }
	  return ((nTecla <= 47) || (nTecla >= 58)); } // qualquer caracter menos os nmeros de 0 a 9
	else if (sMask.charAt(i-1) == "a") { // apenas caracteres literais (formata automaticamente para minuscula)...
	  if(evtKeyPress.keyCode >= 65 && evtKeyPress.keyCode <= 90){ //a - z
		  evtKeyPress.keyCode = evtKeyPress.keyCode + 32;
	  }
	  return ((nTecla <= 47) || (nTecla >= 58)); } // qualquer caracter menos os nmeros de 0 a 9
	else if (sMask.charAt(i-1) == "*") { // apenas caracteres literais...
	  return ((nTecla <= 47) || (nTecla >= 58)); } // qualquer caracter menos os nmeros de 0 a 9
	else { // qualquer caracter...
	  return true;
	}
  }  else {
	return true;
  }
}


function mask_horas(edit,evento){
  	if(evento.keyCode<48 || evento.keyCode>57){
		evento.returnValue=false;
  	}
  	if(edit.value.length==2){
		edit.value+=":";
	}
}

function codificaURL(valor){
	if (valor !=undefined){
		valor = valor.replace(/‘/g,"'").replace(/’/g,"'").replace(/“/g,"\"").replace(/”/g,"\"");
	}

	valor = encodeURIComponent(valor)
	return valor;
}

/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Robert Nyman | http://robertnyman.com/ */
function removeHTMLTags(strInputCode,delSpaces){
	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
		return (p1 == "lt")? "<" : ">";
	});
	var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
	if (delSpaces) strTagStrippedText = strTagStrippedText.replace(/(\s|&nbsp;)/g, "");
	return strTagStrippedText;
}
