// JavaScript Documentvar ok = false;function setUrlToIFrame(parente, iframe, url){ 	if (parente == 0){	  document.getElementById(iframe).src = url;	} else if (parente == 1) {		parent.document.getElementById(iframe).src = url;	} else if (parente == 2) {		parent.parent.document.getElementById(iframe).src = url;	}}function getTamanhoArquivo(arq, out, outTam){//	alert('arq='+arq+' dest='+out);	if (arq != ''){		var ajax = getXmlHttp();		//se tiver suporte ajax		if (ajax) {			try{				ajax.open("POST", "getTamanhoArquivo.php", true);				ajax.onreadystatechange = function() {					//enquanto estiver processando...emite a msg de carregando					if (ajax.readyState == 1) {						document.getElementById(out).innerHTML = 'Verificando! Aguarde...';  					}									//apos ser processado - verifica o resultado 					if (ajax.readyState == 4 ) { 						res = ajax.responseText;						if (res != '') { 							document.getElementById(out).innerHTML = 'Última verificação ' + Date(); 							document.getElementById(outTam).value = res; 						}	else { // caso retornar vazio é inválido							document.getElementById(out).innerHTML = "Não foi possíver obter o tamanho";						}					}				}				//passa o nome do arquivo				var params = "arq="+arq;				ajax.send(params);			}catch (e){				alert(e.description);			}		} 	}else{		document.getElementById(out).innerHTML = "Arquivo não informado";	}}var faixasContador = new Array();function addFaixas(){	var ini = 1;	var fim = 20;	for (i = 0; i < 39; i++){		faixa = new Array();		faixa.faixa = "Faixa " + (i + 1) + " de " + ini + " até " + fim;		faixa.ini = ini;		faixa.fim = fim;		faixasContador[faixasContador.length] = faixa;		ini += 20;		fim += 20;	}}	addFaixas();function getFaixaContador(par){  	for (i = 0; i < faixasContador.length; i++){ 		if ((par >= faixasContador[i].ini) && (par <= faixasContador[i].fim)){ 			document.getElementById('ContadorFaixa').value = faixasContador[i].faixa;				break;		}	}	if (faixasContador.length == i){		document.getElementById('ContadorFaixa').value = "Faixa não encontrada!";	}}function Valida(campo, valor, tipo, div, msg){	if (valor != ''){		var ajax = getXmlHttp();		//se tiver suporte ajax		if (ajax) {			try {				ajax.open("GET", "http://www.jbsoft.com.br/jb/sys/valida.php?valor=" + valor + "&tipo=" + tipo, true);	//			ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");	//			ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");	//			ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");	//			ajax.setRequestHeader("Pragma", "no-cache");				ajax.onreadystatechange = function() {					//enquanto estiver processando...emite a msg de carregando					if (ajax.readyState == 1) {						document.getElementById(div).innerHTML = 'Verificando! Aguarde...';  					}									//apos ser processado - verifica o resultado 					if (ajax.readyState == 4 ) {						res = ajax.responseText.replace(/^\s+|\s+$/g, ""); // limpa os espaços no início e final						if ((ajax.responseText.substring(0, 5) == '<?xml')){              document.getElementById(div).innerHTML = 'Erro: ' + ajax.responseText;            } else if (res != '') { 							document.getElementById(campo).value = res; 							document.getElementById(div).innerHTML = '&nbsp';						}	else { // caso retornar vazio é inválido							document.getElementById(div).innerHTML = msg;						}					}				}				//passa o codigo do cliente escolhido			//	var params = "valor="+valor+"&tipo="+tipo;				ajax.send(null);			}catch (e) {				alert(e.description);			}		} 	} }function noEnter(e){	if (document.all){		if (event.keyCode == 13){			event.keyCode = 9;			return true;		} 	} else {		var tecla = e.keyCode;		if (tecla == 13) { //event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;			// event.keyCode = 9;		  // alert(tecla);			return false;		}	}} //document.onkeydown = noEnter(window.event); //window.onkeydown = noEnter;function validaInscricao(num, div){	n = new String(num);	n = n.replace('', '', 'g');	if (n == '') {		document.getElementById(div).innerHTML = 'Inscrição Estadual não informada!';	} else { 		if (n.toString().toUpperCase() != 'ISENTO') {		  n = n.replace(/[^\d]/g, '');		  if (n.toString() == ''){		    document.getElementById(div).innerHTML = 'Inscrição Estadual inválida!';		  }		} else {		  document.getElementById(div).innerHTML = '&nbsp;';	  }	}}function validaCnpjCpf(num, div, tipo){	if ((tipo == 1) && !validaCnpj(num)){ // CNPJ		document.getElementById(div).innerHTML = 'CNPJ Inválido!';	} else if ((tipo == 2) && !validaCpf(num)) { // CPF		document.getElementById(div).innerHTML = 'CPF Inválido!';	} else {		document.getElementById(div).innerHTML = '&nbsp;';	}}function validaCnpj(cnpj) {	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;	digitos_iguais = 1;  cnpj = cnpj.replace (".", "");  cnpj = cnpj.replace (".", "");		cnpj = cnpj.replace ("/", ""); 		cnpj = cnpj.replace ("-", ""); 		if (cnpj.length != 14) { return false; }	for (i = 0; i < cnpj.length - 1; i++) {		if (cnpj.charAt(i) != cnpj.charAt(i + 1)) {			digitos_iguais = 0; break;		}	}	if (!digitos_iguais) {		tamanho = cnpj.length - 2		numeros = cnpj.substring(0,tamanho);		digitos = cnpj.substring(tamanho);		soma = 0;		pos = tamanho - 7;		for (i = tamanho; i >= 1; i--) {			soma += numeros.charAt(tamanho - i) * pos--;			if (pos < 2) { pos = 9; }		}		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;		if (resultado != digitos.charAt(0)) { 			return false; 		}		tamanho = tamanho + 1;		numeros = cnpj.substring(0,tamanho);		soma = 0;		pos = tamanho - 7;		for (i = tamanho; i >= 1; i--) {			soma += numeros.charAt(tamanho - i) * pos--;			if (pos < 2) { pos = 9; }		}		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;		if (resultado != digitos.charAt(1)) {			return false; 		}		return true;	} else { return false; }} function validaCpf(cpf) {	var numeros, digitos, soma, i, resultado, digitos_iguais;	digitos_iguais = 1;  cpf = cpf.replace (".", "");  cpf = cpf.replace (".", "");		cpf = cpf.replace ("-", ""); 	if (cpf.length != 11) { return false; }	for (i = 0; i < cpf.length - 1; i++)		if (cpf.charAt(i) != cpf.charAt(i + 1)) {			digitos_iguais = 0; break;		}	if (!digitos_iguais) {		numeros = cpf.substring(0,9);		digitos = cpf.substring(9);		soma = 0;		for (i = 10; i > 1; i--) {			soma += numeros.charAt(10 - i) * i;		}		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;		if (resultado != digitos.charAt(0)) { return false; }		numeros = cpf.substring(0,10);		soma = 0;		for (i = 11; i > 1; i--) {			soma += numeros.charAt(11 - i) * i;		}		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;		if (resultado != digitos.charAt(1)) { return false; }		return true;	} else { return false; }}function validaField(field, div, msg){	if (document.getElementById(field).value != ''){		document.getElementById(div).innerHTML = '&nbsp;';	} else {		document.getElementById(div).innerHTML = msg;	}}function setHtmlToDiv(value, div){	if (value == 0){		document.getElementById(div).innerHTML = '&nbsp;';	}else if ((div == 'divIndicacao') && (value == 'cliente')){		document.getElementById(div).innerHTML =		    '<table border="0" cellpadding="0" cellspacing="0" width="100%">'      +  '<tr>'      +   '<td style="text-align: right; width:160px"><label><font color="#ff0000">* </font>'			+    '<strong>N&uacute;mero de S&eacute;rie: </strong></label></td>'			+   '<td width="50">'			+     '<input name="indicacaoSerie" id="indicacaoSerie" size="10" class="input" maxlength="10" type="text" '			+      ' onKeyPress="return Format(this.id, \'9999999999\', event);" onBlur="getClientesFromXml(3);"></td>'			+   '<td width="20">'	    +    '<img src="jb/img/pesquisar.png" id="pesquisar" name="pesquisar" onClick="getClientesFromXml(2);" '	    +     ' title="Abrir pesquisa de cliente" style="cursor:pointer"></td>'	    +    '<td style="text-align: left"><input name="indicacaoNome" id="indicacaoNome" style="width:87%; border:none" readonly="readonly" '	    +     ' maxlength="150" type="text" /></td>'      +  '</tr>'      + '</table>';	}else if ((div == 'divIndicacao') && (value == 'outros')){	  document.getElementById(div).innerHTML =			'<table width="100%" border="0" cellspacing="0" cellpadding="0">'		+  '<tr>'    +   '<td style="text-align: right; width:160px">'		+    '<label><font color="#ff0000">* </font><strong>Nome: </strong></label></td>'    +   '<td><input name="indicacaoNome" id="indicacaoNome" style="width:90%" class="input" '		+	   ' maxlength="150" type="text" /></td>'    +  '</tr>'		+ '</table>'      + '<table border="0" cellpadding="0" cellspacing="0" width="100%">'		+	 '<tr>'    +  	'<td style="text-align: right; width:160px"><font color="#ff0000">* </font>'    +    '<label><strong>Tipo de Inscrição: </strong></label></td>'    +  	'<td><select name="pessoa2" id="pessoa2" onChange="setMascara2(this.value); '		+ 	 	 ' Format(\'indicacaoCnpj\', getMascara2(), event);" class="select">'    +      '<option id="1" value="1">CNPJ</option>'    +    	 '<option id="2" value="2" selected="selected">CPF</option>'    +  		'</select></td>'    +  '</tr>'    + '</table>'    + '<table border="0" cellpadding="0" cellspacing="0" width="100%">'    +  '<tr>'    +   '<td style="text-align: right; width:160px">'		+      '<label><font color="#ff0000">* </font><strong>CPF / CNPJ: </strong></label></td>'    +   '<td>'    +	   '<table border="0" cellpadding="0" cellspacing="0" width="100%">'		+		  '<tr>'    +      '<td width="130"><input name="indicacaoCnpj" id="indicacaoCnpj" size="22" class="input" ' 		+        ' maxlength="18" type="text" onKeyPress="return Format(this.id, getMascara2(), event);" '    +        ' onBlur="validaCnpjCpf(this.value, \'divCnpjInvalidoInd\', document.getElementById(\'pessoa2\').value);">'    +      '</td>'    +      '<td><font color="#FF0000;" size="2"><b><div id="divCnpjInvalidoInd">&nbsp;</div></b></font></td>'    +     '</tr>'    +    '</table>'    +   '</td>'    +  '</tr>'           +  '<tr>'    +	  '<td style="text-align: right; width:160px">'	  +     '<label><font color="#ff0000">* </font><strong>Fone: </strong></label></td>'    +   '<td><input name="indicacaoFone" id="indicacaoFone" size="30" class="input" maxlength="15" type="text" '	  +	    'onKeyPress="return Format(this.id, \'(999) 9999-9999\', event);"></td>'    +  '</tr>'    +  '<tr>'    + 	'<td style="text-align: right; width:160px"><label><strong>E-mail: </strong></label></td>'    +   '<td><input name="indicacaoEmail" style="width:90%" class="input" maxlength="150" type="text"></td>'    +  '</tr>'    + '</table>';	}else if (div == 'divCepilAcessos'){		document.getElementById(div).innerHTML =			  '<table border="0" cellpadding="0" cellspacing="0" width="100%">'			+  '<tr>'			+ 	'<td style="text-align: right; width:160px"><label><font color="#ff0000">* </font><strong>N&uacute;mero de Acessos: </strong></label></td>'			+		'<td><input name="cepilAcessos" id="cepilAcessos" size="7" class="input" maxlength="6" type="text" '			+    ' onKeyPress="return Format(this.id, \'999999\', event);"></td>'			+	 '</tr>'			+	 '<tr>'			+	  '<td style="text-align: right; width:160px"><label><font color="#ff0000">* </font><strong>Valor: </strong></label></td>'			+   '<td><input name="cepilValor" id="cepilValor" size="12" class="input" maxlength="10" type="text" '			+     ' onKeyPress="return FormataValor(this.id, 10, event)" style="text-align:right"></td>'			+  '</tr>'     				+ '</table>';			}else if (div == 'divFolhaFaixa'){		document.getElementById(div).innerHTML =				'<table border="0" cellpadding="0" cellspacing="0" width="100%">'			+	 '<tr><td style="text-align: right; width:160px">'			+   '<label><font color="#ff0000">* </font><strong>Faixa de Funcion&aacute;rios: </strong></label></td>'			+   '<td><select name="folhaFaixa" id="folhaFaixa" class="select">'			+    '<option value="0" selected="selected">Selecione uma faixa</option>'			+    '<option value="01">1 a 25 Funcion&aacute;rios</option>'			+	   '<option value="02">26 a 50 Funcion&aacute;rios</option>'			+    '<option value="03">51 a 100 Funcion&aacute;rios</option>'			+    '<option value="04">101 a 200 Funcion&aacute;rios</option>'			+    '<option value="05">201 a 300 Funcion&aacute;rios</option>'			+    '<option value="06">301 a 400 Funcion&aacute;rios</option>'						+    '<option value="07">401 a 500 Funcion&aacute;rios</option>'			+    '<option value="08">501 a 600 Funcion&aacute;rios</option>'						+	   '<option value="09">601 a 700 Funcion&aacute;rios</option>'			+    '<option value="10">701 a 800 Funcion&aacute;rios</option>'			+	   '<option value="11">801 a 900 Funcion&aacute;rios</option>'			+    '<option value="12">901 a 1000 Funcion&aacute;rios</option>'			+    '<option value="13">1001 a 1100 Funcion&aacute;rios</option>'			+    '<option value="14">1101 a 1200 Funcion&aacute;rios</option>'			+    '<option value="15">1201 a 1300 Funcion&aacute;rios</option>'			+    '<option value="16">1301 a 1400 Funcion&aacute;rios</option>'			+    '<option value="17">1401 a 1500 Funcion&aacute;rios</option>'			+    '<option value="18">1501 a 1600 Funcion&aacute;rios</option>'			+    '<option value="19">1601 a 1700 Funcion&aacute;rios</option>'			+    '<option value="20">1701 a 1800 Funcion&aacute;rios</option>'			+    '<option value="21">1801 a 1900 Funcion&aacute;rios</option>'			+    '<option value="22">1901 a 2000 Funcion&aacute;rios</option>'			+    '<option value="23">2001 a 2100 Funcion&aacute;rios</option>'			+    '<option value="24">2101 a 2200 Funcion&aacute;rios</option>'			+    '<option value="25">2201 a 2300 Funcion&aacute;rios</option>'			+    '<option value="26">2301 a 2400 Funcion&aacute;rios</option>'			+    '<option value="27">2401 a 2500 Funcion&aacute;rios</option>'			+    '<option value="28">2501 a 2600 Funcion&aacute;rios</option>'			+    '<option value="29">2601 a 2700 Funcion&aacute;rios</option>'			+    '<option value="30">2701 a 2800 Funcion&aacute;rios</option>'			+    '<option value="31">2801 a 2900 Funcion&aacute;rios</option>'			+    '<option value="32">2901 a 3000 Funcion&aacute;rios</option>'			+    '<option value="33">3001 a 3100 Funcion&aacute;rios</option>'			+		'</select></td>'			+	 '</tr>'			+	 '<tr>'			+		'<td style="text-align: right; width:160px"><label><strong>N&uacute;mero de M&aacute;quina: </strong></label></td>'			+ 	'<td><input name="folhaMaquina" id="folhaMaquina" size="12" class="input" maxlength="10" type="text" '			+     ' onKeyPress="return Format(this.id, \'9999999999\', event);" style="text-align:left" ></td>'			+	 '</tr>'     				+	 '<tr>'			+		'<td style="text-align: right; width:160px"><label><font color="#ff0000">* </font><strong>Valor: </strong></label></td>'			+ 	'<td><input name="folhaValor" id="folhaValor" size="12" class="input" maxlength="10" type="text" '			+     ' onKeyPress="return FormataValor(this.id, 10, event)" style="text-align:right" ></td>'			+	 '</tr>'     				+	'</table>';			}else if (div == 'divContadorEmpresas'){		document.getElementById(div).innerHTML =						  '<table border="0" cellpadding="0" cellspacing="0" width="100%">'      +  '<tr>'      +   '<td style="text-align: right; width:160px"><label><font color="#ff0000">* </font><strong>N&uacute;mero de Empresas: </strong></label></td>'      +   '<td width="60"><input name="contadorEmpresas" id="contadorEmpresas" size="7" class="input" '			+    ' maxlength="6" type="text" onKeyPress="return Format(this.id, \'999999\', event);" '			+    ' onBlur="getFaixaContador(this.value);"></td><td align="left"><input name="ContadorFaixa" '			+    ' id="ContadorFaixa" style="width:87%; border:none" readonly="readonly" maxlength="150" type="text" '			+    ' value="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"/></td>'      +  '</tr>'      +  '<tr>'      +   '<td style="text-align: right; width:160px"><label><font color="#ff0000">* </font><strong>Valor: </strong></label></td>'      +   '<td colspan="2"><input name="contadorValor" id="contadorValor" size="12" class="input" maxlength="10" '			+    ' type="text" onKeyPress="return FormataValor(this.id, 10, event)" style="text-align:right" ></td>'      +  '</tr>'	        + '</table>';	}}// inicio da funcao que retorna um objeto Ajax =========================================// ULI 14/06/2009function getXmlHttp(){   xmlhttp = null;	if (XMLHttpRequest == 'undefined') {		msxmls = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", 							"MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP", "MSXML.DOMDocument"];		for (var i=0; i < msxmls.length; i++) {			try { 				xmlhttp = new ActiveXObject(msxmls[i]);				break;			}catch (e) { } 		}	}else{ 	  try {		  xmlhttp = new XMLHttpRequest(); 		}catch (e){ }	}	if (xmlhttp == null){	  alert("Navegador não tem suporte para AJAX! \nAlgumas informações serão exibidas parcialmente!");	} 	return xmlhttp;}// final da funcao que retorna um objeto Ajax =========================================// funccao que faz o XMLHttpRequest e chama a funcao resposeActionfunction getAjaxResponse(url, responseType, elementToUpdate){ 	ajax = getXmlHttp();	//se tiver suporte ajax	if (ajax){ 		try{			ajax.open("GET", url, true);			ajax.onreadystatechange = function() {				//apos ser processado - chama funcao processXML que vai varrer os dados				if(ajax.readyState == 4) { 					if (responseType == 'xml'){ //alert(ajax.responseText); 						responseAction(elementToUpdate, ajax.responseXML);					} else {						responseAction(elementToUpdate, ajax.responseText);					}				}			}			ajax.send(null);		}catch (e){			alert(e.description); 		}	}}// final funccao que faz o XMLHttpRequest// funcao que chama a funcao conforme o tipo do element que sera atualizadofunction responseAction(el, response){	switch(el.type) {		case "text": break;		case "textarea": break;		case "button": break;		case "reset": break;		case "submit": break;		case "file": break;		case "hidden": break;		case "password": break;		case "image": break;		case "radio": break;		case "checkbox": break;		case "select-one":			setUpdateComboFromXml(el, response); break;		case "select-multiple": break;		default:			alert("Element type: " + el.type + " no optin in case!\nName: " + el.name + "\nId: " + el.id);	}}	// final funcao que chama a funcao conforme o tipo do element que sera atualizado// inicio da funcao que faz update no element combo function setUpdateComboFromXml(obj, xml){ 	obj.options.length = 1;	obj.options[0].value = '0';	if (xml){		//pega a tag cidade 		itens = xml.getElementsByTagName("option"); 		//total de elementos contidos na tag options		if(itens.length > 0) { 			obj.options[0].text = 'Selecione ';			//percorre o arquivo XML paara extrair os dados			for(i = 0 ; i < itens.length ; i++) {				//cria um novo option dinamicamente  				option = document.createElement("option");				//atribui um ID a esse elemento				option.setAttribute("id", itens[i].getElementsByTagName("id")[0].firstChild.nodeValue);				//atribui um valor				option.value = itens[i].getElementsByTagName("value")[0].firstChild.nodeValue;				//atribui um texto				option.text  = itens[i].getElementsByTagName("text")[0].firstChild.nodeValue;				//finalmente adiciona o novo elemento				obj.options.add(option);			}		} else {			//caso o XML volte vazio, printa a mensagem abaixo			obj.options[0].text = 'Nenhum ';		}	  	}else{ 		obj.options[0].text = 'Erro ';	}}// final inicio da funcao que faz update no element combo // inicio da funcao que retorna os clientes ===========================================var parPesquisa;function getClientesFromXml(par) { 	var params = '';	parPesquisa = par;	if (parPesquisa == 3){		if (document.getElementById('indicacaoSerie').value > 0){			showHint('Verificando a série do cliente! Aguarde...', 'visible', 'Cancelar', 'loading.gif');		}else{			return false;		}	}else{		showHint('Carregando a lista de clientes! Aguarde...', 'visible', 'Cancelar', 'loading.gif');  	document.getElementById('imgLoading').style.visibility = 'visible';	}	ajax = getXmlHttp();	//se tiver suporte ajax	if (ajax) { 	  try {			ajax.open("POST", "http://www.jbsoft.com.br/jb/sys/getClientesToXml.php", true);			if (ajax.overrideMimeType){		    ajax.overrideMimeType("text/xml; charset=iso-8859-1");		  }		  ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');      ajax.setRequestHeader("encoding", "iso-8859-1"); 			ajax.onreadystatechange = function() {				//apos ser processado - chama funcao processXML que vai varrer os dados				if(ajax.readyState == 4 ) {					if(ajax.responseXML) { 						setPesquisa(ajax.responseXML);					}					}			}			if (par == 3){				//passa o codigo do cliente escolhido 				params = "par="+document.getElementById('indicacaoSerie').value;			}			ajax.send(params);		}catch (e){			alert(e.description);		}	} else {		showHint('Não foi possível obter a lista de clientes!', 'visible', 'Fechar', 'erro.png');		if (parPesquisa == 1) {			if (document.getElementById('razao')){				document.getElementById('razao').value = ''; 				document.getElementById('divProduto').style.visibility = 'hidden';					}		} else {			document.getElementById('indicadorNome').value = ''; 		}	}}// final da funcao que retorna os clientes ============================================// inicio da funcao que gera a pesquisa ===============================================// armazena a lista para o filtro var clientes;function setPesquisa(obj){ 	clientes = new Array();	//pega a tag cliente	var listaClientes = obj.getElementsByTagName("cliente");	//total de elementos contidos na tag cidade	if(listaClientes.length > 0) { 		//percorre o arquivo XML paara extrair os dados		for (i = 0; i < listaClientes.length; i++){ 			codigo = listaClientes[i].getElementsByTagName("codigo")[0].firstChild.nodeValue; 			nome = listaClientes[i].getElementsByTagName("nome")[0].firstChild.nodeValue; 			tpinscricao = listaClientes[i].getElementsByTagName("tpinscricao")[0].firstChild.nodeValue; 			addCliente(codigo, nome, tpinscricao);			if (parPesquisa == 3) {				setCliente(i);			}		}		if (parPesquisa != 3){			abrePesquisa();		  document.getElementById('hint').style.visibility = 'hidden';		  document.getElementById('imgLoading').style.visibility = 'hidden';			}	} else {		//caso o XML volte vazio, printa a mensagem abaixo		if (parPesquisa == 3){			showHint('Série não encontrada! Clique em pesquisar para listar todos.', 'hidden', 'Fechar', 'erro.png');		}else{			showHint('Você não tem clientes cadastrados!', 'visible', 'Fechar', 'erro.png');		}		if (parPesquisa == 1){			if (document.getElementById('razao')){				document.getElementById('razao').value = ''; 				document.getElementById('divProduto').style.visibility = 'hidden';			}		} else if (document.getElementById('indicadorNome')) {			document.getElementById('indicadorNome').value = ''; 		}	}	  	function addCliente(cod, nom, tp){		cliente = new Array();		cliente.codigo = cod;		cliente.nome = nom;		cliente.tpinscricao = tp;		clientes[clientes.length] = cliente;	}	}function abrePesquisa(p){	html  = '<table width="100%" border="1" cellspacing="0" cellpadding="0">';	html += '<tr><th width="42">Série</th><th>Nome</th></tr>';	html += '</table><div id="divLista" style="overflow:auto">'; //	html += '</table><div id="divLista">'; 	html += '<table width="100%" border="1" cellspacing="0" cellpadding="0">';		for (i = 0; i < clientes.length; i++){		if (p){			if ((clientes[i].nome.toLowerCase().indexOf(p.toLowerCase()) > -1) || (!p) || 					(String(clientes[i].codigo).indexOf(p) > -1)){				html += '<tr><td align="right" width="50">'+clientes[i].codigo+'</td><td><a href="#" onclick="parent.setCliente('+i+');">'+clientes[i].nome+"</a></td><tr>";			}		}else{			html += '<tr><td align="right" width="50">'+clientes[i].codigo+'</td><td><a href="#" onclick="parent.setCliente('+i+');">'+clientes[i].nome+"</a></td><tr>";		}	}		html += '</table></div>';	setObjToCenter(document.getElementById('popUp'), 400, getWinHeight() - 200);	popUp.document.getElementById('divListaClientes').innerHTML = html;	popUp.document.getElementById('divLista').style.height = getWinHeight() - 300;	document.getElementById('popUp').style.visibility = 'visible';	document.getElementById('imgLoading').style.visibility = 'visible';}	function setCliente(i){	if (parPesquisa == 1){		var tipo;		if (clientes[i].tpinscricao == 1){			tipo = "Raz&atilde;o Social: ";		} else {			tipo = "Nome: ";		}		document.getElementById('divClienteVelho').innerHTML =				'<table border="0" cellpadding="0" cellspacing="0" width="100%">'			+  '<tr>'			+   '<td style="text-align: right; width:160px"><font color="#ff0000">* </font>'			+    '<label><strong>N&uacute;mero de S&eacute;rie: </strong></label></td>'			+   '<td align="left"><input name="codigo" id="codigo" size="8" class="input" maxlength="6" '			+    'type="text" readonly="readonly" value="'+clientes[i].codigo+'"></td>'			+  '</tr>'			+  '<tr>'			+   '<td style="text-align:right; width:160px"><div id="lblRazao">'			+    '<font color="#ff0000">* </font><b>'+tipo+'</b></div></td>'			+   '<td colspan="2"><input name="razao" id="razao" style="width:90%" class="input" maxlength="150" '			+    'type="text" value="'+clientes[i].nome+'" readonly="readonly"/></td>'			+  '</tr>'			+ '</table>';		document.getElementById('divNovoCliente').innerHTML = '&nbsp;';		document.getElementById('divClienteVelho').style.visibility = 'visible';		document.getElementById('divProduto').style.visibility = 'visible';		document.getElementById('contrato').focus();	} else {		document.getElementById('indicacaoSerie').value = clientes[i].codigo;		document.getElementById('indicacaoNome').value = clientes[i].nome; 		fechaHint();	}	document.getElementById('popUp').style.visibility = 'hidden';	document.getElementById('imgLoading').style.visibility = 'hidden';	document.getElementById('cepilDistro').focus();}// final da funcao que gera a pesquisa ================================================// inicio da funcao que retorna as cidades ============================================function getCidadesFromXml(uf){ 	var ajax = getXmlHttp();	//se tiver suporte ajax	if(ajax) {		//deixa apenas o elemento 1 no option, os outros sao excluidos		document.forms['formNovoCliente'].cidade.options.length = 1;		idOpcao  = document.getElementById("opcoes");		idOpcao.innerHTML = "Carregando...";   		try {			ajax.open("POST", "jb/sys/getCidadesToXml.php", true);			ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");		//	ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");		//	ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");		//	ajax.setRequestHeader("Pragma", "no-cache");			// ajax.setRequestHeader("encoding", "UTF-8"); 						ajax.onreadystatechange = function() {				//enquanto estiver processando...emite a msg de carregando				if(ajax.readyState == 1) {					idOpcao.innerHTML = idOpcao.innerHTML + ".";   				}				//apos ser processado - chama funcao processXML que vai varrer os dados				if(ajax.readyState == 4 ) {					if(ajax.responseXML) { 						setCidadesCombo(ajax.responseXML);					}	else {						//caso nao seja um arquivo XML emite a mensagem abaixo						idOpcao.innerHTML = "Primeiro selecione o estado 2";					}				}			}			//passa o codigo do estado escolhido			var params = "estado="+uf;			ajax.send(params);		}catch (e){			alert(e.description);		}	}}// final da funcao que retorna as cidades ==========================================// inicio da funcao que adiciona as cidades no combo ===============================function setCidadesCombo(obj){	//pega a tag cidade	var dataArray   = obj.getElementsByTagName("cidade");	//total de elementos contidos na tag cidade	if(dataArray.length > 0) {		//percorre o arquivo XML paara extrair os dados		for(var i = 0 ; i < dataArray.length ; i++) {			var item = dataArray[i];			//conteudo dos campos no arquivo XML			var codigo    =  item.getElementsByTagName("id")[0].firstChild.nodeValue;			var descricao =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;			idOpcao.innerHTML = "Selecione a cidade";			//cria um novo option dinamicamente  			var novo = document.createElement("option");			//atribui um ID a esse elemento			novo.setAttribute("id", "opcoes");			//atribui um valor			novo.value = codigo;			//atribui um texto			novo.text  = descricao;			//finalmente adiciona o novo elemento			document.forms['formNovoCliente'].cidade.options.add(novo); 		}	} else {		//caso o XML volte vazio, printa a mensagem abaixo		idOpcao.innerHTML = "Primeiro selecione o estado";	}	  }// final da funcao que adiciona as cidades no combo ================================function fechaHint(){	document.getElementById('divHint').innerHTML = '&nbsp;';	document.getElementById('hint').style.visibility = 'hidden';	document.getElementById('hint').style.zIndex = 0;	document.getElementById('imgLoading').style.zIndex = 0;	document.getElementById('imgLoading').style.visibility = 'hidden';	document.getElementById('imgLoading').src = '';	if (ok) {    document.getElementById('novo').click();    if (document.getElementById('imprimir')){      document.getElementById('imprimir').style.visibility = 'visible';    }	}}function showHint(msg, imgLoading, btnCaption, imagem){//	document.getElementById('imgLoading').src = 'http://www.jbsoft.com.br/jb/img/' + imagem;//	document.getElementById('imgLoading').style.visibility = imgLoading;	document.getElementById('cancelar').value = btnCaption;  msg = msg.replace('<br>', '\n');  msg = msg.replace('<br />', '\n');	document.getElementById('divHint').innerHTML = msg;	document.getElementById('hint').style.visibility = 'visible';	setObjToCenter(document.getElementById('hint'), 400, 100);}function setObjToCenter(obj, w, h){	obj.style.position = 'absolute';	if ((getWinHeight() > h) && (h > 0)){		obj.style.top = (getDocPosTop() + ((getWinHeight() - h) / 2)) + 'px';	  //obj.style.top = 0;	  //alert(cad_pedido.height);		obj.style.height = h + 'px';	} else {		obj.style.top = 0 + 'px';	}	if ((getWinWidth() > w) && (w > 0)){		obj.style.left = (getDocPosLeft() + ((getWinWidth() - w) / 2)) + 'px';		obj.style.width = w + 'px';	} else {		obj.style.left = 0 + 'px';	}}function getWinWidth(){  if (document.all){	  return document.body.clientWidth;  } else {	  return window.innerWidth;  }}function getWinHeight(){  if (document.all){	  return document.body.clientHeight;  } else {	  return window.innerHeight;  }}function getDocPosTop(){    var h = window.pageYOffset ||           document.body.scrollTop ||           document.documentElement.scrollTop;   return h ? h : 0;}function getDocPosLeft(){   var w = window.pageXOffset ||           document.body.scrollLeft ||           document.documentElement.scrollLeft;   return w ? w : 0;	}/**** Descrição.: formata um campo do formulário de acordo com a máscara informada...* Parâmetros: - objForm (o Objeto Form) - strField (string contendo o nome do textbox) * sMask (mascara que define o formato que o dado será apresentado, * usando o algarismo "9" para definir números e o símbolo "!" para qualquer caracter...* - evtKeyPress (evento)* Uso: <input type="text" name="xxx" onkeypress="return Format(document.rcfDownload, 'str_cep', '99999-999', event);">* Observação: As máscaras podem ser representadas como os exemplos abaixo:* CEP -> 99.999-999* CPF -> 999.999.999-99* CNPJ -> 99.999.999/9999-99* Data -> 99/99/9999* Tel Resid -> (99) 999-9999* Tel Cel -> (99) 9999-9999* Processo -> 99.999999999/999-99* C/C -> 999999-!* E por aí vai...***/function Format(strField, sMask, event) { 	  var fldLen = 0, mskLen = 0, i = 0; var nCount = 0; var sCod = "";	var nTecla = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;	var sValue = document.getElementById(strField).value;	// Limpa todos os caracteres de formatação que tiver na variável.	sValue = sValue.toString().replace(/[^\d]/g, "");//	sValue = sValue.toString().replace(".", "", "g");//	sValue = sValue.toString().replace("/", "", "g");//	sValue = sValue.toString().replace("(", "", "g");//	sValue = sValue.toString().replace(")", "", "g");//	sValue = sValue.toString().replace(" ", "", "g");	fldLen = sValue.length;	mskLen = sMask.length;	mskLen = fldLen; 	if ((nTecla != 8) && (nTecla != 9)) { // backspace e tab		while (i <= mskLen) {			bolMask = ((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++; 			}	else { 			  sCod += sValue.charAt(nCount); 				nCount++; 			} 			i++; 		}		document.getElementById(strField).value = sCod; 		if (sMask.charAt(i-1) == "9") { // apenas números...			return ((nTecla > 47) && (nTecla < 58)); // números de 0 a 9		} else { 		  return true; 		} // qualquer caracter...	}	else { 		return true; 	} } //Fim da Função Máscaras Geraisfunction FormataValor(id, tammax, event) {  var tecla = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;	//           delete           tab           backspace            números	if ((tecla == 46) || (tecla == 9) || (tecla == 8) || ((tecla > 47) && (tecla < 58))){		vr = document.getElementById(id).value;		vr = vr.toString().replace( "/", "" );		vr = vr.toString().replace( "/", "" );		vr = vr.toString().replace( ",", "" );		vr = vr.toString().replace( ".", "" );		vr = vr.toString().replace( ".", "" );		vr = vr.toString().replace( ".", "" );		vr = vr.toString().replace( ".", "" );		tam = vr.length; 		if ((tam < tammax) && (tecla != 8) && (tecla != 9) && (tecla != 46)) { 			tam = vr.length + 1; 		} 		if (tecla == 8) { 			tam = tam - 1; 		}		if (tam < 3){			document.getElementById(id).value = vr; 		}		if ((tam > 2) && (tam <= 5)){			document.getElementById(id).value = vr.substr(0, tam - 2) + ',' + vr.substr(tam - 2, tam); 		}		if ((tam >= 6) && (tam <= 8)){			document.getElementById(id).value = vr.substr(0, tam - 5) + '.' + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam); 		}		if ((tam >= 9) && (tam <= 11)){			document.getElementById(id).value = vr.substr(0, tam - 8) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam); 		}		if ((tam >= 12) && (tam <= 14)){			document.getElementById(id).value = vr.substr(0, tam - 11) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam); 		}		if ((tam >= 15) && (tam <= 17)){			document.getElementById(id).value = vr.substr(0, tam - 14) + '.' + vr.substr(tam - 14, 3) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);		}	} else {		return false;	}}// seta a mascara que vai validar o campo cnpjvar mascara = '99.999.999/9999-99';function getMascara(){	return mascara;}var mascara2 = '999.999.999-99';function getMascara2(){	return mascara2;}function setMascara2(tipo){	if (tipo == 1){		mascara2 = '99.999.999/9999-99';	} else {		mascara2 = '999.999.999-99';	} }function valorEstaEm(valor, lista) {	for (i = 0; i < lista.length; i++) {		if (valor == lista[i]){		 	return true;		}	}	return false;}function setMascara(tipo){	if (tipo == 1){		mascara = '99.999.999/9999-99';	} else if (tipo == 2){		mascara = '999.999.999-99';	} else if (tipo == 3) {		mascara = '99.999.99999/99';	} else {		mascara = '999.99999.99.9';	}	setCaptionLabels(tipo);}function setCaptionLabels(p){   if (p == 2){ 		document.getElementById('lblRazao').innerHTML = '<font color="#ff0000">* </font><b>Nome: </b>';		document.getElementById('lblCnpj').innerHTML = '<font color="#ff0000">* </font><b>CPF: </b>';		document.getElementById('lblIe').innerHTML = '<font color="#ff0000">* </font><b>Registro Geral, RG: </b>';	}else{		document.getElementById('lblRazao').innerHTML = '<font color="#ff0000">* </font><b>Raz&atilde;o Social: </b>';		document.getElementById('lblIe').innerHTML = '<font color="#ff0000">* </font><b>Inscri&ccedil;&atilde;o Estadual: </b>';		document.getElementById('lblCnpj').innerHTML = '<font color="#ff0000">* </font><b>CNPJ: </b>';	}}
