/*charset = UTF-8*/
var cursorTypeCss = (navigator.appVersion.indexOf("MSIE 5")>-1) ? "hand" : "pointer";

//_--__--__--__--__--__--__--__--__--__--__--__--__--__--__--__--__--__--__--__--__--__--_

function getNav() {
    var nv = navigator.userAgent;
    var vs = navigator.appVersion;
    var q = "IE";
    if (nv.indexOf("Opera")>-1) q = "OPERA";
    if (nv.indexOf("Firefox")>-1) q = "FIREFOX";
    if (nv.indexOf("Netscape")>-1) q = "NETSCAPE";
    if (nv.indexOf("Mozilla")>-1 && nv.indexOf("Netscape")==-1 && nv.indexOf("MSIE")==-1) q = "MOZILLA";
    
    if (q=="IE") {
        var avs = vs.split(";");
        vs = parseFloat(avs[1].substring(5));
    }
    
    var r = { n: q, v: vs };
    
    return r;
}
var NV = getNav();
//*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*

// FUNO PROCESSA AJAX
var resultAjax; //usado para pegar resultado do Ajax
function goAjax(pagina,parametros,funcao,id) {  
    var st_atual=0;
    var fncObj = null;
    var reqHTTP = false;
    resultAjax = "";
    
    var loading = (id.length>0) ? document.getElementById(id) : null;
	if (loading!=null) loading.innerHTML = "<div style='text-align:center; padding:3px; height:100%; background-color:#ffffcc; color:#000000;'>Aguarde processando...</div>";
        
    try {
    
        if (window.ActiveXObject) { //IE
                reqHTTP = new ActiveXObject("Microsoft.XMLHTTP");
                try {
                        reqHTTP = new ActiveXObject("Msxml2.XMLHTTP") // Verso 6
                } 
                catch(e) {
                        reqHTTP = new ActiveXObject('Microsoft.XMLHTTP')  // Verso 5.5
                }

        } else if (window.XMLHttpRequest) //no IE
                reqHTTP = new XMLHttpRequest();

        reqHTTP.onreadystatechange = function() {
            st_atual = reqHTTP.readyState;

            if (st_atual==4) { 
			
				if (loading!=null) loading.innerHTML = "";				
				
				if (reqHTTP.status==200)
                    resultAjax = reqHTTP.responseText;                                         
                else {
                    //resultAjax = '{ERRO} "AJAX": O servidor retornou: ' + reqHTTP.status + ' --> ' + reqHTTP.statusText;
					var w = window.open("","erro");	w.document.write(reqHTTP.responseText);
					//resultAjax = '{ERRO} ATENÇÃO: <hr /> Violação de integridade da(s) tabela(s) do Banco de dados e/ou Não  permitido duplicar registros e/ou Excluir registro(s) já relacionado(s)! <hr />(' + reqHTTP.status + ' --> ' + reqHTTP.statusText + ')';
				}

				if (resultAjax.toUpperCase().indexOf("{WINDOW-WRITE-TRACE}")>-1 ) {
					var w = window.open("","trace");	
					w.document.write(resultAjax);
					
				} else if (resultAjax.toUpperCase().indexOf("{ERRO}")>-1 || resultAjax.toUpperCase().indexOf("{TRACE}")>-1) {
                    //alert(resultAjax.replace(/\\n/g,"\n"));
					dialog(false,true,resultAjax.substring( resultAjax.indexOf("}") + 1 ),"");
					
				} else if (resultAjax.toUpperCase().indexOf("{EXCEPTION}")>-1) {
					resultAjax = trim(resultAjax.substring(11));
					resultAjax = resultAjax.replace(/\\n/g,"\n"); //Para validar quebra de linha no javascript com resultado vindo do ajax
					resultAjax = resultAjax.replace(/\\t/g,"\t"); //Para validar tabulaes no javascript com resultado vindo do ajax
                    alert("ATENÇÃO:\n\n" + resultAjax);
					
				} else if (resultAjax.toUpperCase().indexOf("{NOT-SESSION}")>-1) {
					this.goReload = function() { top.location.reload(); }
                    dialog(false,true,"ATENÇÃO:\n\nSua sessão expirou, logar novamente!","goReload()");
					
				} else if (resultAjax.toUpperCase().indexOf("{RELOAD}")>-1) {
                    top.location.reload();
					
                } else
                    fncObj = (funcao.length>0 ? eval(funcao) : null);

            }
        } 

        //Configurao geral essencial
        reqHTTP.open("POST",pagina,true);
        reqHTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");      
        reqHTTP.setRequestHeader("Cache-Control","no-store, no-cache, must-revalidate");   //-->   Limpa e evita armazemento 
        reqHTTP.setRequestHeader("Cache-Control","post-check=0, pre-check=0");             //      em cache nos navegadores
        reqHTTP.setRequestHeader("Pragma", "no-cache");
        reqHTTP.send(parametros);

    }
    catch (e) {
		if (loading!=null) loading.innerHTML = "";
        resultAjax = '{ERRO} "Script": ' + e.toString();
        dialog(false,true,resultAjax,"");
    }
}
//____________________________________________________________________________
//Monta uma query string com os parametros para serem enviados pelo goAjax
/*
*	f = referencia formulário
*	s = querystring add  gerada
*/
function setParams(f,s) {
	var qs = (s.length==0) ? "null=0" : s;	
	var n = "", v = "", cp="", cbx="", nOld="";
	for (var i = 0; i < f.elements.length; i++) { //alert(i);
		n = "";
		v = "";
		cp = f.elements[i]; //alert(cp.name + " = " + cp.value);
		
		if (cp.disabled==false) {
			v = cp.value;
			if (cp.type.indexOf("radio")>-1) {
				if (cp.checked) n = cp.name;
			} else
				n = cp.name;
			
			//Se houver vrios campos checkbox com mesmo nome no repetir nome na query string
			if (cp.type.indexOf("checkbox")>-1 && cbx != cp.name) {
				cbx = cp.name;
				v = getValueListCheckbox(f,cbx); 
			}
			
			if (cp.type.indexOf("select")>-1) v = getListValues(cp).value;
			
			qs += (n.length>0 && n!=null && n!=nOld) ? '&' + n + '=' + escape(v.toString()) : "";
			nOld = n; //Campo anterior
		}
	} 	
	return qs;
}

//---------------------------------

//Valida tags script vindas de uma resposta do ajax
function validScriptResultAjax(idResult) { 	
	var conteudo = document.getElementById(idResult);
	var newElement = document.createElement("script");
	var scripts = conteudo.getElementsByTagName("script");
	for(i=0;i<scripts.length;i++) {
		newElement.text = scripts[i].innerHTML;
	} //alert(newElement.text);
	conteudo.appendChild(newElement);
}

//---------------------------------

//verifica se existe lista de checkbox, se houver retorna valores em lista
function getValueListCheckbox(f,n) {
	var cp = f.elements[n]; //alert(cp.name + "\n\n" + y);
	var y = cp.length;
	var s = "";
	if (typeof y != "undefined") {
		var r = new Array();
		for (var i=0;i<y;i++) { //alert(y); alert(cp[i].checked);
			if (cp[i].checked) r.push(cp[i].value);
		}
		s = r.join(",");
	} else s = cp.value;
	
	return s.trim();
}

//---------------------------------

//Retorna valores dos campos select na forma de Array
function getListValues(f){		
	var valorOp = new Array();	
	var textOp = new Array();
	for(var i = 0; i < f.options.length; i++){
		if (f.options[i].selected){
			valorOp.push(f.options[i].value);
			textOp.push(f.options[i].text);
		}
	}	
	return { value: valorOp, text: textOp };
}

//================================================

function limpaCampos(f) {	
	var e = null;
    for (var a = 0; a < f.elements.length; a++) {
		e = f.elements[a];
		
		if (e.type.indexOf("select")>-1){
			if (e.id == "combotofilter"){
				e.options[0].text = "Aguardando filtragem!";
				e.options[0].value = "";
				e.options[0].selected = true;
				e.disabled = true;
			}
		}
        if (e.selectedIndex){
			if (e.id == "combotofilter"){
				e.options[0].text = "Aguardando filtragem!";
				e.options[0].value = "";
				e.options[0].selected = true;
				e.disabled = true;
			}else{
				e.options[0].selected = true;
			}
		}
        if (e.type.indexOf("checkbox")>-1) {
			if (e.value.toUpperCase()=="N" || e.value.toUpperCase()=="S") e.value="N";
			e.checked = false;
		}
        if (e.type.indexOf("text")>-1 || e.type.indexOf("password")>-1 || e.type.indexOf("textarea")>-1) e.value = "";
    }
}
//#############################################################################

//Retorna somente numeros
function onlyNumber(e) {
	e.value = e.value.replace(/\D/g,"");
}

//----------------------------------------------------------

String.prototype.trim = function() {
	var r = this;
	var er = /^\s|\s$/;
	while (er.test(r)) r = r.replace(/^\s|\s$/g,"");
	return r.toString();
}

//----------------------------------------------------------

function getChar13(s) {
	var ql = String.fromCharCode(13);
	if (s.indexOf(ql)>-1) {
		while (s.indexOf(ql)>-1) {
			s = s.replace(ql,"{13}");      
			s = s.replace(String.fromCharCode(9),"");  
			s = s.replace(String.fromCharCode(10),""); 
		}
	} //alert(s);
	return s;
}

//#############################################################################
function sendMail(path,corpo,assunto,para,de,cc,bcc,anexos, rfp) {
	var b = true;
	if (para.trim().length>0) {
		
		//document.write("Caminho: "+path+"<br />Corpo: "+corpo+"<br />Assunto: "+assunto+"<br />de: "+de+"<br />Para: "+para+"<br />cc: "+cc+"<br />bcc: "+bcc+"<br /> anexos "+anexos);
		var qs = "corpo=" + escape(corpo) + "&assunto=" + escape(assunto) + "&para=" + escape(para) + "&de=" + escape(de) + "&cc=" + escape(cc) + "&bcc=" + escape(bcc) + "&anexos=" + escape(anexos) + "&rfp=" + escape(rfp);
		getAcao(path + "/libs/asp/crud/sendMail.asp",qs,null);		
	}
	return b;
}
//#############################################################################

/*
* Funcao que usa funcao ajax e inclui conteudo text/html no id especificado
* 		- url = endereco da pagina
* 		- qs = querystring a passar (get)
*/
function getAcao(url,qs,idCp) { //alert(url + "\n\n" + qs + "\n\n" + idCp);
	goAjax(url,qs,"posAjaxAcao()","");	
	this.posAjaxAcao = function() { //alert(resultAjax);
		if (resultAjax.indexOf("{INFO}")>-1) {
			dialog(false,true, resultAjax.substring( resultAjax.indexOf("}")+1 ) ,"");
		}
		if (idCp!=null) setValorResult(idCp,resultAjax);
	}	
}
//............................
function setValorResult(idCp,s) { //alert(s + '\n\n' + document.getElementById(idCp).tagName.toUpperCase());
	var el = document.getElementById(idCp);
	var tg = el.tagName.toUpperCase(); //alert(tg);
	if ( tg.indexOf("INPUT")==-1 && tg.indexOf("TEXTAREA")==-1 && tg.toUpperCase().indexOf("SELECT")==-1 ) { 
		//Para ids de elementos
		el.innerHTML = s;
	} else {
		//Para campos de forms
		var cp = document.forms[0].elements[idCp]; //alert(cp);
		if (s.length>0) {
				//cp.disabled = false;
				//Preencher Select				
				if (cp.type.toLowerCase().indexOf("select")>-1 ) { //alert(s);
					var des = false;
					if (cp.disabled==true){
						des = true;
					}
					var o=null, d = new Array();
					d = eval(s);					
					cp.length = 0;
					
					var lg = cp.getAttribute("nolegend"); //true ou false
					lg = lg!=null ? eval(lg) : false;
					//alert(d[1]);
					for (var i=(lg?0:0) ;i<d.length;i++) addOptions(cp,d[i][0],d[i][1]);
					cp.disabled=des;
				} else {
					cp.value = s; //alert("Valor text: " + cp.value + " = " + s);
				}
		} else {
			var o=null, d = new Array();
			d = eval(s);					
			cp.length = 0;
			var lg = cp.getAttribute("nolegend"); //true ou false
			lg = lg!=null ? eval(lg) : false;
			//alert(d[1]);
			addOptions(cp,"","Nenhum dado encontrado!");
			cp.disabled = true;
		}
		
	}
	return void(0);
}

//================================================

function goExcluir(id,path,descritor,evt) {
	var ev = (NV.n=="IE") ? evt.srcElement : evt.target;

	//Se o elemento for linha de uma table
	this.delLinha = function() {
		var tb=null, row = ev.parentNode.parentNode;
		if (row.tagName.toUpperCase()=="TR") {
			var i=0, x=0, tb = row.parentNode.parentNode
			for (i=row.cells.length-1;i>=0;i--) row.deleteCell(i);	
			
			//Refazer cores linhas
			for (i=0;i<tb.rows.length;i++) { 
				if (tb.rows[i].className.toUpperCase().indexOf("LINHACOR")>-1 && tb.rows[i].cells.length>0) { 					
					tb.rows[i].className = "linhaCor" + x;
					x = (x==0?1:0);
				}
			}
			
		} else location.reload();
	}
	
	dialog(true,true,"Excluir registro agora?","posGoExcluir()");
	this.posGoExcluir = function() {
		if (resultDialog==true) {
			if (path.indexOf(".asp")>-1) {
				var qs = "";
				if (path.indexOf("?")>-1) {
					qs = "&" + path.substring( path.indexOf("?")+1 ); //alert(qs);
					path = path.substring(0,path.indexOf("?"));
				} //alert(path);
				goAjax(path,"acao=excluir" + qs,'posAjax()','');	
			} else
				goAjax(path + "crud.asp","acao=excluir&id="+escape(id)+"&descritor="+escape(descritor),'posAjax()','');				
				
		}
	}
	
	this.posAjax = function() { 
		if (resultAjax.indexOf("{OK}")>-1) delLinha();
		if (resultAjax.indexOf("{INFO}")>-1) dialog(false,true,resultAjax.substring(6),"");
	}
}


//================================================

/* Exclui registros em vrias tabelas usando controle de transao. */
function goExcluirTrans(id, path, arquivo) {
	
	dialog(true,true,"Excluir registro agora?","questExcluir()")
	
	this.questExcluir = function() { 
		if (resultDialog==true) goFormPost(path+arquivo+"?id="+id,'_self');	
	}
}
//================================================

//================================================

function goEnviaEmail(path, arquivo) {
	
	dialog(true,true,"Deseja enviar a cotação aos fornecedores?","posConform()")
	
	this.posConform = function() { 
		if (resultDialog==true) goFormPost(path + arquivo,'_self');	
	}
}
//================================================

/**
* Passeia por cada campo do form verificando se  exigido preenchimento com base
* na estrutura do nome dos campos. Seo o segundo caracter for "N",  exigido
*/
function isFieldsNotNull(f) {
	var b = true;	//---> Flag
	var dc = "";	//---> Descrio dos campos
	var cp = null; 	//---> ref. campo form
	var msg = ""; 	//---> Guarda mensagens de cada campo com "value" invlido
	var n = "";		//---> Vai guardar referencia do primeiro campo exigido
	var s = "";
	var r = "";
	var m = "";
	var c = 0;
	var y = 0;
	var e = null;
	var descCp = "";
	
	//alert(f.elements.length);
	
	for (var i=0;i<f.elements.length;i++){
		cp = f.elements[i];

		try {
			s = (cp.name.toLowerCase()!="acao") ? cp.name.substring(1,2).toUpperCase() : "";
		} catch (e) {
			s = "";
		}
		//alert(cp.name + "\n\n -> " + s);
		
		c = 0;		

		if (cp.type.indexOf("text")>-1 || cp.type.indexOf("image")>-1 || cp.type.indexOf("password")>-1 || cp.type.indexOf("select")>-1) {
			
			descCp = cp.getAttribute("title");
			descCp = descCp!=null ? descCp : "Preencha o campo " + cp.name;
			
			if (s=="N" && cp.value.trim().length==0) {
				if (n.length==0) n = cp;
				msg += "<li style='line-height:20px;'>Preencha o campo - <em>" + descCp.toUpperCase() + "</em></li>";
			}	
			
			if (cp.name.toUpperCase().substring(0,1)=="D" && s=="N" && cp.value.trim().length>0 && !isDate(cp.value.trim())) {
				if (n.length==0) n = cp;
				msg += "<li style='line-height:20px;'>O campo - <em>" + descCp.toUpperCase() + "</em> possui uma data invlida!</li>";
			}	
			
		} 
		//alert(msg);

		if (cp.type.indexOf("radio")>-1 || cp.type.indexOf("checkbox")>-1) {				

			//Corre todos elementos do grupo de campos
			this.getGrpCp = function () {
				var t=0;
				for (var x=0;x<y;x++) {
					if (s.toUpperCase()=="N" && !r[x].checked) t++;					
				}	
				return t;
			}
			
			//verificar se h mais de um campo
			r = eval("f."+cp.name); 

			y = r.length; //Total de elementos
			e = (typeof y=="undefined") ? r : r[0];
			descCp = e.getAttribute("title");
			descCp = descCp!=null ? descCp : "Preencha o campo " + e.name;
			//alert(descCp);
			
			if (cp.type.indexOf("checkbox")>-1) {					
				
				c = 0;					
				//Verificar se h grupo
				if (typeof y!="undefined") { 
					c = getGrpCp(); 
					dc = "<li style='line-height:20px;'>Marque no mnimo uma das opes - <em>" + descCp.toUpperCase() + "</em></li>";					
				} 
				
			} else {
				c = getGrpCp(); 
				dc = "<li style='line-height:20px;'>Marque uma das opes - <em>" + descCp.toUpperCase() + "</em></li>";
			}
							
			//se foi um grupo
			if (c==y) msg += msg.indexOf(dc)==-1 ? dc : "";					
		
		} 
		
	}	

	this.getCp = function() {
		if (n.length>0 && n!=null)
			n.focus();	 //Foco primeiro campo exigido
	}
	
	if (msg.length>0) { 
		msg = (msg.indexOf("<li")>-1) ? "<ul class='formResultTexto'>" + msg + "</ul>" : msg;
		dialog(false,true,msg,"getCp()");
		b = false;
	}
	
	return b;
}
//.............................................
function goSubmit(f,func,funcPos,path,limparCampos) {
	
	var btAcao = document.form1.bt_gravar;
	var txtOld = "Gravar";
	
	if (isFieldsNotNull(f)) {		
	
		if (btAcao!=null) { 
			btAcao.disabled = true;
			txtOld = btAcao.value;
			btAcao.value = "Aguarde...";
		}
		
		//Funes adcionais para execuo antes do submit
		if (func!=null) eval(func);

		s = setParams(document.form1,''); //alert(s);		
		goAjax(path + "crud.asp",s,'posAjax()','');
	}
	
	this.posAjax = function() { //alert(resultAjax);
		var tp = (resultAjax.indexOf("{ERRO}")>-1) ? false : true;
		var msg = (tp==false) ? resultAjax : "";
		if (resultAjax.indexOf("{INFO}")>-1) dialog(tp,true,msg,"fcPosDialog()");
		else fcPosDialog();
	}
	
	this.fcPosDialog = function() {
		if (resultAjax.indexOf("{OK}")>-1 && resultAjax.indexOf("incluir")>-1 && limparCampos) {			
			limpaCampos(f);
		}
		
		//Funes adcionais para execuo aps do submit
		if (funcPos!=null) eval(funcPos);
		
		if (btAcao!=null) { 
			btAcao.disabled = false;
			btAcao.value = txtOld;
		}
		
	}
}
//.............................................

function goSubmitForm(f,url) {
	url += "?"+setParams(f,""); //alert(url);
	goFormPost(url,"");
}

//.............................................
function goGravar(pag,f,path) {
	//f (isFieldsNotNull(f)) {		
		var q = setParams(f,''); //alert(q);
		goAjax(path + pag, q, 'posAjax()' ,'');
	//}
	
	this.posAjax = function() { //alert(resultAjax);
		var tp = (resultAjax.indexOf("{ERRO}")>-1) ? false : true;
		var msg = (tp==false) ? resultAjax : "";
		dialog(tp,true,msg,"fcPosDialog()");		
	}
	
	this.fcPosDialog = function() {
		if (resultAjax.indexOf("{OK}")>-1 && resultAjax.indexOf("incluir")>-1) {			
			limpaCampos(f);
		}	
	}
}

//================================================
/**
*	t = tipo de mensagem, info ou erro
*	md = se  modal
*	msg = texto do corpo da janela
*	func = funo adcional para executar quando a janela for fechada
*/
var resultDialog=null;
var TIME_CLOSE_DIALOG = null;
function dialog(t,md,msg,func) {
	var cls = (t==true) ? "formResultOk" : "formResultErro";
	var tit = (t==true) ? "Formulário processado com sucesso" : "Ocorreram os seguintes erros no formulário:";
	var vBt = "Fechar";
	var vBt2 = "";	
	
	var srcTop = (NV.n=="IE") ? document.documentElement.scrollTop : window.pageYOffset; //alert(srcTop);
	
	//Medidas tela
	var x = parseInt(document.body.offsetWidth) - 17;   
	var y = parseInt(document.body.offsetHeight);
	y =  y > parseInt(screen.availHeight) ? parseInt(screen.availHeight) + srcTop : y;
	
	if (NV.n!="IE") { //Netscape, Mozila, Firefox e Opera
		x = parseInt(window.innerWidth) - 20; 
		y = parseInt(window.innerHeight) + 20 + srcTop;
	}
	
	//Se msg, tiver seu ltimo carater = ?, criar aspecto de confirm()
	if (msg.charAt(msg.length-1)=='?') {
		cls = "formResultOk";
		tit = "Atenção:";
		vBt = "Sim";
		vBt2 = "Não";
	}
	
	var s = "<div id='dialog_XXX' class='formResult " + cls + "'>";
		s += "<div class='formResultTopo'>" + tit + "</div>";
		s += "<div style='padding:15px'>" + msg + "</div>";
		s += "<div style='padding-bottom:20px;text-align:center;'><form>";
		s += "<input type='button' id='btWinDialog' value='" + vBt + "' class='formBotao' onclick='fechaDialog(true);'>";
		if (vBt2.length>0) s += "&nbsp;&nbsp;<input type='button' id='btWinDialog2' value='" + vBt2 + "' class='formBotao' onclick='fechaDialog(false);'>";
		s += "</form></div>";
	s += "</div>";
	
	var wm = document.getElementById("ModalWinDialog");
	var fr = document.getElementById("__iframeIE");	 //Usar um iframe para corrigir falha IE
	var el = document.getElementById("winDialog");
	var sb = document.getElementById("winDialogSombra");
	if (el==null) {
		el = document.createElement("div");
		el.id = "winDialog";
		el.style.position = "absolute";
		el.style.zIndex = "10";
		el.style.width = "505px";
		el.style.left = ( (x - parseInt(el.style.width)) / 2) + "px";
		el.style.visibility = "visible";
		el = document.body.appendChild(el);
		
		if(NV.n=="IE") { //Apenas para IE		
			fr = document.createElement("iframe");
			fr.id = "__iframeIE";
			fr.style.position = "absolute";
			fr.style.zIndex = (parseInt(el.style.zIndex)-1).toString();
			fr.style.width = parseInt(el.style.width)-2 + "px";
			fr.style.left = parseInt(el.style.left) + "px";						
			fr.style.visibility = "visible";
			fr.src = "";
			fr.style.filter = "alpha(opacity=00)";
			fr = document.body.appendChild(fr);	
		}
		
		sb = document.createElement("div");
		sb.id = "winDialogSombra";
		sb.style.position = "absolute";
		sb.style.zIndex = (parseInt(el.style.zIndex)-2).toString();
		sb.style.width = parseInt(el.style.width) + "px";
		sb.style.left = parseInt(el.style.left)+5 + "px";
		sb.style.visibility = "visible";
		sb.style.background = "#000000";
		sb.style.filter = "alpha(opacity=30)";
		sb.style.opacity = "0.30";
		sb = document.body.appendChild(sb);
		
				
		if (md==true) {  //Tratando estado modal
				
			wm = document.createElement("iframe");
			wm.id = "ModalWinDialog";
			wm.style.position = "absolute";
			wm.style.zIndex = (parseInt(el.style.zIndex)-3).toString();
			wm.style.width = x + "px";
			wm.style.height = y + "px";
			wm.style.top = "0px";			
			wm.style.left = "0px";	
			wm.style.visibility = "visible";
			wm.src = "";
			wm.style.filter = "alpha(opacity=00)";
			wm.style.opacity = "0.00";
			wm.style.backgroundColor = "#000000";
			wm = document.body.appendChild(wm);

		}
	}
	el.innerHTML = s;	

	setTopDlg = function(){ 	
		el.style.top = ( ((parseInt(screen.availHeight)/2)-parseInt(el.offsetHeight)-50) + parseInt(document.documentElement.scrollTop) ) + "px";
		
		if (NV.n=="IE") { //Apenas para IE
			fr.style.height = parseInt(el.offsetHeight)-20 + "px";
			fr.style.top = parseInt(el.style.top) + "px";
		}
		
		sb.style.top = parseInt(el.style.top)+5 + "px";
		sb.style.height = parseInt(el.offsetHeight)-17 + "px";
	}
	validEvents("scroll","setTopDlg()",true);
	setTopDlg();
	
	//colocar foco no botao fechar da dialog
	document.getElementById("btWinDialog").focus();
	
	this.fechaDialog = function(b) {
		validEvents("scroll","setTopDlg()",false);
		clearTimeout(TIME_CLOSE_DIALOG);
		if (NV.n=="IE") document.body.removeChild( document.getElementById("__iframeIE") );
		if (md==true) document.body.removeChild( document.getElementById("ModalWinDialog") );
		document.body.removeChild( document.getElementById("winDialog") );	
		document.body.removeChild( document.getElementById("winDialogSombra") );		
		resultDialog = b;
		if (func.length>0) eval(func);
	}	
	
	clearInterval(TIME_CLOSE_DIALOG);
	//Fechar dialog se não houver msg
	if (msg.length==0) {
		TIME_CLOSE_DIALOG = setTimeout("fechaDialog(true)",1000);
	}
}

//================================================

function condicional(perg,func) {
	perg += perg.indexOf("?")==-1 ? "?" : "";
	dialog(true,true,perg,"resp()");	
	this.resp = function() { if (resultDialog) eval(func); }
}

//================================================

function getLink(url,tgt) {
	var obj = null;
	try {		
		if (tgt.toLowerCase().indexOf("blan") > 0 ) window.open(url,"nome_janela_"+url);
		else {
			obj = eval(tgt+".location");
			obj.href = url;
		}		
	} catch (e) {
		alert( "ERRO: " + this.name + "\n\n" + e.toString() );	
	}
}

//================================================

//Retorna objeto mais acima de tag
function getFather(el,tag) {
	var f = null;
	if (el.tagName!="BODY") {		
		el = el.parentNode;
		while (el.tagName!="BODY") {
			if (el.tagName==tag.toUpperCase()) { 
				f = el;	
				break;
			}
			el = el.parentNode;				
		}
	}
	return f;	
}

//================================================

function goFormOpenWindow(url) {
	var nw = window.open("","goFormOpenWindow","toolbars=yes,status=yes;");
	goFormPost(url,"goFormOpenWindow");
}

//================================================

function goFormPost(url,tgt) {
	var qs = "";
		
	var f = document.createElement("form");
	f.action = (url.indexOf("?")>-1) ? url.substring( 0, url.indexOf("?") ) : url;
	f.method = "post";		
	f.target = tgt;
	
	//Criar campos hidden 
	var qs = url.substring( url.indexOf("?")+1 ).split("&");
	var ch = new Array();
	for (var i=0;i<qs.length;i++) {
		ch[i] = document.createElement("input");
		ch[i].type = "hidden";
		ch[i].name = qs[i].substring( 0, qs[i].indexOf("=") );
		ch[i].value = qs[i].substring( qs[i].indexOf("=")+1 );
		f.appendChild(ch[i]);
	}
	
	f = document.body.appendChild(f);
	f.submit();	
}

//#############################################################################

function maxLength(cp,mx) {
	var v = cp.value;
	if (v.length>mx) cp.value = v.substring(0,mx);
}

//#############################################################################
function formatDecimal(f,dc) {
	var str = f.value;
	var Dgts = "0123456789,";
	var temp = "";
	var dgt = "";
		
    for ( var i = 0; i < str.length; i++ ) {
    	dgt = str.charAt(i);
      	if ( Dgts.indexOf(dgt) >= 0 ) {
			if (dgt == "," & temp.indexOf(",") < 0) temp += dgt;
          	if (dgt != ",") temp += dgt;
		}
    }
	if (temp.indexOf(",") > 0) temp = temp.substring(0,temp.indexOf(",")+1+dc);
    f.value = temp;
}
//#############################################################################
function setValorNumero(f,vMax) {
	var mx = vMax;
	var dc = mx.indexOf(".")>-1 ? mx.substring(mx.indexOf(".")+1).length : 0; 
	maxChar = mx.replace(/\D/g,"").length;
	formatDecimal(f,dc);
	var v = f.value.trim().replace(",",".");;
	v = parseFloat(v)>parseFloat(vMax) ? mx : v;
	v = v.replace(".",",");
    f.value = v.substring(0, v.indexOf(",")==-1?maxChar:maxChar+1 );		
}
//#############################################################################
 function setValorNumeroPonto(f,evt){
	var tecla = NV.n=='IE'?event.keyCode:evt.keyCode;	 
//	alert(f.value.length);	
	chkponto = function(){
		if (parseInt(f.value.length) > 0){
			var t = 0;
			for (var i = 0; i < parseInt(f.value.length); i++){
				if(f.value.charAt(i) == ".") t = t + 1;				
			}
			if ((t >= 1) && (tecla == 46)) return false;
		}
		return true;
	}
	 
	if (tecla > 45 && tecla < 58 && tecla != 47  && chkponto())
		return true;
	else
		{
			if (tecla != 8)
				event.keyCode = 0;
			else
				return true;
		}		
}
//Execute função caso seja precionado algumas das teclas de code: aCC
function getKeyCode(evt,funcao,aCC) {
    var s="",fnc=null;
    var f = (NV.n=="IE") ? evt.srcElement : evt.target; //alert('Elm: ' + f.tagName);
    var c = evt.keyCode;
    for (var i=0;i<aCC.length;i++) {
        if (c==parseInt(aCC[i]) & f.tagName!="TEXTAREA") fnc = eval(funcao);
    }
    return false;
}
//#############################################################################
var TIMEKEYUP = null;
function timeKeyUp(fnc) {
	clearTimeout(TIMEKEYUP);
	TIMEKEYUP = setTimeout(fnc,1100);
}
//#############################################################################
function keyEnter(event,fnc) {
	if (event.keyCode == 13) { 
		eval(fnc);
	}
}
//#############################################################################
/**
*	id = id do objeto para inserir o componente
*	nome = nome do componente input
*	vl_inicial = valor incial a carregar
*	vl_somar = valor a somar no processo
*	vl_min e vl_max = valores minimo e mximo que comnponente aceitar
*/
function numericUpDown(id,nome,vl_inicial,vl_somar,vl_min,vl_max,objFunc) {
		
	var larg=30;
	var VALOR = vl_inicial;
		
	this.setWidth = function (p) {
		larg = p;
	}
	
	function setValue(n) {
		if (n.indexOf("0")>-1) {
			VALOR += vl_somar;			
		} else {
			VALOR -= vl_somar;			
		}
		
		VALOR = VALOR<vl_min ? vl_min : VALOR;			
		VALOR = VALOR>vl_max ? vl_max : VALOR;
		document.getElementById("_"+nome).value = VALOR; 
		
		eval(objFunc);
	}
	
	function setinha(ids,p) {	
		var tm = 3;	//Indica o tamanho da seta	
		if (p<2) {
		
			var m = document.createElement("div");
			m.id = "mainSetinha_"+p;
			m.style.position = "relative";
			m.style.top = "1px";
			m.style.textAlign = "center";
			
			document.getElementById(ids).appendChild(m);
			
			var e = null;
			var w = (p==0) ? 1 : tm+(tm-1);
			for (var i=0;i<tm;i++) {					
				e = document.createElement("div");
				e.style.overflow = "hidden";
				e.style.fontSize = "1px";
				e.style.height = "1px";				
				e.style.width = w+"px";
				e.style.backgroundColor = "#000000";
				e.style.margin = "0 auto";
				m.appendChild(e);
				w = (p==0) ? w+2 : w-2;
			}
		}
	}

	//==============================================================

	this.show = function() {
	
		var largBts = 12;

		var main = "<table cellpadding='0' cellspacing='0px'><tr><td id='nud_cp'></td><td id='nud_bts'></td></tr></table>";
		
		document.getElementById(id).innerHTML = main;	
								
		var cp = document.createElement("input");
		cp.type = "text";
		cp.name = nome;
		cp.id = "_" + cp.name;
		cp.value = VALOR;
		cp.style.width = larg + "px";
		cp.style.height = "16px";
		cp.style.textAlign = "right";
		cp.style.paddingRight = "3px";
		cp.style.borderLeft = "1px solid #333333";
		cp.style.borderTop = "1px solid #333333";
		cp.style.borderRight = "1px solid #cccccc";
		cp.style.borderBottom = "1px solid #cccccc";
					
		document.getElementById("nud_cp").appendChild(cp);			
		
		cp.onkeyup = function() {
			this.value = this.value.replace(/\D*/g,"").substring(0,9);
			timeKeyUp(objFunc);
		}	
		
		cp.onblur = function () {
			setValue(this.value);
		}
		
		cp.onmouseup = function () {
			this.select();	
		}
		
		//--------------------------------------------			
		
		var bts = document.createElement("div"); //grade dos boes
		bts.style.borderLeft = "1px solid #666666";
		bts.style.borderTop = "1px solid #666666";
		bts.style.borderRight = "1px solid #ebebeb";
		bts.style.borderBottom = "1px solid #ebebeb";
		bts.style.width = largBts+2 + "px";

		document.getElementById("nud_bts").appendChild(bts);
		
		
		var h = (navigator.appVersion.indexOf("MSIE 5")>-1) ? 10 : parseInt(cp.offsetHeight)/2 - 3;
		
		var n = null;	//cria botes
		for (var i=0; i<=1; i++) {
			n = document.createElement("div");
			n.id = "_mud"+i;
			n.style.height = h + "px";
			n.style.width = largBts + "px";
			n.style.cursor = cursorTypeCss;
			n.style.borderLeft = "1px solid #ebebeb";
			n.style.borderTop = "1px solid #ebebeb";
			n.style.borderRight = "1px solid #666666";
			n.style.borderBottom = "1px solid #666666";
			n.style.backgroundColor = "#cccccc";	
										
			bts.appendChild(n);	
			
			setinha(n.id,i);
			
			//-----------------------------------------
			
			n.onmouseup = function() {
				this.style.borderLeft = "1px solid #ebebeb";
				this.style.borderTop = "1px solid #ebebeb";
				this.style.borderRight = "1px solid #666666";
				this.style.borderBottom = "1px solid #666666";
				setValue(this.id);
			}
			
			n.onmouseover = function() {
				this.style.backgroundColor = "#E1E1E1";
			}
			
			n.onmouseout = function() {
				this.style.backgroundColor = "#cccccc";
			}
			
			n.onmousedown = function() {
				this.style.borderLeft = "1px solid #666666";
				this.style.borderTop = "1px solid #666666";
				this.style.borderRight = "1px solid #ebebeb";
				this.style.borderBottom = "1px solid #ebebeb";
			}
		}			
		
	}		
	
}

//#############################################################################
//Retorna posio absoluta do elemento "el"
function getAbsolutePos(el) {
	var SL = el.scrollLeft;
	var ST = el.scrollTop;
	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent) { //Passa por cada elemento parent at chegar no ltimo, o que ser usado como parametro de posio
			var tmp = this.getAbsolutePos(el.offsetParent);
			r.x += tmp.x;
			r.y += tmp.y;
	}
	return r;
}

//#############################################################################

function addRowListaMncp(f,id,path) { //alert(f.value);
	var tb = document.getElementById(id);
	var rFirst = 3;
	
	var v = f.split("#"); 
 	var c=null, l=null, b=true;
	
	var s = "";
	for (var i=rFirst-1;i<tb.rows.length;i++) {
		
		s = tb.rows[i].cells[0].innerHTML;
		if ( s.indexOf(v[1])>-1 ) {
			b = false;
			dialog(false,true,"Este município já esta na lista!","");
			break;
		}
	}
	
	if (b && v[1]!="null") {
		l = tb.insertRow(rFirst-1);			
		c = l.insertCell(0);		
		c.innerHTML = v[1] + ' <input type="hidden" name="NG__CD_MNCP" value="' + v[0] + '" />';				
				
		c = l.insertCell(1);	
		c.innerHTML = '<span class="formLabel"><input name="NG__CP1" type="text" desc="Preencha o campo Aliquota do município ' + v[1] + '" class="formInput formPequeno" value="' + v[2] + '" /> % </span>';
		
		c = l.insertCell(2);		
		c.innerHTML = '<div align="center"><input type="checkbox" name="SG__CP2" value="N" onclick="this.value=(this.checked?\'S\':\'N\')" /></div>';	
		
		c = l.insertCell(3);		
		c.innerHTML = '<img style="cursor:' + cursorTypeCss + '" src="' + path + 'imagens/icons/delete.gif" alt="Excluir linha" title="Excluir linha" onclick="" />';	
		c.style.width = "16px";
	}
}

//#############################################################################

function preparaDadosFormCamposMultiplo(f,func,path) {
	
	this.getLength = function (c) {
		var t = 0;
		try { t = c.length; } catch(e) {};
		if (isNaN(t)) t=1;
		return t; 
	}
	
	//alert(getLength(f.NG__CP1));
	
	var i = 0;
	for (i=0;i<f.elements.length;i++) {
		
	}
	
}
//#############################################################################
function addOptions(cp,valor,texto) {	
	var oOption = document.createElement("Option");
	oOption.value = valor;
	oOption.text = texto;
	oOption.setAttribute("idx",cp.options.length);
	try { cp.add(oOption, null); } // NS/FF
	catch(e) { cp.add(oOption); } // IE
	return oOption;
}
//------------------------------------------
function deleteOptionsMultiple(evt) {
	var ev = NV.n=="IE" ? event : evt;
	var e = NV.n=="IE" ? ev.srcElement : ev.target; 
	var i, p, s=-1, o=[];
	if (ev.keyCode==46) { //Pressionou Delete
		for(i=0;i<e.options.length;i++)  {
			if(!e.options[i].selected) {				
				o.push( [e.options[i].value,e.options[i].text] );
			} else 
				s = s==-1?i:s;
		}
		e.length = 0;
		for(i=0;i<o.length;i++) addOptions(e,o[i][0],o[i][1]);
		if (e.options.length>0 && s!=null) e.options[ s<e.options.length?s:s-1 ].selected = true;
	}
}
//############################################################################

//Verifica existência de valor em selects
function isOptionExist(cp,s,t) {
	var v = "";
	for(var i=0;i<cp.options.length;i++) {
		v = t==0?cp.options[i].value:cp.options[i].text;
		if (s.toUpperCase()==v.toUpperCase()) return true;
	}
	return false;
}

//############################################################################
//Preenche combo com lista de valores
//----> listValues tem que ser uma string com formato possível de transformar num array bidimencional
function setOptionsSelects(cb,listValues,vDefault) {
	var o = null, op = null, d = new Array(); 
	d = eval(listValues);
	cb.length = 0;
	for (var i=0;i<d.length;i++) {
		o = addOptions(cb,d[i][0],d[i][1]);	
		if (o.value.toUpperCase()==vDefault.toUpperCase()) {
			o.selected = true;
			op = o; //option atual selecionado
		}
	}
	return op;
}
//############################################################################
//c = combo | v = value | t = text | ex = se comparao ser para o text integral ou apenas trecho. 0 = parcial e 1 = integral
function selOptionTextValue(c,v,t) {
	var o = null;
	for(var i=0; i<c.length; i++) {
		o = c.options[i];
		if ( o.value.trim().toUpperCase()==v.toUpperCase() && o.text.trim().toUpperCase().indexOf(t.trim().toUpperCase())>-1 ) {
			o.selected = true;
			break;
		}
	}
}
//############################################################################

function selectToSelect(cb1,cb2,cpAddValue) {
	var o = null, v;
	for (var i=0;i<cb1.options.length;i++) {
		o = cb1.options[i];
		v = cpAddValue.concat(o.text);
		if ( o.selected && !isOptionExist(cb2,v,1) ) addOptions(cb2,o.value,v);
	}	
}

//############################################################################
/*
* e = Array de valores. geralmente usado para uma seleo multipla em campo select, haver vários valores
* cp = nome do combo a preencher
* url = caminho do arquivo que gera string do combo
*/

function carregaCombo(e,cp,url) {
	var s = new Array();
	for (var i = 0; i < e.options.length; i++) {
		if (e.options[i].selected) s.push(e.options[i].value);	
	} //alert(s);
	var f = eval("document.form1."+ cp); //alert(f);
	if (s.length>0) { 
		goAjax(url,"param=" + escape(s),"posAjax()",'');	
	}
	//--------------------------------------------
	this.posAjax = function() { //alert(resultAjax);
		if (resultAjax.length>0) setOptionsSelects(f,resultAjax,"");
	}
}

//############################################################################

//Funo para importao de arquivos
function goImportFile(s,s2) {
	var strParam = "";
	for (var i=0; i < s.length; i++)
	{
		if (s[i].checked == true)
		{
			strParam = strParam + s[i].value;
		}
	}
	
	if (strParam != "") { 
		//alert(strParam);
		//goAjax("fileimport.asp","param=" + escape(strParam) + "&param2=" + escape(s2),"posAjax()",'');	
		location.href = "fileimport.asp?param=" + escape(strParam) + "&param2=" + escape(s2);
	}
	//--------------------------------------------
	this.posAjax = function() { //alert(resultAjax);
		dialog(true,true,resultAjax,"");
	}
}

//############################################################################

//id_btsell = id do bot ou elemento que ser a cionador da function
//c = referencia do campo da lista de checkbox
function selAllCBX(id_btsell,c) {
	var bt = document.getElementById(id_btsell);
	var ck = bt.innerHTML.indexOf("Des")>-1 ? false : true;
	bt.innerHTML = (bt.innerHTML.indexOf("Des")>-1 ? "Marcar todos" : "Desmarcar todos");
	var t = c.length;
	if (typeof t!="undefined") {
		for(var i=0;i<t;i++) {
			if (!c[i].disabled) c[i].checked = ck;
		}
	}							
}
	
//############################################################################
//Verifica se valor existe no Array
Array.prototype.isValueExist = function(v) {
	var b = false;
	for (var i=0;i<this.length;i++) { //alert( this[i].toUpperCase() + " = " + v.toUpperCase() );
		if (this[i].toUpperCase()==v.toUpperCase()) b = true;
	}	
	return b;
}

//############################################################################

function retornaCheck(f){
	var x = f.length;
	
	if (typeof x != "undefined") {
		var valorOp = new Array();
		
		for(var i = 0; i < x; i++){
			if (f[i].checked){
				valorOp.push(f[i].value);
			}
		}
	}else{
		valorOp = f.value;	
	}
	return valorOp;
}

//############################################################################
//Apenas para IE6-
function fixLayerIE6(el) {
	var fr = document.getElementById(el.id + "_iframeIE");
	if(NV.n=="IE" && el!=null) { 		
		if (fr==null) {
			fr = document.createElement("iframe");
			fr.id = el.id + "_iframeIE";
		}
		var z = parseInt(el.style.zIndex)-1;
		var w = parseInt(el.offsetWidth);
		var h = parseInt(el.offsetHeight);
		
		//se as propriedades offset não retornarem nada, tentar as style...
		if ( w==0 && parseInt(el.style.width)>0 ) w = parseInt(el.style.width);
		if ( h==0 && parseInt(el.style.width)>0 ) h = parseInt(el.style.height);
		
		//se estes valores forem zero, é porque el é uma tabela, com isso devo recuperar medidas para cada célula
		if (w==0) {
			var tb = getCellMaxTable(el); //Retorna qual linha tem mais célunas e quantas são			
			var c = null;  
			for(var y=0;y<tb.lengthCells;y++) {
				c = el.rows[tb.indexRowMaxCells].cells[y];
				w += parseInt(c.style.width);
				h += parseInt(c.style.height);					
			}		
		}
		with(fr.style) {
			position = "absolute";		
			zIndex = z;
			width = w + "px";
			height = h + "px";
			top = parseInt(el.style.top) + "px";		
			left = parseInt(el.style.left) + "px";							
			filter = "alpha(opacity=00)";
		}		
		document.body.appendChild(fr);
	}	
	return fr;
}
//------------------------------------------
function clearFixLayerIE6(fr) {
	if(fr!=null) document.body.removeChild(fr);	
}	
//----------------------------------------------------------------------------
//Verifica qual é a medida e qual linha/coluna de uma tabela tem mais celulas
function getCellMaxTable(tb) {
	var c = 0,i,tC,y;
	for(y=0;y<tb.rows.length;y++) {
		tC = tb.rows[y].cells.length;
		if (c<tC) { //Linha com mais células e seu index
			c = tC;
			i = y;
		}
	}	
	return { lengthCells:c , indexRowMaxCells:i };
}
//############################################################################
//Funo para tratar formatao de Porcentagem ex: 10% ou 10,2 e no 10,0

function setaTextoFinal(ok, target, unicode, separador, casasDecimais, valorMaximo){
    // unicode  o algarismo, -1 se no tiver algarismo e separador  10.
    if (ok){
        target.focus();
        var range = document.selection.createRange();
        var numUndo = 1;
        if (range.text != ""){
            range.text = "";
            numUndo++;
        }
        range.select();
        range.text = unicode == 10 ? separador : unicode != -1 ? unicode : "";
        var mascaraEstouroInteiros = new RegExp("^\\d{" + (target.maxLength - casasDecimais) + "}$");
        var mascaraComSeparador = new RegExp("^\\d{0,"+(target.maxLength-casasDecimais-1)+"}" + separador + "\\d{0,"+casasDecimais+"}$");
        var mascaraSemSeparador = new RegExp("^\\d{0,"+(target.maxLength-casasDecimais-1)+"}$");
        if (casasDecimais && !mascaraComSeparador.test(target.value) && !mascaraSemSeparador.test(target.value) && !mascaraEstouroInteiros.test(target.value)){
            for (var i = 0; i<numUndo; i++){
                document.execCommand("Undo");
            }
        }

        var mascara = new RegExp("^" + separador + "\\d*$");
        if (mascara.test(target.value) && target.value.length < target.maxLength){ //comea com separador
            target.focus();
            var range = document.selection.createRange();
            range.moveStart("textedit",-1);
            range.moveEnd("textedit",-1);
            range.text = "0";
        }

        mascara = new RegExp("^0\\d+,?\\d*$"); //texto comea com zero seguido de nmeros, tiro o zero.
        while (casasDecimais && mascara.test(target.value)){
            target.focus();
            var range = document.selection.createRange();
            range.moveStart("textedit",-1);
            range.moveEnd("textedit",-1);
            range.moveEnd("character",1);
            range.text = "";
        }

        /*mascara = new RegExp("^\\d{" + (target.maxLength - 1 - casasDecimais) + "}$");
        if ((unicode > -1) && (casasDecimais > 0) && (target.maxLength > target.value.length) && mascara.test(target.value)){ //acabou o espao para inteiros e no tem separador ainda e o usurio no est apagando.
            target.focus();
            var range = document.selection.createRange();
            range.moveStart("textedit",1);
            range.moveEnd("textedit",1);
            range.text = separador;
        }*/

        if ((casasDecimais > 0) && (target.maxLength > target.value.length) && mascaraEstouroInteiros.test(target.value)){ //acabou o espao para inteiros e o usurio apagou o separador. Agora ele comea a digitar os decimais.
            target.focus();
            var range = document.selection.createRange();
            range.moveStart("textedit",1);
            range.moveStart("character",-1);
            range.moveEnd("textedit",1);
            range.moveEnd("character",-1);
            range.text = separador;
        }

        while (valorMaximo != null && valorMaximo != undefined && eval(target.value.replace(",",".")) > valorMaximo){
            target.focus();
            var range = document.selection.createRange();
            range.moveStart("textedit",1);
            range.moveStart("character",-1);
            range.moveEnd("textedit",1);
            range.text = "";
        }

        ok = false;
    }
}

function formataDecimal(e, casasDecimais, valida, valorMaximo){
    var separador = ',';
    if (!e) var e = window.event; //ie
    var unicode=e.charCode? e.charCode : e.keyCode; //ie
    var tecla = String.fromCharCode(unicode); 
    var target = e.target ? e.target : e.srcElement; //ie
    var selecao = "";
    if (document.selection) { // ie
        selecao = document.selection.createRange().text;
    }

    var ok = false;
    switch (unicode) {
        case 8: //backspace
            target.focus();
            var range = document.selection.createRange();
            if (!range.text.length){
                range.moveStart("character",-1);
            }

            var numUndo = 0;
            if (range.text != ""){
                range.text = "";
                numUndo++;
            }
            range.select();
            var mascaraComSeparador = new RegExp("^\\d{0,"+(target.maxLength-casasDecimais-1)+"}" + separador + "\\d{0,"+casasDecimais+"}$");
            var mascaraSemSeparador = new RegExp("^\\d{0,"+(target.maxLength-casasDecimais-1)+"}$");
            if (casasDecimais && !mascaraComSeparador.test(target.value) && !mascaraSemSeparador.test(target.value)){
                for (var i = 0; i<numUndo; i++){
                    document.execCommand("Undo");
                }
            }
            ok = false;
            break;
        case 9: //tab
        case 13: //enter
            if (valida){
                validaDecimal(target, casasDecimais);
            }
            ok = true;
            break;
        case 33: //pgdown
        case 34: //pgup
        case 35: //end
        case 36: //home
        case 37: //seta para esquerda
        case 39: //seta para direita
            ok = true;
            break;
        case 46: //delete
            target.focus();
            var range = document.selection.createRange();
            if (!range.text.length){
                range.moveEnd("character",1);
            }

            var numUndo = 0;
            if (range.text != ""){
                range.text = "";
                numUndo++;
            }
            range.select();
            var mascaraComSeparador = new RegExp("^\\d{0,"+(target.maxLength-casasDecimais-1)+"}" + separador + "\\d{0,"+casasDecimais+"}$");
            var mascaraSemSeparador = new RegExp("^\\d{0,"+(target.maxLength-casasDecimais-1)+"}$");
            if (casasDecimais && !mascaraComSeparador.test(target.value) && !mascaraSemSeparador.test(target.value)){
                for (var i = 0; i<numUndo; i++){
                    document.execCommand("Undo");
                }
            }

            ok = false;
            break;
        default:
            // a partir daqui, somente algarismos ou separador
            if (unicode > 47 && unicode < 58){ //algarismos
                unicode -= 48;
                ok = true;
            } else {
                if (unicode > 95 && unicode < 106){ //teclado numrico
                    unicode -= 96;
                    ok = true;
                } else {
                    var mascara = new RegExp("^\\d*$");
                    target.focus();
                    var range = document.selection.createRange();
                    if (casasDecimais && (mascara.test(target.value) || range.text.indexOf(separador) > 0)){ //no tem separador ou o mesmo foi selecionado e tem casasDecimais
                        switch (unicode) {
                            case 194:// . teclado numrico
                                unicode -= 184;
                                ok = true;
                                break;
                            case 110:// , teclado numrico
                                unicode -= 100;
                                ok = true;
                                break;
                            case 190:// .
                                unicode -= 180;
                                ok = true;
                                break;
                            case 188:// ,
                                unicode -= 178;
                                ok = true;
                                break;
                        }
                    }
                }
            }
            setaTextoFinal(ok, target, unicode, separador, casasDecimais, valorMaximo);
            ok = false;
    }
    return ok;
}

//################################################################################################################################

function isDate(d) { //Verifica se data
    //Separa valores
    var dd = d.substring(0,d.indexOf("/"));	
    var mm = d.substring(d.indexOf("/")+1,d.lastIndexOf("/"));
    var aa = d.substring(d.lastIndexOf("/")+1,10);
    //alert(dd + " - " + mm + " - " + aa);

    //Inverter data para valor ingls, e cria data
    var dt = new Date(mm+"/"+dd+"/"+aa);
    var ddd = dt.getDate();
    var mmm = (dt.getMonth()+1);
    var aaa = dt.getFullYear();            
    //alert(ddd + " - " + mmm + " - " + aaa);

    return ( (dd==ddd & mm==mmm & aa==aaa) & parseInt(aa) > 1900 ) ? true : false;
}

//################################################################################################################################

function cDate(s){
	var dt = null;
	if (isDate(s)) {
		//Separa valores
		var dd = s.substring(0,s.indexOf("/"));	
		var mm = s.substring(s.indexOf("/")+1,s.lastIndexOf("/"));
		var aa = s.substring(s.lastIndexOf("/")+1,10);
	
		//Inverter data para valor inglês, e cria data
		dt = new Date(mm+"/"+dd+"/"+aa);
	}
	return dt;
}

//################################################################################################################################

function validMasksForm(f) {
	var cp = null, msk="", m="";
	for (var i=0; i<f.elements.length; i++) {
		cp = f.elements[i];
		msk = cp.getAttribute("mask");
		if (msk!=null) m = msk; //alert(m);
		//campos data
		if (cp.type.indexOf("text")>-1) {			
			if (cp.name.charAt(0)=="D" || m=="99/99/9999") {
				$(cp).mask("99/99/9999",{placeholder:" "});
				cp.onkeyup = function() { 
					var er = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
					if ( er.test(this.value) && !isDate(this.value) ) {
						//this.select();
					}
				}
			}
		}
	}
	return true;					
}

//################################################################################################################################
//Executa funes annimas que foram lidas dos eventos. No IE traz uma string com function no nome
function executeFuncAnon(f) { //alert(f);
	var er = (/\bfunction\b/).exec(f); //No firefox a string que representa os eventos
	if (er) f = f.substring( f.indexOf("{")+1, f.lastIndexOf("}") );
	f = eval(f.toString());	
}

//################################################################################################################################

//Atribui o valor ao campo verificando antes o type
function setValue(f,cp,s) {
			
	if (s.length>0) {
		
		//Campos Select
		if (cp.type.indexOf("select")>-1) {
			
			for (var y=0; y<cp.options.length;y++) {
				op = cp.options[y]; //alert(op.text + "\n\n" + op.value + " = " + s);
				if ( op.value.toLowerCase()==s.toLowerCase() ) { //alert(cp.name + " = " + op.value);
					op.selected = true;
				}
			}
			
		} else if (cp.type.indexOf("radio")>-1 | cp.type.indexOf("checkbox")>-1) { //Campos Radio
			
				//verificar se h mais de um campo
				r = eval("f."+cp.name);
				x = r.length; //Total de elementos
								
				//Corre todos elementos do grupo de campos Checkbox
				this.setGrpCp = function () {
					for (var z=0; z<x;z++) { alert(r[z].name + " ---------> " + r[z].value + " = " + s);
						if (r[z].value.toUpperCase()==s.toUpperCase()) { 
							if (s.toUpperCase()=="N" || s.toUpperCase()=="S") {
								r[z].value = s.toUpperCase();
								r[z].checked = s.toUpperCase()=="S" ? true : false;
							} else 
							r[z].checked = true;
						}
						break;
					}
				}
			
				if (cp.type.indexOf("checkbox")>-1) { //alert(cp.name + " = " + cp.value + "\n\n" + s);
							
					//Verificar se há grupo
					if (!isNaN(x))  
						setGrpCp();
					else {
						if (s.toUpperCase()=="N" || s.toUpperCase()=="S") {
							cp.value = s.toUpperCase();
							cp.checked = s.toUpperCase()=="S" ? true : false;
						} else
							cp.checked = (cp.value==s) ? true : false;
					}						
					
				} else { //Radio
					//alert(cp.name + " ---> " + cp.value.toUpperCase() + " == " + s.toUpperCase()) 
					if (cp.value.toUpperCase()==s.toUpperCase()) cp.checked = true;					
				}
				
		} else {
			//Campos Text, Textarea, Hidden
			while (s.indexOf("{13}")>-1 || s.indexOf("{10}")>-1 || s.indexOf("{9}")>-1) {
				s = s.replace("{13}",String.fromCharCode(13));  
				s = s.replace("{10}",String.fromCharCode(10));  
				s = s.replace("{9}",String.fromCharCode(9));      
			}
			cp.value = s;	
		}
	}
	return true;
}
//################################################################################################################################

//Nos casos de uma combo servir outra, via seleção, aguardar a segunda preencher, e setar seu valor vindo do getDados
var timeReadState = []
function validComboBoxEvents(cp,cp2,vdf) {
	var chg = cp.onchange.toString();
	chg = chg.replace("this.value","'" + escape(cp.value) + "'"); //alert(chg);
	executeFuncAnon(chg);	
	
	readStateCp = function() { //alert(cp2.options.length);
		if (cp2.options.length>0) {
			clearInterval(timeReadState[cp.name]);
			for(var i=0; i<cp2.options.length; i++) {
				o = cp2.options[i]; //alert(o.value.trim().toUpperCase() + " = " + vdf.toUpperCase());
				if ( o.value.trim().toUpperCase()==vdf.toUpperCase() ) {
					o.selected = true;
					//break;
				}
			}
		}
	}
	
	timeReadState[cp.name] = setInterval(readStateCp,100);	
}

//################################################################################################################################

//Muda value de acordo com estado do checkbox
function setValuesCheckBox(f,vlTrue,vlFalse) {	
	f.value = f.checked ? vlTrue : vlFalse;
}

//################################################################################################################################

//Muda estado de estado do checkbox
function setCheckBox(f,evt) {
	var e = NV.n=="IE"?event.srcElement:evt.target;
	e = e.tagName=="INPUT"? (e.type.indexOf("checkbox")==-1?false:true) : false;
	if(!e) f.checked = !f.checked;
}

//################################################################################################################################

//Marca checkbox que tenha value dentro do array de valores listValues
function setCheckedCheckBox(f,listValues) {
	var e, ck, i, y;
	for(i=0;i<f.elements.length;i++){
		e = f.elements[i];
		if (e.type.indexOf("checkbox")>-1) {
			ck = false;
			for(y=0;y<listValues.length;y++) {				
				if (e.value.toUpperCase()==listValues[y].toUpperCase()) {
					ck = true;
					break;
				}
			}
			e.checked = ck;
		}
	}	
}
//################################################################################################################################

function setRadioChecked(rd) {
	rd.checked = rd.checked ? false : true;
}

//################################################################################################################################

function popup(url,n,w,h,r,sb,sts)
{
	var t = parseInt((screen.availHeight-h)/2);
    var l = parseInt((screen.availWidth-w)/2);
    return window.open(url, n,"width="+w+",height="+h+",top="+t+",left="+l+",resizable="+r+",scrollbars="+sb+",status="+sts);
}

//################################################################################################################################
function getGrava(url,qs,funcPre,funcPos) {
	var b = eval(funcPre);	
	if (b) goAjax(url,qs,"posAjax()","");	
	this.posAjax = function() { eval(funcPos) }
}
//---------------------------
function posGetGravar(s) {
	var b = resultAjax.indexOf("{INFO}")>-1 ? false : true;
	var msg = resultAjax.substring( resultAjax.indexOf("}")+1 );
	
	this.fc = function() {
		if (typeof s=="string")	self.location.href = s;
		else return void(0);
	}
	
	dialog(b,true,msg,"fc()");
}
//################################################################################################################################

function setCombo(url,cp,vlSql) {	
	var f = eval("document.forms[0]."+ cp); //alert(f);
	f.length = 0; //Limpa combo
	
	goAjax(url,"cp="+escape(cp)+"&vlSql="+escape(vlSql),"posAjax()",'');	
	
	this.posAjax = function() { //alert(resultAjax);
		if (resultAjax.length>0) setOptionsSelects(f,resultAjax,"");
	}	
}

//################################################################################################################################
function previewPrint(s) {
	var wp = popup('','preview','800px','450px','yes','yes','yes');	
	s = ('<html><head><script>window.onerror = function() { return true; };</script><link href="../../libs/css/layout.css" rel="stylesheet" type="text/css" /><link href="../../libs/css/geral.css" rel="stylesheet" type="text/css" /><style>#pag_reg{display: none;}</style></head><body><br /><br />') + s + ("</body></html>");
	wp.document.write(s);
}
//################################################################################################################################
function goXLS(url) {
	var f = document.form1;	
	if(confirm("De acordo com o número de registros filtrados a criação de um arquivo XLS pode demorar alguns minutos, deseja continuar?")) {
		f.action = url;	
		f.submit();
	}
}
//################################################################################################################################
function loadingAjax(msg,path) {	
	var bk = document.getElementById("iframe_background_loadindAjax");
	
	if (bk==null) {	
	
		if (NV.n!="IE") document.body.style.overflow = "hidden";
		
		var mw = parseInt(document.body.offsetWidth);	
		var mh = parseInt(document.body.offsetHeight);
		if (NV.n!="IE") mh += 5;
		
		bk = document.createElement("iframe");
		bk.id = "iframe_background_loadindAjax";
		with (bk.style) {
			width = mw + "px";
			height = mh + "px";
			backgroundColor = "#cccccc";
			filter = "alpha(opacity=0)";
			opacity = "0";
			position = "absolute";
			top = "0px";
			left = "0px";
		}
		
		fd = document.createElement("div");
		fd.id = "fundo_background_loadindAjax";
		with (fd.style) {
			width = parseInt(bk.style.width) + "px";
			//height = parseInt(bk.style.height) + "px";
			height = 100 + "%";
			backgroundColor = "#000000";
			filter = "alpha(opacity=20)";
			opacity = "0.2";
			position = "absolute";
			top = "0px";
			left = "0px";
		}
			
		ct = document.createElement("div");
		ct.id = "container_background_loadindAjax";
		with (ct.style) {
			width = "300px";
			height = "50px";			
			position = "absolute";
			border = "3px solid #cccccc";
			backgroundColor = "#ffffff";
			top = ((parseInt(screen.availHeight)/2)-90) + "px";
			left = ((mw/2)-150) + "px";
		}
		ct.innerHTML = "<table cellspacing='10px'><tr><td style='font: bold 14px Arial; color:#333333;text-align:center;'>" + msg + "</td></tr>";
		document.body.appendChild(bk);
		document.body.appendChild(fd);
		document.body.appendChild(ct);
		
		setTopCt = function(){ 	
			ct.style.top = (((parseInt(screen.availHeight)/2)-90)+parseInt(document.documentElement.scrollTop)) + "px";
		}
		validEvents("scroll","setTopCt()",true);
		
	} else {
		validEvents("scroll","setTopCt()",false);
		document.body.removeChild(ct);
		document.body.removeChild(fd);
		document.body.removeChild(bk);
		
		if (NV.n!="IE") document.body.style.overflow = "auto";
	}
	return true;	
}
//################################################################################################################################
//Cria aspecto para combos que estão sendo carregadas por ajax
var timeColorCbx = null;
function loadingCombo(e,b) {
	e.length = 0;
	if (b) {			
		e.disabled = true;
		addOptions(e,"","Aguarde, consultando");	
		e.style.fontWeight = "bold"
		e.style.fontVariant = "small-caps";
		e.style.backgroundColor = "#ffffCA";
		loading = function() {
			var op = e.options[0];
			op.text = (op.text.indexOf(" . . .")>-1) ? op.text.replace(" . . .","") : op.text.concat(" ."); 
		}
		timeColorCbx = setInterval(loading,200);
	} else {
		clearInterval(timeColorCbx);
		e.style.fontWeight = "normal"
		e.style.fontVariant = "normal";
		e.style.backgroundColor = "#ffffff";
		e.disabled = false;
	}	
}
//################################################################################################################################
function setFilterCombo(cb,qs,url) {
	var w = parseInt(cb.offsetWidth);
	var ifr = null;
	var n = "filter" + cb.name;
	var txt = document.getElementById(n);
	
	//querystring adcional vinda do combofilter
	qs = qs.length>0 ? "&"+qs : qs;
	
	if (txt==null) {			
		if (NV.n=="IE") {
			ifr = document.createElement("iframe");
			with (ifr) {
				id = "iframe_" + n; 
				src = "";
				style.width = w + "px";
				style.height = "27px";
				style.filter = "alpha(opacity=0)";
				style.position = "absolute";
			}
			document.body.appendChild(ifr);	
		}		
		txt = document.createElement("input");
		with (txt) {
			type = "text";
			id = n;
			style.width = (w-9) + "px";
			style.height = "20px";
			style.backgroundColor = "#ffffcc";
			style.font = "bold 14px Verdana,Arial";
			style.letterSpacing = "1px";
			style.color = "#333333";
			style.border = "2px solid #ff0000";
			style.padding = "2px 0 0 5px";
			style.position = "absolute";	
		}
		document.body.appendChild(txt);		
		validEvents("body.click","closeTxt(event,false)",true);
		
		txt.onkeyup = function(evt) {
			var ev = (NV.n=="IE") ? event : evt;
			if (ev.keyCode==13) closeTxt(ev,true);
		}		
		txt.onblur = function() { closeTxt(event,true); }		
		txt.focus();
		
		document.form1.onsubmit = function() { return false; };
	} 
	
	//Trata posicionammentos absolutos
	var pCb = getAbsolutePos(cb);
	var top = parseInt(pCb.y);
	var left = parseInt(pCb.x);
	top = cb.multiple ? top-25 : top-2;
	
	if (ifr!=null) {
		ifr.style.top = top + "px";
		ifr.style.left = left + "px";
	}
	
	txt.style.top = top + "px";
	txt.style.left = left + "px";
	txt.focus();

	this.closeTxt = function(evt,b) {
		var vl = txt.value.trim();
		var e = (NV.n=="IE") ? evt.srcElement : evt.target;
		var id = e.id.toLowerCase();
		if ( id.indexOf("filter")==-1 || b ) {			
			
			//Remove input e iframe
			document.body.removeChild( txt );
			if (ifr!=null) document.body.removeChild( ifr );
			
			//Retira função do event
			validEvents("body.click","closeTxt(event,false)",false);
			
			//Chama Ajax para preencher combo
			if (vl.length>0) setComboFilter( url, "t=" + escape(cb.name) + "&qs=" + escape( vl.replace(/\'/g,"") ) + qs );
		}
	}
	
	//Chama Ajax
	this.setComboFilter = function(url,qs) {
		loadingCombo(cb,true); //alert(qs);
		goAjax(url,qs,"posFilterAjax()",'');		
	}
	
	//Processa resposta Ajax, atualiza combo
	this.posFilterAjax = function() {
		loadingCombo(cb,false);
		
		cb.length = 0; //Limpa combo
		if (resultAjax.length>0) {
			var d = new Array(); 
			var lg = " carregando: "
			d = eval(resultAjax);
			
			var t = d.length;
			var lgP = "";
			for (var i=0;i<t;i++) {					
				addOptions( cb, d[i][0], d[i][1] );

				lgP = lgP.length==0 ? cb.options[0].text : lgP
				cb.options[0].text = lg + Math.round( ((i+1)*100 / t) ) + "%";
			}
			if (t>0 && cb.options.length>0) cb.options[0].text = lgP;
			//-------------------------
			if (t=1) cb.focus();
			//-------------------------
		} else {
			addOptions(cb,"","Nenhum dado encontrado!");
			cb.disabled = true;
		}	
	}
}
//################################################################################################################################
function getListas(id,url,params,func) {
	var d = document.getElementById(id);
	var h = (parseInt(d.offsetHeight)/2)-15;
	d.innerHTML = "<div style='margin-top:" + h + "px;text-align:center;color:#333333;'><img src='../../imagens/ajax-loader.gif' align='texttop' style='margin-right:20px'>Aguarde, consultando...</div>";

	goAjax(url,params,'posAjax()','');
	
	this.posAjax = function() {
		
		//var c10 = String.fromCharCode(10);
		//var c13 = String.fromCharCode(13);
		//while (resultAjax.indexOf(c10)>-1 || resultAjax.indexOf(c13)>-1) {
			//resultAjax = resultAjax.replace(c10," ");      
			//resultAjax = resultAjax.replace(c13," ");
		//}
		//window.open("","rsajx").document.write(resultAjax);
		
		d.innerHTML = resultAjax;
		if (func!=null) eval(func);
		
		validScriptResultAjax(id);
		setGridDados();
		setGridDados();
	}	
}
//################################################################################################################################
function getFiltrarLista(url) {
	if(url!=0) setFormsFilterList(); //Função do componente filtrar lista dados, definida em util.js
	var f = document.formFiltrarLista;
	btFiltrar = function(b) { 
		f.bt_filtrarLista.disabled = b; 
		if (document.forms[1]!=null) calendarInput(document.forms[1]);
	}
	btFiltrar(true);
	var URL = (url!=null && url!=0 && url!="undefined") ? url : "getGridLista.asp";
	getListas("gridListaDados",URL,setParams(f,""),"btFiltrar(false)");
}
//################################################################################################################################
function goURL(pag,target) {
	target = target.toLowerCase();
	if (target.indexOf("blan")>-1) window.open(pag,"newPage");
	else {
		var obj = eval(target + ".location");
		obj.href = pag;
	}
}
//################################################################################################################################
//Delete coluna de tabelas
function deleleColTable(id,col) {
	var tb = document.getElementById(id);
	if (tb!=null) {
		for (var i=0;i<tb.rows.length;i++) {
			if (tb.rows[i].cells.length>=col) tb.rows[i].deleteCell(col-1);
		}
	}
}
//################################################################################################################################
function getParams(args,param,valueDefault) {
	var s = valueDefault;
	var a = args.split(";");
	var d, p, v;
	for(var i=0;i<a.length;i++) {
		d = a[i].trim();
		p = d.substring(0,d.indexOf(":"));
		v = d.substring(d.indexOf(":")+1);
		if (p.toLowerCase()==param.toLowerCase()) {
			s = v.indexOf(",")>-1 ? v.split(",") : v;
			s = v=="true"||v=="false" ? eval(v) : v;
			break;
		}
	}
	return s;
}
//################################################################################################################################
var TIMER_READ_STATE_UPLOAD_FILE = null;
function uploadFile(file,path,dlg,fcPos) {
	var f = getFather(file,"form");
	if (file.value.trim().length==0) {		
		dialog(false,true,"Selecione um arquivo antes de tentar anexar!","");
	} else {
		
		$("#bt_go_upload").fadeOut(300);
		$("#status_upload_file").fadeIn(300);	
		$("#container_files").animate({opacity:0.2},500);
		
		this.posUploadFile = function(b) {
			file.disabled = false;
			$("#bt_go_upload").fadeIn(300);
			$("#status_upload_file").fadeOut(300);
			$("#container_files").animate({opacity:1},500);
			if(b && document.getElementById(f.idlistfiles.value)!=null) getListas(f.idlistfiles.value,path+"modulos/_uploadFiles/getListFiles.asp?tempfile="+escape(f.tempfile.value)+"&tempfilesub="+escape(f.tempfilesub.value)+"&idlistfiles="+escape(f.idlistfiles.value),"",null);
		}
		
		var ifr = document.getElementById("iframe_upload_file");
		if (ifr==null) alert("Iframe não existe!");
		
		//Formulário -------------------------------------------			
			f.target = "iframe_upload_file";
			f.action = path+"modulos/_uploadFiles/uploadFile.asp";
			f.method = "post";
			f.enctype = "multipart/form-data";
			f.submit();
		//------------------------------------------------------
		
		file.disabled = true;		
		
		readStateUploadFiles = function() {
			var resp = parent.iframe_upload_file.document.body.innerHTML;
			if (resp.toUpperCase().indexOf("{UPLOAD_FILE_TERMINED:")>-1) {
				clearInterval(TIMER_READ_STATE_UPLOAD_FILE);
				var b = resp.indexOf("ERROR")>-1?false:true;
				posUploadFile(b);
				if (dlg) dialog( b , true, resp.substring( resp.indexOf("}")+1 ), "");
				if (fcPos!=null) eval(fcPos);
			}
		}
		
		TIMER_READ_STATE_UPLOAD_FILE = setInterval(readStateUploadFiles,1000);
		
	}
	return true;
}
//--------------------------------------------------------
function deleteAnexo(tempfile,tempfilesub,file,idLista) {
	dialog(true,true,'Excluir o anexo <strong>' + file + '</strong> agora?', "posDeleteAnexo()");
	this.posDeleteAnexo = function() {
		if (resultDialog) goAjax("../_uploadFiles/deleteFile.asp","file=" + escape(file) + "&tempfile=" + escape(tempfile) + "&tempfilesub=" + escape(tempfilesub),"posAjaxDeleteAnexo()","");
	}	
	this.posAjaxDeleteAnexo = function(){ getListas(idLista,"../_uploadFiles/getListFiles.asp","tempfile=" + escape(tempfile) + "&tempfilesub=" + escape(tempfilesub) + "&idlistfiles=" + escape(idLista),null); }
}

//################################################################################################################################
function focusOneInputForm(){
	var e, f;
	for(var y=0;y<document.forms.length;y++){
		f = document.forms[y];
		if(f!=null){
			var t = f.elements.length;
			for(var i=0;i<t;i++){
				e = f.elements[i]; 
				if (e.toString().length>0 && e.type.indexOf("hidden")==-1 && !e.disabled) {
					try{
						e.focus();	
						break;	
					} catch(ex){}
				}
			}
			if(i<t-1) break;
		}
	}
	return true;
}
//################################################################################################################################

String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

//################################################################################################################################

function validarEmail(email) {
   return (email.search(/^([a-zA-Z0-9])([a-zA-Z0-9\._-])*@(([a-zA-Z0-9])+(\.))+([a-zA-Z]{2,4})+$/) != -1);
}
//################################################################################################################################


function valor_pt2en(valor)
{
	return parseFloat(valor.toString().replace(/\./g,"").replace(/\,/g,"."));
}

function valor_en2pt(valor)
{
	return valor.toString().replace(/\,/g,"").replace(/\./g,",");
}


function formatCurrency(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + ',' + cents);
}

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (e.keyCode) ? e.keyCode : e.which;
    //var whichCode = (window.Event) ? e.which : e.keyCode;
    //alert(whichCode);
    if (whichCode == 13 || whichCode == 8 || (whichCode == 0)) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    //alert(key);
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
	len = objTextBox.value.length;
    
    //alert(len);
	for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}


