
// Passa focus para o proximo campo
function prxCampoFocus(campo) {
    var obj_index = (-1);
    for (var i=0; i < document.forms[0].elements.length; i++) {
        if (document.forms[0].elements[i].name == campo) {
            obj_index = i;
        } else {
            if (obj_index >= 0) {
                if ((!document.forms[0].elements[obj_index + (i - obj_index)].readOnly) && 
                    (document.forms[0].elements[obj_index + (i - obj_index)].type != "hidden") &&
                    (document.forms[0].elements[obj_index + (i - obj_index)].disabled != true)) {
                    try {
                     document.forms[0].elements[obj_index + (i - obj_index)].focus();
                    } catch (e) {}
					
                    obj_index = (-1);
                     break;
                }
            } 
        }
    }
    if (obj_index > (-1)) {
        document.forms[0].elements[0].focus();
    }        
}

// janela consulta
function openConsulta(URL, campo, reloadPage) {
    var w = 600;
    var h = 400;	
    var t = (screen.height - h) / 2;
    var l = (screen.width  - w) / 2; 
    
    if (campo.value == '') {
            window.open(URL, '_blank', 'toolbar=no,location=no,resizable=no,scrollbars=yes,status=yes,width='+w+',height='+h+',top='+t+',left='+l);
    } else {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch(ee) {
            try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                try {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(E) {
                    xmlhttp = false;
                }
            }
        }
        // Exibe consultando
        
		try {
			consulta();
			
			// Abre a url
			xmlhttp.open("GET", URL+'&ajax=S', true); 
			
			// Executada quando o navegador obtiver o código
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4){
					//Lê o texto
					var texto=xmlhttp.responseText;             
					
					//Desfaz o urlencode
					texto=texto.replace(/\+/g," ");
					texto=unescape(texto);
					
					if (!texto == '') {
						var splitResult = texto.split(";##;");
						if ((texto.split(campo.name).length) > 2) {
							window.open(URL, '_blank', 'toolbar=no,location=no,resizable=no,scrollbars=yes,status=yes,width='+w+',height='+h+',top='+t+',left='+l);
						
						} else {
							for(var i = 0; i < (splitResult.length - 1); i++) {
								document.getElementsByName(splitResult[i])[0].value = splitResult[i+1];
								i++;
							}
						    prxCampoFocus(splitResult[0]);						
						    
						    if (reloadPage)  {
								self.reloadPage();
							}
						}
				   } else {
						campo.value = '';
						campo.focus();						
				   }
				   consultaOff();
				}
			}
			xmlhttp.send(null)
		} catch(e) {}
    }
    return false;
}

// URL = link modal
// input = referencia do objeto clicado
// conObriga = consulta obrigatoria 
function conModal(URL, input, conObriga) {
    var w = 600;
    var h = 400;	
    var t = (screen.height - h) / 2;
    var l = (screen.width  - w) / 2; 
	var campo = $(input).prev("input"); // Campo anterior a lupa
	var reloadPage = $(input).attr("rel") == "S" ? true : false; // reloadPage = se vai ter retorno

	if (conObriga && conObriga.val() == '') {
		input.className = "";
		return false;
	}
	
    if (campo.val() == '') {
		input.alt = URL+"&mod=S&keepThis=true&TB_iframe=true&height=400&width=569"; 
    } else {
    	input.className = "";
    	   	
        try {
            xmlhttp = new XMLHttpRequest();
        } catch(ee) {
            try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                try {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(E) {
                    xmlhttp = false;
                }
            }
        }
        try {    
        		consulta(); 
                // Abre a url
                xmlhttp.open("GET", URL+'&ajax=S', true); 

                // Executada quando o navegador obtiver o código
                xmlhttp.onreadystatechange=function() {
                        if (xmlhttp.readyState==4){
                                //Lê o texto
                                var texto=xmlhttp.responseText;             

                                //Desfaz o urlencode
                                texto=texto.replace(/\+/g," ");
                                texto=unescape(texto);

                                if (!texto == '') {
                                        var splitResult = texto.split(";##;");

                                        for(var i = 0; i < (splitResult.length - 1); i++) {
                                                document.getElementsByName(splitResult[i])[0].value = splitResult[i+1];
                                                i++;
                                        }
                                    prxCampoFocus(splitResult[0]);
                                    
                                    if (reloadPage)  {
										self.reloadPage();
									}
                           } else {
                                campo.val('');
                                campo.focus();
                           }
                           consultaOff();
                        }
                }
                xmlhttp.send(null)
        } catch(e) {}
    }    
    return false;
}

function formatar(src, mask, type) {
	
	var evento = (window.Event) ? window.Event : event
	
	if (evento.keyCode == 8) {
		alert('')
	}
	
	if (evento.keyCode != 8) {
		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);
		}
	}
}

// Verifica se somente números foram digitados no campo;
function isValidNumberValue (objTextControl) {
	var strValidNumber = "1234567890";

   for (nCount = 0; nCount < objTextControl.length; nCount++) {
      strTempChar=objTextControl.substring(nCount,nCount+1);
      if ( strValidNumber.indexOf(strTempChar,0)==-1) {
         return false; 
      }
   } 
   return true;
} 



// Verifica se a Data digitada é válida
function isValidData(vfield)
{
   var diaStr, mesStr, anoStr
   var diaInt, mesInt, anoInt
   var tam, sep1, sep2, verAno
   
   tam = vfield.value.length;
   
   if (tam > 0) {
	   
	   sep1 = parseInt(vfield.value.indexOf("/", 0));
	   if (sep1 < 0){
		  alert("A Data digitada deve ter o seguinte formato: DD/MM/AAAA !");
		  return false;
	   }
	   sep2 = parseInt(vfield.value.indexOf("/", sep1 + 1))
	   if (sep2 < 5) {
		  alert("A Data digitada deve ter o seguinte formato: DD/MM/AAAA !");
		  return false;
	   }
	   verAno = tam-sep2;
	   if(verAno < 5 ) {
		  alert("As datas devem ser preenchidas utilizando 4 dígitos para informar o Ano (ex.: DD/MM/AAAA)!");
		  return false;
	   }
	   diaStr = vfield.value.substring(0, sep1);
	   if(diaStr.substring(0, 1) == "0") {
		  diaStr = diaStr.substring(1, 2);
	   }
	   
	   if (isValidNumberValue(diaStr)) {
		  mesStr = vfield.value.substring(sep1+1, sep2); 
		  if(mesStr.substring(0, 1) == "0") {
			 mesStr = mesStr.substring(1, 2);
		  }
		  if (isValidNumberValue(mesStr)) {
			 anoStr = vfield.value.substring(sep2+1, tam);
			 if (isValidNumberValue(anoStr)) {
				diaInt = parseInt(diaStr);
				mesInt = parseInt(mesStr);
				anoInt = parseInt(anoStr);
				if ((diaInt <= 0) || (diaInt > 31)) {
				   alert("O dia informado não é válido!");
				   return false;
				}
				if ((mesInt <= 0) || (mesInt > 12)) {
				   alert("O mês informado não é válido!");
				   return false;
				}
				if ((mesInt == 4) || (mesInt == 6) || (mesInt == 9) || (mesInt == 11)) {
				   if( diaInt > 30) {
					  alert("O mês informado não possui mais de 30 dias!");
					  return false;
				   }
				}
				if (mesInt == 2) {
				   if ((anoInt % 4 == 0) && ( (anoInt % 100 != 0) || (anoInt % 400 == 0))) {
					  if (diaInt > 29) {
						 alert("O mês informado não possui mais de 29 dias!");
						 return false;
					  }
				   }
				   else {
					  if(diaInt > 28) {
						 alert("O mês informado não possui mais de 28 dias!");
						 return false;
					  }
				   }
				   return true;
				} 
				return true;
			 }
			 else { 
				alert("O campo deve conter somente números!");
				return false; 
			 }
		  }
		  else { 
			 alert("O campo deve conter somente números!");
			 return false; 
		  }
	   }
	   else {
		  alert("O campo deve conter somente números!");
		  return false; 
	   }
   }
   else {
	  return true; 
   }
}

function href_form(form, tip_tela, nom_tela) {		 	
	var val = validateForm(form, 'noAlert');
	if (tip_tela != "") {
		form.target = "pod1";
		if (tip_tela == "impressao_0002p") {
			form.action = nom_tela + ".jsp?print=2";	
		}
		else {
			form.action = nom_tela + ".jsp?print=S";	
		}
		if (val != false) {
			var janela = openWindow("","pod1","location=no,menubar=yes,toolbar=yes,titlebar=no,status=yes,top=0,left=0,scrollbars=yes,resizable=yes", 760, 500);
		}
	} else {
		form.target = "";
		form.action = "";				
	}
	return val
}

// ----- Remove dados null para update fields.
function checkNull(param) {
	if (param == 'null') param = '';
	else if (param == '0') param = '';
	else param = param;
	return param;
}

// ----- Remove os caracteres inválidos ao submeter o formulário.
function remove_chars(form) { 
    for(var i=0; i < form.elements.length; i++) {
		form.elements[i].value = replaceAll(form.elements[i].value, "\'", "");
		form.elements[i].value = replaceAll(form.elements[i].value, "\"", "");
	}
}

//if(!(/^\w+([\.-_-]?\w+)*@\w+([\.-_-]?\w+)*(\.\w{2,4})+$/.test(document.atendimento.email.value))) {
function replaceAll(oldStr,findStr,repStr) {
	var srchNdx = 0;
	var newStr = "";
	while (oldStr.indexOf(findStr,srchNdx) != -1) {
   		newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
    	newStr += repStr;
   		srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
  	}
	newStr += oldStr.substring(srchNdx,oldStr.length);
  	return newStr;
}

// ------ Habilita e desabilita com readonly.
function makeReadOnly(imput) {
	var x=document.getElementById(imput)
	x.readOnly=true
}
function delReadOnly() {
	var x=document.getElementById(imput)
	x.readOnly=false
}
// ----- Fim.

// ----- Troca o link do formulário e chama impressão.
function target_form(form, tip_tela, nom_tela) {		 	
	var val = validateForm(form, 'noAlert');
	
	if (tip_tela != "") {
		form.target = "pod1";
		form.action = nom_tela + "p.jsp";	
		if (val != false) {
			var janela = openWindow("","pod1","location=no,menubar=yes,toolbar=yes,titlebar=no,status=yes,top=0,left=0,scrollbars=yes,resizable=no", 700, 500);
		}
	} else {
		form.target = "";
		form.action = "";				
	}
}
function openWindow(URL, windowName, windowFeatures, w, h) {
  var t = (screen.height - h) / 2;
  var l = (screen.width  - w) / 2; 
  window.open(URL, windowName, windowFeatures+',width='+w+',height='+h+',top='+t+',left='+l);
  return false;
}

function inputMaskFloat(evnt, field) {
  //var key = document.all ? evnt.keyCode : document.layers ? evnt.which : 0;
  var key = evnt.keyCode;
  
  var val = field.value;
  if (key == 9 || key == 13)
    return true;
  else
  if ((key > 47 && key < 58) || (key > 95 && key < 106) || (key == 8)) {
    if (key == 8) {
      val = val.substring(0, val.length-3) + val.substring(val.length-2, val.length-1);
      if (val.length < 3)
        val = '0' + val;
	} else {
	  val = val.substring(0, val.length-3) + val.substring(val.length-2, val.length);
	  if (val.length < field.maxLength-1)
	    val += String.fromCharCode(key > 95 ? key-48 : key);
	  if (val.charAt(0) == '0')
		val = val.substring(1, val.length);
    }
    val = val.substring(0, val.length-2) + ',' + val.substring(val.length-2, val.length);
	field.value = val;
  }
  return false;
}

function inputMaskFloatClearAll(evnt, field) {

	if ((field.value == '') && (evnt.keyCode != 9)) {
	    field.value = '0,00';
	}
	
	var key = evnt.keyCode;
	var val = field.value;
	  
	  if ((key == 8) && (val == '0,00')) {
		  field.value = '';
		  return false;
	  }
	  
	  if (key == 9 || key == 13)
	    return true;
	  else
	  if ((key > 47 && key < 58) || (key > 95 && key < 106) || (key == 8)) {
	    if (key == 8) {
	      val = val.substring(0, val.length-3) + val.substring(val.length-2, val.length-1);
	      if (val.length < 3)
	        val = '0' + val;
		} else {
		  val = val.substring(0, val.length-3) + val.substring(val.length-2, val.length);
		  if (val.length < field.maxLength-1)
		    val += String.fromCharCode(key > 95 ? key-48 : key);
		  if (val.charAt(0) == '0')
			val = val.substring(1, val.length);
	    }
	    val = val.substring(0, val.length-2) + ',' + val.substring(val.length-2, val.length);
		field.value = val;
	  }
	  return false;
	}

function updateCounter(field, value) {
  field.value = value.length;
}

function Tecla(e) {
	var tecla = "";
	if (document.all) {
   		tecla = event.keyCode; // ----- Internet Explorer
	} else if(document.layers) {
   		tecla = e.which; // ----- Internet Explorer
	} else {
		tecla = e.which; // ----- Firefox
	}
   	if (tecla > 47 && tecla < 58 || tecla == 0) {// ----- Numeros de 0 a 9
    	return true;
	} else {
    	return false;
   	}
}

function RetiraAcentos(Campo) {
   var Acentos = "áàãââÁÀÃÂéêÉÊíÍóõôÓÔÕúüÚÜçÇabcdefghijklmnopqrstuvxwyz~<>:;?/°}]º^~`´{[+=§()*&¨¬%¢$#³@²!.";
   var Traducao ="AAAAAAAAAEEEEIIOOOOOOUUUUCCABCDEFGHIJKLMNOPQRSTUVXWYZ";
   var Posic, Carac;
   var TempLog = "";
   for (var i=0; i < Campo.length; i++)
   {
   Carac = Campo.charAt (i);
   Posic  = Acentos.indexOf (Carac);
   if (Posic > -1)
	  TempLog += Traducao.charAt (Posic);
   else
      TempLog += Campo.charAt (i);
   }
      return (TempLog);
}

function textCounter(campo, countcampo, maxlimit){ 
	if (campo.value.length > maxlimit) { 
		campo.value = campo.value.substring(0, maxlimit); 
	} else { 
		countcampo.value = maxlimit - campo.value.length; 
	} 
} 

//moveTo(-4,-4);
//resizeTo(screen.width+8,screen.height-20);


// ### TRATAMENTO DE ERROS NO FORMULARIO ###
var highlightcolor="#FFD7D7";

var ns6=document.getElementById&&!document.all;
var previous='';
var eventobj;
var intended=/INPUT|TEXTAREA|SELECT|OPTION/
var erros = new Array();

//Function to check whether element clicked is form element
function checkel(which){
	if (which.style&&intended.test(which.tagName)) {
		if (ns6&&eventobj.nodeType==3)
			eventobj=eventobj.parentNode.parentNode
			return true
		} else
			return false
}

//Function to highlight form element
function highlight(e){
eventobj=e;

if (previous!=''){
	if (checkel(previous))
		previous.style.backgroundColor='';
		previous=eventobj;
	if (checkel(eventobj))
		eventobj.style.backgroundColor=highlightcolor;
	} else{
		if (checkel(eventobj))
		eventobj.style.backgroundColor=highlightcolor;
		previous=eventobj;
	}
	eventobj.focus();
}

function fErrors (campo, descricao) {
	this.campo = campo;
	this.descricao = descricao;
}

function addErro(campo, descricao) {
	erros[erros.length] = new fErrors(campo, descricao);
}

function fErroFormulario(errors) {
	if (errors.length != 0) {
		var formatError = "";
		var x = document.getElementById('idError');
 
		for (var i = 0; i < errors.length; i++) {
			formatError += "<li style=\"cursor:pointer\" title=\"Clique para ir ao campo\" onclick=\"highlight(document.forms[0]."+errors[i].campo+");\"> "+errors[i].descricao+"</li>";
		}			
		x.style.display = 'block';
		x.innerHTML = "<div id=msgError><div id=topError>Erro ao preencher o formul&aacute;rio</div><div id=descError>" + formatError + "</div></div>";	
		document.location=('#');
	}
	erros = new Array();
	return (errors.length == 0);
}
// ### FIM TRATAMENTO DE ERROS NO FORMULARIO ###

function erroFormulario(errors) {
	if (errors.length != 0) {
		var formatError = "";
		var x = document.getElementById('idError');
		
		for (var i = 0; i < errors.length; i++) {
			formatError += "<li> "+errors[i]+"</li>";
		}			
		x.style.display = 'block';
		x.innerHTML = "<div id=msgError><div id=topError>Erro ao preencher o formul&aacute;rio</div><div id=descError>" + formatError + "</div></div>";	
		document.location=('#');
	}	
	return (errors.length == 0);
}

function limpaError() {
	document.getElementById('idError').style.display = 'none';
}

/*
 * Remove caracteres informados trim()
 * Exemplo: s = ".......Exemplo=======";
 * Resultado: s.trim(".="); //ambos  s.trim(".=", 1); //esquerda  s.trim(".=", 2) // direita;
 */
String.prototype.trim = function(c, t){
    return c = "[" + (c == undefined ? " " : c.replace(/([\^\]\\-])/g, "\\\$1")) + "]+",
    this.replace(new RegExp((t != 2 ? "^" : "") + c + (t != 1 ? "|" + c + "$" : ""), "g"), "");
}

// FORMATAÇÃO DE CAMPOS
addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

MaskInput = function(f, m){
	function mask(e){
		var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[À-ÿ]/i, "8": /./ },
			rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
		function accept(c, rule){
			for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
				if(r & i && patterns[i].test(c))
					break;
				return i <= r || c == rule;
		}
		var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
		(!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
			r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
			: (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
			r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
	}
	for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
		addEvent(f, i, mask);
};

/* exemplo
	MaskInput(f.fone, "(99)9999-9999"); //telefone "(99)9999-9999"
	MaskInput(f.data, "99/99/9999"); // data "99/99/9999"
	MaskInput(f.etc, "Cc99-*C"); // máscara = letra + letra sem acento + 2 números + tracinho + qualquer digito + letra "Cc99-*C"
	MaskInput(f.except, "E^abc"); // permite qualquer coisa menos a, b ou c "E^abc"
	MaskInput(f.only, "O^abc"); // permite somente a, b ou c "O^abc"
	MaskInput(f.letra, "C^"); // somente letras "C^"
	MaskInput(f.letra2, "C^ "); //somente letras e, tb espaço em branco "C^ "
	MaskInput(f.numero, "9^abc"); //somente números e, as letras a, b e c "9^abc"
*/
// FIM FORMATAÇÃO DE CAMPOS
 
 fmtMoney = function(n, c, d, t){
    var m = (c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".",
        /(\d+)(?:(\.\d+)|)/.exec(n + "")), x = m[1].length > 3 ? m[1].length % 3 : 0;
    return (x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g,
        "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : "");
};

function Dia(Data_DDMMYYYY) {
	string_data = Data_DDMMYYYY.toString();
	posicao_barra = string_data.indexOf("/");
	if (posicao_barra!= -1) {
		dia = string_data.substring(0,posicao_barra);
		return dia;
	} else {
		return false;
	}
}

function Mes(Data_DDMMYYYY) {
	string_data = Data_DDMMYYYY.toString();
	posicao_barra = string_data.indexOf("/");
	if (posicao_barra!= -1) { 
		dia = string_data.substring(0,posicao_barra);
		string_mes = string_data.substring(posicao_barra+1,string_data.length);
		posicao_barra = string_mes.indexOf("/");
		if (posicao_barra!= -1) {
			mes = string_mes.substring(0,posicao_barra);
			mes = Math.floor(mes);
			return mes;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function Ano(Data_DDMMYYYY) {
	string_data = Data_DDMMYYYY.toString();
	posicao_barra = string_data.indexOf("/");
	if (posicao_barra!= -1) {
		dia = string_data.substring(0,posicao_barra);
		string_mes = string_data.substring(posicao_barra+1,string_data.length);
		posicao_barra = string_mes.indexOf("/");
		if (posicao_barra!= -1) {
			mes = string_mes.substring(0,posicao_barra);
			mes = Math.floor(mes);
			ano = string_mes.substring(posicao_barra+1,string_mes.length);
			return ano;
		} else {
			return false;
		}
	} else {
		return false;
	}
}




function checkMesAno(dataAtual, mes, ano) {
	var valueMes = mes.value;
	var valueAno = ano.value;
	var dataInformada = "01/"+valueMes+"/"+valueAno;

	if (valueMes.length == 1)
		mes.value = "0"+valueMes;
		
	if (valueMes == "") {
		addErro(mes.name, 'Mes deve ser informado.');
	} else if (isNaN(valueMes)) {
		addErro(mes.name, 'Mes valor incorreto.');
	} else if (valueMes > 12) {
		addErro(mes.name, 'Mes valor incorreto.');
	}
	if (valueAno == "") {
		addErro(ano.name, 'Ano deve ser informado.');
	} else if (valueAno.length != 4) {
		addErro(ano.name, 'Ano valor incorreto.');	
	} else if (isNaN(valueAno)) {
		addErro(ano.name, 'Ano valor incorreto.');
	}
		
	dia1=Dia(dataAtual);
	mes1=Mes(dataAtual);
	mes1=Math.floor(mes1)-1;
	ano1=Ano(dataAtual);
	dataAtual = new Date(ano1,mes1,dia1);

	dia2=Dia(dataInformada);
	mes2=Mes(dataInformada);
	mes2=Math.floor(mes2)-1;
	ano2=Ano(dataInformada);
	dataInformada = new Date(ano2,mes2,dia2);

	diferenca = dataAtual.getTime() - dataInformada.getTime();
	diferenca = Math.floor(diferenca / (1000 * 60 * 60 * 24));

	/*@cc_on @*/
	/*@if (@_win32 && @_jscript_version>=5)
	
	function confirm(str)
	{
	    execScript('n = msgbox("'+str+'","257", "Atenção")', "vbscript");
	    return(n == 1);
	}
	@end @*/

	if ((diferenca > 60 || diferenca < -60) && erros.length == 0)				
		//return (6 == window.execScript('n = msgbox("Deseja realmente iniciar o processo com o Mes/Ano '+valueMes+'/'+valueAno+' ?","257")', "vbscript"));
		return confirm('Deseja realmente iniciar o processo com o Mes/Ano '+valueMes+'/'+valueAno+' ?');
	else 
		return true;
}

function checkPeriodo(dat_atual, oDat_inicial, oDat_final) {
	var sDatInicial = "";
	var sDatFinal = "";
	if (oDat_inicial.value == undefined && oDat_final.value == undefined) {
		sDatInicial = oDat_inicial;
		sDatFinal = oDat_final;
	} else {
		sDatInicial = oDat_inicial.value;
		sDatFinal = oDat_final.value
	}
	dat_inicial = sDatInicial;
	dat_final = sDatFinal;
		
	if (dat_inicial != "" && dat_final != "") {
		dia1=Dia(dat_inicial);
		mes1=Mes(dat_inicial);
		mes1=Math.floor(mes1)-1;
		ano1=Ano(dat_inicial);
		dat_inicial = new Date(ano1,mes1,dia1);
	
		dia2=Dia(dat_final);
		mes2=Mes(dat_final);
		mes2=Math.floor(mes2)-1;
		ano2=Ano(dat_final);
		dat_final = new Date(ano2,mes2,dia2);
		
		dia3=Dia(dat_atual);
		mes3=Mes(dat_atual);
		mes3=Math.floor(mes3)-1;
		ano3=Ano(dat_atual);
		dat_atual = new Date(ano3,mes3,dia3);
		
		diferenca = dat_final.getTime() - dat_inicial.getTime();
		diferenca = Math.floor(diferenca / (1000 * 60 * 60 * 24));
		
		diferenca1 = dat_atual.getTime() - dat_inicial.getTime();
		diferenca1 = Math.floor(diferenca1 / (1000 * 60 * 60 * 24));	
	
		/*@cc_on @*/
		/*@if (@_win32 && @_jscript_version>=5)
		
		function confirm(str)
		{
		    execScript('n = msgbox("'+str+'","257", "Atenção")', "vbscript");
		    return(n == 1);
		}
		@end @*/
	
		if (((diferenca > 60 || diferenca < -60) || (diferenca1 > 60 || diferenca1 < -60)) && erros.length == 0)				
			return confirm('Deseja realmente iniciar o processo com o Período '+sDatInicial+' a '+sDatFinal+' ?');
		else 
			return true;
	} else {
		return true;
	}
}

String.prototype.pad = function(l, s, t){
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
        + this + s.substr(0, l - t) : this;
};

// Validação de cpf.
function isNum(str) {
	var VBlnIsNum;
	VIntTam = str.length;
	VBlnIsNum = true;
	if (VIntTam == 0) {
		return false;
	} else {
		for (i=0; i < VIntTam; i++) {
			if (str.substring(i,i+1) < '0' || str.substring(i,i+1) > '9') {
				VBlnIsNum = false;
			}
		}
		return VBlnIsNum;
	}
}

//Função de validação de CPF
function isCPF(st) {
	var field = st;
	st = st.value;
	st = replaceAll(st, ".", "");
	st = replaceAll(st, "-", "");
	var retorno = true;
	if (st == "")
		return (false);
	l = st.length;

	//aleterado para se usuário não digitar os zeros na frente do CPF, completar sozinho
	if ((l == 9) || (l == 8)) {
		for (i = l ; i < 10; i++) {
			st = '0' + st
		}
	}
	l = st.length;
	st2 = "";
	for (i = 0; i < l; i++) {
		caracter = st.substring(i,i+1);
		if ((caracter >= '0') && (caracter <= '9'));
			st2 = st2 + caracter;
		}
		if ((st2.length > 11) || (st2.length < 10))
			retorno = false;
		if (st2.length==10)
			st2 = '0' + st2;
		digito1 = st2.substring(9,10);
		digito2 = st2.substring(10,11);
		digito1 = parseInt(digito1,10);
		digito2 = parseInt(digito2,10);
		sum = 0; mul = 10;
		for (i = 0; i < 9 ; i++) {
			digit = st2.substring(i,i+1);
			tproduct = parseInt(digit ,10) * mul;
			sum += tproduct;
			mul--;
		}
		dig1 = ( sum % 11 );
		if ( dig1==0 || dig1==1 )
			dig1=0;
		else
			dig1 = 11 - dig1;
		if (dig1!=digito1)
			retorno = false;
		sum = 0;
		mul = 11;
		for (i = 0; i < 10 ; i++) {
			digit = st2.substring(i,i+1);
			tproduct = parseInt(digit ,10)*mul;
			sum += tproduct;
			mul--;
		}
		dig2 = (sum % 11);
		if ( dig2==0 || dig2==1 )
			dig2=0;
		else
			dig2 = 11 - dig2;
		if (dig2 != digito2)
			retorno = false;
		
		if (!retorno) {
			if(!confirm('CPF inválido, deseja continuar?')) {
				field.focus();
				field.select();
			}
		}
		
}

function validateDate(valor) {
	var date=valor;
	var ardt=new Array;
	var ExpReg=new RegExp("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}");
	ardt=date.split("/");
	erro=false;
	if ( date.search(ExpReg)==-1){
		erro = true;
		}
	else if (((ardt[1]==4)||(ardt[1]==6)||(ardt[1]==9)||(ardt[1]==11))&&(ardt[0]>30))
		erro = true;
	else if ( ardt[1]==2) {
		if ((ardt[0]>28)&&((ardt[2]%4)!=0))
			erro = true;
		if ((ardt[0]>29)&&((ardt[2]%4)==0))
			erro = true;
	}
	if (erro) {
		return false;
	}
	return true;
}

function isEnableField(field) {
	return !field.disabled; 
}

