function currencyFormat(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
alert(whichCode);
if (whichCode == 13) return true;  // Enter
key = String.fromCharCode(whichCode);  // Get key value from key code
if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';
if (len == 1) fld.value = '0'+ decSep + '0' + aux;
if (len == 2) fld.value = '0'+ decSep + aux;
if (len > 2) {
aux2 = '';
for (j = 0, i = len - 3; i >= 0; i--) {
if (j == 3) {
aux2 += milSep;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
fld.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
fld.value += aux2.charAt(i);
fld.value += decSep + aux.substr(len - 2, len);
}
return false;
}


function MascaraCPFCNPJ(t){
p = t.value
a = t.name
if (document.frm.tipo[0].checked == true){
document.frm.cpf_cnpj.maxLength = "14";
	if (p.length == 3) {
		t.value = p + "."
		}
	if (p.length == 7) {
		t.value = p + "."
		}
	if (p.length == 11) {
		t.value = p + "-"
		}
	}
if (document.frm.tipo[1].checked == true){
document.frm.cpf_cnpj.maxLength = "18";
	if (p.length == 2) {
		t.value = p + "."
		}
	if (p.length == 6) {
		t.value = p + "."
		}
	if (p.length == 10) {
		t.value = p + "/"
		}
	if (p.length == 15) {
		t.value = p + "-"
		}
	}
}

function ExibeFoto(imagen){
//alert(imagen):
	foto = "foto";
	var local=document.getElementById(foto);
	local.src = imagen;
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}


function addItem(obj,strText,strValue,blSel,intPos){ 
     var newOpt,i,ArTemp,selIndex; 
     selIndex = (blSel)?intPos:obj.selectedIndex; 
     newOpt = new Option(strText,strValue); 
     Len = obj.options.length+1 
     if (intPos > Len) return 
     obj.options.length = Len 
     if (intPos != Len) { 
          ArTemp = new Array(); 
          for(i=intPos;i<obj.options.length-1;i++) 
               ArTemp[i] = Array(obj.options[i].text,obj.options[i].value); 
          for(i=intPos+1;i<Len;i++) 
               obj.options[i] = new Option(ArTemp[i-1][0],ArTemp[i-1][1]); 
     } 
     obj.options[intPos] = newOpt; 
     if (selIndex > intPos) 
          obj.selectedIndex = selIndex+1; 
     else if (selIndex == intPos)  
          obj.selectedIndex = intPos; 
} 


function MascaraFone(t){
p = t.value
a = t.name
if (p.length == 1) {
	t.value = "(" + p
	}
if (p.length == 4) {
	t.value = p + ")"
	}
if (p.length == 9) {
	t.value = p + "-"
	}
	
}


function PlacaVeiculo(t){
p = t.value
a = t.name
if (p.length == 3) {
	t.value = p + "-"
	}
}

function ValidaFone(obj){
src = obj.value
src = src.replace("(","");
src = src.replace(")","");
src = src.replace("-","");
src = src.replace(" ","");
//alert(src);
	if (isNaN(src)==true){
		alert("Telefone incorreto. Digite-o novamente!");
		obj.value = "";
		obj.focus();
		return false;
	}
}
//onkeypress="return txtBoxFormat(this, '(99)9999-9999', event);"
function txtBoxFormat(objeto, sMask, evtKeyPress) {
	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

	if ( document.all ) { // Internet Explorer
		nTecla = evtKeyPress.keyCode;
	} //if
	else { // Nestcape
		nTecla = evtKeyPress.which;
	}

	sValue = objeto.value;

	// Limpa todos os caracteres de formatação que
	// já estiverem no campo.
	sValue = sValue.toString().replace( ":", "" );
	sValue = sValue.toString().replace( ":", "" );
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( " ", "" );
	sValue = sValue.toString().replace( " ", "" );
	fldLen = sValue.length;
	mskLen = sMask.length;
	
	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;
	
	while ( i <= mskLen ) {
		bolMask = ((sMask.charAt(i) == ":") || (sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
		bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

		if ( bolMask ) {
			sCod += sMask.charAt(i);
			mskLen++;
		} //if
		else {
			sCod += sValue.charAt(nCount);
			nCount++;
		} //Fim do else
		i++;
	} //Fim do while

	objeto.value = sCod;

	if ( nTecla != 8 ) { // backspace
		if ( sMask.charAt(i-1) == "9" ) { // apenas números...
			return ((nTecla > 47) && (nTecla < 58));
		} // números de 0 a 9
		else { // qualquer caracter...
			return true;
		} //Fim do else
	} //if
	else {
		return true;
	} //Fim do else
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.id; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' deve conter um endereço de email válido.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' deve conter somente números.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' deve conter um número entre '+min+' e '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' é obrigatório.\n'; }
  } if (errors) alert('O(s) seguinte(s) erro(s) ocorreu(ram):\n'+errors);
  document.MM_returnValue = (errors == '');
}
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function confirma(pagina,msg){
	if(confirm(msg)){
		window.location = pagina;
		}
}

function ConfirmaAjax(pagina,msg,elemento){
	if(confirm(msg)){
		ajaxGet(pagina,document.getElementById(elemento),true);
	}
}

function ValidaData(valor){
var verifica
vardata = valor.value
tam = valor.value.length
if(vardata != "") {
	if (tam == 10) {
	  dia = vardata.substring(0,2)
	  sep1 = vardata.substring(2,3)
	  mes = vardata.substring(3,5)
	  sep2 = vardata.substring(5,6)
	  ano = vardata.substring(6,10)
	
	// tam = Len(vardata)
	  erro = 'Ocorreu o seguinte erro na Data:\n '
	  if (tam==8) {
	  valor.focus()
	  alert('Preencha a Data corretamente\n [ DD/MM/AAAA ]')
	  } else {
	  if (mes > 12){
		erro = erro + '- Mês Inválido'
		verifica = 'false'
	  }  
		  if (mes==01||mes==03||mes==05||mes==07||mes==08||mes==10||mes==12){
			if (dia > 31) {
				erro = erro + '- Dia Inválido para o respectivo mês'
				verifica = 'false'
			}
		  } else if (mes== 04 || mes==06 || mes==10 || mes==11){
			if (dia > 30){
				erro = erro + '- Dia Inválido para o respectivo mês'
				verifica = 'false'
			}
		  } else if (mes==02) {
			if (dia > 28) {
				erro = erro + '- Dia Inválido para o respectivo mês'
				verifica = 'false'
			}		
		  } 
		  } 
		  if(verifica == 'false'){
			erro = erro + '\nPreencha novamente';
			alert(erro);
			valor.focus();
			return false;
		  } else {
			return true;
		}
	} else {
		alert("Por favor,\nPreencha a data corretamente,\nno formato (dd/mm/aaaa)")
	}
}
}

//document.getElementById(nome_div).innerHTML = tags;

function ValidaForm(){
	MM_validateForm('fornecedor','','R','num_documento','','R','dt_emissao','','R','nota_fiscal','','R','valor_total','','R','qtde','','R','plano_contas','','R','centro','','R','agente','','R','observacoes','','R');
	if(document.MM_returnValue && verificaSoma("frm_pagar", true) && ChecaDiasEspecie('frm_pagar')){
		document.frm_pagar.submit();
	}
}

function spread(){
	MM_validateForm('valor_total','','R','qtde','','R');
	if(document.MM_returnValue && ValidaData(document.getElementById('dt_emissao'))){
		ajaxGet('tab_parcela.asp?acao=spread&valor=' + document.getElementById('valor_total').value +'&parcelas=' + document.getElementById('qtde').value,document.getElementById('parcelas'),true);
		document.getElementById("subm").disabled = false;
	} 
}

function pega_dias(campo, data, elemento){
	MM_validateForm('dt_emissao','','R');
	if(ValidaData(document.getElementById(campo)) && ValidaData(document.getElementById('dt_emissao'))){
		ajaxGet('tab_parcela.asp?acao=dias&data2=' + data +'&data1=' + document.getElementById('dt_emissao').value,document.getElementById(elemento),false);
	} else {
		document.getElementById(campo).value=="";
		//document.getElementById(campo).focus();
	}
}

function FormData(objeto, evento){
	return txtBoxFormat(objeto, '99/99/9999', evento);
}
function FormValor(objeto, evento){
	return currencyFormat(objeto,'.',',', evento);
}

function CvtNumber(num){
	num = num.replace(/\$|\./gi,'');
	num = num.replace(/,/g,'.');
	return(num);
}
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,-/g,'');
	if(isNaN(num)) num = "0";
	cents = Math.floor((num*100+0.5)%100);
	num = Math.floor((num*100+0.5)/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 (num + "," + cents);
}

function ChecaDiasEspecie(formulario){
	var inputs = document.getElementById(formulario).getElementsByTagName('input');
	var combo = document.getElementById(formulario).getElementsByTagName('select');
	for(var i=0;i<inputs.length;i++){
		if(inputs[i].value == ""){
			alert('Preencha corretamente o campo de dias!');
			inputs[i].focus()
			return false;
			break;
		}
	}
	
	for(var i=0;i<combo.length;i++){
		if(combo[i].value == ""){
			alert('Selecione a espécie da transação!');
			combo[i].focus()
			return false;
			break;
		}
	}
	
	return true;
	
}
function verificaSoma(formulario, alerta) {
    var soma = 0;
	var valor_total = CvtNumber(document.getElementById("valor_total").value);
    var inputs = document.getElementById(formulario).getElementsByTagName('input');
    for (var i=0;i<inputs.length;i++) {
        //if (inputs[i].getAttribute('type') == 'text') {
		if (inputs[i].getAttribute('comp') == 'valor') {
			if(inputs[i].value == ""){
			soma += 0
			} else {
            soma += parseFloat(CvtNumber(inputs[i].value));
			//soma += CvtNumber(inputs[i].value);
			}
       }
    }
	soma = CvtNumber(formatCurrency(soma));
	if (soma != valor_total) {
		if(alerta){
        	alert('A soma dos valores deve ser ' + formatCurrency(valor_total) + '!');
		}
		if(valor_total > soma){
			var diferenca = valor_total - soma;
			var ind= "-";
		} else {
			var diferenca = soma - valor_total;
			var ind= "+";
		}
		document.getElementById("diferenca").innerHTML = "R$ " + ind + formatCurrency(diferenca);
		document.getElementById("restante").innerHTML = "R$ " + formatCurrency(soma);
		return false;
    } else {
	document.getElementById("diferenca").innerHTML = "R$ 0,00";
	document.getElementById("restante").innerHTML = "R$ " + formatCurrency(soma);
    return true;
	}
}
// Página contas_pagar_quitação.asp
function SomaJurosMulta(){
		if(isNaN(parseFloat(CvtNumber(document.getElementById("valor").value)))){
			var valor = 0;
		} else {
			var valor = parseFloat(CvtNumber(document.getElementById("valor").value));
		}
		//alert(valor);
		if(isNaN(parseFloat(CvtNumber(document.getElementById("multa").value)))){
			var pc_multa = 0;
		} else {
			var pc_multa = parseFloat(CvtNumber(document.getElementById("multa").value));
		}
		//alert(pc_multa);
		if(isNaN(parseFloat(CvtNumber(document.getElementById("juros").value)))){
			var juros = 0;
		} else {
			var juros = parseFloat(CvtNumber(document.getElementById("juros").value));
		}
		//alert(juros);
		if(isNaN(parseFloat(CvtNumber(document.getElementById("desconto").value)))){
			var desconto = 0;
		} else {
			var desconto = parseFloat(CvtNumber(document.getElementById("desconto").value));
		}
		//alert(juros);
		var soma = valor + pc_multa + juros - desconto;
		document.getElementById("valor_parcela").value = formatCurrency(soma);
}
//Impressão dos Frames de relatório
function Imprimir(){
	window.frames(0).focus();
	window.print();
}

function popUp(URL,larg,alt) {
var esquerda = ((screen.width - larg)/2);
var topo = ((screen.height - alt)/2);
var day = new Date();
var id = day.getTime();
var tam1 = larg;
var ext1 = alt;

eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width="+tam1+",height="+ext1+",left ="+esquerda+",top ="+topo+"');");
}

function popUpFoto(URL,larg,alt) {
var esquerda = ((screen.width - larg)/2);
var topo = ((screen.height - alt)/2);
var day = new Date();
var id = day.getTime();
var tam1 = larg;
var ext1 = alt;

eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=0,width="+tam1+",height="+ext1+",left ="+esquerda+",top ="+topo+"');");
}


function AjustaTabela(id, margem){
	var tamanho = parseFloat(screen.height) - margem;
	document.getElementById(id).height = tamanho;
}

function clonaSelect(div, cmp){ 
	var htmlSELECT = document.getElementById(cmp).innerHTML;
	var cmp2 = cmp + Math.random() 
	
	// Cria o novo select
	var novoSelect = document.createElement("SELECT");
	novoSelect.id = cmp2;
	//alert(document.getElementById(cmp).name);
	novoSelect.name = document.getElementById(cmp).name;

//Insere o select dentro do objeto
	
	var td = document.getElementById(div);
	var esp = document.createElement("br");
	esp.id = "br"+cmp2;
	td.appendChild(esp);
	td.appendChild(novoSelect);
	
	// Cria o link para a remoção do select
	pickLink=document.createElement('a');
	pickText=document.createTextNode(' [X] ');

	// adicionar o texto como um child do link
	td.appendChild(pickLink);
	pickLink.appendChild(pickText);
	pickLink.setAttribute('href','javascript: void(0);');
	pickLink.id = "lnk"+cmp2;
	//Seta a função de remoção do link e do select
	pickLink.onclick = function(){removeSelect(div, cmp2, "lnk"+cmp2, "br"+cmp2);}
	
	if(navigator.appName == "Microsoft Internet Explorer") { // Bug IE do InnerHtml
		select_innerHTML(document.getElementById(cmp2), htmlSELECT);
	} else {
		document.getElementById(cmp2).innerHTML = htmlSELECT;
	}
		
}

function removeSelect(div, cmp, lnk, esp){
	var td = document.getElementById(div);
	var campo = document.getElementById(cmp);
	var l = document.getElementById(lnk);
	var br = document.getElementById(esp);
	td.removeChild(campo);
	td.removeChild(l);
	td.removeChild(br);
}

/*
******************************************
* Event Listener Function v1.4           *
* Autor: Carlos R. L. Rodrigues          *
* Serve para a manipulação das máscaras  *
******************************************
*/
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;
};

function formataMoeda(o, n, dig, dec){
    o.c = !isNaN(n) ? Math.abs(n) : 2;
    o.dec = typeof dec != "string" ? "," : dec, o.dig = typeof dig != "string" ? "." : dig;
    addEvent(o, "keypress", function(e){
        if(e.key > 47 && e.key < 58){
            var o, s, l = (s = ((o = this).value.replace(/^0+/g, "") + String.fromCharCode(e.key)).replace(/\D/g, "")).length, n;
            if(o.maxLength + 1 && l >= o.maxLength) return false;
            l <= (n = o.c) && (s = new Array(n - l + 2).join("0") + s);
            for(var i = (l = (s = s.split("")).length) - n; (i -= 3) > 0; s[i - 1] += o.dig);
            n && n < l && (s[l - ++n] += o.dec);
            o.value = s.join("");
        }
        e.key > 30 && e.preventDefault();
    });
}

function setaIndex(elem, valor) {
	Combo = document.getElementById(elem);
	
	k = Combo.options.length;

	for(i=0;i<k;i++) {
		CID1 = Combo.options[i].value;
		if (valor == CID1){
		//alert("valor = " + valor);
		//alert("CIDl = " + CID1);
		 break;
		}
	}
	
	if (i==k) i=0;
	Combo.selectedIndex = i;	
}

function PreencheCampo(cmp, vlr){
	var campo = document.getElementById(cmp);
	if(campo){
		campo.value = vlr.toUpperCase();
	} else {
		alert("Campo não encontrado!");
	}
}