﻿function ExpandeImg(paramID, img)
{

   if(document.getElementById(paramID).style.display == 'none')
   {
	  img.src='../../Imgs/IconeMenosQuadrado.gif';
      document.getElementById(paramID).style.display = 'block';
   }
   else
   {
      document.getElementById(paramID).style.display = 'none';
      img.src='../../Imgs/IconeMaisQuadrado.gif';
   }

}


// JScript File
function TrocaList(ListOrigem,ListDestino) 
{
	var i;
	for (i = 0; i < ListOrigem.options.length ; i++)
	{
		if (ListOrigem.options[i].selected == true)
		{
			var Op = document.createElement("OPTION");
			Op.text = ListOrigem.options[i].text;
			Op.value = ListOrigem.options[i].value;
			ListDestino.options.add(Op);
			ListOrigem.options.remove(i);
			i--;
		}
	}
}

function TrocaListTodos(ListOrigem,ListDestino) 
{
	var i;
	for (i = 0; i < ListOrigem.options.length ; i++)
	{
			var Op = document.createElement("OPTION");
			Op.text = ListOrigem.options[i].text;
			Op.value = ListOrigem.options[i].value;
			ListDestino.options.add(Op);
			ListOrigem.options.remove(i);
			i--;
	}
}

/*Funções de Janela*//*Funções de Janela*//*Funções de Janela*/
/*Funções de Janela*//*Funções de Janela*//*Funções de Janela*/

//Função para abrir uma janela popup centralizada
function openWin(sURL,sNome,iWidth,iHeight)
{
	janela=window.open(sURL,sNome,"status=yes,menubar=no,toolbar=no,width="+ iWidth +",height="+ iHeight +",scrollbars=yes, top="+ (screen.height - iHeight)/2 +",left="+(screen.width - iWidth)/2 + ",directories=no");

    //interceptacao de erro na abertura da janela
    text = "Se a janela nao estava abrindo\ntalvez seja porque voce tenha um\nprograma bloqueador de pop-up!\nObservacao » O windows XP service pack 2\nbloqueia pop-ups!";
    if(janela == null) { alert(text); return; }
    //fim
    //janela.moveTo(350,150);
}

//Função para abrir uma janela popup centralizada
function openWindow(sURL,sNome,iWidth,iHeight,iresizable)
{
	janela=window.open(sURL,sNome,"resizable="+ iresizable +",status=yes,menubar=no,toolbar=no,width="+ iWidth +",height="+ iHeight +",scrollbars=yes, top="+ (screen.height - iHeight)/2 +",left="+(screen.width - iWidth)/2 + ",directories=no");

    //interceptacao de erro na abertura da janela
    text = "Se a janela nao estava abrindo\ntalvez seja porque voce tenha um\nprograma bloqueador de pop-up!\nObservacao » O windows XP service pack 2\nbloqueia pop-ups!";
    if(janela == null) { alert(text); return; }
    //fim
    //janela.moveTo(350,150);
}
//Função para abrir uma janela popup centralizada
function openWindow(sURL,sNome,iWidth,iHeight,iresizable, iscroll)
{
	janela=window.open(sURL,sNome,"resizable="+ iresizable +",status=yes,menubar=no,toolbar=no,width="+ iWidth +",height="+ iHeight +",scrollbars="+ iscroll +", top="+ (screen.height - iHeight)/2 +",left="+(screen.width - iWidth)/2 + ",directories=no");

    //interceptacao de erro na abertura da janela
    text = "Se a janela nao estava abrindo\ntalvez seja porque voce tenha um\nprograma bloqueador de pop-up!\nObservacao » O windows XP service pack 2\nbloqueia pop-ups!";
    if(janela == null) { alert(text); return; }
    //fim
    //janela.moveTo(350,150);
}

//Função para abrir uma janela popup centralizada
function openWindow(sURL,sNome,iWidth,iHeight,iresizable, iscroll, menubar)
{
	janela=window.open(sURL,sNome,"resizable="+ iresizable +",status=yes,menubar="+ menubar +",toolbar=no,width="+ iWidth +",height="+ iHeight +",scrollbars="+ iscroll +", top="+ (screen.height - iHeight)/2 +",left="+(screen.width - iWidth)/2 + ",directories=no");

    //interceptacao de erro na abertura da janela
    text = "Se a janela nao estava abrindo\ntalvez seja porque voce tenha um\nprograma bloqueador de pop-up!\nObservacao » O windows XP service pack 2\nbloqueia pop-ups!";
    if(janela == null) { alert(text); return; }
    //fim
    //janela.moveTo(350,150);
}

//Função para abrir uma janela popup centralizada
function openModalDialog(sURL,sNome,iWidth,iHeight,iresizable)
{
	if (window.showModalDialog) 	
	{
		window.showModalDialog(sURL, sNome, "dialogHeight: " + iHeight + "px; dialogWidth: " + iWidth + "px; dialogTop: px; dialogLeft: px; center: Yes; help: No; resizable: " + iresizable + "; status: No; dialogHide: No; edge: Sunken; scroll: Yes; unadorned:no;");
	}
	else
	{
		janela=window.open(sURL,sNome,"resizable="+ iresizable +",status=yes,menubar=no,toolbar=no,width="+ iWidth +",height="+ iHeight +",scrollbars=yes, top="+ (screen.height - iHeight)/2 +",left="+(screen.width - iWidth)/2 + ",directories=no,modal=true");

		//interceptacao de erro na abertura da janela
		text = "Se a janela nao estava abrindo\ntalvez seja porque voce tenha um\nprograma bloqueador de pop-up!\nObservacao » O windows XP service pack 2\nbloqueia pop-ups!";
		if(janela == null) { alert(text); return; }
	}
	
	
}

//Função para abrir uma janela popup centralizada
function openModalDialog(sURL,sNome,iWidth,iHeight,iresizable, iscroll)
{
	if (iscroll == null || iscroll == '')
	{
		iscroll = 'no';
	}

	if (window.showModalDialog)
	{
		window.showModalDialog(sURL, sNome, "dialogHeight: " + iHeight + "px; dialogWidth: " + iWidth + "px; dialogTop: px; dialogLeft: px; center: Yes; help: No; resizable: " + iresizable + "; status: Yes; dialogHide: No; edge: Sunken; scroll: "+ iscroll +"; unadorned:no;");
	}
	else
	{
		janela=window.open(sURL,sNome,"resizable="+ iresizable +",status=yes,menubar=no,toolbar=no,width="+ iWidth +",height="+ iHeight +",scrollbars="+ scroll +", top="+ (screen.height - iHeight)/2 +",left="+(screen.width - iWidth)/2 + ",directories=no,modal=yes");

		//interceptacao de erro na abertura da janela
		text = "Se a janela nao estava abrindo\ntalvez seja porque voce tenha um\nprograma bloqueador de pop-up!\nObservacao » O windows XP service pack 2\nbloqueia pop-ups!";
		if(janela == null) { alert(text); return; }
	}
}

function abrePopupModal(pagina, popupname, strWidth, strHeight, nLeftLocal, nTopLocal, bScroll)
{
	if (checkModal()) return;
	
	if (!nLeftLocal && nLeftLocal !=0)
		nLeftLocal = 0

	if (!nTopLocal && nTopLocal !=0)
		nTopLocal = 0
	
	if (strHeight >= 400)
		nTopLocal = 20
		
	if (strWidth >= 700)
		nLeftLocal = 20
	
	if (!bScroll) 
		strScroll = ",scrollbars=no"
	else 
		strScroll = ",scrollbars=yes"
	
	if (parent.document)
	{
		if (winModalWindow)
		{
			if (winModalWindow.closed)
			{
				winModalWindow = window.open(pagina, popupname, "dependent=yes,width=" + strWidth + ",height=" + strHeight + ",left=" + nLeftLocal + ",top=" + nTopLocal + strScroll);
				parent.winModalWindow = winModalWindow
				parent.parent.winModalWindow = winModalWindow
				parent.parent.parent.winModalWindow = winModalWindow
				winModalWindow.focus();
			}
		}
		else
		{
			winModalWindow = window.open(pagina, popupname, "dependent=yes,width=" + strWidth + ",height=" + strHeight + ",left=" + nLeftLocal + ",top=" + nTopLocal + strScroll);
			parent.winModalWindow = winModalWindow
			parent.parent.winModalWindow = winModalWindow
			parent.parent.parent.winModalWindow = winModalWindow
			winModalWindow.focus();
		}
	}
	else
	{
		if (winModalWindow)
		{
			if (winModalWindow.closed)
			{
				winModalWindow = window.open(pagina, popupname, "dependent=yes,width=" + strWidth + ",height=" + strHeight + ",left=" + nLeftLocal + ",top=" + nTopLocal + strScroll);
				winModalWindow.focus();
			}
		}
		else
		{
			winModalWindow = window.open(pagina, popupname, "dependent=yes,width=" + strWidth + ",height=" + strHeight + ",left=" + nLeftLocal + ",top=" + nTopLocal + strScroll);
			winModalWindow.focus();
		}
	}
	return false;
}

function checkModal()
{

	if (!winModalWindow)
	{
		return false;
	}
	else if (winModalWindow.closed)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function ResizeWindow(Largura,Altura)
{
	if ( (window.self.screen.height != Altura) || (window.self.screen.height != Largura) )
	{
		try
		{
			window.self.resizeTo(Largura, Altura);
		}
		catch(ex)
		{
			//alert(ex);
			vazio = ex;
		}
	}
}

/* FIM :: Funções de Janela*//* FIM :: Funções de Janela*//* FIM :: Funções de Janela*/
/* FIM :: Funções de Janela*//* FIM :: Funções de Janela*//* FIM :: Funções de Janela*/

function ConfirmComPostBack(NomeBotao, Msg, Hidden)
{
	decisao = confirm(Msg);

	if (decisao)
	{
	  document.getElementById(Hidden).value  = '1';
	  __doPostBack(NomeBotao,'');
	}
}

function ConfirmListar(NomeBotao, Hidden)
{
	if (confirm("O registro ainda não foi salvo. Deseja salvá-lo?"))
	{
    	document.getElementById(Hidden).value = "1";
    }
	else
	{
	    document.getElementById(Hidden).value = "0";
	}
	
	__doPostBack(NomeBotao,'');
}






function checkDateGapInt(ObjData)
{	
	var dataInicial = new Date('01/01/1753');
	var dataFinal	= new Date('01/01/1753');
	
	if (ObjData.FormatoFull == true)
	{
   		dataInicial = new Date(formaDataDDMMYYYY(ObjData.dataInicio.value));
		dataFinal = new Date(formaDataDDMMYYYY(ObjData.dataFim.value));
	}
	else
	{
		dataInicial = new Date(formaDataDDMMYYYY(ObjData.dataInicio.value));
		dataFinal = new Date(formaDataDDMMYYYY(ObjData.dataFim.value));

		
	}
	
	var dataLimiteMinimo = new Date('01/01/1753');
	var dataLimiteMaximo = new Date('31/12/9999');

   	if (dataInicial > dataFinal)
	{
		//'A data inicial deve ser menor que a final!
	   //alert(ObjData.MensagemPadrao);
	   return false;
	}
   	
   	if (dataInicial < dataLimiteMinimo || dataInicial > dataLimiteMaximo)
	{
	   alert(ObjData.MensagemPadraoOutRange);
	   ObjData.dataInicio.focus();
	   return false;
	}
	
	if (dataFinal < dataLimiteMinimo || dataFinal > dataLimiteMaximo)
	{
	   alert(ObjData.MensagemPadraoOutRange);
	   ObjData.dataFim.focus();
	   return false;
	}
	return true;
}


function checkDateGap(ObjData)
{	
	var dataInicial = new Date('01/01/1753');
	var dataFinal	= new Date('01/01/1753');
	
	if (ObjData.FormatoFull == true)
	{
   		dataInicial = new Date(formaDataMMDDYYYY(ObjData.dataInicio.value));
		dataFinal = new Date(formaDataMMDDYYYY(ObjData.dataFim.value));
	}
	else
	{
		//dataInicial = new Date(formaDataMMYYY_MMDDYYYY(ObjData.dataInicio.value));
		//dataFinal = new Date(formaDataMMYYY_MMDDYYYY(ObjData.dataFim.value));
		dataInicial = new Date(formaDataYYYYMMDD(ObjData.dataInicio.value));
		dataFinal = new Date(formaDataYYYYMMDD(ObjData.dataFim.value));
	}
	
	var dataLimiteMinimo = new Date('01/01/1753');
	var dataLimiteMaximo = new Date('31/12/9999');

   	if (dataInicial > dataFinal)
	{
		//'A data inicial deve ser menor que a final!
	   //alert(ObjData.MensagemPadrao);
	   return false;
	}
   	
   	if (dataInicial < dataLimiteMinimo || dataInicial > dataLimiteMaximo)
	{
	   alert(ObjData.MensagemPadraoOutRange);
	   ObjData.dataInicio.focus();
	   return false;
	}
	
	if (dataFinal < dataLimiteMinimo || dataFinal > dataLimiteMaximo)
	{
	   alert(ObjData.MensagemPadraoOutRange);
	   ObjData.dataFim.focus();
	   return false;
	}
	return true;
}

//====================================================================================================
//	Nome:		FormataDMA2AMD
//	Descrição:	Formata a data para o padrão universal.
//====================================================================================================
function FormataDMA2AMD(data)
{
	var arrayData = data.split("/");
	return arrayData[2] + "-" + arrayData[1] + "-" + arrayData[0]; 
}

function formaDataMMDDYYYY(data)
{
	data		  = data.split("/");
	return data[1] + '/' + data[0] + '/' + data[2];
}

function formaDataDDMMYYYY(data)
{
	data		  = data.split("/");
	return data[0] + '/' + data[1] + '/' + data[2];
}

function formaDataMMYYY_MMDDYYYY(data)
{
	data		  = data.split("/");
	dataFormatada = data[0] + '/' + '01' + '/' + data[1];
	return  dataFormatada;
}

function formaDataYYYYMMDD(data)
{
	data		  = data.split("/");
	dataFormatada = data[2] + '/' + data[1] + '/' + data[0];
	return  dataFormatada;
}

/* FIM :: refente a validação de datas*/

function RetornaItemVSFormatado(valor)
{
	return '<ul><li>' + valor + '</ul></li>';
}

/*Função que valida se Data é maior que a outra*/

function DataValida()
{
	objetos = RecuperaObjData();
	
	if(objetos.dataInicio.value!="" && objetos.dataFim.value!="")
	{
		return checkDateGap(objetos);
	}
	else if(objetos.dataInicio.value!="" || objetos.dataFim.value!="")
	{
		return false;
	}
}

/********/



function validaCpf(val)
{
	var valor = document.all[val.controltovalidate].value;
	return isCpf(valor);
}


//#**************************************************************************
// Função	 : FormataCPF(Campo, teclapres)
// Objetivo  : Faz a máscara do CPF.
// Parametro : val - tecla a ser pressionada.
// Exemplo   : FormataCPF(this,event)
//#**************************************************************************
//function FormataCPF(Campo, teclapres)
function FormataCPF(Campo, event)
{
	var tecla = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

	if (!(((tecla>47)&&(tecla<58))|(tecla==13)|(tecla==44)|(tecla==46)))
		event.returnValue = false;
	//var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace(/[-\.]/g, "");
	tam = vr.length + 1;
	if (tecla != 9 && tecla != 8){
	if (tam > 3 && tam < 7)
	Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, tam);
	if (tam >= 7 && tam <10)
	Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,tam-6);
	if (tam >= 10 && tam < 12)
	Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,3) + '-' + vr.substr(9,tam-9);
	}
}
//#**************************************************************************
// Função	 : FormataCNPJ(Campo, teclapres)
// Objetivo  : Faz a máscara do CPF.
// Parametro : val - tecla a ser pressionada.
// Exemplo   : FormataCNPJ(this, event)
//#**************************************************************************
function FormataCNPJ(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace(/[-\.\/]/g, "");
	tam = vr.length + 1 ;
	if (tecla != 9 && tecla != 8){
	if (tam > 2 && tam < 6)
	Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
	if (tam >= 6 && tam < 9)
	Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
	if (tam >= 9 && tam < 13)
		Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
	if (tam >= 13 && tam < 15)
	Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
	}
}


//#**************************************************************************
// Função	 : ValidaCNPJ(tammax,teclapres)
//#**************************************************************************
function validaCnpj(val)
{
	var valor = document.all[val.controltovalidate].value;
	return isCnpj(valor);
}

function validaCpfCnpj(val)
{
	var valor = document.all[val.controltovalidate].value;
	return isCpfCnpj(valor);
}

//
// @author Márcio d'Ávila
// @version 1.0, 2004

var NUM_DIGITOS_CNPJ = 14;
var NUM_DIGITOS_CPF  = 11;

//
// 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 dif = pSize - this.length;
	var s = this;
	if (dif > 0)
	{
		for (; dif!=0; dif--) s = pCharPad + s;
	}
	return (s);
} //String.lpad



// 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.

function formatNumber(pNum)
{
	//alert("Format");
	var reSimbolos = /\D/g;
	return numero = pNum.replace(reSimbolos, "");
} //unformatNumber
function unformatNumber(pNum)
{
	var reSimbolos = /\D/g;
	var reZeroEsq = /^0+/;
	var numero = pNum.replace(reSimbolos, "");
	return (numero.replace(reZeroEsq, ""));
} //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).

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-base pBase de
// CNPJ (12 dígitos) ou CPF (9 dígitos) fornecido. pIsCnpj é booleano e
// informa se o número-base fornecido é CNPJ (default = false).
// @param String pBase
// 	String do número-base (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).
//
function dvCpfCnpj(pBase, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? 8: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pBase, 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 pCnpj fornecida é um CNPJ válido.
// Qualquer formatação que não seja algarismos é desconsiderada.
// @param String pCnpj
// 	String fornecida para ser testada.

function isCnpj(pCnpj)
{
	if (pCnpj.length == 0)
	{
	
		return true;
		
	}
	var numero = formatCpfCnpj(pCnpj, false, true);
	var base = numero.substring(0, 8);
	var ordem = numero.substring(8, 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 (i=1; i<8; i++)
	{
		algUnico = 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 pCpf fornecida é um CPF válido.
// Qualquer formatação que não seja algarismos é desconsiderada.
// @param String pCpf
// 	String fornecida para ser testada.

function isCpf(pCpf)
{
	if (pCpf.length == 0)
	{
		return true;
	}
	var numero = formatCpfCnpj(pCpf, false, 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 (i=1; i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isCpf


function isCpfCnpj(pCpfCnpj)
{
	var reSimbolos = /\D/g;
	var numero = pCpfCnpj.replace(reSimbolos, "");
	if (numero.length > NUM_DIGITOS_CPF)
		return isCnpj(pCpfCnpj)
	else
		return isCpf(pCpfCnpj);
} //isCpfCnpj






function validaData(str) { 

	dia = (str.value.substring(0,2)); 
    mes = (str.value.substring(3,5)); 
	ano = (str.value.substring(6,10)); 

	cons = true; 
	
	// verifica se foram digitados números
	if (isNaN(dia) || isNaN(mes) || isNaN(ano)){
		alert("Preencha a data somente com números."); 
		str.value = "";
		str.focus(); 
		return false;
	}
		
    // verifica o dia valido para cada mes 
    if ((dia < 01)||(dia < 01 || dia > 30) && 
		(mes == 04 || mes == 06 || 
		 mes == 09 || mes == 11 ) || 
		 dia > 31) { 
    	cons = false; 
	} 

	// verifica se o mes e valido 
	if (mes < 01 || mes > 12 ) { 
		cons = false; 
	} 

	// verifica se e ano bissexto 
	if (mes == 2 && ( dia < 01 || dia > 29 || 
	   ( dia > 28 && 
	   (parseInt(ano / 4) != ano / 4)))) { 
		cons = false; 
	} 
    
	if (cons == false) { 
		alert("A data inserida não é válida: " + str.value); 
		str.value = "";
		str.focus(); 
		return false;
	} 
}

// colocar no evento onKeyUp passando o objeto como parametro
function MaskDatafull(val)
{
   	var pass = val.value;
	var expr = /[0123456789]/;
		
	for(i=0; i<pass.length; i++){
		// charAt -> retorna o caractere posicionado no índice especificado
		var lchar = val.value.charAt(i);
		var nchar = val.value.charAt(i+1);
	
		if(i==0){
		   // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
		   // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
		   // instStr.search(expReg);
		   if ((lchar.search(expr) != 0) || (lchar>3)){
			  val.value = "";
		   }
		   
		}else if(i==1){
			   
			   if(lchar.search(expr) != 0){
				  // substring(indice1,indice2)
				  // indice1, indice2 -> será usado para delimitar a string
				  var tst1 = val.value.substring(0,(i));
				  val.value = tst1;				
 				  continue;			
			   }
			   
			   if ((nchar != '/') && (nchar != '')){
				 	var tst1 = val.value.substring(0, (i)+1);
				
					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
			   }

		 }else if(i==4){
			
				if(lchar.search(expr) != 0){
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;
					continue;			
				}
		
				if	((nchar != '/') && (nchar != '')){
					var tst1 = val.value.substring(0, (i)+1);

					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
				}
   		  }
		
		  if(i>=6){
			  if(lchar.search(expr) != 0) {
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;			
			  }
		  }
	 }
	
     if(pass.length>10)
		val.value = val.value.substring(0, 10);
	 	return true;
}


//*********** somente números *******************

function ValidaNumeros(tecla, exibeMsg)
{
if(typeof(tecla) == 'undefined')

var tecla = window.event;

var codigo = (tecla.which ? tecla.which : tecla.keyCode ? tecla.keyCode : tecla.charCode);

// permite números, 8=backspace, 46=del e 9=tab

if ( (codigo >= 48 && codigo <= 57) || (codigo >= 96 && codigo <= 105) || codigo == 8 || codigo == 46 || codigo == 9 )

{ return true; }
else
{ if (exibeMsg){alert("Apenas números são permitidos !");} return false; } 

}


function SomenteNumero(e) {
    var tecla = (window.event) ? event.keyCode : e.which;
    if ((tecla > 47 && tecla < 58)) return true;
    else {
        if (tecla != 8) return false;
        else return true;
    }
}




function ReturnOnlyUnformatNumber(pNum)
{
	//alert("Format");
	var reSimbolos = /\D/g;
	pNum.value = pNum.value.replace(reSimbolos, "");
} 
function ReturnOnlyNumber(pNum)
{
	var reSimbolos = /\D/g;
	var reZeroEsq = /^0+/;
	var numero = pNum.value.replace(reSimbolos, "");
	pNum.value = numero.replace(reZeroEsq, "");
} 

//Mascara_Hora
function MascaraHora_Evento(obj, culture, event)
{ 
    var hs = obj.value;
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    
    if (keyCode >= 48 && keyCode <= 57 && hs.length < 5)
    {
        var hora01 = ''; 
        hora01 = hora01 + obj.value; 
        
        if(hora01.charAt(0)==':' || hora01.charAt(1) == ':')
            obj.value = "";
        else {
            if (hora01.length == 2)
            { 
                hora01 = hora01 + ':'; 
                obj.value = hora01;
            } 
        }
        if (hora01.length == 4)
        { 
            if (Verifica_Hora(hora01))
            {
                obj.value = hora01;
            }
            else
            {
                obj.value = "";
                //e.preventDefault? e.preventDefault() : e.returnValue = false;
                event.returnValue = false;
            }
        }
    }
    else if (culture == "en-us")
    {
        var hora01 = obj.value;
        if (hora01.substring(0,2) < 12)
        {
            if (keyCode == 32 && hora01.length == 5)
            {
                event.returnValue = true;
            }
            else if ((keyCode == 97 || keyCode == 112 || keyCode == 65 || keyCode == 80 )  && hora01.length == 6)
            {
                event.returnValue = true;
            }
            else if ((keyCode == 109  || keyCode == 77) && hora01.length == 7) 
            {
                event.returnValue = true;
            }
            else
            {
                event.returnValue = false;
            }
        }
        else
        {
            //event.preventDefault? event.preventDefault() : event.returnValue = false;
            event.returnValue = false;
        }
    }
    else
    {
        event.returnValue = false;
    }
} 

function Verifica_Hora(value)
{ 
    hrs = (value.substring(0,2)); 
    min = (value.substring(3,5)); 
               
    if (!((hrs < 00 ) || (hrs > 23) || ( min < 00) ||( min > 59)))
    { 
        return true;
    } 
    else
        return false;
} 


function CompleteHora_Evento(obj, culture,event){ 
    if (obj.value.length == 1)
    {
        if (obj.value.charAt(0) == ':')
            obj.value = "";
        else{
        valor = obj.value;
        obj.value = "0" + valor + ":00";
        }
    }
    else if (obj.value.length == 2)
    {
        if(obj.value.charAt(0) == ':' || obj.value.charAt(1) == ':')
            obj.value = "0" + obj.value + "00"
        else
            obj.value = obj.value + ":00";
    }
    else if (obj.value.length == 4)
    {
        obj.value = obj.value + "0";
    }
    if (!Verifica_Hora(obj.value)) 
    {
        obj.value = "";
        //e.preventDefault? e.preventDefault() : e.returnValue = false;
        event.returnValue = false;
    }
    else
    {
        if (culture == "en-us")
        {
            var hora01 = obj.value;
            if (hora01.substring(0,2) < 12 && hora01.length == 5)
            {
                obj.value = obj.value + " AM";
            }
            else if (hora01.substring(0,2) < 12 && hora01.length == 6)
            {
                obj.value = obj.value + "AM";
            }
            else if (hora01.length == 7)
            {
                obj.value = obj.value.toUpperCase() + "M";
            }
            else
            {
                obj.value = obj.value.toUpperCase();
            }
        }
    }
} 



/*********************/

function isDate(str, ExibeMsg) 
{ 
	if(Cultura == null || Cultura == "")
	{ Cultura ="pt-br";}

	if(str.value.length < 10)
	{
		if(ExibeMsg)
		{ alert("Data Inválida."); }
		str.value = "";
		str.focus(); 
		return false;	
	}

	dia = (Cultura != "en-us" ? (str.value.substring(0,2)) : (str.value.substring(3,5))); 
    mes = (Cultura != "en-us" ? (str.value.substring(3,5)) : (str.value.substring(0,2)));
	ano = (str.value.substring(6,10)); 

	cons = true; 
	
	// verifica se foram digitados números
	if (isNaN(dia) || isNaN(mes) || isNaN(ano))
	{
		if(ExibeMsg)
		{ alert("Preencha a data somente com números."); }
		str.value = "";
		str.focus(); 
		return false;
	}
		
    // verifica o dia valido para cada mes 
    if ((dia < 01)||(dia < 01 || dia > 30) && 
		(mes == 04 || mes == 06 || 
		 mes == 09 || mes == 11 ) || 
		 dia > 31) { 
    	cons = false; 
	} 

	// verifica se o mes e valido 
	if (mes < 01 || mes > 12 ) { 
		cons = false; 
	} 

	// verifica se e ano bissexto 
	if (mes == 2 && ( dia < 01 || dia > 29 || 
	   ( dia > 28 && 
	   (parseInt(ano / 4) != ano / 4)))) { 
		cons = false; 
	} 
    
	if (cons == false) 
	{ 
		if(ExibeMsg)
		{ alert("A data inserida não é válida: " + str.value); }
		str.value = "";
		str.focus(); 
		return false;
	} 
}

function isDate(str) 
{ 
	if(Cultura == null || Cultura == "")
	{ Cultura ="pt-br";}

	if(str.length < 10)
	{ return false;	}

	dia = (Cultura != "en-us" ? (str.substring(0,2)) : (str.substring(3,5))); 
    mes = (Cultura != "en-us" ? (str.substring(3,5)) : (str.substring(0,2)));
	ano = (str.substring(6,10)); 

	cons = true; 
	
	// verifica se foram digitados números
	if (isNaN(dia) || isNaN(mes) || isNaN(ano))
	{ return false; }
		
    // verifica o dia valido para cada mes 
    if ((dia < 01)||(dia < 01 || dia > 30) && 
		(mes == 04 || mes == 06 || 
		 mes == 09 || mes == 11 ) || 
		 dia > 31) { 
    	cons = false; 
	} 

	// verifica se o mes e valido 
	if (mes < 01 || mes > 12 ) { 
		cons = false; 
	} 

	// verifica se e ano bissexto 
	if (mes == 2 && ( dia < 01 || dia > 29 || 
	   ( dia > 28 && 
	   (parseInt(ano / 4) != ano / 4)))) { 
		cons = false; 
	} 
    
	if (cons == false) 
	{  return false; } 
	else
	{ return true; }
}

// colocar no evento onblur passando o objeto como parametro
function CompletaMesAno(src,culture,event)
{
	if(src.value == "")
	{ return; }

	var arrayData = src.value.split("/");
	var dataSistema = new Date(); 
	
	var _dia = dataSistema.getDate(); 
	var _mes = dataSistema.getMonth()+1; 
	var _ano = dataSistema.getYear(); 

	
	var dia = 0;
	var mes = 0;
	var ano = 0;
	
	if (culture == "en-us")
    { 
		mes = arrayData[0];
		
		if(arrayData[1] != null)
		{ dia = arrayData[1]; }
		else
		{dia = (_dia > 9 ? _dia : "0" + _dia);}
		
		if(arrayData[2] != null)
		{ ano = arrayData[2]; }
		else
		{ano = _ano;}	
		
		var blnData = isDate(mes + "/" + dia + "/" + ano);
		
		if(blnData)
		{
			src.value = mes + "/" + dia + "/" + ano;
			return event.returnValue = true;
		}
		else
		{ 
			/*if(culture.split[0] == "en")
			{ alert(""); }
			else if(culture.split[0] == "es")
			{ alert(""); }
			else
			{ alert("Data Inválida"); }
			*/
			src.value = "";
			return event.returnValue = false; 
		}
		    
    }
    else
    {
		dia = arrayData[0];
		
		if(arrayData[1] != null)
		{ mes = arrayData[1]; }
		else
		{mes = _mes;}
		
		if(arrayData[2] != null)
		{ ano = arrayData[2]; }
		else
		{ano = _ano;}	
		
		var blnData = isDate(dia + "/" + mes + "/" + ano);
		
		if(blnData)
		{
			src.value = dia + "/" + mes + "/" + ano;
			return event.returnValue = true;
		}
		else
		{ 
			src.value = "";
			return event.returnValue = false; 
		}
		
    }
	
	/*event.returnValue = false;
    }
    else
    {
        if (culture == "en-us")
        {	*/
}

// colocar no evento onKeyUp passando o objeto como parametro
function Mascara_Data(val)
{
   	var pass = val.value;
	var expr = /[0123456789]/;
		
	for(i=0; i<pass.length; i++){
		// charAt -> retorna o caractere posicionado no índice especificado
		var lchar = val.value.charAt(i);
		var nchar = val.value.charAt(i+1);
	
		if(i==0){
		   // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
		   // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
		   // instStr.search(expReg);
		   if ((lchar.search(expr) != 0) || (lchar>3)){
			  val.value = "";
		   }
		   
		}else if(i==1){
			   
			   if(lchar.search(expr) != 0){
				  // substring(indice1,indice2)
				  // indice1, indice2 -> será usado para delimitar a string
				  var tst1 = val.value.substring(0,(i));
				  val.value = tst1;				
 				  continue;			
			   }
			   
			   if ((nchar != '/') && (nchar != '')){
				 	var tst1 = val.value.substring(0, (i)+1);
				
					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
			   }

		 }else if(i==4){
			
				if(lchar.search(expr) != 0){
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;
					continue;			
				}
		
				if	((nchar != '/') && (nchar != '')){
					var tst1 = val.value.substring(0, (i)+1);

					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
				}
   		  }
		
		  if(i>=6){
			  if(lchar.search(expr) != 0) {
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;			
			  }
		  }
	 }
	
     if(pass.length>10)
		val.value = val.value.substring(0, 10);
	 	return true;
}


//Ex.: onkeypress="return MascCEP(event,this,'#####-###');" size="10" maxlength="9"

function MascCEP(e,src,mask) 
{
    if(window.event) 
    { _TXT = e.keyCode; } 
    else if(e.which) 
    { _TXT = e.which; }
    
    if(_TXT > 47 && _TXT < 58) 
    { 
		var i = src.value.length; 
		var saida = mask.substring(0,1); 
		var texto = mask.substring(i);
 
		if (texto.substring(0,1) != saida) 
		{ src.value += texto.substring(0,1); } 
		
		return true; 
	} 
	else 
	{ 
		if (_TXT != 8) 
		{ return false; } 
		else 
		{ return true; }
    }
}

//#**************************************************************************
//#**************************************************************************
// Funções para usar com ASP.NET CustomValidator
//#**************************************************************************
//#**************************************************************************

//====================================================================================================
//	Nome:		ValidaPeriodoData
//	Descrição:	Valida a data de um determinado período, para que uma não seja maior que a outra.
//====================================================================================================

function ValidaPeriodoData(source, arguments) 
{
	objetos = RecuperaObjData();
	
	
	
	if ((objetos.dataInicio.value.length < 10) || (objetos.dataFim.value.length < 10))
	{
		arguments.IsValid = true;
	}
	else
	{
		if(objetos.dataInicio.value!="" && objetos.dataFim.value!="")
		{
			arguments.IsValid = checkDateGap(objetos);
		}
		else 
		{
			arguments.IsValid = true;
		}
	}
}
//====================================================================================================
//	Nome:		ValidaData
//	Descrição:	
//====================================================================================================
function ValidaPeriodoDataInt(source, arguments) 
{
	objetos = RecuperaObjData();
	
	if(objetos.dataInicio.value!="" && objetos.dataFim.value!="")
	{
		arguments.IsValid = checkDateGapInt(objetos);
	}
	else if(objetos.dataInicio.value=="" && objetos.dataFim.value=="")
	{
		arguments.IsValid = true;
	}
	else
	{
	    arguments.IsValid = false;
	}
}
//====================================================================================================
//	Nome:		ValidaPeriodoData_1
//	Descrição:	
//====================================================================================================
function ValidaPeriodoData_1(source, arguments) 
{
	objetos = RecuperaObjData_1();
	
	if(objetos.dataInicio.value!="" && objetos.dataFim.value!="")
	{
		arguments.IsValid = checkDateGap(objetos);
	}
	else if(objetos.dataInicio.value=="" && objetos.dataFim.value=="")
	{
		arguments.IsValid = true;
	}
	else
	{
	    arguments.IsValid = false;
	}
}

//====================================================================================================
//	Nome:		ValidaCustomCPF
//	Descrição:	
//====================================================================================================
function ValidaCustomCPF(source, arguments)
{
    valor = arguments.Value;

    if(isCpf(valor) && valor.length == 11)
    {
        arguments.IsValid = true;
    }
    else
    {
      arguments.IsValid = false;  
    }
}
//====================================================================================================
//	Nome:		ValidaCustomCPFMask
//	Descrição:	
//====================================================================================================
function ValidaCustomCPFMask(source, arguments)
{
    valor = arguments.Value;

	if(valor == "")
	{ arguments.IsValid = true; }
	else
	{
		if(isCpf(valor) && valor.length == 14)
		{
			arguments.IsValid = true;
		}
		else
		{
		  arguments.IsValid = false;  
		}
	}
}


//====================================================================================================
//	Nome:		ValidaPeriodoData
//	Descrição:	Valida a data
//====================================================================================================

function ValidaPeriodoDataMask(source, arguments) 
{
	//fullValidate = arguments.Value;
	// Valida um campo de data.
	alert(source.ControleValidado);
	
	if(isDate(document.getElementById(source.ControleValidado), false))
	{ arguments.IsValid = true; }
	else
	{ arguments.IsValid = false; }
}

//====================================================================================================
//	Nome:		ValidaCustomNumeroHabilitacao
//	Descrição:	
//====================================================================================================
function ValidaCustomNumeroHabilitacao(source, arguments) {

    valor = arguments.Value;

    if (valor == "")
        arguments.IsValid = true;
    else
        arguments.IsValid = ValidaQuantidadeCaracter(valor, 9);
}

//====================================================================================================
//	Nome:		ValidaCustomNumeroHabilitacao
//	Descrição:	
//====================================================================================================
function ValidaCustomRegistroHabilitacao(source, arguments) {

    valor = arguments.Value;

    if (valor == "")
        arguments.IsValid = true;
    else
        arguments.IsValid = ValidaQuantidadeCaracter(valor, 11);
}

function ValidaQuantidadeCaracter(valor, qtde) {
    return (valor.length == qtde);
}


