//********************************************************************************
// Objetivo  :	Troca imagem do botao
// Premissas :	Nenhuma
// Entradas  :	strIDimg - Nome do botao
//				strimg - nome da figura
// Retorno   :	Nenhum
//********************************************************************************
function ChangeImageBtn(strIDimg, strimg)
{	
	eval("document.all." + strIDimg + ".src = '../Imagem/"+ strimg +"'");
}

//********************************************************************************
// Objetivo  :	Volta a página anterior
// Premissas :	Nenhuma
// Entradas  :	
// Retorno   :	Nenhum
//********************************************************************************
function BackHistory()
{	
	history.back();
}


//********************************************************************************
// Objetivo  :	Exibe mensagem pedindo confirmação para inclusão
// Premissas :	Nenhuma
// Entradas  :	Nenhuma
// Retorno   :	true ou false
//********************************************************************************
function ConfirmaInclusao()
{
	var bConfirmou = window.confirm("Confirma a inclusão do registro?");
	if (bConfirmou)
		return true;
	else
		return false;
}

//********************************************************************************
// Objetivo  :	Exibe mensagem pedindo confirmação para alteração
// Premissas :	Nenhuma
// Entradas  :	Nenhuma
// Retorno   :	true ou false
//********************************************************************************
function ConfirmaAlteracao()
{
	var bConfirmou = window.confirm("Confirma a alteração do registro selecionado?");
	if (bConfirmou)
		return true;
	else
		return false;
}

//********************************************************************************
// Objetivo  :	Exibe mensagem pedindo confirmação para exclusão
// Premissas :	Nenhuma
// Entradas  :	Nenhuma
// Retorno   :	true ou false
//********************************************************************************
function ConfirmaExclusao()
{
	var bConfirmou = window.confirm("Confirma a exclusão do registro selecionado?");
	if (bConfirmou)
		return true;
	else
		return false;
}


//********************************************************************************
// Objetivo  :	Permite que seja digitado somente números
// Premissas :	Nenhuma
// Entradas  :	Nenhuma
// Retorno   :	true ou false
//********************************************************************************
function VerCampoNumericoInt()
{
	var nKey = window.event.keyCode;
	if (!(nKey > 47 && nKey < 58))
		return false;
	else
		return true;
}


//********************************************************************************
// Objetivo  :	Elimina os caracteres em branco a esquerda
// Premissas :	Nenhuma
// Entradas  :	ptexo - String a ter os caracteres eliminados
// Retorno   :	string sem os caracters em branco
//********************************************************************************
function ltrim(ptexto) 
{
    var i = 0;
    while (( i < ptexto.length ) && (ptexto.charAt(i)== " ")) {
        i++;
    }
    return (ptexto.substring(i,ptexto.length));
}


//********************************************************************************
// Objetivo  :	Elimina os caracteres em branco a direita
// Premissas :	Nenhuma
// Entradas  :	ptexo - String a ter os caracteres eliminados
// Retorno   :	string sem os caracters em branco
//********************************************************************************
function rtrim(ptexto)
{
    var i = ptexto.length-1;
    while ( (i>0) && (ptexto.charAt(i) == " ") ) {
        i--;
    }
    return (ptexto.substring(0,i+1));
}

//********************************************************************************
// Objetivo  :	Elimina os caracteres em branco a esquerda e a direita
// Premissas :	Nenhuma
// Entradas  :	ptexo - String a ter os caracteres eliminados
// Retorno   :	string sem os caracters em branco
//********************************************************************************
function trim(ptexto)
{
    return ltrim(rtrim(ptexto));
}


//********************************************************************************
// Objetivo  : Verifica se data até é menor que a data de
// Premissas : Nenhuma
// Entradas  : strDataDe, strDataAte
// Retorno   : true ou false
//********************************************************************************
function VerificaFaixaData(strDataDe, strDataAte)
{
	if (strDataDe.length > 0  && strDataAte.length > 0)
	{
		var strDiaDe = strDataDe.substr (0, 2);
		var strMesDe = strDataDe.substr (3, 2);
		var strAnoDe = strDataDe.substr (6, 4);

		var strDiaAte = strDataAte.substr (0, 2);
		var strMesAte = strDataAte.substr (3, 2);
		var strAnoAte = strDataAte.substr (6, 4);

		var intDataDe = Number( strAnoDe + strMesDe + strDiaDe)
		var intDataAte = Number( strAnoAte + strMesAte + strDiaAte)
	
		if (intDataDe > intDataAte)
		{
			alert('Data Até inferior a Data De');
			return false;
		}
		else
		{
			return true;
		}
	}
	return true;
}



//********************************************************************************
// Objetivo  : Retorno text do item selecionado de um combo
// Premissas : Nenhuma
// Entradas  : objCombo
// Retorno   : string
//********************************************************************************
function TextSelCombo(objCombo)

{
	var strRetorno = "";

	
	for (var intCont = 0; intCont < objCombo.length ; intCont++)
	{
		if (objCombo.children.item(intCont).selected == true)
		{
			strRetorno = objCombo.children.item(intCont).text;
		}
	}

	return strRetorno;
	
}


//********************************************************************************
// Objetivo  :	Recarregar página (usado quando se clica em cancelar)
// Premissas :	Nenhuma
// Entradas  :	URL da página a ser redirecionada
// Retorno   :	Nenhum
//********************************************************************************
function LimparForm(strURL)
{
	window.location.href = strURL.substr(0,strURL.search('.asp')+4);
}


//********************************************************************************
// Objetivo  :	Limpar tabela
// Premissas :	Nenhuma
// Entradas  :	Nenhuma
// Retorno   :	Nenhum
//********************************************************************************
function LimparTabela()
{
	while(document.all.tblDados.rows.length > 0) 
	{
		document.all.tblDados.deleteRow(0);
	}

}

//********************************************************************************
// Objetivo  :	Limpar tabela da tela Monitor
// Premissas :	Nenhuma
// Entradas  :	Nenhuma
// Retorno   :	Nenhum
//********************************************************************************
function LimparTabelaMonitor()
{
	while(document.all.tblLimExced.rows.length > 0) 
	{
		document.all.tblLimExced.deleteRow(0);
	}
	while(document.all.tblLimMargem.rows.length > 0) 
	{
		document.all.tblLimMargem.deleteRow(0);
	}
	while(document.all.tblIntMon.rows.length > 0) 
	{
		document.all.tblIntMon.deleteRow(0);
	}
}

//********************************************************************************
// Objetivo  :	Troca de página
// Premissas :	Nenhuma
// Entradas  :	Nome da Página
// Retorno   :	Nenhum
//********************************************************************************
function TrocaPagina(strPagina)
{
	window.location.href = strPagina;
}


//********************************************************************************
// Objetivo : Formata  um CPF/CNPJ valido para o componente
// Premissas : 
// Entradas : CPF/CNPJ
// Saídas : CPF/CNPJ somente com numeros
function LimpaCPFCNPJ(strNum)
{
	strNum = strNum.replace('.','');
	strNum = strNum.replace('/','');
	strNum = strNum.replace('-','');

	return strNum;
}

// Objetivo	 : Utilizado para só aceitar digitação de valores alfanuméicos
// Premissas : Nenhuma
// Entradas	 : Nenhum
// Saídas	 : True ou False (evento onkeypress)
function PressAlfaNumeric()
{	
	var nKey;
	nKey = window.event.keyCode;
	if (((nKey <= 47) || (nKey >= 58 )) &&  ((nKey <=64 ) || (nKey >= 91 )) && ((nKey <= 96) || (nKey > 122)) )
	{
   		window.event.keyCode = 0;
   		return false;
   	}
	return true;
}


// Objetivo: Verifica se tecla digitada é valida para campo real
// Premissas : não há
// Entradas: strchar: Valor a ser comparado
// Saídas : True ou False
function isValidRealPosDigit(strchar) {
    return ("0123456789,".indexOf(strchar)>=0);
}
	
// Objetivo: Verifica se tecla digitada é valida para campo real
// Premissas : Precisa da função isValidRealPosDigit
// Entradas: strchar: Valor a ser comparado
// Saídas : True ou False
function PressNumericPercentDelimited(pCampo, pInteiro, pFracao) {
	
	var pKey = String.fromCharCode(event.keyCode);
	var blnRet = isValidRealPosDigit(pKey);
	var pCampoComp = String(pCampo.value);
	var blnInteiro = true;
	var intInteiro = 0;
	var intFracao = 0;
		
	if (blnRet) {
		if (pKey == ",") {
			if (pCampoComp.length == 0)
				blnRet = false;
			else {
				for (i = 0; i < pCampoComp.length; ++i) {
					var ch = pCampoComp.substring(i, i+1);
					if (ch==",")
						blnRet = false;
				}
			}
		}
	}
	if (blnRet)
		if (pKey != ",") {
			for (i=0; i < pCampoComp.length; ++i) {
				var ch = pCampoComp.substring(i, i+1);
				if (ch == ",") {
					blnInteiro = false;
				}
				else
					if (blnInteiro)
						intInteiro++
					else
						intFracao++
			}
			if (blnInteiro)
				intInteiro++
			else
				intFracao++
				
			if (intInteiro > pInteiro || intFracao > pFracao)
				blnRet = false;
				
		}
		
	if (!blnRet)
		window.event.keyCode = 0;
}


// Objetivo	 : Utilizado para só aceitar digitação de valores alfanuméicos e espaços
// Premissas : Ser usada no evento onKeyPress
// Entradas	 : Nenhum
// Saídas	 : Nenhuma
function CaixaAlta(){	
	var nKey;
	nKey = window.event.keyCode;
   	if ((nKey >= 97) && (nKey <= 122)) {
   		window.event.keyCode = nKey - 32;
   	}

}

// Objetivo	 : Verifica caractere digitado é numérico
// Premissas : utilizar no onkeypress, onkeydown e onkeyup (para evita "Copy/Paste")
// Entradas	 : Nenhum
// Saídas	 : True ou False (evento onkeypress)
function PressNumeric()
{
	var lngKey;			// Código ASC da tecla digitada
		
	lngKey = window.event.keyCode;	
		
	if ( ((lngKey <= 47)||(lngKey >= 58)) && (lngKey != 9) ) 
	{
		window.event.keyCode = 0;
		return false;
	}
			
	return true;
}

// Objetivo	 : Verifica quantidade de caractere digitado num objeto
// Premissas : utilizar no onkeypress, onkeydown e onkeyup (para evita "Copy/Paste")
// Entradas	 : Nenhum
// Saídas	 : True ou False (evento onkeypress)
function TamanhoMaximo(objCampo, numTamanho) {
	var strString = String(objCampo.value);
	if ( (strString.length > (numTamanho-1)) && (window.event.keyCode != 46) && (window.event.keyCode != 9) ) 	{
		window.event.keyCode = 0;
		return false;
	}
	return true;
}

// Objetivo	 : Efetua o intercâmbio entre os strings
// Premissas : Nenhuma
// Entradas	 : str - string utilizado
//			   oq - string pesquisado
//			   por - string que se quer substituir
// Saídas	 : O string modificado
function Troca(str,oq,por){ 
	while (str.indexOf(oq) > -1) 
		str = str.replace(oq,por); 
    return(str); 
} 

function FormataData(obj){ 
    var valor = obj.value;
    valor = Troca(valor,'/','');
    if (valor.length > 2){ 
		valor = valor.substring(0,2) + "/" + valor.substring(2,valor.length); 
    } 
    if (valor.length > 5){ 
		valor = valor.substring(0,5) + "/" + valor.substring(5,valor.length); 
    } 
    obj.value = valor;
}

function FormataHora(obj){ 
	var valor = obj.value;
    valor = Troca(valor,':','');
    if (valor.length > 2){ 
		valor = valor.substring(0,2) + ":" + valor.substring(2,valor.length); 
    } 
    obj.value = valor;
}

function eData(objTextbox,nome){
	var erro;
    erro='';
    var dia,mes,ano, strData;
    strData = objTextbox.value;
    if (strData.length != 10){
		alert("Favor preencher o campo " + nome + ".");		
		return false;
	}
    dia = strData.substr(0,2);    
    mes = strData.substr(3,2);    
    ano = strData.substr(6,4);    
    
    if (dia<1 || dia>31){
	    erro='O dia do campo ' + nome + ' deve estar entre 1 e 31!\n';
    }
    if (mes<1 || mes>12){
        erro=erro + 'O mês do campo ' + nome + ' deve estar entre 1 e 12!\n';
    }
    else{
        var meses = new  Array("","Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro")
        if (((mes==4 || mes==6 || mes==9 || mes==11) && (dia>30))){
	        erro=erro + 'O mês ' + meses[mes] + ' do campo ' + nome + ' possui apenas 30 dias!\n';     
        }
        else if (dia > 31){
            erro=erro + 'O mês ' + meses[mes] + ' do campo ' + nome + ' possui apenas 31 dias!\n';     
        }
    }
    if (ano<1753 || ano>9999){
	    erro=erro + 'O ano do campo ' + nome + ' deve estar entre 1.753 e 9.999!\n';
    }             
    else if (mes==2){
	    if (ano % 4 > 0 && dia > 28){
	        erro=erro + 'O mês fevereiro do ano ' + ano + ' do campo ' + nome + ' possui apenas 28 dias!\n';  
        } 
        else if (dia > 29){
            erro=erro + 'O mês fevereiro do ano ' + ano + ' do campo ' + nome + ' possui apenas 29 dias!\n';  
        }
    }                    
    if (erro.length>0){
	    alert(erro);
	    objTextbox.focus();
        return false;
    }
        return true;
}

function eHora(objTextbox,nome){
	var erro;
    erro='';
    var hora, minuto, strHora;
    strHora = objTextbox.value;
    if (strHora.length != 5){
		alert("Favor preencher corretamente o campo " + nome + " (HH:MM).");		
		return false;
	}
    hora = strHora.substr(0,2);    
    minuto = strHora.substr(3,2);    
    
    if (hora>23){
	    erro='A hora do campo ' + nome + ' deve estar entre 00 e 23!';
    } else {
		if (minuto>59){
			erro=erro + 'Os minutos do campo ' + nome + ' devem estar entre 00 e 59!';
		}
	}
    if (erro.length>0){
	    alert(erro);
	    objTextbox.focus();
        return false;
    }
    return true;
}

function autoTab(input,len,e) {
	var keyCode = (isNaN) ? e.which : e.keyCode; 
	var filter = (isNaN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	var x;
	if(input.value.length >= len && !containsElement(filter,keyCode)) {
		input.value = input.value.slice(0, len);
		try{
		input.form[(getIndex(input)+1) % input.form.length].focus();
		}
		catch(e){
			//despreza o erro
			return;
		}
}


function containsElement(arr, ele) {
	var found = false, index = 0;
	while(!found && index < arr.length)
		if(arr[index] == ele)
			found = true;
		else
			index++;
	return found;
 }

function getIndex(input) {
	var index = -1, i = 0, found = false;
	while (i < input.form.length && index == -1)
		if (input.form[i] == input)index = i;
			else i++;
		return index;
	}
	return true;
}

function soDate(){
	if (!(event.keyCode>47 && event.keyCode<58) && (event.keyCode != 47) && (event.keyCode != 45) && (event.keyCode != 9) ){
		event.keyCode=0;
	}
}

function soHora(){
	if (!(event.keyCode>48 && event.keyCode<59) && (event.keyCode != 48) && (event.keyCode != 9) ){
		event.keyCode=0;
	}
}


/**
Verifica se o a string possui apenas numeros,
no parametro vValue deve ser enviada a string a ser avaliada
**/

function isnumber(vValue){
	num = '0123456789'
	var temp;
	for (var i=0; i<vValue.length; i++) {
		temp = "" + vValue.substring(i, i+1);				
		if (num.indexOf(temp) <0){ 
			return false;
		}
	}
	return true;
}


/**
Verifica se o a string possui apenas caracteres,
no parametro vValue deve ser enviada a string a ser avaliada
**/

function isstring(vValue){
	num = '0123456789'
	var temp;
	for (var i=0; i<vValue.length; i++) {
		temp = "" + vValue.substring(i, i+1);				
		if (num.indexOf(temp) >=0){ 
			return false;
		}
	}
	return true;
}

/**
Verifica o tipo de dados que esta sendo entrado pelo usuario, e checa 
se esta de acordo com o tipo esperado
field = campo(input) que devera ser validado
tipo  = tipo de dados que e esperado, 0 - string; 1- numeric
**/

function validatipodados(field, tipo){
	ok = true;
 	if (!isnumber(field.value) && tipo==1){
		alert('Dados inválidos, este campo aceita apenas números');
 		ok=false;
 	}
 	if (!isstring(field.value) && tipo==0){
		alert('Dados inválidos, este campo aceita apenas texto');
 		ok=false;
 	}
	
	if (!ok) {
		field.focus();
		field.select();
	}
	return ok;
}


/**
Verifica se o campo foi preenchido
obj  = deve ser enviado o objeto input ou select
tipo = tipo de objeto que esta sendo enviado, 0-input;1-select,2-radio ou checkbox
msg = True, False - Indica se a mensagem ALERT irá ou não aparecer
**/

function campopreenchido(obj, tipo){
	ok=true;

	//validacao de objeto input
	if (tipo==0){
		if (obj.value == '' || obj.value == null ) {
			obj.focus()
			ok=false;
		}
	}
	
	//validacao de objeto select
	if (tipo==1){
		if (obj.selectedIndex == 0) {
			obj.focus()
			ok=false;
		}
	}
	
	//array de radio button, verifica se há algum item selecionado
	if (tipo==2){		
		ok=false;
		if (isNaN(obj.length)){
			if (obj.checked ){
				ok=true;			
			}
		} 
		else{
			for (var i=0; i<obj.length; i++){
				if (obj[i].checked){
					ok=true;
					break;
				}
			}
		}
	}
	
	//se for radio button, o focu tem que ser enviado 
	//para o primeiro item do array
	if (!ok){
		alert("O preenchimento deste campo é obrigatório, preencha por favor!!!")
		if (obj.length > 0){
			obj[0].focus();
		}
		else{
			obj.focus();		
		}
	}
	
	return ok;
	
}
<!--

