	function MM_preloadImages() 
	{
		var d=document; if(d.images)
		{ 
			if(!d.MM_p) d.MM_p=new Array();
			var i,j=d.MM_p.length,a=MM_preloadImages.arguments; 
			for(i=0; i < a.length; i++)
			if (a[i].indexOf('#')!=0)
			{ 
				d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];
			}
		}
	}

	function ImprimeBoleto()
	{
		JanelaComparar("Boleto.aspx","Boleto","700","600")
	}

	function validaBundle()
	{
		var CodProduto = "";
		valeuCompra = true;
		delimit = "Regra_";
		atualMinimo = 0;
		atualContagem = 0;
		var msgErro = "";

		divs=document.getElementsByTagName("input");
		for (i=0;i<divs.length;i++) 
		{
			if (divs[i].type == "hidden")
			{
				if (divs[i].name.length > 6)
				{
					if (divs[i].name.indexOf(delimit) >= 0)
					{
						divs2=document.getElementsByTagName("input");

						atualMinimo = Number(divs[i].value);
						atualContagem = 0;

						for (j=0;j<divs2.length;j++) 
						{
							if (divs[j].type == "checkbox")
							{
								if (divs[i].name.replace(delimit, '') == divs[j].name)
								{
									if (divs[j].checked)
									{
										atualContagem++;
										
										if (CodProduto == "")
											CodProduto = divs[j].value;
										else
											CodProduto = CodProduto + "|"+divs[j].value;
									}
								}								
							}
						}

						if (atualContagem != atualMinimo)
						{
							if (msgErro == "")
							{
								msgErro = "Falta ajustar para " + atualMinimo + " produto(s) no grupo " + divs[i].name.replace(delimit, '');
							}
							else
							{
								msgErro = msgErro + ", " + atualMinimo + " produto(s) no grupo " + divs[i].name.replace(delimit, '');
							}
							valeuCompra = false;
						}
					}
				}
			}
		}		

		if (valeuCompra)
		{
			qtde = document.getElementById("txtQtde").value;
	
			if (qtde != "" && !isNaN(qtde))
			{
				index.ComprarBundle(CodProduto, qtde, callback_ComprarCross);
			}
			else
			{
				alert("Você precisa especificar a quantidade que deseja comprar!");
			}
		}
		else
		{
			msgErro += " para validar a compra do Bundle!"
			alert(msgErro);
		}
	}

	function MostraSeriais(PedCodigo, ProCodigo, Pagina)
	{
		if (!isNaN(PedCodigo) && !isNaN(ProCodigo))
		{
			Janela(Pagina+'?ProdutoCodigo='+ProCodigo+'&PedidoCodigo='+PedCodigo, '650', '350');
		}
	}


	function ComprarProdutosBusca(prod)
	{
		if (!isNaN(prod))
		{
			busca.ComprarBusca(prod, callback_ComprarCross);
		}
	}

	function ComprarProdutosCross(prod1, prod2)
	{
		if (!isNaN(prod1) && !isNaN(prod2))
		{
			detalhes.ComprarCross(prod1, prod2, callback_ComprarCross);
		}
	}

	function callback_ComprarCross(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		if (res.value)
		{
			top.location.href = res.value;
		}
	}

	function MudaEstado()
	{	
		if (document.getElementById("RODA:drpEstados").value != "")
		{
			if (confirm("Você está escolhendo visuzalizar os preços para o estado de " + document.getElementById("RODA:drpEstados").value + " com carater de consulta/orçamento\nnão sendo possível finalizar suas compras. Isso fará com que a sua cesta seja esvaziada e os preços atualizados.\n\nDeseja continuar?"))
			{
				__doPostBack('RODA$drpEstados','');
				return true;
			}
			else
			{
				document.getElementById("RODA:drpEstados").value = document.getElementById("RODA:EstadoBase").value;
				return false;
			}
		}
		else
		{
			if (confirm("Você está escolhendo visuzalizar os preços normais para a sua conta possibilitando finalizar suas compras.\nIsso fará com que a sua cesta seja esvaziada e os preços atualizados.\n\nDeseja continuar?"))
			{
				top.location.href='index.aspx?acao=LimparEstado'
				return true;
			}
			else
			{
				document.getElementById("RODA:drpEstados").value = document.getElementById("RODA:EstadoBase").value;
				return false;
			}
		}
	}

	function GuardaEstado()
	{
		if (document.getElementById("RODA:drpEstados").value != "")
		{
			document.getElementById("RODA:EstadoBase").value = document.getElementById("RODA:drpEstados").value;
		}	
	}

	function GuardaDocEstadual(campo)
	{
		document.getElementById("CadastroDctoEstadual").value = campo.value;		
	}

	function GuardaDocFederal(campo, tipo)
	{
		document.getElementById("CadastroTipo").value = tipo;
		document.getElementById("CadastroDctoFederal").value = campo.value;		
	}

	function AtualizaCNPJ(RevendaID, pagina)
	{
		TrocaImagem("loading_CNPJ", "visible");

		if (pagina == "cadastro_tipo5")
			cadastro_tipo5.CarregaCNPJ(RevendaID, callback_CarregaCNPJ)
		else if (pagina == "cadastro_tipo3")
			cadastro_tipo3.CarregaCNPJ(RevendaID, callback_CarregaCNPJ)
	}

	function callback_CarregaCNPJ(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("docCNPJ_Revenda").value = res;
		
		if (res.error)
		{
			alert(res.error);
		}

		TrocaImagem("loading_CNPJ", "hidden");
	}
	
	function AtualizaDocumentos(campo, pessoa, pagina)
	{
		achou = false;

		document.getElementById("docEstadual_" + pessoa).title = "";
		document.getElementById("docFederal_" + pessoa).title = "";
		document.getElementById("CadastroDctoEstadual").value = "";
		document.getElementById("CadastroDctoFederal").value = "";
		document.getElementById("docEstadual_" + pessoa).innerHTML = "";

		document.getElementById("drpDocEstadual_" + pessoa).innerHTML = "";
		document.getElementById("drpDocFederal_" + pessoa).innerHTML = "";

		try
		{
			document.getElementById("RequerDocFederal_" + pessoa).style.display = "none";
			document.getElementById("RequerDocEstadual_" + pessoa).style.display = "none";
		}
		catch(err)
		{
		}

		document.getElementById("docFederal_" + pessoa).innerHTML = "";
		document.getElementById("ibtCadastrar_" + pessoa).style.display = "none";
	
		if (campo)
		{
			if (campo.value != "")
			{
				achou = true;
				TrocaImagem("loading_" + pessoa, "visible");

				if (pagina == "index")
					index.CarregaDocumentos(campo.value, pessoa, callback_CarregaDocumentos)
				else if (pagina == "cadastro_tipo2")
					cadastro_tipo2.CarregaDocumentos(campo.value, pessoa, callback_CarregaDocumentos)
				else if (pagina == "cadastro_tipo3")
					cadastro_tipo3.CarregaDocumentos(campo.value, pessoa, callback_CarregaDocumentos)
				else if (pagina == "cadastro_tipo4")
					cadastro_tipo4.CarregaDocumentos(campo.value, pessoa, callback_CarregaDocumentos)
				else if (pagina == "cadastro_tipo5")
					cadastro_tipo5.CarregaDocumentos(campo.value, pessoa, callback_CarregaDocumentos)
				else if (pagina == "convidado")
					convidado.CarregaDocumentos(campo.value, pessoa, callback_CarregaDocumentos)
			}
		}

		if (!achou)
		{

			document.getElementById("docEstadual_" + pessoa).title = "";
			document.getElementById("docFederal_" + pessoa).title = "";

			document.getElementById("CadastroDctoEstadual").value = "";
			document.getElementById("CadastroDctoFederal").value = "";

			document.getElementById("docEstadual_" + pessoa).innerHTML = "";
			document.getElementById("docFederal_" + pessoa).innerHTML = "";
			document.getElementById("ibtCadastrar_" + pessoa).style.display = "none";

			document.getElementById("drpDocEstadual_" + pessoa).innerHTML = "";
			document.getElementById("drpDocFederal_" + pessoa).innerHTML = "";

			try
			{
				document.getElementById("RequerDocFederal_" + pessoa).style.display = "none";
				document.getElementById("RequerDocEstadual_" + pessoa).style.display = "none";
			}
			catch(err)
			{
			}
		}
	}

	function callback_CarregaDocumentos(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		var pessoa;

		if (document.getElementById("CadastroTipo").value == "R")
		{
			pessoa = "PJ";
		}
		else
		{
			pessoa = "PF";
		}


		if (res.value[1] != "")
		{
			document.getElementById("docEstadual_" + pessoa).title = res.value[0];
			document.getElementById("docEstadual_" + pessoa).innerHTML = res.value[1] + ": ";
			document.getElementById("drpDocEstadual_" + pessoa).innerHTML = res.value[2];
		}
		else
		{
			if (res.value[2] != "")
			{
				document.getElementById("docEstadual_" + pessoa).title = res.value[0];
				document.getElementById("docEstadual_" + pessoa).innerHTML = "Documento Estadual: ";
				document.getElementById("drpDocEstadual_" + pessoa).innerHTML = res.value[2];
			}			
		}

		if (res.value[4] != "")
		{
			document.getElementById("docFederal_" + pessoa).title = res.value[3];
			document.getElementById("docFederal_" + pessoa).innerHTML = res.value[4] + ": ";
		}
		else
		{
			document.getElementById("docFederal_" + pessoa).title = res.value[3];
			document.getElementById("docFederal_" + pessoa).innerHTML = "Documento Federal: ";
		}

		document.getElementById("drpDocFederal_" + pessoa).innerHTML = res.value[5];

		try
		{
			document.getElementById("RequerDocFederal_" + pessoa).style.display = "block";
			document.getElementById("RequerDocEstadual_" + pessoa).style.display = "block";
		}
		catch(err)
		{
		}
		
		document.getElementById("ibtCadastrar_" + pessoa).style.display = "block";
		document.getElementById("ibtCadastrar_" + pessoa).style.display = "block";

		TrocaImagem("loading_" + pessoa, "hidden");

		if (res.error)
		{
			alert(res.error);
		}
	}

	/************ SELECIONA OPÇÕES DE FINANCIAMENTO PARA A COMPRA + VALOR FRETE *******************/

	function AtualizaFinanciamento(campo, empresa)
	{
        //objPortador = document.getElementById("pnlDadosRetira_" + empresa);
        
		obj = document.getElementById("pnlPagamento_" + empresa);
		campoTipo = document.getElementById("radFrete_Pago_" + empresa);
		tipo = (campoTipo.checked ? "P" : "A");

		if (campo)
		{
			if (campo.value != "")
			{
				TransportadoraID = "";
				delimitador = campo.value.indexOf("_");

				if (delimitador != -1)
				{
					TransportadoraID = campo.value.substr(0, delimitador);
					MeioTransporteID = campo.value.substr(delimitador+1);
				}
				else
				{
					TransportadoraID = campo.value;
					MeioTransporteID = "";
				}

				document.getElementById("Pedido_TransportadoraID_" + empresa).value = TransportadoraID;
				document.getElementById("Pedido_MeioTransporteID_" + empresa).value = MeioTransporteID;
				document.getElementById("Pedido_FinanciamentoID_" + empresa).value = "";

				obj.style.display = "block";

				if (empresa == "EstoqueLocal")
				{
				    //alert('aki1');
					TrocaImagem("loading_EstoqueLocal", "visible");
					ValorFrete_EstoqueLocal(tipo, TransportadoraID, empresa);
				}
				else if (empresa == "EstoqueOperador")
				{
					//alert('aki1');
					TrocaImagem("loading_EstoqueOperador", "visible");
					ValorFrete_EstoqueOperador(tipo, TransportadoraID, empresa);
				}
			}
			else
			{
				obj.style.display="none";

				document.getElementById("Pedido_TransportadoraID_" + empresa).value = "";
				document.getElementById("Pedido_MeioTransporteID_" + empresa).value = "";
				document.getElementById("Pedido_FinanciamentoID_" + empresa).value = "";
				document.getElementById("spanFreteValor_" + empresa).innerHTML = " - - - ";
				document.getElementById("spanCompraValor_" + empresa).innerHTML = " - - - ";
			}
		}
		else
		{
			obj.style.display="none";

			document.getElementById("Pedido_TransportadoraID_" + empresa).value = "";
			document.getElementById("Pedido_MeioTransporteID_" + empresa).value = "";
			document.getElementById("Pedido_FinanciamentoID_" + empresa).value = "";
			document.getElementById("spanFreteValor_" + empresa).innerHTML = " - - - ";
			document.getElementById("spanCompraValor_" + empresa).innerHTML = " - - - ";
		}
	}

	/************ RECUPERA VALOR DO FRETE PARA TODAS AS EMPRESAS *******************/

	function ValorFrete_EstoqueLocal(tipo, id_Transportadora, empresa)
	{
	    //alert('aki2');
		passo1.CarregaValorFrete(tipo, id_Transportadora, empresa, callback_ValorFrete_EstoqueLocal);
	}

	function ValorFrete_EstoqueOperador(tipo, id_Transportadora, empresa)
	{
		//alert('aki2');
		passo1.CarregaValorFrete(tipo, id_Transportadora, empresa, callback_ValorFrete_EstoqueOperador);
	}

	function callback_ValorFrete_EstoqueLocal(res)
	{
		//alert('aki3');
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("spanFreteValor_EstoqueLocal").innerHTML = res.value;
		ValorCompra_EstoqueLocal();
	}

	function callback_ValorFrete_EstoqueOperador(res)
	{
		//alert('aki3');
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("spanFreteValor_EstoqueOperador").innerHTML = res.value;
		ValorCompra_EstoqueOperador();
	}

	/************ RECUPERA OPÇÕES DE FINANCIAMENTO PARA TODAS AS EMPRESAS *****************/

	function CarregaFinanciamento(empresa)
	{
		if (empresa ==  "EstoqueLocal")
		{
		    //alert('aki6');
			passo1.CarregaFinanciamentos_EstoqueLocal(callback_CarregaFinanciamentos_EstoqueLocal);
		}
		else if (empresa ==  "EstoqueOperador")
		{
		    //alert('aki6');
			passo1.CarregaFinanciamentos_EstoqueOperador(callback_CarregaFinanciamentos_EstoqueOperador);
		}
	}

	function callback_CarregaFinanciamentos_EstoqueLocal(res)
	{
		//alert('aki7');
		if (res.error)
		{
			alert(res.error);
		}

		if (res.value.length > 0)
		{
			Formas = res.value[0];
			Pagtos = res.value[1];
			Select = res.value[2];
			
			for (i=0; i<Formas.length; i++)
			{
				document.getElementById("spanFrete_EstoqueLocal_" + Formas[i]).innerHTML = Pagtos[i];
				//document.getElementById("Pedido_FinanciamentoID_EstoqueLocal").value = Select[i];
			}

			TrocaImagem("loading_EstoqueLocal", "hidden");
		}
		//alert('aki8');
	}

	function callback_CarregaFinanciamentos_EstoqueOperador(res)
	{
		//alert('aki7');
		if (res.error)
		{
			alert(res.error);
		}

		if (res.value.length > 0)
		{
			Formas = res.value[0];
			Pagtos = res.value[1];
			Select = res.value[2];
			
			for (i=0; i<Formas.length; i++)
			{
				document.getElementById("spanFrete_EstoqueOperador_" + Formas[i]).innerHTML = Pagtos[i];
				//document.getElementById("Pedido_FinanciamentoID_EstoqueOperador").value = Select[i];
			}

			TrocaImagem("loading_EstoqueOperador", "hidden");
		}
		
		//alert('aki8');
	}

	/************ RECUPERA VALOR TOTAL DA COMPRA PARA TODAS AS EMPRESAS *******************/

	function ValorCompra_EstoqueLocal()
	{
		//alert('aki4');
		passo1.CarregaValorTotal("EstoqueLocal", callback_ValorCompra_EstoqueLocal);
	}

	function ValorCompra_EstoqueOperador()
	{
		//alert('aki4');
		passo1.CarregaValorTotal("EstoqueOperador", callback_ValorCompra_EstoqueOperador);
	}

	function callback_ValorCompra_EstoqueLocal(res)
	{
		//alert('aki5');
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("spanCompraValor_EstoqueLocal").innerHTML = res.value;
		CarregaFinanciamento("EstoqueLocal");
	}

	function callback_ValorCompra_EstoqueOperador(res)
	{
	    //alert('aki5');
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("spanCompraValor_EstoqueOperador").innerHTML = res.value;
		CarregaFinanciamento("EstoqueOperador");
	}

	/************ FORMA DE PAGAMENTO DO FRETE PARA TODAS AS EMPRESAS QNDO CLIENTE RETIRA **/

	function FormaFrete_EstoqueLocal_Retira(formaFrete, empresa, EmpresaID)
	{
		TrocaImagem("loading_EstoqueLocal", "visible");
		document.getElementById("Pedido_TransportadoraID_EstoqueLocal").value = EmpresaID;
		document.getElementById("Pedido_Frete_EstoqueLocal").value = "0";
		passo1.CarregaFrete(formaFrete, empresa, callback_FormaFrete_EstoqueLocal_Retira);
	}

	function callback_FormaFrete_EstoqueLocal_Retira(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("spanFrete_EstoqueLocal").innerHTML = res.value;

		cliente = document.getElementById("ClienteID");
		campo = document.getElementById("drpFrete_EstoqueLocal");
		if (cliente && campo)
		{
			campo.disabled = true;
			campo.value = cliente.value;
			AtualizaFinanciamento(campo, "EstoqueLocal");
		}
	}

	function FormaFrete_EstoqueOperador_Retira(formaFrete, empresa, EmpresaID)
	{
		TrocaImagem("loading_EstoqueOperador", "visible");
		document.getElementById("Pedido_TransportadoraID_EstoqueOperador").value = EmpresaID;
		document.getElementById("Pedido_Frete_EstoqueOperador").value = "0";
		passo1.CarregaFrete(formaFrete, empresa, callback_FormaFrete_EstoqueOperador_Retira);
	}

	function callback_FormaFrete_EstoqueOperador_Retira(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("spanFrete_EstoqueOperador").innerHTML = res.value;

		cliente = document.getElementById("ClienteID");
		campo = document.getElementById("drpFrete_EstoqueOperador");
		if (cliente && campo)
		{
			campo.disabled = true;
			campo.value = cliente.value;
			AtualizaFinanciamento(campo, "EstoqueOperador");
		}
	}

	/************ FORMA DE PAGAMENTO DO FRETE PARA TODAS AS EMPRESAS *******************/

	function FormaFrete_EstoqueLocal(formaFrete, empresa)
	{
		TrocaImagem("loading_EstoqueLocal", "visible");
		document.getElementById("Pedido_Frete_EstoqueLocal").value = (formaFrete == 'P' ? "1" : "0");
		AtualizaFinanciamento("", "EstoqueLocal");
		passo1.CarregaFrete(formaFrete, empresa, callback_FormaFrete_EstoqueLocal);
	}

	function FormaFrete_EstoqueOperador(formaFrete, empresa)
	{
		TrocaImagem("loading_EstoqueOperador", "visible");
		document.getElementById("Pedido_Frete_EstoqueOperador").value = (formaFrete == 'P' ? "1" : "0");
		AtualizaFinanciamento("", "EstoqueOperador");
		passo1.CarregaFrete(formaFrete, empresa, callback_FormaFrete_EstoqueOperador);
	}

	function callback_FormaFrete_EstoqueLocal(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("spanFrete_EstoqueLocal").innerHTML = res.value;
		TrocaImagem("loading_EstoqueLocal", "hidden");
	}

	function callback_FormaFrete_EstoqueOperador(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("spanFrete_EstoqueOperador").innerHTML = res.value;
		TrocaImagem("loading_EstoqueOperador", "hidden");
	}

	/**************************************************************************************/

	/************ FORMA DE PAGAMENTO DO FRETE GRATIS PARA TODAS AS EMPRESAS *******************/

	function FormaFreteGratis_EstoqueLocal(formaFrete, empresa)
	{
		TrocaImagem("loading_EstoqueLocal", "visible");
		document.getElementById("Pedido_Frete_EstoqueLocal").value = (formaFrete == 'P' ? "1" : "0");
		AtualizaFinanciamento("", "EstoqueLocal");
		passo1.CarregaFrete(formaFrete, empresa, callback_FormaFreteGratis_EstoqueLocal);
	}

	function FormaFreteGratis_EstoqueOperador(formaFrete, empresa)
	{
		TrocaImagem("loading_EstoqueOperador", "visible");
	
		document.getElementById("Pedido_Frete_EstoqueOperador").value = (formaFrete == 'P' ? "1" : "0");
        
		AtualizaFinanciamento("", "EstoqueOperador");
		passo1.CarregaFrete(formaFrete, empresa, callback_FormaFreteGratis_EstoqueOperador);
	}

	function callback_FormaFreteGratis_EstoqueLocal(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("spanFrete_EstoqueLocal").innerHTML = res.value;

		cliente = document.getElementById("ClienteID");
		campo = document.getElementById("drpFrete_EstoqueLocal");
		campo.disabled = true;

		if (cliente && campo)
		{
			AtualizaFinanciamento(campo, "EstoqueLocal");
		}
	}

	function callback_FormaFreteGratis_EstoqueOperador(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		document.getElementById("spanFrete_EstoqueOperador").innerHTML = res.value;

		cliente = document.getElementById("ClienteID");
		campo = document.getElementById("drpFrete_EstoqueOperador");
		campo.disabled = true;
		if (cliente && campo)
		{
			AtualizaFinanciamento(campo, "EstoqueOperador");
		}
	}

	/**************************************************************************************/



	function RedirecionaFecha()
	{
		
		setTimeout ("window.self.close();",500);			
	}

	function SelecionarTodosChecks(campo)
	{
		divs=document.getElementsByTagName("input");
		for (i=0;i<divs.length;i++) 
		{
			if (divs[i].type == "checkbox")
			{
				if (divs[i].name == "Comparacao")
				{
					divs[i].checked = campo.checked;
				}
			}
		}
	}

	function MostraVencimentos(id2, visibilidade, id)
	{
		obj2=document.getElementById(id);
		obj1=document.getElementById(id2);

		if (visibilidade == "block")
		{
			obj1.innerHTML = obj2.innerHTML;
		}
		else
		{
			obj1.innerHTML = "";
		}
	}

	function MudaOpcoesImg(radCampo, valorFinanciado)
	{
		if (radCampo)
		{
			radCampo.checked = true;
			GuardaPagamento(radCampo, valorFinanciado)
			TogglePedido(radCampo.id);
		}
	}
	
	function MudaOpcoes(radCampo)
	{
		if (radCampo)
		{
			if (radCampo.checked)
			{
				GuardaPagamento(radCampo)
				TogglePedido(radCampo.id);
			}
		}
	}

	function GuardaPagamento(radCampo, valorFinanciado)
	{
		iSelecionado = -1;
		
		delimitador = radCampo.id.indexOf("_");
		empresa = radCampo.id.substr(delimitador+1);
		forma = radCampo.id.substr(3,3);

		divs = document.getElementsByTagName("input");
		for (i=0;i<divs.length;i++) 
		{
			if (divs[i].type == "radio")
			{
				if (divs[i].id.indexOf('FinanFinanc_') >= 0 && divs[i].id.indexOf('_' + empresa + '_') >= 0)
				{
                    divs[i].checked = false;
					document.getElementById("Pedido_FinanciamentoID_" + empresa).value = "";
					
					if (divs[i].id.indexOf(forma) >= 0 && iSelecionado == -1) {
					    iSelecionado = i;
                    }
				}
			}
		}
		
		FormaPagamentoID = "";
		if (forma == "DIN")
			FormaPagamentoID = "1031";
		else if (forma == "CHQ")
			FormaPagamentoID = "1032";
		else if (forma == "CCC")
			FormaPagamentoID = "1033";
		else if (forma == "COD")
			FormaPagamentoID = "1035";
		else if (forma == "CAR")
			FormaPagamentoID = "1037";

		document.getElementById("Pedido_FormaPagamentoID_" + empresa).value = FormaPagamentoID;
		
		// 02/09/2009 - Quando a opcao for credito em conta, deve vir pré-selecionado A Vista
		if (iSelecionado != -1 && forma == "CCC") {
			divs[iSelecionado].checked = true;
			divs[iSelecionado].click();
		}
		
		
	}

	function callback_GuardaValorFinanc(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		TrocaImagem("loading_EstoqueLocal", "hidden");
		TrocaImagem("loading_EstoqueOperador", "hidden");
	}

	function GuardaFinanciamento(radCampo, valorFinanciado)
	{
		TrocaImagem("loading_EstoqueLocal", "visible");
		TrocaImagem("loading_EstoqueOperador", "visible");
	
		delimitador1 = radCampo.id.indexOf("Estoque");
		semi_empresa = radCampo.id.substr(delimitador1);

		delimitador = semi_empresa.indexOf("_");
		empresa = semi_empresa.substr(0,delimitador);
		
		passo1.GuardaValorFinanc(valorFinanciado, empresa, callback_GuardaValorFinanc);

		if (radCampo)
		{
			if(radCampo.checked)
			{
				document.getElementById("Pedido_FinanciamentoID_" + empresa).value = radCampo.value;
			}
		}
	}

	function RetornaURLImg()
	{
		return "http://clientes.ikeda.com.br/Alcateia/Imagens/";
	}

	function mOvr(src,clrOver) {
		if (!src.contains(event.fromElement)) 
		{
			src.style.cursor = 'hand';
			src.className = clrOver;
		}
	}

	function CarregaAtras(URL)
	{
	  	if (window.parent != null)
		{
			try
			{
				window.parent.location = URL;
				window.parent.focus();						
			}
			catch(err)
			{
			}
		}		
	}

	function JanelaConfigurador(url)
	{
	    var nome = 'Configurador';
	    var width = 1000;
	    var height = 635;
	
		var w = window.screen.width;
		var h = window.screen.height;
		var l = (w-width)/2;
		var t = (h-height)/2;

		wAbout = window.open(url, nome, 'SCROLLBARS=yes,RESIZABLE=no,TOOLBAR=no,STATUS=no,MENUBAR=no,width='+width+',height='+height+',top='+t+',left='+l);

		wAbout.blur();
		window.focus();	
		wAbout.focus();
	}
	
	function JanelaComparar(url,nome,width,height)
	{
		var w = window.screen.width;
		var h = window.screen.height;
		var l = (w-width)/2;
		var t = (h-height)/2;

		if (nome == "")
		{
			nome = "Alcateia";
		}
		
		wAbout = window.open(url, nome, 'SCROLLBARS=yes,RESIZABLE=no,TOOLBAR=no,STATUS=no,MENUBAR=no,width='+width+',height='+height+',top='+t+',left='+l);

		wAbout.blur();
		window.focus();	
		wAbout.focus();
	}

	function Janela(url,width,height)
	{
		var w = window.screen.width;
		var h = window.screen.height;
		var l = (w-width)/2;
		var t = (h-height)/2;
		
		wAbout = window.open(url, "Alcateia", 'SCROLLBARS=yes,RESIZABLE=no,TOOLBAR=no,STATUS=no,MENUBAR=no' );

		wAbout.blur();
		window.focus();	
		wAbout.resizeTo(width,height);
		wAbout.moveTo(l, t);
		wAbout.focus();
	}

	function JanelaSemScroll(url,width,height)
	{
		var w = window.screen.width;
		var h = window.screen.height;
		var l = (w-width)/2;
		var t = (h-height)/2;
		
		wAbout = window.open(url, "Alcateia", 'SCROLLBARS=no,RESIZABLE=no,TOOLBAR=no,STATUS=no,MENUBAR=no' );

		wAbout.blur();
		window.focus();	
		wAbout.resizeTo(width,height);
		wAbout.moveTo(l, t);
		wAbout.focus();
	}

	function CompararItems()
	{
		var totalItens = 0;
		var ItensCod = "";

		divs=document.getElementsByTagName("input");
		
		for (i=0;i<divs.length;i++) 
		{
			if (divs[i].type == "checkbox")
			{
				if (divs[i].name == "Comparacao")
				{
					if(divs[i].checked)
					{
						if (ItensCod == "")
						{
							ItensCod = divs[i].value;
						}
						else
						{
							ItensCod += ";" + divs[i].value;
						}

						//ItensCod += divs[i].value + ";"; // Novo
						totalItens++;
					}
				}
			}
		}

		if (totalItens > 1)
		{
			JanelaComparar("","JanelaComparador",780,600)
			
			document.itensComparar.ItensCodigos.value = ItensCod;
			document.itensComparar.target = "JanelaComparador";
			document.itensComparar.submit();
		}
		else
		{
			document.itensComparar.ItensCodigos.value = "";
			alert("Você precisa selecionar mais de 1 produto pra poder fazer a comparação de produtos!");
		}
	}

	function mOut(src,clrIn) {
		if (!src.contains(event.toElement)) {
			src.style.cursor = 'default';
			src.className = clrIn;
		}
	}


	function UpdateQtde(qtde)
	{
	    var nome = qtde.name;
   
	    if (qtde.value <= 200) {
		    document.qtdeUpdate.CestaItemID.value = nome;
		    document.qtdeUpdate.Quantidade.value = qtde.value;
		    document.qtdeUpdate.submit();
		} else {
		    window.alert('Quantidade inválida');
		    // qtde.value = '';
		}
	}

	function TestaValor(keyCode, campo) {

	    if (keyCode == 13) {
	        UpdateValor(campo);
	        return false;
	    }
	}
	
	function UpdateValor(campo)
	{
		erro = false;
		
		nome = campo.name;
		valor_new = Number(campo.value.replace(".","").replace(",","."));

		if (valor_new.length <= 0)
		{
			alert('O Valor Final para venda do produto, não pode ser vazio!');
			erro = true;		
		}

		if (!erro)
		{
		    document.valorUpdate.CestaItemID.value = nome;
		    document.valorUpdate.PrecoFaturamento.value = campo.value;
		    document.valorUpdate.submit();
		}
	}

	function GuardaValorBase(campo)
	{
		// document.valorUpdate.ProdutoValorBase.value = campo.value;
	}

	function FormataValor(campo,tammax,teclapres) 
	 {
		var tecla = teclapres.keyCode;

		vr = campo.value;
		vr = vr.replace( "/", "" );
		vr = vr.replace( "/", "" );
		vr = vr.replace( ",", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );

		tam = vr.length;

		if (tam < tammax && tecla != 8)
		{
			tam = vr.length + 1;
		}

		if (tecla == 8 )
		{
			tam = tam - 1; 
		}

		if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)
		{
			if (tam <= 2)
			{ 
				campo.value = vr; 
			}
			else if ((tam > 2) && (tam <= 5))
			{
				campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam );
			}
			else if ((tam >= 6) && (tam <= 7))
			{
				campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
			}
		}
	}

	function PreencheEndereco(pagina)
	{
		var CEPCompleto;

		if (document.getElementById("txtCEP1").value.length = 5 && document.getElementById("txtCEP2").value.length == 3)
		{
			for (j=0; j<document.forms[0].elements.length; j++) 
			{
//				document.forms[0].elements[j].disabled = true;
//				document.forms[0].elements[j].style.display="none"
			}

//			document.getElementById("ibtCadastrar").style.display="none"

			TrocaImagem("loading", "visible");
			CEPCompleto = document.getElementById("txtCEP1").value+document.getElementById("txtCEP2").value;

			if (pagina == "revenda")
				revenda.CarregaEndereco(CEPCompleto, callback_CarregaEndereco);
			else if (pagina == "contato")
				contato.CarregaEndereco(CEPCompleto, callback_CarregaEndereco);
			else if (pagina == "cadastro_tipo2")
				cadastro_tipo2.CarregaEndereco(CEPCompleto, callback_CarregaEndereco);
			else if (pagina == "cadastro_tipo3")
				cadastro_tipo3.CarregaEndereco(CEPCompleto, callback_CarregaEndereco);
			else if (pagina == "cadastro_tipo4")
				cadastro_tipo4.CarregaEndereco(CEPCompleto, callback_CarregaEndereco);
			else if (pagina == "cadastro_tipo5")
				cadastro_tipo5.CarregaEndereco(CEPCompleto, callback_CarregaEndereco);
			else if (pagina == "pj")
				pj.CarregaEndereco(CEPCompleto, callback_CarregaEndereco);
			else if (pagina == "pf")
				pf.CarregaEndereco(CEPCompleto, callback_CarregaEndereco);
		}	
	}

	function callback_CarregaEndereco(res)
	{
		if (res.error)
		{
			alert(res.error);
		}

		try
		{
		    document.getElementById("txtCidade").disabled = false;
		    document.getElementById("txtEstado").disabled = false;

			if (res.value[0] != "")
			{
				alert(res.value[0]);
			}

			if (res.value.length > 1)
			{
//				for (j=0; j<document.forms[0].elements.length; j++) 
//				{
//					document.forms[0].elements[j].disabled = false;
//					document.forms[0].elements[j].style.display="block";
//				}

				document.getElementById("ibtCadastrar").style.display="block";

				if (res.value[1] != "")
				{
					document.getElementById("txtEndereco").value = res.value[1];
				}
				if (res.value[2] != "")
				{
					document.getElementById("txtNumero").value = res.value[2];
				}
				if (res.value[3] != "")
				{
					document.getElementById("txtBairro").value = res.value[3];
				}
				if (res.value[4] != "")
				{
					document.getElementById("txtCidade").value = res.value[4];
					document.getElementById("txtCidade").readOnly = true;
				}
				if (res.value[5] != "")
				{
					document.getElementById("txtEstado").value = res.value[5];
					document.getElementById("txtEstado").readOnly = true;
				}
				if (res.value[7] != "")
				{
					document.getElementById("txtDDDTelefone").value = res.value[7];
				}
			}
		}
		catch(err)
		{
			alert("Erro JavaSCript : " + err.message + "\nErro Ajax : " + res.error);
		}

		TrocaImagem("loading", "hidden");
	}
	
	function valCep(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("txtCEP1").value != "" && document.getElementById("txtCEP2").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function valPais(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("CadastroTipo").value == "R")
		{
			if (document.getElementById("drpPais_PJ").value != "")
			{
				arguments.IsValid = true;
			}
		}
		else
		{
			if (document.getElementById("drpPais_PF").value != "")
			{
				arguments.IsValid = true;
			}
		}
	}

	function valRevenda(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("drpRevendas").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function valDocFederal_PJ(source, arguments)
	{
		arguments.IsValid = true;

		if (document.getElementById("CadastroTipo").value == "R")
		{
			if (document.getElementById("txtDocFederal_PJ").value == "")
			{
				arguments.IsValid = false;
			}
			else
			{
				if (document.getElementById("docFederal_PJ").innerHTML.indexOf("CNPJ") >= 0)
				{
					arguments.IsValid = validaCNPJ(document.getElementById("txtDocFederal_PJ").value);
				}
			}
		}
	}

	function valDocFederal_PF(source, arguments)
	{
		arguments.IsValid = true;

		if (document.getElementById("CadastroTipo").value == "C")
		{
			if (document.getElementById("txtDocFederal_PF").value == "")
			{
				arguments.IsValid = false;
			}
			else
			{
				if (document.getElementById("docFederal_PF").innerHTML.indexOf("CPF") >= 0)
				{
					arguments.IsValid = validaCPF(document.getElementById("txtDocFederal_PF").value);
				}
			}
		}
	}

	function valDocEstadual_PJ(source, arguments)
	{
		arguments.IsValid = true;

		if (document.getElementById("CadastroTipo").value == "R")
		{
			try
			{
				if (document.getElementById("txtDocEstadual_PJ").value == "")
				{
					arguments.IsValid = false;
				}
			}
			catch(err)
			{
			}
		}
	}

	function valDocEstadual_PF(source, arguments)
	{
		arguments.IsValid = true;

		if (document.getElementById("CadastroTipo").value == "C")
		{
			try
			{
				if (document.getElementById("txtDocEstadual_PF").value == "")
				{
					arguments.IsValid = false;
				}
			}
			catch(err)
			{
			}
		}
	}

	function validaNomeOrcamento(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("txtNomeOrcamento").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function Valida_EstoqueLocal(source, arguments)
	{
		arguments.IsValid = true;

		if (document.getElementById("Pedido_Frete_EstoqueLocal").value == "")
		{
			arguments.IsValid = false;
		}
		if (document.getElementById("Pedido_TransportadoraID_EstoqueLocal").value == "")
		{
			arguments.IsValid = false;
		}
		if (document.getElementById("Pedido_FormaPagamentoID_EstoqueLocal").value == "")
		{
			arguments.IsValid = false;
		}
		if (document.getElementById("Pedido_FinanciamentoID_EstoqueLocal").value == "")
		{
			arguments.IsValid = false;
		}

		try {
		    if (document.getElementById("RetPortador_EstoqueLocal").value == "")
		    {
			    arguments.IsValid = false;
		    }
		    
		    if (document.getElementById("RetDocPortador_EstoqueLocal").value == "")
		    {
			    arguments.IsValid = false;
		    }
		    
		    if (document.getElementById("RetDocFederalPortador_EstoqueLocal").value == "")
		    {
			    arguments.IsValid = false;
		    }
		    else
		    {
			    arguments.IsValid = validaCPF(document.getElementById("RetDocFederalPortador_EstoqueLocal").value);
		    }
		    
		} catch(err) {}
	}

	function Frete_EstoqueLocal(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("Pedido_Frete_EstoqueLocal").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function Transportadora_EstoqueLocal(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("Pedido_TransportadoraID_EstoqueLocal").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function FormaPagamento_EstoqueLocal(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("Pedido_FormaPagamentoID_EstoqueLocal").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function Financiamento_EstoqueLocal(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("Pedido_FinanciamentoID_EstoqueLocal").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function Valida_EstoqueOperador(source, arguments)
	{
		arguments.IsValid = true;

		if (document.getElementById("Pedido_Frete_EstoqueOperador").value == "")
		{
			arguments.IsValid = false;
		}
		if (document.getElementById("Pedido_TransportadoraID_EstoqueOperador").value == "")
		{
			arguments.IsValid = false;
		}
		if (document.getElementById("Pedido_FormaPagamentoID_EstoqueOperador").value == "")
		{
			arguments.IsValid = false;
		}
		if (document.getElementById("Pedido_FinanciamentoID_EstoqueOperador").value == "")
		{
			arguments.IsValid = false;
		}
		try {
		    if (document.getElementById("RetPortador_EstoqueOperador").value == "")
		    {
			    arguments.IsValid = false;
		    }
		    
		    if (document.getElementById("RetDocPortador_EstoqueOperador").value == "")
		    {
			    arguments.IsValid = false;
		    }
		    
		    if (document.getElementById("RetDocFederalPortador_EstoqueOperador").value == "")
		    {
			    arguments.IsValid = false;
		    }
		    else
		    {
			    arguments.IsValid = validaCPF(document.getElementById("RetDocFederalPortador_EstoqueOperador").value);
		    }
		    
		} catch(err) {}
	}

	function Frete_EstoqueOperador(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("Pedido_Frete_EstoqueOperador").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function Transportadora_EstoqueOperador(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("Pedido_TransportadoraID_EstoqueOperador").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function FormaPagamento_EstoqueOperador(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("Pedido_FormaPagamentoID_EstoqueOperador").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function Financiamento_EstoqueOperador(source, arguments)
	{
		arguments.IsValid = false;

		if (document.getElementById("Pedido_FinanciamentoID_EstoqueOperador").value != "")
		{
			arguments.IsValid = true;
		}
	}

	function Valida_Portador_Nome_EstoqueLocal(source, arguments)
	{
		arguments.IsValid = true;

	    if (document.getElementById("RetPortador_EstoqueLocal").value == "")
	    {
		    arguments.IsValid = false;
	    }
	}
	
    function Valida_Portador_Documento_EstoqueLocal(source, arguments)
	{
		arguments.IsValid = true;

	    if (document.getElementById("RetDocPortador_EstoqueLocal").value == "")
	    {
		    arguments.IsValid = false;
	    }
	}
	
    function Valida_Portador_DocumentoFed_EstoqueLocal(source, arguments)
	{
		arguments.IsValid = true;

	    if (document.getElementById("RetDocFederalPortador_EstoqueLocal").value == "")
	    {
		    arguments.IsValid = false;
	    }
	    else
	    {
	        arguments.IsValid = validaCPF(document.getElementById("RetDocFederalPortador_EstoqueLocal").value);
	    }
	}
	
	function Valida_Portador_Nome_EstoqueOperador(source, arguments)
	{
		arguments.IsValid = true;

	    if (document.getElementById("RetPortador_EstoqueOperador").value == "")
	    {
		    arguments.IsValid = false;
	    }
	}
	
    function Valida_Portador_Documento_EstoqueOperador(source, arguments)
	{
		arguments.IsValid = true;

	    if (document.getElementById("RetDocPortador_EstoqueOperador").value == "")
	    {
		    arguments.IsValid = false;
	    }
	}
	
    function Valida_Portador_DocumentoFed_EstoqueOperador(source, arguments)
	{
		arguments.IsValid = true;

	    if (document.getElementById("RetDocFederalPortador_EstoqueOperador").value == "")
	    {
		    arguments.IsValid = false;
	    }
	    else
	    {
	        arguments.IsValid = validaCPF(document.getElementById("RetDocFederalPortador_EstoqueOperador").value);
	    }
	}
	
	function formatValue(valor) 
	{
		if(valor.indexOf(".") != -1)
		{
			valor = valor.replace(".", ",");
		}
		else
		{
			valor = valor+",00";
		}
		return valor; 
	}

	function Toggle(item) 
	{
		Collapse();

		obj=document.getElementById(item);
		visible=(obj.style.display!="none")
		cel=document.getElementById("c" + item);

		if (visible) 
		{
			obj.style.display="none";
			try
			{
				cel.className = 'corDestaqueItem';
				keyAct=document.getElementById("x" + item);
				keyAct.innerHTML="<img src='"+RetornaURLImg()+"/folder.gif' width='16' height='16' hspace='4' vspace='0' border='0'>";
			}
			catch(err)
			{
			}
		} 
		else 
		{
			obj.style.display="block";
			try
			{
				//cel.style.background='#084200';
				cel.className = 'corDestaqueItemSel';
				keyAct=document.getElementById("x" + item);
				keyAct.innerHTML="<img src='"+RetornaURLImg()+"/textfolder.gif' width='16' height='16' hspace='4' vspace='0' border='0'>";
			}
			catch(err)
			{
			}
		}
	}
	

	function TogglePedido(item) 
	{
		CollapsePedido(item);

		obj = document.getElementById("fin" + item.substr(3));

		if (obj)
		{
			visible = (obj.style.display!="none")
			if (visible) 
			{
				obj.style.display="none";
			} 
			else 
			{
				obj.style.display="block";
			}
		}
	}

	function Expand() 
	{
		divs=document.getElementsByTagName("DIV");
		for (i=0;i<divs.length;i++) 
		{
			keyExp=document.getElementById("x" + divs[i].id);
			celExp=document.getElementById("c" + divs[i].id);
			if (keyExp)
			{
				divs[i].style.display="block";
				celExp.style.background='#084200';
				keyExp.innerHTML="<img src='"+RetornaURLImg()+"/textfolder.gif' width='16' height='16' hspace='4' vspace='0' border='0'>";
			}
		}
	}

	function Collapse()
	{
		divs=document.getElementsByTagName("DIV");
		for (i=0;i<divs.length;i++) 
		{
			celCol=document.getElementById("c" + divs[i].id);
			if (celCol)
			{
				divs[i].style.display="none";
				try
				{
					//celCol.style.background='#7ba56b';
					celCol.className = 'corDestaqueItem';
				}
				catch(err)
				{
				}
			}
		}
	}

	function CollapsePedido(item)
	{
		divs = document.getElementsByTagName("DIV");
		for (i=0;i<divs.length;i++) 
		{
			if (divs[i].id.substr(0,3) == "fin")
			{
				keyCol=document.getElementById(divs[i].id);
				if (keyCol)
				{
					if (divs[i].id.substr(divs[i].id.length-8) == item.substr(divs[i].id.length-8))
					{
						divs[i].style.display="none";
					}
				}
			}
		}
	}

	function ChangeImage_(numero){
	
		thumbs = new Array(4);
		thumbs[1] = document.imgDetalhe2Produto;
		thumbs[2] = document.imgDetalhe3Produto;
		thumbs[3] = document.imgDetalhe4Produto;
		thumbs[4] = document.imgDetalhe5Produto;
		aux = document.imgDetalhe1Produto.src;
		document.imgDetalhe1Produto.src = thumbs[numero].src;
		thumbs[numero].src = aux;
	}

	function ChangeImage(imagem) 
	{
		aux = document.imgDetalhe1Produto.src;
		document.imgDetalhe1Produto.src = imagem.src;
		imagem.src = aux;
	}

	function ColocaFocoEm(NomeBtn, e) 
	{ 
		try
		{
			var key;  
			 
			if (window.event) 
			{    
				key = event.keyCode;   
			}
			else
			{     
				key = e.which; 
			}
			
			if (key == 13)
			{
				document.getElementById(NomeBtn).click();
				return false;
			} else {
			    return true;
			}
		}     
		catch(err)
		{
			alert(err);
		}
	}

	function ColocaFocoCesta(campo, e) 
	{ 
		try
		{
			var key;  
			 
			if (window.event) 
			{    
				key = event.keyCode;   
			}
			else
			{     
				key = e.which; 
			}
  
			if (key == 13)
			{
				campo.blur();
				return false;
			}
		}     
		catch(err)
		{
			alert(err);
		}
	}

	function TrocaImagem(name, visibilidade)
	{
		try
		{
			document.getElementById(name).style.visibility = visibilidade;
		}
		catch(err)
		{
		}
	}

	function FecharPedido(nome_empresa)
	{
		rad_sim = document.getElementById("radRetira_sim");
		rad_nao = document.getElementById("radRetira_nao");

		if (rad_sim && rad_nao)
		{
			if(confirm('Você tem certeza que deseja ir para o fechamento de pedido?\nOpção de entrega : ' + (rad_sim.checked ? 'Retirar produto(s) na ' + nome_empresa + '.' : 'Entregar via transportadora a escolher.')))
			{
				return true;			
			}
		}

		return false;	
	}

	function TipoCadastro(tipo)
	{
		document.getElementById("CadastroTipo").value = tipo;
	}

	function mask(str,textbox,loc,delim,limit)
	{
		var locs = loc.split(',');
		
		for (var i = 0; i <= locs.length; i++)
		{
			for (var k = 0; k <= str.length; k++)
			{
				if (k == locs[i])
				{
					if (str.substring(k, k+1) != delim)
					{
						str = str.substring(0,k) + delim + str.substring(k,str.length)
					}
				}
			}
		}
		
		textbox.value = str.substring(0,limit)
		
		if (textbox.value.length == limit)
		{
			Mostra(textbox, limit);
		}
	}

	function Mostra(quem, tammax) 
	{
		VerifiqueTAB=true;

		if (quem.value.length == tammax && VerifiqueTAB)
		{
			var i=0,j=0, indice=-1;
			
			for (i=0; i<document.forms.length; i++) 
			{
				for (j=0; j<document.forms[i].elements.length; j++) 
				{
					if (document.forms[i].elements[j].name == quem.name) 
					{
						indice=i;
						break;
					}
				}
				if (indice != -1)
				{
					break;
				}
			}
			for (i=0; i<=document.forms[indice].elements.length; i++) 
			{
				if (document.forms[indice].elements[i].name == quem.name) 
				{
					try
					{
						while ((document.forms[indice].elements[(i+1)].type == "hidden") && (i < document.forms[indice].elements.length)) 
						{
							i++;
						}
						document.forms[indice].elements[(i+1)].focus();
					}
					catch(err)
					{
					}
					
					VerifiqueTAB=false;
					break;
				}
			}
		}
	}

	function SomenteNumeroFirefox(e) 
	{ 
	  var key //= (window.event) ? event.keyCode : e.which;   
	  
	  if (window.event)     
		key = event.keyCode   
	  else     
		key = e.which   // Was key that was pressed a numeric character (0-9) or backspace (8)?   
		
	  if ( key > 47 && key < 58 || key == 8 )     
		return; // if so, do nothing   
	  else // otherwise, discard character     
		if (window.event) //IE       
			window.event.returnValue = null;     
		else //Firefox       
			e.preventDefault();
	}  

	function Mascara(textBox, mask) 
	{
		 var i      = textBox.value.length;
		 var saida  = mask.substring(0,1);
		 var texto  = mask.substring(i);
		 
		 if (texto.substring(0,1) != saida) 
		 {
			  textBox.value += texto.substring(0,1);
		 }
	}

	function HabilitaDesabilita(codigo)
	{
		if (codigo=='8')
		{
			document.Form1.txtNumPedido.disabled=false
			document.Form1.txtMesIni.disabled=true
			document.Form1.txtAnoIni.disabled=true
			document.Form1.txtMesFim.disabled=true
			document.Form1.txtAnoFim.disabled=true
			document.Form1.txtNumPedido.focus()
		}
		else if (codigo=='9')
		{
			document.Form1.txtNumPedido.disabled=true
			document.Form1.txtMesIni.disabled=false
			document.Form1.txtAnoIni.disabled=false
			document.Form1.txtMesFim.disabled=false
			document.Form1.txtAnoFim.disabled=false
			document.Form1.txtMesIni.focus()
		}
		else
		{
			document.Form1.txtNumPedido.disabled=true
			document.Form1.txtMesIni.disabled=true
			document.Form1.txtAnoIni.disabled=true
			document.Form1.txtMesFim.disabled=true
			document.Form1.txtAnoFim.disabled=true
		}
	}

	function GuardaFormatoPedido(campo)
	{
		if (campo)
		{
			if (campo.value != "")
			{
				for (j=0; j<document.forms[0].elements.length; j++) 
				{
					document.forms[0].elements[j].disabled = true;
				}
				document.getElementById("ibtProsseguir").style.display="none"
				TrocaImagem("loading", "visible");

				index.CarregaFormatoPedido(campo.value, callback_GuardaFormatoPedido)
			}
		}
	}

	function callback_GuardaFormatoPedido(res)
	{
		if (!res.error)	
		{
			document.getElementById("FormatoFiltro").value = res.value;
		}

		for (j=0; j<document.forms[0].elements.length; j++) 
		{
			document.forms[0].elements[j].disabled = false;
		}
		document.getElementById("ibtProsseguir").style.display="block"
		TrocaImagem("loading", "hidden");
	}

	function GuardaFormatoTitulos(campo)
	{
		if (campo)
		{
			if (campo.value != "")
			{
				for (j=0; j<document.forms[0].elements.length; j++) 
				{
					document.forms[0].elements[j].disabled = true;
				}
				document.getElementById("ibtProsseguir").style.display="none"
				TrocaImagem("loading", "visible");

				index.CarregaFormatoTitulos(campo.value, callback_GuardaFormatoTitulos)
			}
		}
	}

	function callback_GuardaFormatoTitulos(res)
	{
		if (!res.error)	
		{
			document.getElementById("FormatoFiltro").value = res.value;
		}

		for (j=0; j<document.forms[0].elements.length; j++) 
		{
			document.forms[0].elements[j].disabled = false;
		}
		document.getElementById("ibtProsseguir").style.display="block"
		TrocaImagem("loading", "hidden");
	}

	function CarregaLimitesCredito(campo)
	{
		for (j=0; j<document.forms[0].elements.length; j++) 
		{
			document.forms[0].elements[j].disabled = true;
		}
		document.getElementById("ibtProsseguir").style.display="none"
		TrocaImagem("loading", "visible");

		document.getElementById("txtLimiteCredito").value = "";
		document.getElementById("txtSaldoAnterior").value = "";
		document.getElementById("txtSaldoCredito").value = "";
		document.getElementById("txtTaxaDolar").value = "";

		if (campo)
		{
			if (campo.value != "")
			{
				index.CarregaLimites(campo.value, callback_CarregaLimitesCredito)
			}
		}
	}

	function callback_CarregaLimitesCredito(res)
	{
		if (res.error)
		{
			alert(res.error);
		}		

		if (res.value[0])
		{
			document.getElementById("txtLimiteCredito").value = res.value[0];
			document.getElementById("txtSaldoAnterior").value = res.value[1];
			document.getElementById("txtSaldoCredito").value = res.value[2];
			document.getElementById("txtTaxaDolar").value = res.value[3];
		}

		for (j=0; j<document.forms[0].elements.length; j++) 
		{
			document.forms[0].elements[j].disabled = false;
		}
		document.getElementById("ibtProsseguir").style.display="block"
		TrocaImagem("loading", "hidden");
	}

	function validaCNPJ(numero) 
	{
		retorno = true;
		
		if (numero == "")
		{
			retorno = false;
		}
		else
		{
			CNPJ = numero;
			
			erro = new String;
			if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! "; 
			if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
			if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! ";
			}
			//substituir os caracteres que não são números
			if(document.layers && parseInt(navigator.appVersion) == 4){
					x = CNPJ.substring(0,2);
					x += CNPJ. substring (3,6);
					x += CNPJ. substring (7,10);
					x += CNPJ. substring (11,15);
					x += CNPJ. substring (16,18);
					CNPJ = x; 
			} else {
					CNPJ = CNPJ. replace (".","");
					CNPJ = CNPJ. replace (".","");
					CNPJ = CNPJ. replace ("-","");
					CNPJ = CNPJ. replace ("/","");
			}
			var nonNumbers = /\D/;
			if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! "; 
			var a = [];
			var b = new Number;
			var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
			for (i=0; i<12; i++)
			{
					a[i] = CNPJ.charAt(i);
					b += a[i] * c[i+1];
			}
			if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
			b = 0;
			for (y=0; y<13; y++) {
					b += (a[y] * c[y]); 
			}
			if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
			if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
					erro +="Dígito verificador com problema!";
			}
			if (erro.length > 0){
				retorno = false;
			}
		}

		return retorno;
	}

	function validaCPF(numero) 
	{
		retorno = true;
		
		if (numero == "")
		{
			retorno = false;
		}
		else
		{
			cpf = numero;
			cpf = cpf.replace(".", "");
			cpf = cpf.replace(".", "");
			cpf = cpf.replace(".", "");
			cpf = cpf.replace(",", "");
			cpf = cpf.replace("-", "");
			cpf = cpf.replace(" ", "");
	
			erro = new String;
					if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n"; 
					var nonNumbers = /\D/;
					if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n"; 
					if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
							erro += "Numero de CPF invalido!"
			}
			var a = [];
			var b = new Number;
			var c = 11;
			for (i=0; i<11; i++){
					a[i] = cpf.charAt(i);
					if (i < 9) b += (a[i] * --c);
			}
			if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
			b = 0;
			c = 11;
			for (y=0; y<10; y++) b += (a[y] * c--); 
			if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
			if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
					erro +="Digito verificador com problema!";
			}
			if (erro.length > 0){
					//alert(erro);
					retorno = false;
			}
		}    
		return retorno;
	}
	
	function ValidaLogin()
	{
		var msg = "";
		if (document.getElementById("RODA_txtSenha").value == "")
		{
			document.getElementById("RODA_rfvSenha").style.display = "block";
			msg = "O Campo Senha é obrigatório!\n";
		}
		else
		{
			document.getElementById("RODA_rfvSenha").style.display = "none";
		}

		if (document.getElementById("RODA_txtLogin").value == "")
		{
			document.getElementById("RODA_rfvLogin").style.display = "block";
			msg += "O Campo ID é obrigatório!";
		}
		else
		{
			document.getElementById("RODA_rfvLogin").style.display = "none";
		}

		if (msg != "")
		{
			alert(msg);
			return false;
		}

		return true;
	}
	
	function ComprarProdutos(EmpresaId, FinalidadeID, CFOPID, ProdutoID, ProdutoCrossID)
	{
        var qtdd    = '';
        var url     = '';
        var msg     = '';

		if (!isNaN(ProdutoID) && !isNaN(ProdutoCrossID))
		{
		    obj_qtdd = document.getElementById('qtdd_' + EmpresaId + '_' + FinalidadeID + '_' + CFOPID + '_' + ProdutoID + '_' + ProdutoCrossID);
		    if (obj_qtdd != null) {
		        qtdd = obj_qtdd.value;
		        if (isNaN(qtdd)) qtdd = '1';
		    } else {
		        qtdd = '1';
		    }
		    
		    if (qtdd > 200) {
		        window.alert('Compra máxima possível é de 200 unidades !');
		        return;
		    }
		
		    url = 'Comprar.aspx?EmpresaID=' + EmpresaId + '&FinalidadeID=' + FinalidadeID + '&CFOPID=' + CFOPID + '&Qtde=' + qtdd + '&ProdutoID=' + ProdutoID;
		    if (ProdutoCrossID != 0) {
		        url += '&ProdutoCrossID=' + ProdutoCrossID;
		        
		        msg = qtdd + ' unidade(s) dos produtos ' + ProdutoID + ' e ' + ProdutoCrossID + ' foram inserida(s) no carrinho.'

            } else {
                msg = qtdd + ' unidade(s) do produto ' + ProdutoID + ' foram inserida(s) no carrinho.'
            }
		    msg += '\n\nDeseja comprar mais produtos?';

		    //if (confirm(msg)) {
		    if (newConfirm('Carrinho de Compra', msg, 1, 1, 0)) {
                url += '&SegueCarrinho=0';
		    } else {
		        url += '&SegueCarrinho=1';
		    }

			location.href = url;
		} else {
            window.alert('Produtos Inválidos');
		}
	}
	
	function fMaskDate(src)
    {
	    if (((event.keyCode) > 47) && ((event.keyCode) < 58))
	    {
		    mask = '##/##/####';

		    var i = src.value.length;
		    var saida = mask.substring(0,1);
		    var texto = mask.substring(i);
		    if (texto.substring(0,1) != saida)  src.value += texto.substring(0,1);
    			
		    return(true)
	    }
	    else return(false)
    }

