
/*
Nome da Função: AdicionarCarrinho(id_produto, id_loja)
	Parametro id_produto: Nro. de identificação do produto
	Parametro id_loja: Nro. de identificação da loja
	Parametro opcao_carrinho: valor do campo hidden ou selectbox
	Parametro opcao_carrinho_2: valor do campo hidden ou selectbox
Descrição da Função: Adicionar o produto no carrinho de compras da loja
Desenvolvido por: Joao Paulo Wodiani
Data: 13/09/2007
*/

function AdicionarCarrinho(id_produto, id_loja, opcao_carrinho, opcao_carrinho_2)
{
	document.frmPost.idproduto.value = id_produto;
	
	if(eval(opcao_carrinho)=="")
	{
		alert("Por favor, selecione a opção do produto para continuar comprando!");
	}
	else
	{
		
		if(eval(opcao_carrinho_2)=="")
		{
			alert("Por favor, selecione a segunda opção do produto para continuar comprando!");
		}else{
		
			document.frmPost.idproduto_detalhe.value = 0;
			document.frmPost.idproduto_detalhe_2.value = 0;
			document.frmPost.idloja.value = id_loja;
			document.frmPost.frmAcao.value = 'A';
			
			//document.frmPost.action = 'adiciona_carrinho.php';
			document.frmPost.submit();
		}
	}
}

/**
 * Adicionar o produto no carrinho de compras, com a opção de quantidade.
 *
 * @param integer $id_produto ID do produto
 * @param integer $id_loja ID da loja
 * @param string $opcao_carrinho Valor do campo hidden ou combobox
 * @param string $opcao_carrinho_2 Valor do campo hidden ou combobox
 * @param string $quantidade Quantidade do produto
 * @return void
 *
 * @author João Pedro <joao.pedro@ecompleto.com.br>
 * @since 12/02/2010 (br)
 */
function newAdicionarCarrinho(id_produto, id_loja, opcao_carrinho, opcao_carrinho_2, quantidade) {

	document.frmPost.idproduto.value = id_produto;
	
	if(eval(opcao_carrinho)=="")
	{
		alert("Por favor, selecione a opção do produto para continuar comprando!");
	}
	else
	{
		
		if(eval(opcao_carrinho_2)=="")
		{
			alert("Por favor, selecione a segunda opção do produto para continuar comprando!");
		}else{
			
			if(quantidade==""){
				quantidade=1;
			}
		
			document.frmPost.idproduto_detalhe.value = 0;
			document.frmPost.idproduto_detalhe_2.value = 0;
			document.frmPost.idloja.value = id_loja;
			document.frmPost.qtde.value = quantidade;
			document.frmPost.frmAcao.value = 'A';
			
			document.frmPost.submit();
			
		}
	}
	
}


/*
Nome da Função: FecharPedido(id_basket, id_loja)
	Parametro id_basket: Nro. de identificação do carrinho de compras
	Parametro id_loja: Nro. de identificação da loja	
Descrição da Função: Fechar o pedido do cliente
Desenvolvido por: Joao Paulo Wodiani
Data: 14/05/2007
*/
function FecharPedido(id_loja)
{
	document.frmPost.idloja.value = id_loja;
	//carregando forma entrega
	obj = document.basket.forma_entrega;
	for(i=1;i<obj.length;i++)
	{
		if(obj[i].checked)
		{
			document.frmPost.forma_entrega.value = obj[i].value;			
		}
	}
	
	if(document.frmPost.forma_entrega.value=="")
	{
		alert("Digite o Cep e Selecione a Forma de Entrega do seu pedido!");
	}
	else
	{
		
		document.frmPost.frmAcao.value = 'FP';
		
		document.frmPost.action = 'adiciona_carrinho.php';
		document.frmPost.submit();
	}
}


/*
Nome da Função: AtualizarCarrinho(id_produto, id_loja)
	Parametro id_loja: Nro. de identificação da loja
Descrição da Função: Atualizar a quantidade de produtos no Carrinho de compras
Desenvolvido por: Joao Paulo Wodiani
Data: 12/05/2007
*/
function AtualizarCarrinho(id_loja, formulario)
{
	
	if(document.frmPost.itens.value>0)
	{
		
		fnc_AtualizaCarrinho(id_loja, formulario);
		
		document.frmPost.frmAcao.value = 'U';
		document.frmPost.action = 'adiciona_carrinho.php';
		document.frmPost.submit();
	}
	else
	{
		alert("Não existe nenhum item no seu carrinho de compras!");
	}
}


/*
Nome da Função: RemoverCarrinho(id_produto, id_loja)
	Parametro id_produto: Nro. de identificação do produto
	Parametro id_produto_detalhe: Nro. de identificação do detalhe de produto
	Parametro id_produto_detalhe_2: Nro. de identificação do detalhe de produto	
	Parametro id_loja: Nro. de identificação da loja
Descrição da Função: Remover o produto do carrinho de compras da loja
Desenvolvido por: Joao Paulo Wodiani
Data: 12/05/2007
*/
function RemoverCarrinho(id_produto, id_produto_detalhe, id_produto_detalhe_2, id_loja)
{
	document.frmPost.idproduto.value = id_produto;
	document.frmPost.idproduto_detalhe.value = id_produto_detalhe;
	document.frmPost.idproduto_detalhe_2.value = id_produto_detalhe_2;
	document.frmPost.idloja.value = id_loja;
	document.frmPost.frmAcao.value = 'R';
	
	document.frmPost.action = 'adiciona_carrinho.php';
	document.frmPost.submit();
}

function AtualizarEmbalagemPresente(id_produto, id_loja)
{
	document.frmPost.idproduto.value = id_produto;
	document.frmPost.idloja.value = id_loja;
	document.frmPost.frmAcao.value = 'EP';	
	document.frmPost.action = 'adiciona_carrinho.php';
	document.frmPost.submit();
}

/*
Nome da Função: LimparCarrinho(id_loja)
	Parametro id_loja: Nro. de identificação da loja
Descrição da Função: Remover todos os produtos do carrinho de compras da loja
Desenvolvido por: Joao Paulo Wodiani
Data: 13/05/2007
*/
function LimparCarrinho(id_loja)
{
	document.frmPost.idloja.value = id_loja;
	document.frmPost.frmAcao.value = 'LT';
	
	document.frmPost.action = 'adiciona_carrinho.php';
	document.frmPost.submit();
}


/*
Nome da Função: CalcularFrete(cep)
	Parametro cep1: Prefixo Cep com 5 caracteres numéricos
	Parametro cep2: Prefixo Cep com 3 caracteres numéricos
	Parametro formulario: nome do formulario que possui os campos origem ex. 'document.basket'
Descrição da Função: Calcular Frete do endereço da loja para o endereço do cliente
Desenvolvido por: Joao Paulo Wodiani
Data: 13/05/2007
*/
function CalcularFrete(id_loja, formulario)
{

	erro = 0;

	if(document.basket.cep1.value.length<5)
	{
		alert("Cep incompleto!");
		document.basket.cep1.focus();
		erro = 1;
	}
	if(document.basket.cep2.value.length<3 && erro == 0)
	{
		alert("Cep incompleto!");
		document.basket.cep2.focus();
		erro = 1;
	}

	if(erro == 0)
	{

		if(document.frmPost.itens.value>0)
		{
			fnc_AtualizaCarrinho(id_loja,formulario);
		}

		document.frmPost.cep.value = document.basket.cep1.value + document.basket.cep2.value;
		document.frmPost.frmAcao.value = 'CF';
		document.frmPost.action = 'adiciona_carrinho.php';
		document.frmPost.submit();
	}
}


/*
Nome da Função: IdentificarCadastro()
Descrição da Função: Verifica se o cadastro é novo ou já existente
Desenvolvido por: Joao Paulo Wodiani
Data: 16/06/2007
*/
function IdentificarCadastro(frm)
{

	if(frm.email.value=="")
	{
		alert("Por favor, informe o seu e-mail!");
		frm.email.focus();
		return(false);
	}else
	{
		if(!ValidaEmail(frm.email.value))
		{
			alert("E-mail inválido, verifique!");
			frm.email.value = "";
			frm.email.focus();
			return(false);
		}
	}

	if(frm.meu_cadastro[1].checked)
	{
		if(frm.senha.value=="")
		{
			alert("Por favor, informe a sua senha!");
			frm.senha.focus();
			return(false);
		}
	}
	
}



/*
Nome da Função: createXMLHTTP()
Descrição da Função: Função necessária para metodos AJAX
Desenvolvido por: ------
Data: ------
*/
function createXMLHTTP() {
	try {
		var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
		var xmlhttp = false;
		for (var i=0; i < arrSignatures.length; i++) {
			try {	
				var oRequest = new ActiveXObject(arrSignatures[i]);
				xmlhttp = oRequest;
				break;
			} catch (oError) {
			}
		}
		if(!xmlhttp && typeof XMLHttpRequest != 'undefined')
		{
			//PARA O FIREFOX
			xmlhttp = new XMLHttpRequest();
		}
		
		return xmlhttp;
	} catch(e){ alert(e); }
}

/*
Nome da Função: URLDecode(psEncodeString)
Descrição da Função: Decodifica um codigo encapsulado em AJAX
Desenvolvido por: ------
Data: ------
*/
function URLDecode(psEncodeString) {
	var lsRegExp = /\+/g;
	return unescape(String(psEncodeString).replace(lsRegExp, " "));
}

/*
Nome da Função: fu_rollover(foto, caminho)
Descrição da Função: Exibir foto media do produtos
Desenvolvido por: Joao Paulo Wodiani
Data: 08/05/2007
*/
function fu_rollover(name, link_imagem) {
        if (document.images) {
                document.images[name].src = link_imagem;
        }
}


/*
Nome da Função: FloatValidate(objeto, aceitaVirgula, e)
Descrição da Função: Proibir a digitação de valores não numericos em um campo text, memo
Desenvolvido por: Joao Paulo Wodiani
Data: 12/05/2007
*/
function FloatValidate(objeto, aceitaVirgula, e)
{
	//Console.log("t_");
	var key;
	var keychar;
	var keydecimal;
	var decimal=0;
	
	if(!e.keyCode)
	{
		key = e.which;
	}
	else
	{
		key = e.keyCode;
	}
	//}
	
	keychar = String.fromCharCode(key).toLowerCase();
	

	if(key==8 || key==9 || key==13 || key==35 || key==36 || key==37 || key==39 || key==46 || key==116)
	{
		if(!e.keyCode && keychar==".")
		{
			return false;
		}
		else
			return true;
	}
	
	for(var i=0;i<objeto.length;i++)
	{
		//alert(objeto.substr(i,1));
		if(objeto.substr(i,1)==",")
		{
			decimal = i;
		}
	}
	if(("0123456789").indexOf(keychar) > -1)
	{
		if(decimal == 0)
		{
			return true;
		}
		else
		{
			if(decimal+2>=objeto.length)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	else if((keychar==",") && (aceitaVirgula==true))
	{
		return (decimal == 0)
	}
	else
	{
		return false;
	}
}

/*
Nome da Função: validaCNPJ(valor)
  Parametro valor: contem o valor que vai ser validado
  Retorno: booleano
Descrição da Função: funcao para validar se o CNPJ e valido
Desenvolvido por: Joao Paulo Wodiani
Data: 08/06/2008
 */
function validaCNPJ(valor) {
	try {
		var CNPJ = valor;
		if (CNPJ.length > 18)
			CNPJ = CNPJ.substring(1, CNPJ.length);
		
	    erro = new String;
	    if (CNPJ.length < 18) erro += "é necessário 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 nao sao numeros
	    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 ("/","");
	    }
		if(CNPJ.length==14) erro = "";
			
	    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 do CNPJ.";
	    }
		if (erro.length > 0){
	        return false;
		}
		return true;
	} catch (e) {}
}
/*
Nome da Função: ValidaCPF(valor)
  Parametro valor: contem o valor que vai ser validado
  Retorno: booleano
Descrição da Função: funcao para validar se o CPF e valido
Desenvolvido por: Joao Paulo Wodiani
Data: 08/06/2008
 */
function ValidaCPF(valor){
	try {

		s = valor;
		if (isNaN(s)) {
			return false;
		}
		
		var i;
		var c = s.substr(0,9);
		var dv = s.substr(9,2);
		var d1 = 0;
		for (i = 0; i < 9; i++) {
			d1 += c.charAt(i)*(10-i);
		}
		if (d1 == 0){
			return false;
		}
	    d1 = 11 - (d1 % 11);
	    if (d1 > 9) d1 = 0;         
		if (dv.charAt(0) != d1) {
			return false;         
		}
		d1 *= 2;
		for (i = 0; i < 9; i++) {
			d1 += c.charAt(i)*(11-i);
		}
		d1 = 11 - (d1 % 11);
		if (d1 > 9) d1 = 0;
		if (dv.charAt(1) != d1) {
			return false;
		}
	    return true;
	} catch (e) {}
} 


/*
Nome da Função: ValidaData(data)
  Parametro data: contem a data a ser validada
Descrição da Função: funcao para validar se a data e valida
Desenvolvido por: Joao Paulo Wodiani
Data: 08/06/2008
 */
function ValidaData (data) { 
	try {
		dia = (data.substring(0,2)); 
		mes = (data.substring(3,5)); 
		ano = (data.substring(6,10)); 
	
		situacao = true; 
		// verifica o dia valido para cada mes 
		if (isNaN(dia) || (dia < 01)||(dia < 01 || dia > 30) && (  mes == 04 || mes == 06 || mes == 9 || mes == 11 ) || dia > 31) { 
			situacao = false; 
		}
		// verifica se o mes e valido 
		if (isNaN(mes) || mes < 01 || mes > 12 ) { 
			situacao = false; 
		}
		if (isNaN(ano) ) { 
			situacao = false; 
		}	
		// verifica se e ano bissexto 
		if (mes == 2 && ( dia < 01 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4) ))) { 
			situacao = false; 
		} 
		if (data.value == "") { 
			situacao = false; 
		} 
		if (dia.toLowerCase() == "xx" && mes.toLowerCase() == "xx" && ano.toLowerCase() == "xxxx") {
			situacao = true;
		}
		return situacao;
	} catch (e) {}
} 

/*
Nome da Função: ValidaEmail(email)
  Parametro email: string que contem o email a ser validado
  Retorno: booleano
Descrição da Função: funcao para verificar se o email digitado esta correto
Desenvolvido por: Joao Paulo Wodiani
Data: 08/06/2008
*/
function ValidaEmail(email) {
	try {
		er = /^[0-9a-z_][0-9a-zA-Z._-]+@[a-z0-9][-.a-z0-9]+[.][a-z]+$/;
		if (!er.test(email)) {
			return false;
		}
		return true;
	} catch (e) {}
}

/*
Nome da Função: pulacampo(valor, qtde_caracteres, proximocampo)
Descrição da Função: Pular para o proximo campo, assim que o campo atual estiver totalmente preenchido
Desenvolvido por: Joao Paulo Wodiani
Data: 12/05/2007
*/
function pulacampo(valor, qtde_caracteres, formulario, proximocampo)
{
	f = formulario;
	
	if(valor.length==qtde_caracteres)
	{
		eval("document."+f+"."+proximocampo+".focus()");
	}
}




/*
Nome da Função: ValidarLogon(formulario)
	Parametro formulario: Objeto formulário
Descrição da Função: Validar o preenchimento dos campos de Logon
Desenvolvido por: Joao Paulo Wodiani
Data: 15/05/2007
*/
function ValidarLogon(formulario)
{
	f = formulario;
	
	if(f.email.value=="")
	{
		alert("Por favor, preencha o campo e-mail!");
		f.email.focus();
		return(false);
	}
	
	if(f.senha.value=="")
	{
		alert("Por favor, preencha o campo senha!");
		f.senha.focus();
		return(false);
	}
	
}



/*
Nome da Função: ValidarEmailCadastrar(formulario)
	Parametro formulario: Objeto formulário
Descrição da Função: Validar o preenchimento do campo email para cadastramento do cliente
Desenvolvido por: Joao Paulo Wodiani
Data: 15/05/2007
*/
function ValidarEmailCadastrar(formulario)
{
	f = formulario;
	
	if(f.email.value=="")
	{
		alert("Por favor, preencha o campo e-mail!");
		f.email.focus();
		return(false);
	}
	if(!ValidaEmail(f.email.value))
	{
		alert("Por favor, preencha corretamente o e-mail!");
		f.email.focus();
		return(false);
	}
}

/*
Nome da Função: CarregaCidade(v, id_el, id_inicial = 0)
	Parametro v: valor a ser passado para a pagina ajax
Descrição da Função: Carregar as cidades filtradas pelo estado
Desenvolvido por: Joao Paulo Wodiani
Data: 08/06/2008
*/
function CarregaCidade(v, id_el, id_inicial)
{
	try {
		if (v!="" && v!="0") {
			RemoveItensSelect(id_el);
			var o = new Option("- Selecione a Cidade -" ,"" , false, false);
			document.getElementById(id_el).options[0] = o;
			
			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", 'carregacidades.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function() {
				if (oHTTPRequest.readyState==4){
					RemoveItensSelect(id_el);
					var o = new Option("- Selecione a Cidade -" ,"" , false, false);
					document.getElementById(id_el).options[0] = o;
					v = oHTTPRequest.responseXML.getElementsByTagName('id'); //VALOR DO ID DA CIDADE
					t = oHTTPRequest.responseXML.getElementsByTagName('nome'); //VALOR DO NOME DA CIDADE
					for (i = 0 ; i < v.length ; i++) {
						var o = new Option(URLDecode(t[i].firstChild.nodeValue),v[i].firstChild.nodeValue, false, false);
						document.getElementById(id_el).options[document.getElementById(id_el).options.length] = o;
					}
					
					//carregando cidade
					document.getElementById(id_el).value = id_inicial;
					
				}
				else
				{
					if (document.getElementById(id_el).options[0].text=="carregando.")
						document.getElementById(id_el).options[0].text = "carregando..";
					else if (document.getElementById(id_el).options[0].text == "carregando..")
						document.getElementById(id_el).options[0].text = "carregando...";
					else
						document.getElementById(id_el).options[0].text = "carregando.";
				}
			}
			oHTTPRequest.send("id=" + v);
		}
	} catch(e) { alert(e); }
}

/*
Nome da Função: RemoveItensSelect(id)
	Parametro id: id do elemento
Descrição da Função: remover os options de um elemento select
Desenvolvido por: Joao Paulo Wodiani
Data: 08/06/2008
 */
function RemoveItensSelect(id)
{
	try {
		while (document.getElementById(id).options.length > 0) {
			document.getElementById(id).remove(document.getElementById(id).options.length-1);
		}
	} catch (e) {}
}



/*
Nome da Função: validarEndereco(formulario)
	Parametro formulario: objeto do formulario que possui os campos
Descrição da Função: Validar o preenchimento dos campos de Endereço do Cliente 
Desenvolvido por: Joao Paulo Wodiani
Data: 16/05/2007
*/
function validarEndereco(formulario)
{
	f = formulario;
	
	//start validacao
	if(f.cep1.value=="")
	{
		alert("Por favor, preencha o CEP!");
		f.cep1.focus();
		return(false);
	}
	else
	{
		if(f.cep1.value.length<5)
		{
			alert("O CEP está incompleto, verifique!");
			f.cep1.focus();
			return(false);
		}
	}
	
	if(f.cep2.value=="")
	{
		alert("Por favor, preencha o CEP!");
		f.cep2.focus();
		return(false);
	}
	else
	{
		if(f.cep2.value.length<3)
		{
			alert("O CEP está incompleto, verifique!");
			f.cep2.focus();
			return(false);
		}
	}

	if(f.tipo_endereco.value=="")
	{
		alert("Por favor, preencha o TIPO DE ENDEREÇO!");
		f.tipo_endereco.focus();
		return(false);
	}

	
	if(f.endereco.value=="")
	{
		alert("Por favor, preencha o ENDEREÇO!");
		f.endereco.focus();
		return(false);
	}
	
	if(f.numero.value=="")
	{
		alert("Por favor, preencha o NÚMERO!");
		f.numero.focus();
		return(false);
	}

	if(f.bairro.value=="")
	{
		alert("Por favor, preencha o BAIRRO!");
		f.bairro.focus();
		return(false);
	}

	if(f.bairro.value=="")
	{
		alert("Por favor, preencha o BAIRRO!");
		f.bairro.focus();
		return(false);
	}
	
	if(f.uf.value=="")
	{
		alert("Por favor, preencha a UF!");
		f.uf.focus();
		return(false);
	}
	
	if(f.cidade.value=="")
	{
		alert("Por favor, preencha a CIDADE!");
		f.cidade.focus();
		return(false);
	}

}	


/*
Nome da Função: utilizarEndereco(formulario, id_endereco)
	Parametro formulario: objeto formulario que possui os campos
	Parametro id_endereco: id do endereco no qual o pedido deverá ser enviado ao cliente
Descrição da Função: Setar o Endereço selecionado como Destinatário dos produtos comprados no site
Desenvolvido por: Joao Paulo Wodiani
Data: 16/05/2007
*/
function utilizarEndereco(formulario, id_endereco, id_formaentrega)
{
	
	/* Gisele Silva do Carmo
	19/10/2011
	função que verifica se forma de pagamento está disponível para novo cep selecinado
	*/

	try {
		if (id_endereco!="" && id_endereco!="0") {
			
			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", 'f_endereco_action.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function() {
				if (oHTTPRequest.readyState==4){
					
					v = URLDecode(oHTTPRequest.responseText); //VALOR DO ID DA CIDADE

					
					if (v == "forma de entrega encontrada"){
						
						f = formulario;
						f.frmAcao.value = "USE";
						f.id_endereco.value = id_endereco;
						f.submit();
						
					}else if (v == "forma de entrega alterada"){						
						
						$('.bt_usarendereco').each(function() {
							$(this).removeAttr('onclick');	
						});	
						
						$('.bt_usarendereco').click(function() {
							utilizarEndereco(formulario, id_endereco, id_formaentrega);
							return false;						
						});
					}else{
																	
						$('#new_cep'+id_endereco).html(v);
						$('#new_cep'+id_endereco).show('slow');
						
						$('input:radio[name=forma_entrega]').each(function() {
							$(this).removeAttr('onclick');						
						})
						$('input:radio[name=forma_entrega]').change(function() {							
  							utilizarEndereco(formulario, id_endereco, $(this).val());
						});
											
						
					}
								
										
				}
				
			}
			oHTTPRequest.send("id_endereco=" + id_endereco + "&frmAcao=VFE&id_formaentrega=" + id_formaentrega );
		}
	} catch(e) { alert(e); }
	
}

/*
Nome da Função: editarEndereco(formulario, id_endereco)
	Parametro formulario: objeto formulario que possui os campos
	Parametro id_endereco: id do endereco que será alterado
Descrição da Função: Editar o endereço que o cliente desejar
Desenvolvido por: Joao Paulo Wodiani
Data: 20/05/2007
*/
function editarEndereco(formulario, id_endereco)
{
	f = formulario;
	
	f.frmAcao.value = "UPD";
	f.id_endereco.value = id_endereco;
	
	f.action = 'f_enderecoedit.php';
	f.submit();
}


/*
Nome da Função: editarEndereco_Painel(formulario, id_endereco)
	Parametro formulario: objeto formulario que possui os campos
	Parametro id_endereco: id do endereco que será alterado
Descrição da Função: Editar o endereço que o cliente desejar na Central de Clientes
Desenvolvido por: Joao Paulo Wodiani
Data: 06/10/2009
*/
function editarEndereco_Painel(formulario, id_endereco)
{
	f = formulario;
	
	f.frmAcao.value = "UPD";
	f.id_endereco.value = id_endereco;
	
	f.action = 'f_alterarendereco2.php';
	f.submit();
}



/*
Nome da Função: Validar_FaleConosco(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o envio de mensagens pelo faleconosco
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 01/07/2007
*/
function Validar_FaleConosco(f)
{
	try{

		if(f.nome.value=="")
		{
			alert("Por favor, preencha o seu NOME para contato!");
			f.nome.focus();
			return false;
		}
		if(f.categoria.value=="")
		{
			alert("Por favor, selecione a CATEGORIA do contato!");
			f.categoria.focus();
			return false;
		}
		if(f.assunto.value=="")
		{
			alert("Por favor, preencha o ASSUNTO do contato!");
			f.assunto.focus();
			return false;
		}
		if(!ValidaEmail(f.email.value))
		{
			alert("E-mail incorreto, verifique!");
			f.email.focus();
			return false;
		}
				
		if(f.categoria.value == "Agendamento"){
			
			var hoje = new Date();
			
			if(f.data_1.value == ""){
				alert("Por favor, informe 3 datas e horários mais convenientes para seu atendimento");	
				f.data_1.focus();
				return false;
			}else{
	  
				if(parseData(f.data_1).getDay() == 0){
					alert("Atendimento somente de segunda a sábado, por favor escolha outra data");	
					f.data_1.value = "";	
					f.data_1.focus();
					return false;
				}
				if(parseData(f.data_1) <= hoje){
					alert("Data informada menor ou igual a data atual, por favor escolha outra data");	
					f.data_1.value = "";
					f.data_1.focus();
					return false;
				}
				
			}			
			if(f.data_2.value == ""){
				alert("Por favor, informe 3 datas e horários mais conveniente para seu atendimento");	
				f.data_2.focus();
				return false;
			}else{
				
				if(parseData(f.data_2).getDay() == 0){
					alert("Atendimento somente de segunda a sábado, por favor escolha outra data");	
					f.data_2.value = "";	
					f.data_2.focus();
					return false;
				}
				
				if(parseData(f.data_2) <= hoje){
					alert("Data informada menor ou igual a data atual, por favor escolha outra data");	
					f.data_2.value = "";
					f.data_2.focus();
					return false;
				}
				
			}					
			if(f.data_3.value == ""){
				alert("Por favor, informe 3 datas e horários mais conveniente para seu atendimento");	
				f.data_3.focus();
				return false;
			}else{
				
				if(parseData(f.data_3).getDay() == 0){
					alert("Atendimento somente de segunda a sábado, por favor escolha outra data");	
					f.data_3.value = "";
					f.data_3.focus();
					return false;
				}
				
				if(parseData(f.data_3) <= hoje){
					alert("Data informada menor ou igual a data atual, por favor escolha outra data");	
					f.data_3.value = "";
					f.data_3.focus();
					return false;
				}
				
			}
						
		}else{		
			if(f.texto_memo.value=="")			{
				alert("Por favor, preencha a sua SOLICITAÇÃO!");
				f.texto_memo.focus();
				return false;
			}
		}		
		
		if(f.code.value==""){
			alert("Por favor, preencha o código de segurança para prosseguir!");
			f.code.focus();
			return false;
		}
		
		
	} catch(e){alert(e); return false}
}


function parseData(aText){
	var d = aText.value;
	var tokens = d.split("/");
	var dt = tokens[1] + "/" + tokens[0] + "/" + tokens[2]; 
	myDate=new Date(eval('"'+dt+'"'))
	return myDate;
}
/*
Nome da Função: Validar_FaleConosco2(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o envio de mensagens pelo faleconosco
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 01/07/2007
*/
function Validar_FaleConosco2(f)
{
	try{

		if(f.nome.value=="")
		{
			alert("Por favor, preencha o seu NOME para contato!");
			f.nome.focus();
			return false;
		}
		if(f.categoria.value=="")
		{
			alert("Por favor, selecione a CATEGORIA do contato!");
			f.categoria.focus();
			return false;
		}
		if(f.assunto.value=="")
		{
			alert("Por favor, preencha o ASSUNTO do contato!");
			f.assunto.focus();
			return false;
		}
		if(!ValidaEmail(f.email.value))
		{
			alert("E-mail incorreto, verifique!");
			f.email.focus();
			return false;
		}
		
		if(f.recaptcha_response_field.value==""){
			alert("Por favor, preencha o código de segurança para prosseguir!");
			f.recaptcha_response_field.focus();
			return false;
		}
		
		if(f.texto_memo.value=="")
		{
			alert("Por favor, preencha a sua SOLICITAÇÃO!");
			f.texto_memo.focus();
			return false;
		}
		
	} catch(e){alert(e); return false}
}


/*
Nome da Função: window.onload
Parâmetro: -
Descrição da Função: Executada ao carregar completamente a página.
					 Faz o tratamento de pessoa física/jurídica.
Desenvolvido por: João Pedro N. de Souza <joao.pedro@ecompleto.com.br>
Data: 19/11/2009
*/
/*window.onload = function() {
	formulario = document.frmCadastro;
	cpf = formulario.cpf;
	rg = formulario.rg;
	orgao = formulario.orgao_emissor;
	nacionalidade = formulario.nacionalidade_id;
	
	if(nacionalidade.value == 2) {
		/* é estrangeiro 
		cpf.value = "99999999999";
		cpf.disabled = true;
		
		rg.value = "999999999";
		rg.disabled = true;
		
		orgao.value = "999";
		orgao.disabled = true;
	}

	nacionalidade.onchange = function() {
		if(this.value == 2) {
			/* é estrangeiro 
			cpf.value = "99999999999";
			cpf.disabled = true;
			
			rg.value = "999999999";
			rg.disabled = true;
			
			orgao.value = "999";
			orgao.disabled = true;
		} else {
			/* é brasileiro 
			cpf.value = "";
			cpf.disabled = false;			
			rg.value = "";
			rg.disabled = false;
			orgao.value = "";
			orgao.disabled = false;
		}
	}
}*/

/*
Nome da Função: ValidarCadastro_Cliente(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o cadastro de clientes dos sites
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 17/06/2007
*/
function ValidarCadastro_Cliente(f, validaEndereco)
{
	try{
		/**
		 * VALIDACAO DE PESSOA FISICA
		 */
		if(f.tipo_pessoa[0].checked)
		{
			if(f.nome.value=="")
			{
				alert("Por favor, preencha o NOME completo!");
				f.nome.focus();
				return false;
			}
			if(f.nacionalidade_id.value=="")
			{
				alert("Por favor, selecione a sua NACIONALIDADE!");
				f.nacionalidade_id.focus();
				return false;
			}
			if(f.cpf.value=="")
			{
				alert("Por favor, preencha o CPF!");
				f.cpf.focus();
				return false;
			}else if(f.cpf.value.length < 11){
				alert("Por favor, o CPF está preenchido incorretamente. FALTAM DÍGITOS!");
				f.cpf.focus();
				return false;
			}
			if(f.nacionalidade != 2) {
				if(!ValidaCPF(f.cpf.value))
				{
					alert("CPF incorreto, verifique!");
					f.cpf.focus();
					return false;
				}
			}
			if(f.rg.value=="")
			{
				alert("Por favor, preencha o RG!");
				f.rg.focus();
				return false;
			}
			if(f.orgao_emissor.value=="")
			{
				alert("Por favor, preencha o ÓRGÃO EMISSOR do seu RG!");
				f.orgao_emissor.focus();
				return false;
			}
			if(f.data_nascimento_d.value=="")
			{
				alert("Por favor, preencha a DATA DE NASCIMENTO!");
				f.data_nascimento_d.focus();
				return false;
			}
			if(f.data_nascimento_m.value=="")
			{
				alert("Por favor, preencha a DATA DE NASCIMENTO!");
				f.data_nascimento_m.focus();
				return false;
			}
			if(f.data_nascimento_y.value=="")
			{
				alert("Por favor, preencha a DATA DE NASCIMENTO!");
				f.data_nascimento_y.focus();
				return false;
			}

			if(!ValidaData(f.data_nascimento_d.value + '/' + f.data_nascimento_m.value + '/' + f.data_nascimento_y.value))
			{
				alert("DATA DE NASCIMENTO incorreta, verifique!");
				f.data_nascimento_d.value = '';
				f.data_nascimento_m.value = '';
				f.data_nascimento_y.value = '';
				f.data_nascimento_d.focus();
				return false;
			}
			if(f.sexo.value=="")
			{
				alert("Por favor, selecione o SEXO!");
				f.sexo.focus();
				return false;
			}
			if(f.senha.value=="")
			{
				alert("Por favor, informe a sua nova SENHA!");
				f.senha.focus();
				return false;
			}
			else if(f.senha.value.length<5)
			{
				alert("A SENHA deve possuir no mínimo 5 caracteres!");
				f.senha.focus();
				return false;
			}
			if(f.repetir_senha.value!=f.senha.value)
			{
				alert("A CONFIRMAÇÃO DE SENHA não confere!");
				f.repetir_senha.value = "";
				f.repetir_senha.focus();
				return false;
			}
			if(f.id_como_conheceu_loja.value==""){
				alert("Informe a opção: Como conheceu a Loja!");
				f.id_como_conheceu_loja.value = "";
				f.id_como_conheceu_loja.focus();
				return false;
			}

		}
		else /*** VALIDACAO DE PESSOA JURIDICA */
		{
			if(f.razao.value=="")
			{
				alert("Favor preencher a Razão Social!");
				f.razao.focus();
				return false;
			}
			if(f.cnpj.value=="")
			{
				alert("Favor preencher o C.N.P.J. !");
				f.cnpj.focus();
				return false;
			}else if(f.cnpj.value.length < 11){
				alert("Por favor, o CNPJ está preenchido incorretamente. FALTAM DÍGITOS!");
				f.cnpj.focus();
				return false;
			}
			if(!validaCNPJ(f.cnpj.value))
			{
				alert("Favor preencher o C.N.P.J. corretamente !");
				f.cnpj.focus();
				return false;
			}
			if(f.senha.value=="")
			{
				alert("Por favor, informe a sua nova SENHA!");
				f.senha.focus();
				return false;
			}
			else if(f.senha.value.length<5)
			{
				alert("A SENHA deve possuir no mínimo 5 caracteres!");
				f.senha.focus();
				return false;
			}
			if(f.repetir_senha.value!=f.senha.value)
			{
				alert("A CONFIRMAÇÃO DE SENHA não confere!");
				f.repetir_senha.value = "";
				f.repetir_senha.focus();
				return false;
			}
			if(f.id_como_conheceu_loja.value==""){
				alert("Informe a opção: Como conheceu a Loja!");
				f.id_como_conheceu_loja.value = "";
				f.id_como_conheceu_loja.focus();
				return false;
			}

		}
		
		if(validaEndereco==true)
		{
			if(!ValidarCadastro_Endereco(f))
			{
				return false;	
			}
		}
		
	} catch(e){alert(e); return false}
}


/*
Nome da Função: ValidarCadastro_Endereco(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o cadastro de endereços, meucadastro.php, popup_edit_endereco, etc.
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 17/06/2007
*/
function ValidarCadastro_Endereco(f)
{
	try{

		if(f.tipo_endereco.value=="")
		{
			alert("Por favor, selecione o TIPO DE ENDEREÇO!");
			f.tipo_endereco.focus();
			return false;
		}
		if(f.apelido_endereco.value=="")
		{
			alert("Por favor, preencha o APELIDO DO ENDEREÇO!");
			f.apelido_endereco.focus();
			return false;
		}
		if(f.destinatario_endereco.value=="")
		{
			alert("Por favor, preencha o DESTINATÁRIO!");
			f.destinatario_endereco.focus();
			return false;
		}
		if(f.endereco.value=="")
		{
			alert("Por favor, preencha o ENDEREÇO!");
			f.endereco.focus();
			return false;
		}
		if(f.numero.value=="")
		{
			alert("Por favor, preencha o NÚMERO!");
			f.numero.focus();
			return false;
		}
		if(f.bairro.value=="")
		{
			alert("Por favor, preencha o BAIRRO!");
			f.bairro.focus();
			return false;
		}
		if(f.cep1.value=="")
		{
			alert("Por favor, preencha o CEP!");
			f.cep1.focus();
			return false;
		}
		else
		{
			if(f.cep1.value.length<5)
			{
				alert("Por favor, preencha o CEP corretamente!");
				f.cep1.focus();
				return false;
			}
		}
		if(f.cep2.value=="")
		{
			alert("Por favor, preencha o CEP!");
			f.cep2.focus();
			return false;
		}
		else
		{
			if(f.cep2.value.length<3)
			{
				alert("Por favor, preencha o CEP corretamente!");
				f.cep2.focus();
				return false;
			}
		}
		if(f.esta_cod.value=="")
		{
			alert("Por favor, selecione o ESTADO!");
			f.esta_cod.focus();
			return false;
		}
		if(f.cidade.value=="")
		{
			alert("Por favor, selecione a CIDADE!");
			f.cidade.focus();
			return false;
		}

		$testFones = 0;
		if(f.ddd1.value!="" && f.telefone1.value!="")
		{			
			$testFones++;
		}
		if(f.ddd2.value!="" && f.telefone2.value!="")
		{			
			$testFones++;
		}
		
		if($testFones==0){
			if(f.ddd1.value=="")
			{
				alert("Informe no mínimo 1 Telefone fixo para contato!");
				f.ddd1.focus();
				return(false);
			}
		}
		
		/*if(f.referencia_entrega.value=="")
		{
			alert("Por favor, preencha a REFERÊNCIA PARA ENTREGA das suas compras!");
			f.referencia_entrega.focus();
			return false;
		}*/

		return true;

	} catch(e) { alert(e); return false}
}


function fundoEscuro(bool){
	if(bool){
		qtd = $('#fundo_escuro')
		if(qtd.length == 0){
			
    		var css_n = {'width':'100%', 'height':'100%', 'position':'fixed', 'top':'0px', 'left':'0px', 'background-color':'#000000', 'z-index':'990', 'opacity':'0.8'}
    /* caso seja IE, a configuração é outra */
    		if(navigator.appName.indexOf('Internet Explorer')>0)
       		var css_n = {'width':'100%', 'height':'100%', 'position':'fixed', 'top':'0px', 'left':'0px', 'background-color':'#000000', 'z-index':'990', 'opacity':'0.8'}
			$('body').prepend('<div id="fundo_escuro"></div>')	
			$('#fundo_escuro').css(css_n)
		}
		$('#fundo_escuro').fadeTo(100,0.6)
	}
	else{
		$('#fundo_escuro').fadeOut(100)
	}
}

/*
Nome da Função: ValidarPagamento(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida a finalização do pedido por parte do cliente.
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 24/06/2007
*/
function ValidarPagamento(f)
{
	try{

		obj_PaymentMethod = f.PaymentMethod;
		obj_qtde_vezes = f.qtde_vezes;

		obj1 = false;
		obj2 = false;
		//percorrendo forma de pagamento
		for(i=0;i<obj_PaymentMethod.length;i++)
		{
			if(obj_PaymentMethod[i].checked)
			{
				obj1 = true;
				obj1_valor = obj_PaymentMethod[i].value;
			}
		}

		//percorrendo condicao de pagamento
		for(i=0;i<obj_qtde_vezes.length;i++)
		{
			if(obj_qtde_vezes[i].checked)
			{
				obj2 = true;
				obj2_valor = obj_qtde_vezes[i].value;
			}
		}


		if(!obj1)
		{
			alert("Por favor, selecione a forma de pagamento desejada!");
			return false;
		}

		if(!obj2)
		{
			alert("Por favor, selecione a condição de pagamento desejada!");
			return false;
		}
		
		f.hid_PaymentMethod.value = obj1_valor;
		f.hid_qtde_vezes.value = obj2_valor;
		
		return true;
		

	} catch(e) { alert(e); return false}
}



/*
Nome da Função: popup(pagina, title, largura, altura)
	Parametro pagina: nome do arquivo a ser aberto em popup
	Parametro title: titulo da janela
	Parametro largura: largura da janela
	Parametro altura: altura da janela	
Descrição da Função: Abrir arquivo em uma popup
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 18/06/2007
*/
function popup(pagina, title, largura, altura)
{

	window.open(pagina,title,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width='+largura+',height='+altura+'');

}



/*
Nome da Função: Ordenar(valor, pagina_destino)
	Parametro valor: opção a ordenar
	Parametro pagina_destino: pagina que deve ser recarregada
Descrição da Função: Reordenar categoria de produtos(ou pesquisa) no site da loja
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 04/07/2007
*/
function Ordenar(valor, pagina_destino)
{
	document.frmPost.action = pagina_destino;
	document.frmPost.method = 'GET';
	document.frmPost.orderby.value = valor;
	
	document.frmPost.submit();
}


/*
Nome da Função: SetTipoPagamento
	Parametro id_tipo: identificador do tipo de pagamento
	Parametro anchor: ancora para qual a pagina deve posicionar-se
Descrição da Função: Posicionar página em determinada ancora do conteudo
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 21/06/2007
*/
function SetTipoPagamento(container, ancora)
{
	window.location.hash = ancora;
}



/*
Nome da Função: ValidarEsqueciSenha
	Parametro f: objeto formulario
Descrição da Função: Validar preenchimento dos campos de email
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 28/06/2007
*/
function ValidarEsqueciSenha(f)
{
	if(f.email.value!="")
	{
		if(!ValidaEmail(f.email.value))
		{
			alert("E-mail inválido!");
			f.email.value="";
			f.email.focus();
			return false;
		}
	}
	
	if(f.cpf_cnpj.value!="")
	{
		if(f.cpf_cnpj.value.length == 11) //testa cpf
		{
			if(!ValidaCPF(f.cpf_cnpj.value))
			{
				alert("Cpf Inválido!");
				f.cpf_cnpj.value = "";
				f.cpf_cnpj.focus();
				return false;
			}
		}
		else if(f.cpf_cnpj.value.length == 14) //testa cnpj
		{
			if(!validaCNPJ(f.cpf_cnpj.value))
			{
				alert("Cnpj Inválido!");
				f.cpf_cnpj.value = "";
				f.cpf_cnpj.focus();
				return false;
			}
		}
		else
		{
			alert("Cpf / Cnpj está incompleto!");
			f.cpf_cnpj.value = "";
			f.cpf_cnpj.focus();
			return false;
		}
	}


	if(f.email.value != "" || f.cpf_cnpj.value != "") //caso preenchido
	{
		return true;
	}
	else //caso não preenchido
	{
		alert("Por favor, preencha um dos campos abaixo!");
		f.email.focus();
		return false;
	}


	
}



function CarregaDestino(valor)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", 'carregadestino.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				document.getElementById("frete_destino").innerHTML = URLDecode(oHTTPRequest.responseText);
			} else {
				if (document.getElementById("frete_destino").innerHTML=="carregando.")
					document.getElementById("frete_destino").innerHTML = "carregando..";
				else if (document.getElementById("frete_destino").innerHTML == "carregando..")
					document.getElementById("frete_destino").innerHTML = "carregando...";
				else
					document.getElementById("frete_destino").innerHTML = "carregando.";
			}
		}
		oHTTPRequest.send("descricao="+valor);
	} catch(e) { alert(e); }	
}

function CarregaValorPedido(id_formaentrega, id_basket)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", 'carregavalorpedido.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				document.getElementById("valor_carrinho").innerHTML = URLDecode(oHTTPRequest.responseText);
			} else {
				document.getElementById("valor_carrinho").innerHTML = "<img src='http://www.ecompleto.com.br/i_padrao/loading.gif'>";
			}
		}
		oHTTPRequest.send("id_formaentrega="+id_formaentrega+"&id_basket="+id_basket);
	} catch(e) { alert(e); }	
}


function CarregaValorPedido_DescontoVista(id_formaentrega, id_basket)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", 'carregavalorpedido_desconto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				document.getElementById("valor_avista").innerHTML = URLDecode(oHTTPRequest.responseText);
			} else {
				document.getElementById("valor_avista").innerHTML = "<img src='http://www.ecompleto.com.br/i_padrao/loading.gif'>";
			}
		}
		oHTTPRequest.send("id_formaentrega="+id_formaentrega+"&id_basket="+id_basket);
	} catch(e) { alert(e); }	
}

function CarregaValorPedido_Parcelado(id_formaentrega, id_basket)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", 'carregavalorpedido_parcelado.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				document.getElementById("valor_parcelado").innerHTML = URLDecode(oHTTPRequest.responseText);
			} else {
				document.getElementById("valor_parcelado").innerHTML = "<img src='http://www.ecompleto.com.br/i_padrao/loading.gif'>";
			}
		}
		oHTTPRequest.send("id_formaentrega="+id_formaentrega+"&id_basket="+id_basket);
	} catch(e) { alert(e); }	
}

function CarregaValor_Frete(id_formaentrega, id_basket,imposto)
{
	try {		
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", 'carregavalorfrete.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				document.getElementById("frete_valor").innerHTML = URLDecode(oHTTPRequest.responseText);
				CarregaImposto('', '', id_basket, id_formaentrega,imposto);	
				CarregaValorPedido_DescontoVista(id_formaentrega, id_basket);
				CarregaValorPedido(id_formaentrega, id_basket);
				CarregaValorPedido_Parcelado(id_formaentrega, id_basket);
				
			} else {
				document.getElementById("frete_valor").innerHTML = "<img src='http://www.ecompleto.com.br/i_padrao/loading.gif'>";
			}
		}
		oHTTPRequest.send("id_formaentrega="+id_formaentrega+"&id_basket="+id_basket);
	} catch(e) { alert(e); }	
}


function CarregaTipoPessoa(tipoPessoa)
{
	/*try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", 'carregacliente_tipopessoa.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				document.getElementById("dv_tppessoa").innerHTML = URLDecode(oHTTPRequest.responseText);
			} else {
				if (document.getElementById("dv_tppessoa").innerHTML=="carregando.")
					document.getElementById("dv_tppessoa").innerHTML = "carregando..";
			}
		}
		oHTTPRequest.send("tppessoa="+tipoPessoa);
	} catch(e) { alert(e); }	*/
	return true;
}


function CarregaTipoPessoa_Fisica(tipoPessoa)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", 'carregacliente_tipopessoa_fisica.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				document.getElementById("dv_tppessoa").innerHTML = URLDecode(oHTTPRequest.responseText);
			} else {
				if (document.getElementById("dv_tppessoa").innerHTML=="carregando.")
					document.getElementById("dv_tppessoa").innerHTML = "carregando..";
			}
		}
		oHTTPRequest.send("tppessoa="+tipoPessoa);
	} catch(e) { alert(e); }	
}




/*
Nome da Função: ValidarAltera_Senha(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o preenchimento dos campos senha e faz alteração cadastral
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 25/09/2007
*/
function ValidarSenha_Cliente(f)
{
	try
	{

		if(f.senha_atual.value=="")
		{
			alert("Por favor, informe a sua SENHA atual!");
			f.senha_atual.focus();
			return false;
		}
		if(f.senha.value=="")
		{
			alert("Por favor, informe a sua nova SENHA!");
			f.senha.focus();
			return false;
		}
		else if(f.senha.value.length<5)
		{
			alert("A SENHA deve possuir no mínimo 5 caracteres!");
			f.senha.focus();
			return false;
		}
		if(f.repetir_senha.value!=f.senha.value)
		{
			alert("A CONFIRMAÇÃO DE SENHA não confere!");
			f.repetir_senha.value = "";
			f.repetir_senha.focus();
			return false;
		}
		
		return true;

	} catch(e){alert(e); return false}
}




/*
Nome da Função: ValidarIndique(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o preenchimento dos campos para indicação de produto
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 27/09/2007
*/
function ValidarIndique(f)
{
	
	try
	{
	
		if(f.de.value=="")
		{
			alert("Por favor, preencha o seu NOME!");
			f.de.focus();
			return false;
		}
		if(f.email.value=="")
		{
			alert("Por favor, preencha o seu E-MAIL!");
			f.email.focus();
			return false;
		}
		if(f.para.value=="")
		{
			alert("Informe o NOME do seu amigo!");
			f.para.focus();
			return false;
		}
		if(f.email_para.value=="")
		{
			alert("Informe o E-MAIL do seu amigo!");
			f.repetir_senha.value = "";
			f.repetir_senha.focus();
			return false;
		}
		if(f.code.value=="")
		{
			alert("Preencha o código de VERIFICAÇÃO de mensagens!");
			f.code.value = "";
			f.code.focus();
			return false;
		}
		return true;

	} catch(e){alert(e); return false}
}



function fnc_AtualizaCarrinho(id_loja, formulario)
{

	id_produto = "";
	id_produto_detalhe = "";
	id_produto_detalhe_2 = "";
	qtde = "";
	for(i=0;i<document.frmPost.itens.value;i++)
	{
		if(i==0)
		{
			id_produto = eval(formulario+'.id_produto'+i+'.value');
			id_produto_detalhe = eval(formulario+'.id_produto_detalhe'+i+'.value');
			id_produto_detalhe_2 = eval(formulario+'.id_produto_detalhe'+i+'_2.value');
			if(eval(formulario+'.qtde'+i+'.value')>10)
			{
				//qtde = '10';
				qtde = eval(formulario+'.qtde'+i+'.value');
			}else
			{
				qtde = eval(formulario+'.qtde'+i+'.value');
			}
		}
		else
		{
			id_produto = id_produto + ', ' + eval(formulario+'.id_produto'+i+'.value');
			id_produto_detalhe = id_produto_detalhe + ', ' + eval(formulario+'.id_produto_detalhe'+i+'.value');
			id_produto_detalhe_2 = id_produto_detalhe_2 + ', ' + eval(formulario+'.id_produto_detalhe'+i+'_2.value');				
			if(eval(formulario+'.qtde'+i+'.value')>10)
			{
				//qtde = qtde + ', 10';
				qtde = qtde + ', ' + eval(formulario+'.qtde'+i+'.value');
			}else
			{
				qtde = qtde + ', ' + eval(formulario+'.qtde'+i+'.value');
			}
			
		}
	}
	
	document.frmPost.idloja.value = id_loja;
	document.frmPost.idproduto.value = id_produto;
	document.frmPost.idproduto_detalhe.value = id_produto_detalhe;
	document.frmPost.idproduto_detalhe_2.value = id_produto_detalhe_2;
	document.frmPost.qtde.value = qtde;

}


/*
Nome da Função: Validar_AviseMe(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o preenchimento dos campos
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 23/03/2008
*/
function Validar_AviseMe(f)
{
	
	try
	{
	
		if(f.nome_avise.value=="")
		{
			alert("Por favor, preencha seu nome!");
			f.nome_avise.focus();
			return(false);
		}
		
		if(f.email_avise.value=="")
		{
			alert("Por favor, preencha seu e-mail!");
			f.email_avise.focus();
			return(false);
		}
		
	}
	catch(e){alert(e); return(false);}

}


/*
Nome da Função: RetrieveStatsData(i, r, o)
	Parametro i: id_produto
			  r: referrer
			  o: origem
			  u: url_site
Descrição da Função: Grava Estatistica de Produto
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 16/05/2008
*/
function RetrieveStatsData(i, r, o, u)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", u + '/grava_stats_produto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function() {
			if (oHTTPRequest.readyState==4){
				//alert(oHTTPRequest.responseText);
			} else {
			}
		}
		
		//replacing yet
		r = r.replace(/&/g, "||");
		oHTTPRequest.send("i="+ i +"&o="+ o +"&r="+ r);

	} catch(e) { alert(e); }	
}


/*
Nome da Função: RetrieveStatsDataCategoria(i, r, o)
	Parametro i: id_categoria
			  r: referrer
			  o: origem
Descrição da Função: Grava Estatistica de Categoria
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 09/07/2008
*/
function RetrieveStatsDataCategoria(i, r, o, url)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", url + '/grava_stats_categoria.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function() {
			if (oHTTPRequest.readyState==4){
				//alert(oHTTPRequest.responseText)
			} else {
			}
		}
		
		//replacing yet
		r = r.replace(/&/g, "||");
		oHTTPRequest.send("i="+ i +"&o="+ o +"&r="+ r);

	} catch(e) { alert(e); }
}


/*
Nome da Função: ValidarNews(f)
	Parametro f: objeto formulario
Descrição da Função: Valida o preenchimento do form newsletter
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 18/07/2008
*/
function ValidarNews(f)
{
	if(f.nome.value == ""){ 
		alert("Oops, preencha seu nome!");
		f.nome.focus();
		return(false);
	}

	if(f.email.value == ""){ 
		alert("Oops, preencha seu e-mail!");
		f.email.focus(); return(false);
	}
	else
	{
		if(!ValidaEmail(f.email.value))
		{
			alert("E-mail inválido, verifique!");
			f.email.value = "";
			f.email.focus();
			return(false);
		}
	}
	if(f.code.value == ""){ 
		alert("Oops, preencha o código de segurança!");
		f.code.focus(); return(false);
	}
	
	
}


/*
Nome da Função: ValidarNews_PROMOCIONAL(f)
	Parametro f: objeto formulario
Descrição da Função: Valida o preenchimento do form newsletter para PROMOÇÕES
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 10/11/2010
*/
function ValidarNews_PROMOCIONAL(f)
{
	
	if(f.nome.value == ""){ 
		alert("Oops, preencha seu nome!");
		f.nome.focus();
		return(false);
	}

	if(f.email.value == ""){ 
		alert("Oops, preencha seu e-mail!");
		f.email.focus(); return(false);
	}
	else
	{
		if(!ValidaEmail(f.email.value))
		{
			alert("E-mail inválido, verifique!");
			f.email.value = "";
			f.email.focus();
			return(false);
		}
	}
	if(f.rg.value == ""){ 
		alert("Oops, preencha seu R.G.!");
		f.rg.focus(); return(false);
	}
	if(f.uf.value == ""){ 
		alert("Oops, selecione seu estado!");
		f.uf.focus(); return(false);
	}
	if(f.cidade.value == ""){ 
		alert("Oops, selecione sua Cidade!");
		f.cidade.focus(); return(false);
	}
	if(f.data_nascimento_d.value=="" || f.data_nascimento_m.value=="" || f.data_nascimento_y.value==""){
		alert("Oops, data de nascimento não está preenchida corretamente!");
		f.data_nascimento_d.focus(); return(false);
	}
	if(f.code.value == ""){ 
		alert("Oops, preencha o código de segurança!");
		f.code.focus(); return(false);
	}
	
	
}


/*
Nome da Função: OpenCertDetaisl(url)
	Parametro url: url do site seguro
Descrição da Função: Abre popup Thawte
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 24/07/2008
*/
function OpenCertDetails(url)
				{
					Destination = 'https://www.thawte.com/core/process?process=public-site-seal-cert-details&public-site-seal-cert-details.referer='+ url;
					thewindow = window.open(Destination, 'anew', config='height=580,width=516,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,directories=no,status=no');
				}
				
				
/*
Nome da Função: getMouseXY(e)
	Parametro e: event
Descrição da Função: Busca posição XY do Mouse
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 26/08/2008
*/
function getMouseXY(e) {
	if (IE) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	} else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
	}  
	// catch possible negative values in NS4
	if (tempX < 0){tempX = 0}
	if (tempY < 0){tempY = 0}  
	// show the position values in the form named Show
	// in the text fields named MouseX and MouseY
	document.getElementById('mousex').value = tempX;
	document.getElementById('mousey').value = tempY;
	
	return true;
}


/*
	@Função: ChangeImage() -- Troca Imagens na Popup/Loja
	@params:
		ID = id do Produto
		SEQUENCIA = sequencia da Foto
		TAMANHO = tamanho da Foto P, V, M, G
		DIV = div destino do HTML
	Criado por: Joao Paulo Wodiani <joaopaulo@ecompleto.com.br>
	Data: 09/01/2009
*/
function ChangeImage(id, sequencia, tamanho, div, linkPop)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", 'changeimage.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function() {
			if (oHTTPRequest.readyState==4){
				document.getElementById(div).innerHTML = URLDecode(oHTTPRequest.responseText);
			} else {
				document.getElementById(div).innerHTML = "carregando...";
			}
		}
		oHTTPRequest.send("id=" + id + "&sequencia=" + sequencia + "&tamanho=" + tamanho + "&linkPop="+ linkPop);
	} catch(e) { alert(e); }	
}



function SwapDiv(abre, fecha){
	document.getElementById(abre).style.display = 'block';
	document.getElementById(fecha).style.display = 'none';
}



/*
Nome da Função: Validar_PropostaVeiculo(f)
	Parametro f: objeto formulario
Descrição da Função: Validar Preenchimento de Formulario - PROPOSTA VEÍCULO
Desenvolvido por: Joao Paulo Wodiani
Data: 11/01/2009
*/
function Validar_PropostaVeiculo(f)
{
	if(f.nome.value==""){
		alert("Por favor, preencha seu nome!");
		f.nome.focus();
		return false;
	}
	
	if(f.email.value==""){
		alert("Por favor, preencha seu e-mail!");
		f.email.focus();
		return false;
	}else{
		if(!ValidaEmail(f.email.value))
		{
			alert("Seu E-mail está preenchido incorretamente, verifique!");
			f.email.value = "";
			f.email.focus();
			return false;
		}
	}

	if(f.ddd.value==""){
		alert("Por favor, preencha seu ddd!");
		f.ddd.focus();
		return false;
	}

	if(f.fone.value==""){
		alert("Por favor, preencha seu telefone!");
		f.fone.focus();
		return false;
	}

	if(f.mensagem.value==""){
		alert("Por favor, preencha sua mensagem!");
		f.mensagem.focus();
		return false;
	}
}



/*
Nome da Função: Validar_PropostaVeiculo_Taxi(f)
	Parametro f: objeto formulario
Descrição da Função: Validar Preenchimento de Formulario - PROPOSTA VEÍCULO NOVOTAXI
Desenvolvido por: Joao Paulo Wodiani
Data: 03/07/2009
*/
function Validar_PropostaVeiculo_Taxi(f)
{
	if(f.nome.value==""){
		alert("Por favor, preencha seu nome!");
		f.nome.focus();
		return false;
	}
	
	if(f.email.value==""){
		alert("Por favor, preencha seu e-mail!");
		f.email.focus();
		return false;
	}else{
		if(!ValidaEmail(f.email.value))
		{
			alert("Seu E-mail está preenchido incorretamente, verifique!");
			f.email.value = "";
			f.email.focus();
			return false;
		}
	}

	if(f.ddd.value==""){
		alert("Por favor, preencha seu ddd!");
		f.ddd.focus();
		return false;
	}

	if(f.fone.value==""){
		alert("Por favor, preencha seu telefone!");
		f.fone.focus();
		return false;
	}

	if(f.taxista.value==""){
		alert("Por favor, informe se você é TAXISTA!");
		f.taxista.focus();
		return false;
	}

	if(f.mensagem.value==""){
		alert("Por favor, preencha sua mensagem!");
		f.mensagem.focus();
		return false;
	}
}


/*
Nome da Função: CreateBookmarkLink()
Descrição da Função: Adicionar url aos favoritos
Desenvolvido por: Joao Paulo Wodiani
Data: 20/02/2009
*/
function CreateBookmarkLink(){
	
	title = document.title; 
	url = location.href;

	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }

}


/*
Nome da Função: Qualificar()
Descrição da Função: Qualificar Loja
Desenvolvido por: Joao Paulo Wodiani
Data: 20/02/2009
*/
function Qualificar(f){
	
	try{
	
		obj_nota = f.nota;
		test = false;
	
		for(i=0;i<obj_nota.length;i++){
			if(obj_nota[i].checked){
				test = true;
				break;
			}
		}
		
		if(!test){
			alert("Dê sua nota para a Empresa (de 0 a 10)!");
		}else{
			
			if(f.comentario.value==""){
				alert("Insira o seu comentário sobre a empresa, dê sua opinião!");
				f.comentario.focus();
			}else{
				
				if(confirm("Confirma a sua Avaliação?\n\n'"+ f.comentario.value +"'?")){
					f.submit();
				}
			}
			
		}

	}catch(e){ alert(e); }
	
}


/*
Nome da Função: ComoConheceuLojaOpcao()
Descrição da Função: Habilitar Desabilitar campo de preencher informação QUANDO OUTROS
Desenvolvido por: Joao Paulo Wodiani
Data: 28/05/2009
*/
function ComoConheceuLojaOpcao(f, valor) {

	if (valor==8){
		f.como_conheceu_loja_text.disabled = false;
		f.como_conheceu_loja_text.focus();
	} else {
		f.como_conheceu_loja_text.disabled = true;
	}

}



/*
Nome da Função: ValidarCadastro_Cliente_Alt(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o cadastro de clientes dos sites (SOMENTE ALTERAÇÃO)
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 28/07/2009
*/
function ValidarCadastro_Cliente_Alt(f, validaEndereco)
{
	try{
		/**
		 * VALIDACAO DE PESSOA FISICA
		 */
		if(f.tipo_pessoa.value=='F')
		{
			if(f.nome.value=="")
			{
				alert("Por favor, preencha o NOME completo!");
				f.nome.focus();
				return false;
			}
			if(f.nacionalidade_id.value=="")
			{
				alert("Por favor, selecione a sua NACIONALIDADE!");
				f.nacionalidade_id.focus();
				return false;
			}
			if(f.cpf.value=="")
			{
				alert("Por favor, preencha o CPF!");
				f.cpf.focus();
				return false;
			}else if(f.cpf.value.length < 11){
				alert("Por favor, o CPF está preenchido incorretamente. FALTAM DÍGITOS!");
				f.cpf.focus();
				return false;
			}
			if(f.nacionalidade != 2) {
				if(!ValidaCPF(f.cpf.value))
				{
					alert("CPF incorreto, verifique!");
					f.cpf.focus();
					return false;
				}
			}
			if(f.rg.value=="")
			{
				alert("Por favor, preencha o RG!");
				f.rg.focus();
				return false;
			}
			if(f.orgao_emissor.value=="")
			{
				alert("Por favor, preencha o ÓRGÃO EMISSOR do seu RG!");
				f.orgao_emissor.focus();
				return false;
			}
			if(f.data_nascimento_d.value=="")
			{
				alert("Por favor, preencha a DATA DE NASCIMENTO!");
				f.data_nascimento_d.focus();
				return false;
			}
			if(f.data_nascimento_m.value=="")
			{
				alert("Por favor, preencha a DATA DE NASCIMENTO!");
				f.data_nascimento_m.focus();
				return false;
			}
			if(f.data_nascimento_y.value=="")
			{
				alert("Por favor, preencha a DATA DE NASCIMENTO!");
				f.data_nascimento_y.focus();
				return false;
			}

			if(!ValidaData(f.data_nascimento_d.value + '/' + f.data_nascimento_m.value + '/' + f.data_nascimento_y.value))
			{
				alert("DATA DE NASCIMENTO incorreta, verifique!");
				f.data_nascimento_d.value = '';
				f.data_nascimento_m.value = '';
				f.data_nascimento_y.value = '';
				f.data_nascimento_d.focus();
				return false;
			}
			if(f.sexo.value=="")
			{
				alert("Por favor, selecione o SEXO!");
				f.sexo.focus();
				return false;
			}
			if(f.senha.value=="")
			{
				alert("Por favor, informe a sua nova SENHA!");
				f.senha.focus();
				return false;
			}
			else if(f.senha.value.length<5)
			{
				alert("A SENHA deve possuir no mínimo 5 caracteres!");
				f.senha.focus();
				return false;
			}
			if(f.repetir_senha.value!=f.senha.value)
			{
				alert("A CONFIRMAÇÃO DE SENHA não confere!");
				f.repetir_senha.value = "";
				f.repetir_senha.focus();
				return false;
			}

		}
		else /*** VALIDACAO DE PESSOA JURIDICA */
		{
			if(f.razao.value=="")
			{
				alert("Favor preencher a Razão Social!");
				f.razao.focus();
				return false;
			}
			if(f.cnpj.value=="")
			{
				alert("Favor preencher o C.N.P.J. !");
				f.cnpj.focus();
				return false;
			}else if(f.cnpj.value.length < 11){
				alert("Por favor, o CNPJ está preenchido incorretamente. FALTAM DÍGITOS!");
				f.cnpj.focus();
				return false;
			}
			if(!validaCNPJ(f.cnpj.value))
			{
				alert("Favor preencher o C.N.P.J. corretamente !");
				f.cnpj.focus();
				return false;
			}
			if(f.senha.value=="")
			{
				alert("Por favor, informe a sua nova SENHA!");
				f.senha.focus();
				return false;
			}
			else if(f.senha.value.length<5)
			{
				alert("A SENHA deve possuir no mínimo 5 caracteres!");
				f.senha.focus();
				return false;
			}
			if(f.repetir_senha.value!=f.senha.value)
			{
				alert("A CONFIRMAÇÃO DE SENHA não confere!");
				f.repetir_senha.value = "";
				f.repetir_senha.focus();
				return false;
			}

		}
		
		if(validaEndereco==true)
		{
			if(!ValidarCadastro_Endereco(f))
			{
				return false;	
			}
		}
		
	} catch(e){alert(e); return false}
}


/*
Nome da Função: SetProdutoOpcao1(url, idp, opt1)
	Parametro url: url da página
	Parametro idp: idp produto
	Parametro opt1: opt1 opcao 1
Descrição da Função: Seta Produto-OPCAO
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 03/08/2009
*/
function SetProdutoOpcao1(url, idp, opt1){
	window.location.href = url + '/setprodutoopcao.php?idp=' + idp + '&opt1=' + opt1;
}

/*
Nome da Função: SetProdutoOpcao2(url, idp, opt1, opt2)
	Parametro url: url da página
	Parametro idp: idp produto
	Parametro opt1: opt1 opcao 1
	Parametro opt1: opt2 opcao 2
Descrição da Função: Seta Produto-OPCAO
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 03/08/2009
*/
function SetProdutoOpcao2(url, idp, opt1, opt2){
	window.location.href = url + '/setprodutoopcao.php?idp=' + idp + '&opt1=' + opt1 + '&opt2=' + opt2;
}

/*

/*
Nome da Função: ValidarCadastro_Cliente_FISICA(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o cadastro de clientes dos sites QUE ACEITAM APENAS PESSOA FISICA
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 18/09/2009
*/
function ValidarCadastro_Cliente_FISICA(f, validaEndereco)
{
	try{
		/**
		 * VALIDACAO DE PESSOA FISICA
		 */
		if(f.nome.value=="")
		{
			alert("Por favor, preencha o NOME completo!");
			f.nome.focus();
			return false;
		}
		if(f.nacionalidade_id.value=="")
		{
			alert("Por favor, selecione a sua NACIONALIDADE!");
			f.nacionalidade_id.focus();
			return false;
		}
		if(f.cpf.value=="")
		{
			alert("Por favor, preencha o CPF!");
			f.cpf.focus();
			return false;
		}else if(f.cpf.value.length < 11){
			alert("Por favor, o CPF está preenchido incorretamente. FALTAM DÍGITOS!");
			f.cpf.focus();
			return false;
		}
		if(f.nacionalidade != 2) {
			if(!ValidaCPF(f.cpf.value))
			{
				alert("CPF incorreto, verifique!");
				f.cpf.focus();
				return false;
			}
		}
		if(f.rg.value=="")
		{
			alert("Por favor, preencha o RG!");
			f.rg.focus();
			return false;
		}
		if(f.orgao_emissor.value=="")
		{
			alert("Por favor, preencha o ÓRGÃO EMISSOR do seu RG!");
			f.orgao_emissor.focus();
			return false;
		}
		if(f.data_nascimento_d.value=="")
		{
			alert("Por favor, preencha a DATA DE NASCIMENTO!");
			f.data_nascimento_d.focus();
			return false;
		}
		if(f.data_nascimento_m.value=="")
		{
			alert("Por favor, preencha a DATA DE NASCIMENTO!");
			f.data_nascimento_m.focus();
			return false;
		}
		if(f.data_nascimento_y.value=="")
		{
			alert("Por favor, preencha a DATA DE NASCIMENTO!");
			f.data_nascimento_y.focus();
			return false;
		}

		if(!ValidaData(f.data_nascimento_d.value + '/' + f.data_nascimento_m.value + '/' + f.data_nascimento_y.value))
		{
			alert("DATA DE NASCIMENTO incorreta, verifique!");
			f.data_nascimento_d.value = '';
			f.data_nascimento_m.value = '';
			f.data_nascimento_y.value = '';
			f.data_nascimento_d.focus();
			return false;
		}
		if(f.sexo.value=="")
		{
			alert("Por favor, selecione o SEXO!");
			f.sexo.focus();
			return false;
		}
		if(f.senha.value=="")
		{
			alert("Por favor, informe a sua nova SENHA!");
			f.senha.focus();
			return false;
		}
		else if(f.senha.value.length<5)
		{
			alert("A SENHA deve possuir no mínimo 5 caracteres!");
			f.senha.focus();
			return false;
		}
		if(f.repetir_senha.value!=f.senha.value)
		{
			alert("A CONFIRMAÇÃO DE SENHA não confere!");
			f.repetir_senha.value = "";
			f.repetir_senha.focus();
			return false;
		}
		if(f.id_como_conheceu_loja.value==""){
			alert("Informe a opção: Como conheceu a Loja!");
			f.id_como_conheceu_loja.value = "";
			f.id_como_conheceu_loja.focus();
			return false;
		}
		

		if(validaEndereco==true)
		{
			if(!ValidarCadastro_Endereco(f))
			{
				return false;	
			}
		}
		
	} catch(e){alert(e); return false}
}



/*
Nome da Função: ExcluirListaPresentes(id)
	Parametro id: id da lista de presentes
Descrição da Função: Confirmar Exclusão da Lista de Presentes
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 18/09/2009
*/
function ExcluirListaPresentes(id){
	
	if(confirm('Confirma Exclusão da Lista de Presente? Esta ação não poderá ser desfeita!')){
		window.location.href='lista_presentes_excluir.php?id='+id;
	}
   
}

/*
Nome da Função: ExcluirItemListaPresente(prod, lista)
	Parametro prod: produto
	Parametro lista: lista
Descrição da Função: Confirmar Exclusão da Lista de Presentes
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 18/09/2009
*/
function ExcluirItemListaPresente(prod, lista){
	
	if(confirm('Confirma Remoção deste Produto? Esta ação não poderá ser desfeita!')){
		window.location.href='lista_presentes_removeritem.php?prod='+prod+'&lista='+lista;
	}
   
}



/*
	@Função: Ajax_ProcessaCupom() -- Processa Cupom Desconto
	@params:
		frm = formulario contendo as informações para calculo
	Criado por: Joao Paulo Wodiani <joaopaulo@ecompleto.com.br>
	Data: 31/08/2009
*/
function Ajax_ProcessaCupom(frm){
	
	try {
		
		erro = 0;
		if(frm.cupom1.value.length != 4){
			alert("Por favor, preencha o Cupom Corretamente!");
			frm.cupom1.focus();
			erro = 1;
		}

		if(frm.cupom2.value.length != 4 && erro!=1){
			alert("Por favor, preencha o Cupom Corretamente!");
			frm.cupom2.focus();
			erro = 1;
		}

		if(frm.cupom3.value.length != 4 && erro!=1){
			alert("Por favor, preencha o Cupom Corretamente!");
			frm.cupom3.focus();
			erro = 1;
		}

		if(frm.cupom4.value.length != 4 && erro!=1){
			alert("Por favor, preencha o Cupom Corretamente!");
			frm.cupom4.focus();
			erro = 1;
		}
		
		if(erro!=1){
			url = "processa_cupom.php?couponcode="+ frm.cupom1.value +"-"+ frm.cupom2.value +"-"+ frm.cupom3.value +"-"+ frm.cupom4.value;
			window.location.href=url;
		}

		
	} catch(e) { alert(e); }
	
}
function Ajax_ProcessaCupomCC(id)//processa cupom compra coletiva
{
	
	var erro;
	valor = 0;
	$.ajax({
		url:'processa_cupomcc.php',
		type:'post',
		dataType:'json',
		data:{couponcode:$('#'+id).val()},
		success:function(data)
		{
			$.each(data,function(k,v){
				if(k == 'erro')
				{
					erro = v;
				}
				else if( k == 'mensagem')
				{
					msg = v;
				}
				else if( k == 'valor')
				{
					valor = v;
				}
			})
			
			if(erro){
				alert(msg)
				$('#img_cupomvalido').fadeOut(200);
			}
			else
			{
				window.location = window.location;
				
			}
		}
	})
}



function CarregaFormasEntrega(cep1, cep2, id_basket,imposto)
{
	try {

		var erro = 0;

		if(cep1==""){
			alert('Preencha o CEP!');
			erro = 1;
		}		

		if(cep2=="" && erro==0){
			alert('Preencha o CEP!');
			erro = 1;
		}
		
		if(erro==0){
			
			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", 'carregaformasentrega.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function(){
				if (oHTTPRequest.readyState==4){
					document.getElementById("formas_entrega").innerHTML = URLDecode(oHTTPRequest.responseText);
					document.getElementById("cep").innerHTML = "";
					document.getElementById("ent").style.visibility = "";
					if(imposto==true){
						//alert(imposto)
						CarregaImposto(cep1, cep2, id_basket, '',imposto);
					}
				} else {
					document.getElementById("formas_entrega").innerHTML = "<img src='http://www.ecompleto.com.br/i_padrao/loading.gif'>";
					
				}
			}
			oHTTPRequest.send("cep1="+cep1+"&cep2="+cep2+"&id_basket="+id_basket);
		
		}
	} catch(e) { alert(e); }	
}


function CarregaEmbalagemPresente(id_produto, id_basket, checked)
{
	try {


			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", 'carregaembalagempresente.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function(){
				if (oHTTPRequest.readyState==4){
					//document.getElementById("formas_entrega").innerHTML = URLDecode(oHTTPRequest.responseText);
				} else {
					//document.getElementById("formas_entrega").innerHTML = "<img src='http://www.ecompleto.com.br/i_padrao/loading.gif'>";
				}
			}
			oHTTPRequest.send("id_produto="+id_produto+"&id_basket="+id_basket+"&checked="+checked);
		
		
	} catch(e) { alert(e); }	
}



/*
Nome da Função: ValidarCadastro_Cliente_TRUCKPLAZA(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o cadastro de clientes da TruckPlaza
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 14/10/2009
*/
function ValidarCadastro_Cliente_TRUCKPLAZA(f, validaEndereco)
{
	try{
		/**
		 * VALIDACAO DE PESSOA FISICA
		 */
		if(f.tipo_pessoa[0].checked)
		{
			if(f.nome.value=="")
			{
				alert("Por favor, preencha o NOME completo!");
				f.nome.focus();
				return false;
			}
			if(f.nacionalidade_id.value=="")
			{
				alert("Por favor, selecione a sua NACIONALIDADE!");
				f.nacionalidade_id.focus();
				return false;
			}
			if(f.cpf.value=="")
			{
				alert("Por favor, preencha o CPF!");
				f.cpf.focus();
				return false;
			}else if(f.cpf.value.length < 11){
				alert("Por favor, o CPF está preenchido incorretamente. FALTAM DÍGITOS!");
				f.cpf.focus();
				return false;
			}
			if(f.nacionalidade != 2) {
				if(!ValidaCPF(f.cpf.value))
				{
					alert("CPF incorreto, verifique!");
					f.cpf.focus();
					return false;
				}
			}
			if(f.rg.value=="")
			{
				alert("Por favor, preencha o RG!");
				f.rg.focus();
				return false;
			}
			if(f.orgao_emissor.value=="")
			{
				alert("Por favor, preencha o ÓRGÃO EMISSOR do seu RG!");
				f.orgao_emissor.focus();
				return false;
			}
			if(f.data_nascimento_d.value=="")
			{
				alert("Por favor, preencha a DATA DE NASCIMENTO!");
				f.data_nascimento_d.focus();
				return false;
			}
			if(f.data_nascimento_m.value=="")
			{
				alert("Por favor, preencha a DATA DE NASCIMENTO!");
				f.data_nascimento_m.focus();
				return false;
			}
			if(f.data_nascimento_y.value=="")
			{
				alert("Por favor, preencha a DATA DE NASCIMENTO!");
				f.data_nascimento_y.focus();
				return false;
			}

			if(!ValidaData(f.data_nascimento_d.value + '/' + f.data_nascimento_m.value + '/' + f.data_nascimento_y.value))
			{
				alert("DATA DE NASCIMENTO incorreta, verifique!");
				f.data_nascimento_d.value = '';
				f.data_nascimento_m.value = '';
				f.data_nascimento_y.value = '';
				f.data_nascimento_d.focus();
				return false;
			}
			if(f.sexo.value=="")
			{
				alert("Por favor, selecione o SEXO!");
				f.sexo.focus();
				return false;
			}
			if(f.senha.value=="")
			{
				alert("Por favor, informe a sua nova SENHA!");
				f.senha.focus();
				return false;
			}
			else if(f.senha.value.length<5)
			{
				alert("A SENHA deve possuir no mínimo 5 caracteres!");
				f.senha.focus();
				return false;
			}
			if(f.repetir_senha.value!=f.senha.value)
			{
				alert("A CONFIRMAÇÃO DE SENHA não confere!");
				f.repetir_senha.value = "";
				f.repetir_senha.focus();
				return false;
			}
			if(f.id_como_conheceu_loja.value==""){
				alert("Informe a opção: Como conheceu a Loja!");
				f.id_como_conheceu_loja.value = "";
				f.id_como_conheceu_loja.focus();
				return false;
			}
			if(f.modelo_veiculo.value=="")
			{
				alert("Por favor, informe o modelo do seu Veículo!");
				f.modelo_veiculo.focus();
				return false;
			}
			if(f.ano_veiculo.value=="")
			{
				alert("Por favor, informe o Ano do seu Veículo!");
				f.ano_veiculo.focus();
				return false;
			}
			if(f.placa_veiculo.value=="")
			{
				alert("Por favor, informe a Placa do seu Veículo!");
				f.placa_veiculo.focus();
				return false;
			}



		}
		else /*** VALIDACAO DE PESSOA JURIDICA */
		{
			if(f.razao.value=="")
			{
				alert("Favor preencher a Razão Social!");
				f.razao.focus();
				return false;
			}
			if(f.cnpj.value=="")
			{
				alert("Favor preencher o C.N.P.J. !");
				f.cnpj.focus();
				return false;
			}else if(f.cnpj.value.length < 11){
				alert("Por favor, o CNPJ está preenchido incorretamente. FALTAM DÍGITOS!");
				f.cnpj.focus();
				return false;
			}
			if(!validaCNPJ(f.cnpj.value))
			{
				alert("Favor preencher o C.N.P.J. corretamente !");
				f.cnpj.focus();
				return false;
			}
			if(f.senha.value=="")
			{
				alert("Por favor, informe a sua nova SENHA!");
				f.senha.focus();
				return false;
			}
			else if(f.senha.value.length<5)
			{
				alert("A SENHA deve possuir no mínimo 5 caracteres!");
				f.senha.focus();
				return false;
			}
			if(f.repetir_senha.value!=f.senha.value)
			{
				alert("A CONFIRMAÇÃO DE SENHA não confere!");
				f.repetir_senha.value = "";
				f.repetir_senha.focus();
				return false;
			}
			if(f.id_como_conheceu_loja.value==""){
				alert("Informe a opção: Como conheceu a Loja!");
				f.id_como_conheceu_loja.value = "";
				f.id_como_conheceu_loja.focus();
				return false;
			}			

		}
		
		if(validaEndereco==true)
		{
			if(!ValidarCadastro_Endereco(f))
			{
				return false;	
			}
		}
		
	} catch(e){alert(e); return false}
}

/* mod */
function ModalFechar() {
	var overum = document.getElementById("overlayFrete");
	var overdois = document.getElementById("overlayTbl");
	document.body.removeChild(overum);
	document.body.removeChild(overdois);
	return false;
}

function ModalAbrir(titulo, conteudo) {
	//var strhtml = '';
	
	/*strhtml += '<div id="overlayFrete" style="position: fixed; top: 0; left: 0; width:100%; height:100%; z-index: 20; background: #FFFFFF; -moz-user-select: none; opacity: 0.8;" onclick="javascript:ModalFechar();"></div>';
	strhtml += '<table id="overlayTbl" width="680" height="420" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF" style="z-index: 30; border: 2px solid #CCCCCC; position: fixed; left:50%; top:50%; margin-top: -210px; margin-left: -340px;">';
	strhtml += '<tr style="font: normal 12px Tahoma;">';
	strhtml += '<td id="overlayTitulo" style="padding: 8px;"><strong>'+titulo+'</strong></td>';
	strhtml += '<td align="right" onclick="javascript:ModalFechar();" style="text-align: right; cursor: pointer; font-size:10px;padding: 8px;">fechar [<strong style="color: #F00;">x</strong>]</td>';
	strhtml += '</tr>';
	strhtml += '<tr style="background-color:#CCCCCC; height:1px;"><td colspan="2"></td></tr>';
	strhtml += '<tr height="100%">';
	strhtml += '<td colspan="2" id="overlayConteudo">';
	strhtml += '<div align="center">';
	strhtml += '<iframe width="660" height="380" src="'+conteudo+'" frameborder="no" border="0"></iframe>';
	strhtml += '</div>';
	strhtml += '</td>';
	strhtml += '</table>';
	
	document.body.innerHTML += strhtml;*/
	w = 680;
	h = 420;
	LeftPosition= (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition= (screen.height) ? (screen.height-h)/2 : 0;
	Settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars=no,toolbar=no,menubar=no,resizable=no,status=yes';
	//window.open(conteudo,titulo,Settings);
	
	window.open(conteudo,"mywindow",'top='+TopPosition+',left='+LeftPosition+',height='+h+',width='+w+',toolbar=no,menubar=no'); 
}
/* fim mod */


/*
Nome da Função: CalcularFreteProduto(idp, qtde, cep1, cep2)
	Parametro idp: id_produto
	Parametro qtde: quantidade
	Parametro cep1: cep-principal (5)
	Parametro cep2: cep-sufixo (3)
Descrição da Função: Carregar as cidades filtradas pelo estado
Desenvolvido por: Joao Paulo Wodiani
Data: 16/01/2010
*/
function CalcularFreteProduto(idp, qtde, cep1, cep2, url)
{
	try {
		
		if(qtde==""){
			alert("Preencha a Quantidade!");
			document.getElementById('quantidade').focus();
			return false;
		}

		if(cep1.length<5){
			alert("CEP Incorreto, são necessários 5 caracteres!");
			document.getElementById('cep1').focus();
			return false;
		}

		if(cep2.length<3){
			alert("CEP Incorreto, são necessários 3 caracteres!");
			document.getElementById('cep2').focus();
			return false;
		}

		document.getElementById("frete_calculado").style.display = 'block';
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", url+'/carregacalcularfrete.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				document.getElementById("frete_calculado").innerHTML = URLDecode(oHTTPRequest.responseText);
			} else {
				//document.getElementById("frete_calculado").innerHTML = "<img src='http://www.ecompleto.com.br/i_padrao/loading.gif'>";
				document.getElementById("frete_calculado").innerHTML = "Carregando...";
			}
		}
		oHTTPRequest.send("idproduto="+idp+"&quantidade="+qtde+"&cep1="+cep1+"&cep2="+cep2);
	} catch(e) { alert(e); }
}



/*
Nome da Função: IdentificarCadastro_New()
Descrição da Função: Verifica se o cadastro é novo ou já existente
Desenvolvido por: Joao Paulo Wodiani
Data: 21/06/2010
*/
function IdentificarCadastro_New(frm)
{

	if(frm.email.value=="")
	{
		alert("Por favor, informe o seu e-mail!");
		frm.email.focus();
		return(false);
	}else
	{
		if(!ValidaEmail(frm.email.value))
		{
			alert("E-mail inválido, verifique!");
			frm.email.value = "";
			frm.email.focus();
			return(false);
		}
	}

	if(frm.senha.value=="")
	{
		alert("Por favor, informe a sua senha!");
		frm.senha.focus();
		return(false);
	}
	
}



/*
Nome da Função: Login_Add(f)
	Parametro f: form 
	Descrição da Função: Valida Login para o formulario de cadastro-novo ecompleto
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 21/06/2010
*/
function Login_Add(f){

	if(f.email.value=="")
	{
		alert("Por favor, informe o seu e-mail!");
		f.email.focus();
		return(false);
	}else if(!ValidaEmail(f.email.value)){
		alert("Seu e-mail está preenchido incorretamente, verifique!");
		f.email.focus();
		return(false);
	}
}




/*
Nome da Função: ValidarIndique_New(f)
	Parametro f: objeto formulario que possui os campos
Descrição da Função: Valida o preenchimento dos campos para indicação de produto
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 23/07/2010
*/
function ValidarIndique_New(f, url)
{
	
	try
	{
	
		if(f.de.value=="")
		{
			alert("Por favor, preencha o seu NOME!");
			f.de.focus();
			return false;
		}
		if(f.email.value=="")
		{
			alert("Por favor, preencha o seu E-MAIL!");
			f.email.focus();
			return false;
		}
		if(f.para.value=="")
		{
			alert("Informe o NOME do seu amigo!");
			f.para.focus();
			return false;
		}
		if(f.email_para.value=="")
		{
			alert("Informe o E-MAIL do seu amigo!");
			f.repetir_senha.value = "";
			f.repetir_senha.focus();
			return false;
		}
		if(f.code.value=="")
		{
			alert("Preencha o código de VERIFICAÇÃO de mensagens!");
			f.code.value = "";
			f.code.focus();
			return false;
		}
		
		label = 'produto';
		if(f.tp_registro.value=='V'){
			label = 'veículo';
		}
		
		
		//enviando informações por ajax
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", url+'/indique_amigo_action.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				retorno = URLDecode(oHTTPRequest.responseText);
				if(retorno=="ok"){
					document.getElementById("new_indicacao_action").innerHTML = '<ul><li>A indicação deste '+ label +' foi enviada com sucesso para <strong>'+ f.para.value +'</strong> <span>'+ f.email_para.value +'</span></li></ul>';
					f.para.value="";
					f.email_para.value="";
				}else{
					alert(retorno);
					document.getElementById("new_indicacao_action").style.display = 'none';
					document.getElementById("new_indicacao").style.display = 'block';
				}
			} else {
					document.getElementById("new_indicacao_action").innerHTML = '<ul><li><img src="http://www.ecompleto.com.br/i_padrao/loading.gif"></li></ul>';
					document.getElementById("new_indicacao").style.display = 'none';
					document.getElementById("new_indicacao_action").style.display = 'block';
			}
		}
		oHTTPRequest.send("id="+ f.id.value +"&de="+ f.de.value +"&email="+ f.email.value +"&para="+ f.para.value +"&email_para="+ f.email_para.value +"&code="+ f.code.value +"&ajax=t&comentario="+ f.comentario.value+"&label="+label+"&tp_registro="+f.tp_registro.value);

		return false;

	} catch(e){alert(e); return false}
}


function getBtnSelecione(url){	return '<img src="'+url+'/images/bt_selecione.png" alt="selecione a opção" border="0">'; }
function getBtnComprar(url, idl){	return '<a href="javascript: newAdicionarCarrinho(document.getElementById(\'SetIdProduto\').value, '+idl+', \'document.frmDetalhe.opcao_produto.value\', \'document.frmDetalhe.opcao_produto_2.value\', document.getElementById(\'quantidade_cart\').value);" title="Adicionar ao Carrinho"><img src="'+url+'/images/bt_comprar.png" alt="comprar" border="0"></a>'; }

/*
Nome da Função: SetOpcaoProduto(id_pai, nivel, total_nivel, opcao_1, opcao_2, opcao_3, idl)
	Parametros:
		id_pai => produto
		nivel_atu => nivel_atual
		nivel_des => nivel_desejado
		total_nivel => total niveis
		opcao_1 => text1
		opcao_2 => text2
		opcao_3 => text3
		url => url
		idl => idl
			  
Descrição da Função: Seleciona a Opção do Produto na página
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 06/08/2010
*/
function SetOpcaoProduto(id_pai, nivel_atu, nivel_des, total_nivel, opcao_1, opcao_2, opcao_3, url, idl, listpres)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", url + '/ajax.setopcaoproduto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				if(nivel_atu<total_nivel){
					//limpa as divs com nivel superior					
					for(j=(nivel_atu+1);j<=total_nivel;j++){
						document.getElementById("opcoes_"+ j).innerHTML = "";						
					}
					document.getElementById("opcoes_"+ nivel_des).innerHTML = URLDecode(oHTTPRequest.responseText);
				}else{
					GetOpcaoProduto(id_pai, total_nivel, opcao_1, opcao_2, opcao_3, url, idl, listpres);
				}
			} else {
				if(nivel_atu<total_nivel){
					var_html = '<a title="Adicionar ao Carrinho" href="javascript:exibirMsgOpcao(); "><img border="0" alt="comprar" src="'+url	+'/images/bt_comprar.png"></a>';
					$("#btnComprar").html(var_html);
					document.getElementById("opcoes_"+ nivel_des).style.display='block';
					document.getElementById("opcoes_"+ nivel_des).innerHTML = '<img src="http://www.ecompleto.com.br/i_padrao/loading.gif">';
				}
			}
		}
		oHTTPRequest.send("id="+id_pai+"&nivel_atu="+nivel_atu+"&nivel_des="+nivel_des+"&total_nivel="+total_nivel+"&opcao_1="+opcao_1+"&opcao_2="+opcao_2+"&opcao_3="+opcao_3);
	} catch(e) { alert(e); }	
}


/*
Nome da Função: GetOpcaoProduto(id_pai, total_nivel, opcao_1, opcao_2, opcao_3, url, idl)
	Parametros:
		id_pai => produto
		total_nivel => total_nivel
		opcao_1 => text1
		opcao_2 => text2
		opcao_3 => text3
		url => url
		idl => idl
			  
Descrição da Função: Get Codigo Produto
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 06/08/2010
*/
function GetOpcaoProduto(id_pai, total_nivel, opcao_1, opcao_2, opcao_3, url, idl, listpres)
{
	
	
	try {
		$("#btnComprar").html('<img src="http://www.ecompleto.com.br/i_padrao/loading.gif">');
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", url + '/ajax.getopcaoproduto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if(oHTTPRequest.readyState==4){
				idtemp = URLDecode(oHTTPRequest.responseText);
				try{
					document.getElementById('btaddlista').innerHTML = '<a href="javascript: popup( \''+url+'/lista_pop.php?id='+idtemp+'\', \'lista_presentes\', 620, 320);">Adicionar a Lista de Presentes.</a>';
				}catch(exe){}
					document.getElementById('SetIdProduto').value = idtemp;
				var_html = getBtnComprar(url, idl);
				$("#btnComprar").html(var_html);
				
				 GetDescricaoProduto(URLDecode(oHTTPRequest.responseText), url, listpres);
				 GetExtrasProduto(URLDecode(oHTTPRequest.responseText), url);
				 GetImagemProduto(URLDecode(oHTTPRequest.responseText), url);
				 GetProdutoDisponivel(URLDecode(oHTTPRequest.responseText), url, idl);			
				 if(idl != 58){						
					GetComentariosProduto(URLDecode(oHTTPRequest.responseText), url, idl);				 
					GetFotoMiniProduto(URLDecode(oHTTPRequest.responseText), url);					 
				 }
			}
		}
		oHTTPRequest.send("id="+id_pai+"&total_nivel="+total_nivel+"&opcao_1="+opcao_1+"&opcao_2="+opcao_2+"&opcao_3="+opcao_3);
	} catch(e) { alert(e); }	
}
/*
Nome da Função: GetDescricaoProduto(id_)
	Parametros:
		id => id_produto
			  
Descrição da Função: Get Descricao do Produto
Desenvolvido por: Gisele Silva do Carmo <gisele.carmo@ecompleto.com.br>
Data: 25/08/2010
*/


function GetDescricaoProduto(id, url, listpres){
	
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post",  url + '/ajax.getdescricaoproduto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if(oHTTPRequest.readyState==4){
				
				document.getElementById('carregar_produto').innerHTML = "";
				document.getElementById('carregar_produto').innerHTML =  URLDecode(oHTTPRequest.responseText);
				carregaKitsProdutos(id,url);
			}
		}
	oHTTPRequest.send("id="+id+"&listpres="+listpres);
	} catch(e) { alert(e); }	
}

function carregaKitsProdutos(id_produto,url){
	$.ajax({
		url:url+'/ajax.carregakitproduto.php',
		dataType:'html',
		type:'post',
		data:{id:id_produto},
		beforeSend:function(){	
			$('#produtosKit').html('');
		},
		success:function(data){
			$('#produtosKit').html(data);
		}
	})
}




function GetProdutoDisponivel(id, url, idl){
	
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post",  url + '/ajax.getprodutodisponivel.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if(oHTTPRequest.readyState==4){
				
				disponivel = URLDecode(oHTTPRequest.responseText);
				
				if(disponivel == 0){		
					
					if(idl != 58){
													
						var nome_loja = document.getElementById('nome_loja').value;
						document.getElementById('comprar').style.display = 'none';
						document.getElementById('calcule_frete').style.display = 'none'; 	
						document.getElementById('new_disponibilidade').innerHTML = '';
						document.getElementById('new_disponibilidade').style.display = 'none';
										
						var f_avise = '';
						f_avise +="<span>";
						f_avise +="<strong>Avise-me quando chegar</strong><br />";
						f_avise +="<form name=\"avise_me\" method=\"post\" action=\""+url+"/aviseme_action.php\" onsubmit=\"javascript: return Validar_AviseMe(this);\">";
						f_avise +="<fieldset>";
						f_avise +="<label for=\"nome_avise\">Nome:<br />";
						f_avise +="<input name=\"nome_avise\" type=\"text\" id=\"nome_avise\" maxlength=\"100\" class=\"newsletter\" />";
						f_avise +="</label>";
						f_avise +="<label for=\"email_avise\">E-mail:<br />";
						f_avise +="<input name=\"email_avise\" type=\"text\" id=\"email_avise\" maxlength=\"200\" class=\"newsletter\" />";
						f_avise += "</label>";
						f_avise += "<label><input name=\"autoriza_mailing\" type=\"checkbox\" value=\"1\" /> Desejo receber e-mails da "+nome_loja+"</label>";
						f_avise += "<label><br /><input name=\"bt_gravar\" class=\"bt_news\" type=\"submit\" value=\"Cadastrar\" /></label>";
						f_avise += "<input name=\"id_produto\" type=\"hidden\" value=\""+id+"\" />";
						f_avise += "</fieldset>";
						f_avise += "</form>";
						f_avise += "</span>";	
											
					   document.getElementById('avise').innerHTML = f_avise;
					   document.getElementById('avise').style.display = 'block';	
					}else{
						
						document.getElementById('btnComprar').style.display = 'none';
						
						var f_avise = '';
						f_avise += "<strong>Avise-me quando chegar</strong>";
						f_avise +="<form name=\"avise_me\" method=\"post\" action=\""+url+"/aviseme_action.php\" onsubmit=\"javascript: return Validar_AviseMe(this);\">";
						f_avise += "<p>Nome:";
						f_avise += "<input name=\"nome_avise\" type=\"text\" class=\"avise\"/></p>";
						f_avise += "<p>Email:";
						f_avise += "<input name=\"email_avise\" type=\"text\" class=\"avise\"/></p>";
						f_avise += "<input type=\"hidden\" id=\"id_produto\" name=\"id_produto\" value=\""+id+"\"/>";
						f_avise += "<p><input name=\"autoriza_mailing\" type=\"checkbox\" value=\"\" />";
						f_avise += "Desejo receber e-mails da O&Uuml;S</p>";
						f_avise += "<input type=\"submit\" value=\"cadastrar\" class=\"aviseme_bt\" />";
						f_avise += "</form>";
						document.getElementById('aviseme').innerHTML = f_avise;
					   	document.getElementById('aviseme').style.display = 'block';	
						
					}
					
				}else{	
				
					if(idl != 58){
						document.getElementById('comprar').style.display = 'block';
						document.getElementById('calcule_frete').style.display = 'block';
						document.getElementById('avise').innerHTML = "";
						document.getElementById('avise').style.display = 'none';		
						if(idl != 97){
							GetProdutoFreteGratis(id, url);							
						}
						
					}else{
						document.getElementById('aviseme').innerHTML = "";
					   	document.getElementById('aviseme').style.display = 'none';
						document.getElementById('btnComprar').style.display = 'block';		
					}
					 
					
				}
			}
		}
	oHTTPRequest.send("id="+id);
	} catch(e) { alert(e); }	
}


function GetComentariosProduto(id, url, idl){
	
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post",  url + '/ajax.getcomentariosproduto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if(oHTTPRequest.readyState==4){
				document.getElementById('comentarios').innerHTML = "";
				document.getElementById('comentarios2').innerHTML = "";
				if(idl != 44){
					document.getElementById('comentarios').innerHTML =  URLDecode(oHTTPRequest.responseText);
				}else{
					document.getElementById('comentarios2').innerHTML =  URLDecode(oHTTPRequest.responseText);
				}
			}
		}
	oHTTPRequest.send("id="+id);
	} catch(e) { alert(e); }	
}

function GetExtrasProduto(id, url){
	
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post",  url + '/ajax.getextrasproduto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if(oHTTPRequest.readyState==4){
				document.getElementById('extras').innerHTML =  URLDecode(oHTTPRequest.responseText);
				
			}
		}
	oHTTPRequest.send("id="+id);
	} catch(e) { alert(e); }	
}

function GetImagemProduto(id, url){
	
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post",  url + '/ajax.getimagemproduto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if(oHTTPRequest.readyState==4){
				document.getElementById('imagem').innerHTML =  URLDecode(oHTTPRequest.responseText);				
				 var opcoesZoom = {
					zoomType: 'reverse',
					zoomWidth: 460,
					zoomHeight: 370,
					xOffset: 40,
					yOffset: -6,
					position:"right",
					imageOpacity: 0.3,
					title: false,
					showPreload: true,
					preloadText: 'carregando imagem'
				}	
				$("#imagemMaior").jqzoom(opcoesZoom);
				
				/* seta configurações para o lightbox */
				var opcoesLightbox = {
					overlayBgColor: '#000000',
					overlayOpacity: 0.3,
					fixedNavigation: true,
					imageLoading: 'http://www.ecompleto.com.br/i/lightbox/lightbox-ico-loading.gif',
					imageBlank: 'http://www.ecompleto.com.br/i/lightbox/lightbox-blank.gif',
					imageBtnClose: 'http://www.ecompleto.com.br/i/lightbox/lightbox-btn-close.gif',
					imageBtnPrev: 'http://www.ecompleto.com.br/i/lightbox/lightbox-btn-prev.gif',
					imageBtnNext: 'http://www.ecompleto.com.br/i/lightbox/lightbox-btn-next.gif',
					containerResizeSpeed: 350,
					txtImage: 'Imagem',
					txtOf: 'de',
					keyToClose: 'f',
					keyToPrev: 'a',
					keyToNext: 'p'
				}
				
					   
				/* e ao clicar na imagem maior, lightbox */
				$("a[rel*='lightbox']").lightBox(opcoesLightbox);
				
			
			}
		}
	oHTTPRequest.send("id="+id);
	} catch(e) { alert(e); }	
}

function GetFotoMiniProduto(id, url){
	
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post",  url + '/ajax.getfotominiproduto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if(oHTTPRequest.readyState==4){
				
				 document.getElementById('produtoFotoMini').innerHTML = URLDecode(oHTTPRequest.responseText);
				 $("#produtoFotoMini img").each(function(index) {
					if($(this).attr("alt") != "") {
						/* o alt da imagem deverá estar no padrão imagem_grande_url|imagem_media_url */
						var pedacos = $(this).attr("rel").split("|");
						var imagem_grande = pedacos[0];
						var imagem_media = pedacos[1];
						
						/* preload das imagens */
						/*$("body").append('<img src="'+imagem_grande+'" alt="preload" style="display:none;" />');
						$("body").append('<img src="'+imagem_media+'" alt="preload" style="display:none;" />');*/
						$("body").append('<img src="'+imagem_grande+'" alt="preload" style="width:0px;height:0px;" />');
						$("body").append('<img src="'+imagem_media+'" alt="preload" style="width:0px;height:0px;" />');
						
						/* quando clicar em cada miniatura */
						$(this).click(function() {
							/* faz fade na imagem */
							$("#produtoFotoMedia #table #cell #imagem a img").fadeOut("fast", function() {
								/* quando sumir a imagem, altera o link (para imagem grande) e src da imagem */
								$("#produtoFotoMedia #table #cell #imagem a").attr("href", imagem_grande);
								$("#produtoFotoMedia #table #cell #imagem a img").attr("src", imagem_media);
								/* exibe imagem novamente, com fade */
								$("#produtoFotoMedia #table #cell #imagem a img").fadeIn("fast");
							});
						});
					}
				});
			}
		}
	oHTTPRequest.send("id="+id);
	} catch(e) { alert(e); }	
}

function GetProdutoFreteGratis(id, url){
	 try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post",  url + '/ajax.getprodutofretegratis.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if(oHTTPRequest.readyState==4){
				if(URLDecode(oHTTPRequest.responseText) != ""){
					document.getElementById('new_disponibilidade').innerHTML = "<span>"+URLDecode(oHTTPRequest.responseText+"</span>");
					document.getElementById('new_disponibilidade').style.display = 'block';		
				}
			}
		}
	oHTTPRequest.send("id="+id);
	} catch(e) { alert(e); }	
	 
 }
 
 
 /*
Nome da Função: LoadHeader(div)
	Parametro div: div que irá receber o conteudo
Descrição da Função: carrega o header independente do sistema de cache
Desenvolvido por: Joao Paulo Wodiani
Data: 04/05/2009
*/
function LoadHeader(div, url)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", url + '/LoadHeader.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function() {
			if (oHTTPRequest.readyState==4){
				document.getElementById(div).innerHTML = URLDecode(oHTTPRequest.responseText);
			}
			else
			{
				document.getElementById(div).innerHTML = '<img src="http://www.ecompleto.com.br/i_padrao/loading.gif">';
			}
		}
		oHTTPRequest.send("id=1");
	} catch(e) { alert(e); }
}

		var entity_table = {
		//	34: "&quot;",		// Quotation mark. Not required
			38: "&amp;",		// Ampersand. Applied before everything else in the application
			60: "&lt;",		// Less-than sign
			62: "&gt;",		// Greater-than sign
		//	63: "&#63;",		// Question mark
		//	111: "&#111;",		// Latin small letter o
			160: "&nbsp;",		// Non-breaking space
			161: "&iexcl;",		// Inverted exclamation mark
			162: "&cent;",		// Cent sign
			163: "&pound;",		// Pound sign
			164: "&curren;",	// Currency sign
			165: "&yen;",		// Yen sign
			166: "&brvbar;",	// Broken vertical bar
			167: "&sect;",		// Section sign
			168: "&uml;",		// Diaeresis
			169: "&copy;",		// Copyright sign
			170: "&ordf;",		// Feminine ordinal indicator
			171: "&laquo;",		// Left-pointing double angle quotation mark
			172: "&not;",		// Not sign
			173: "&shy;",		// Soft hyphen
			174: "&reg;",		// Registered sign
			175: "&macr;",		// Macron
			176: "&deg;",		// Degree sign
			177: "&plusmn;",	// Plus-minus sign
			178: "&sup2;",		// Superscript two
			179: "&sup3;",		// Superscript three
			180: "&acute;",		// Acute accent
			181: "&micro;",		// Micro sign
			182: "&para;",		// Pilcrow sign
			183: "&middot;",	// Middle dot
			184: "&cedil;",		// Cedilla
			185: "&sup1;",		// Superscript one
			186: "&ordm;",		// Masculine ordinal indicator
			187: "&raquo;",		// Right-pointing double angle quotation mark
			188: "&frac14;",	// Vulgar fraction one-quarter
			189: "&frac12;",	// Vulgar fraction one-half
			190: "&frac34;",	// Vulgar fraction three-quarters
			191: "&iquest;",	// Inverted question mark
			192: "&Agrave;",	// A with grave
			193: "&Aacute;",	// A with acute
			194: "&Acirc;",		// A with circumflex
			195: "&Atilde;",	// A with tilde
			196: "&Auml;",		// A with diaeresis
			197: "&Aring;",		// A with ring above
			198: "&AElig;",		// AE
			199: "&Ccedil;",	// C with cedilla
			200: "&Egrave;",	// E with grave
			201: "&Eacute;",	// E with acute
			202: "&Ecirc;",		// E with circumflex
			203: "&Euml;",		// E with diaeresis
			204: "&Igrave;",	// I with grave
			205: "&Iacute;",	// I with acute
			206: "&Icirc;",		// I with circumflex
			207: "&Iuml;",		// I with diaeresis
			208: "&ETH;",		// Eth
			209: "&Ntilde;",	// N with tilde
			210: "&Ograve;",	// O with grave
			211: "&Oacute;",	// O with acute
			212: "&Ocirc;",		// O with circumflex
			213: "&Otilde;",	// O with tilde
			214: "&Ouml;",		// O with diaeresis
			215: "&times;",		// Multiplication sign
			216: "&Oslash;",	// O with stroke
			217: "&Ugrave;",	// U with grave
			218: "&Uacute;",	// U with acute
			219: "&Ucirc;",		// U with circumflex
			220: "&Uuml;",		// U with diaeresis
			221: "&Yacute;",	// Y with acute
			222: "&THORN;",		// Thorn
			223: "&szlig;",		// Sharp s. Also known as ess-zed
			224: "&agrave;",	// a with grave
			225: "&aacute;",	// a with acute
			226: "&acirc;",		// a with circumflex
			227: "&atilde;",	// a with tilde
			228: "&auml;",		// a with diaeresis
			229: "&aring;",		// a with ring above
			230: "&aelig;",		// ae. Also known as ligature ae
			231: "&ccedil;",	// c with cedilla
			232: "&egrave;",	// e with grave
			233: "&eacute;",	// e with acute
			234: "&ecirc;",		// e with circumflex
			235: "&euml;",		// e with diaeresis
			236: "&igrave;",	// i with grave
			237: "&iacute;",	// i with acute
			238: "&icirc;",		// i with circumflex
			239: "&iuml;",		// i with diaeresis
			240: "&eth;",		// eth
			241: "&ntilde;",	// n with tilde
			242: "&ograve;",	// o with grave
			243: "&oacute;",	// o with acute
			244: "&ocirc;",		// o with circumflex
			245: "&otilde;",	// o with tilde
			246: "&ouml;",		// o with diaeresis
			247: "&divide;",	// Division sign
			248: "&oslash;",	// o with stroke. Also known as o with slash
			249: "&ugrave;",	// u with grave
			250: "&uacute;",	// u with acute
			251: "&ucirc;",		// u with circumflex
			252: "&uuml;",		// u with diaeresis
			253: "&yacute;",	// y with acute
			254: "&thorn;",		// thorn
			255: "&yuml;",		// y with diaeresis
			264: "&#264;",		// Latin capital letter C with circumflex
			265: "&#265;",		// Latin small letter c with circumflex
			338: "&OElig;",		// Latin capital ligature OE
			339: "&oelig;",		// Latin small ligature oe
			352: "&Scaron;",	// Latin capital letter S with caron
			353: "&scaron;",	// Latin small letter s with caron
			372: "&#372;",		// Latin capital letter W with circumflex
			373: "&#373;",		// Latin small letter w with circumflex
			374: "&#374;",		// Latin capital letter Y with circumflex
			375: "&#375;",		// Latin small letter y with circumflex
			376: "&Yuml;",		// Latin capital letter Y with diaeresis
			402: "&fnof;",		// Latin small f with hook, function, florin
			710: "&circ;",		// Modifier letter circumflex accent
			732: "&tilde;",		// Small tilde
			913: "&Alpha;",		// Alpha
			914: "&Beta;",		// Beta
			915: "&Gamma;",		// Gamma
			916: "&Delta;",		// Delta
			917: "&Epsilon;",	// Epsilon
			918: "&Zeta;",		// Zeta
			919: "&Eta;",		// Eta
			920: "&Theta;",		// Theta
			921: "&Iota;",		// Iota
			922: "&Kappa;",		// Kappa
			923: "&Lambda;",	// Lambda
			924: "&Mu;",		// Mu
			925: "&Nu;",		// Nu
			926: "&Xi;",		// Xi
			927: "&Omicron;",	// Omicron
			928: "&Pi;",		// Pi
			929: "&Rho;",		// Rho
			931: "&Sigma;",		// Sigma
			932: "&Tau;",		// Tau
			933: "&Upsilon;",	// Upsilon
			934: "&Phi;",		// Phi
			935: "&Chi;",		// Chi
			936: "&Psi;",		// Psi
			937: "&Omega;",		// Omega
			945: "&alpha;",		// alpha
			946: "&beta;",		// beta
			947: "&gamma;",		// gamma
			948: "&delta;",		// delta
			949: "&epsilon;",	// epsilon
			950: "&zeta;",		// zeta
			951: "&eta;",		// eta
			952: "&theta;",		// theta
			953: "&iota;",		// iota
			954: "&kappa;",		// kappa
			955: "&lambda;",	// lambda
			956: "&mu;",		// mu
			957: "&nu;",		// nu
			958: "&xi;",		// xi
			959: "&omicron;",	// omicron
			960: "&pi;",		// pi
			961: "&rho;",		// rho
			962: "&sigmaf;",	// sigmaf
			963: "&sigma;",		// sigma
			964: "&tau;",		// tau
			965: "&upsilon;",	// upsilon
			966: "&phi;",		// phi
			967: "&chi;",		// chi
			968: "&psi;",		// psi
			969: "&omega;",		// omega
			977: "&thetasym;",	// Theta symbol
			978: "&upsih;",		// Greek upsilon with hook symbol
			982: "&piv;",		// Pi symbol
			8194: "&ensp;",		// En space
			8195: "&emsp;",		// Em space
			8201: "&thinsp;",	// Thin space
			8204: "&zwnj;",		// Zero width non-joiner
			8205: "&zwj;",		// Zero width joiner
			8206: "&lrm;",		// Left-to-right mark
			8207: "&rlm;",		// Right-to-left mark
			8211: "&ndash;",	// En dash
			8212: "&mdash;",	// Em dash
			8216: "&lsquo;",	// Left single quotation mark
			8217: "&rsquo;",	// Right single quotation mark
			8218: "&sbquo;",	// Single low-9 quotation mark
			8220: "&ldquo;",	// Left double quotation mark
			8221: "&rdquo;",	// Right double quotation mark
			8222: "&bdquo;",	// Double low-9 quotation mark
			8224: "&dagger;",	// Dagger
			8225: "&Dagger;",	// Double dagger
			8226: "&bull;",		// Bullet
			8230: "&hellip;",	// Horizontal ellipsis
			8240: "&permil;",	// Per mille sign
			8242: "&prime;",	// Prime
			8243: "&Prime;",	// Double Prime
			8249: "&lsaquo;",	// Single left-pointing angle quotation
			8250: "&rsaquo;",	// Single right-pointing angle quotation
			8254: "&oline;",	// Overline
			8260: "&frasl;",	// Fraction Slash
			8364: "&euro;",		// Euro sign
			8472: "&weierp;",	// Script capital
			8465: "&image;",	// Blackletter capital I
			8476: "&real;",		// Blackletter capital R
			8482: "&trade;",	// Trade mark sign
			8501: "&alefsym;",	// Alef symbol
			8592: "&larr;",		// Leftward arrow
			8593: "&uarr;",		// Upward arrow
			8594: "&rarr;",		// Rightward arrow
			8595: "&darr;",		// Downward arrow
			8596: "&harr;",		// Left right arrow
			8629: "&crarr;",	// Downward arrow with corner leftward. Also known as carriage return
			8656: "&lArr;",		// Leftward double arrow. ISO 10646 does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests
			8657: "&uArr;",		// Upward double arrow
			8658: "&rArr;",		// Rightward double arrow. ISO 10646 does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests
			8659: "&dArr;",		// Downward double arrow
			8660: "&hArr;",		// Left-right double arrow
			// Mathematical Operators
			8704: "&forall;",	// For all
			8706: "&part;",		// Partial differential
			8707: "&exist;",	// There exists
			8709: "&empty;",	// Empty set. Also known as null set and diameter
			8711: "&nabla;",	// Nabla. Also known as backward difference
			8712: "&isin;",		// Element of
			8713: "&notin;",	// Not an element of
			8715: "&ni;",		// Contains as member
			8719: "&prod;",		// N-ary product. Also known as product sign. Prod is not the same character as U+03A0 'greek capital letter pi' though the same glyph might be used for both
			8721: "&sum;",		// N-ary summation. Sum is not the same character as U+03A3 'greek capital letter sigma' though the same glyph might be used for both
			8722: "&minus;",	// Minus sign
			8727: "&lowast;",	// Asterisk operator
			8729: "&#8729;",	// Bullet operator
			8730: "&radic;",	// Square root. Also known as radical sign
			8733: "&prop;",		// Proportional to
			8734: "&infin;",	// Infinity
			8736: "&ang;",		// Angle
			8743: "&and;",		// Logical and. Also known as wedge
			8744: "&or;",		// Logical or. Also known as vee
			8745: "&cap;",		// Intersection. Also known as cap
			8746: "&cup;",		// Union. Also known as cup
			8747: "&int;",		// Integral
			8756: "&there4;",	// Therefore
			8764: "&sim;",		// tilde operator. Also known as varies with and similar to. The tilde operator is not the same character as the tilde, U+007E, although the same glyph might be used to represent both
			8773: "&cong;",		// Approximately equal to
			8776: "&asymp;",	// Almost equal to. Also known as asymptotic to
			8800: "&ne;",		// Not equal to
			8801: "&equiv;",	// Identical to
			8804: "&le;",		// Less-than or equal to
			8805: "&ge;",		// Greater-than or equal to
			8834: "&sub;",		// Subset of
			8835: "&sup;",		// Superset of. Note that nsup, 'not a superset of, U+2283' is not covered by the Symbol font encoding and is not included.
			8836: "&nsub;",		// Not a subset of
			8838: "&sube;",		// Subset of or equal to
			8839: "&supe;",		// Superset of or equal to
			8853: "&oplus;",	// Circled plus. Also known as direct sum
			8855: "&otimes;",	// Circled times. Also known as vector product
			8869: "&perp;",		// Up tack. Also known as orthogonal to and perpendicular
			8901: "&sdot;",		// Dot operator. The dot operator is not the same character as U+00B7 middle dot
			// Miscellaneous Technical
			8968: "&lceil;",	// Left ceiling. Also known as an APL upstile
			8969: "&rceil;",	// Right ceiling
			8970: "&lfloor;",	// left floor. Also known as APL downstile
			8971: "&rfloor;",	// Right floor
			9001: "&lang;",		// Left-pointing angle bracket. Also known as bra. Lang is not the same character as U+003C 'less than'or U+2039 'single left-pointing angle quotation mark'
			9002: "&rang;",		// Right-pointing angle bracket. Also known as ket. Rang is not the same character as U+003E 'greater than' or U+203A 'single right-pointing angle quotation mark'
			// Geometric Shapes
			9642: "&#9642;",	// Black small square
			9643: "&#9643;",	// White small square
			9674: "&loz;",		// Lozenge
			// Miscellaneous Symbols
			9702: "&#9702;",	// White bullet
			9824: "&spades;",	// Black (filled) spade suit
			9827: "&clubs;",	// Black (filled) club suit. Also known as shamrock
			9829: "&hearts;",	// Black (filled) heart suit. Also known as shamrock
			9830: "&diams;"		// Black (filled) diamond suit
		}

		var convert_helper = function(str, p1) {
			c = p1.charCodeAt(0);
			if(entity_table[c]) // Swap char for a character entity.
				return entity_table[c];
			else // Swap char for a numeric character reference.
				return '&#' + c + ';';
		}
		function convert_htmlentities(input) {
			var input = input;
			if(input != "") {
				output = input.replace(new RegExp("([^a-zA-Z0-9\t\n\v\f\r \x21\x22\x23\x24\x25\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x3a\x3b\x3d\x3f\x40\x5b\x5c\x5d\x5e\x5f\x60\x7b\x7c\x7d\x7e])", "g"), convert_helper);
				return output;
			}
		}
		var revert_helper = function(str, p1, p2) {
			return String.fromCharCode(((p1 == 'x') ? parseInt(p2, 16) : p2));
		}
		function revert_htmlentities(input) {
			var input = output = input;
			if(input != "") {
				for(var i in entity_table)
				if(i != 38)
				output = output.replace(new RegExp(entity_table[i], "g"), String.fromCharCode(i));
				output = output.replace(new RegExp("&#(x?)(\\d+);", "g"), revert_helper);
				output = output.replace(new RegExp(entity_table[38], "g"), String.fromCharCode(38));
				return output;
			}
		}
		
		
		
/*
Nome da Função: CarregaCategoriaFilho
	Parametro v: valor a ser passado para a pagina ajax
Descrição da Função: Carregar Modelos de Veículo
Desenvolvido por: Joao Paulo Wodiani
Data: 07/11/2010
*/
function CarregaCategoriaFilho(v, id_el, id_inicial, label, url)
{
	try {
		if (v!="" && v!="0") {
			RemoveItensSelect(id_el);
			var o = new Option("- Selecione o "+ label +" -" ,"" , false, false);
			document.getElementById(id_el).options[0] = o;
			
			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", url + '/ajax.categoria.carregafilho.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function() {
				if (oHTTPRequest.readyState==4){
					RemoveItensSelect(id_el);
					var o = new Option("- Selecione "+ label +" -" ,"" , false, false);
					document.getElementById(id_el).options[0] = o;
					v = oHTTPRequest.responseXML.getElementsByTagName('id'); //VALOR ID MODELO
					t = oHTTPRequest.responseXML.getElementsByTagName('nome'); //VALOR NOME MODELO
					for (i = 0 ; i < v.length ; i++) {
						var o = new Option(URLDecode(t[i].firstChild.nodeValue),v[i].firstChild.nodeValue, false, false);
						document.getElementById(id_el).options[document.getElementById(id_el).options.length] = o;
					}
					
					//carregando modelo
					document.getElementById(id_el).value = id_inicial;
					
				}
				else
				{
					document.getElementById(id_el).options[0].text = "carregando...";
				}
			}
			oHTTPRequest.send("id=" + v +"&obj="+id_el);
		}
	} catch(e) { alert(e); }
}


/*
Nome da Função: SwapImgMedia
	Parametr	sel : fotoSelec.
				tot : fotoTotal.
Descrição da Função: Trocar fotos médias do Produto/Carro
Desenvolvido por: Joao Paulo Wodiani
Data: 22/11/2010
*/
function SwapImgMedia(sel, tot)
{

	for(i=0;i<tot;i++){
		if(i==sel){
			document.getElementById('imagem2_'+i).style.display = 'block';
		}else{
			document.getElementById('imagem2_'+i).style.display = 'none';
		}
	}

}





/*
Nome da Função: ValidarIndique_PROMOCIONAL
	Parametr	f: objeto formulário
Descrição da Função: Validar Indicação Promocional
Desenvolvido por: Joao Paulo Wodiani
Data: 27/11/2010
*/
function ValidarIndique_PROMOCIONAL(f){
	
	try{
	
		if(f.nome.value==''){
			alert('Preencha seu nome!');
			f.nome.focus();
			return false;
		}
	
		if(f.email.value==''){
			alert('Preencha seu e-mail!');
			f.email.focus();
			return false;
		}
		
		travar = true;
		for(i=0;i<5;i++){
			if(eval('f.nome_amigo'+i+'.value')!="" && eval('f.email_amigo'+i+'.value')!=""){
				travar = false;	
				break;
			}
			
		}
		
		//se nenhum amigo preenchido
		if(travar==true){
			alert('Você precisa indicar pelo menos 1 amigo(a)!');
			f.nome_amigo0.focus();
			return false;
		}
		
	}catch(e){ alert(e); return false; }

}


/*
Nome da Função: AbreImagemDestaque
	Parametros: 
		nome_div = div destino
		id_produto = id_produto
		url = url raiz do site
Descrição da Função: Abrir Imagem Destaque da Loja
Desenvolvido por: Joao Paulo Wodiani
Data: 02/12/2010
*/

function AbreImagemDestaque_New(nome_div, id_produto, url)
{
	
	document.getElementById(nome_div).style.display = 'block';
	document.getElementById(nome_div).style.left = document.getElementById('mousex').value-133+'px';
	document.getElementById(nome_div).style.top = document.getElementById('mousey').value-145+'px';
	
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", url + '/ajax.getpathimagemproduto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				document.getElementById(nome_div).innerHTML = URLDecode(oHTTPRequest.responseText);
			} else {
				document.getElementById(nome_div).innerHTML = "<img src='http://www.ecompleto.com.br/i_padrao/loading.gif'>";
			}
		}
		oHTTPRequest.send("id_produto="+id_produto+"&sequencia=1&tipo=P");
	} catch(e) { alert(e); }
	
}


/*
	@Função: CarregaAnoModelo() -- Carrega Ano Modelo, através da informação do ano fabricação
	@params: 
		ano_fabricacao, valor_ini
	Criado por: Joao Paulo Wodiani <joaopaulo@ecompleto.com.br>
	Data: 22/12/2008
*/
function CarregaAnoModelo(ano_fabricacao, valor_ini) {
	try {

		LimpaSelect('ano_modelo');		

		var o = new Option("---- Selecione ----" ,"" , false, false);
		document.getElementById('ano_modelo').options[0] = o;
		
		if(ano_fabricacao!=""){		
			valor_ini = parseFloat(valor_ini);
			ano_modelo = parseFloat(ano_fabricacao) + 1;
			
			x = false;
			if(valor_ini == ano_modelo){ x = true; }
			var o = new Option(ano_modelo, ano_modelo, false, x);
			document.getElementById('ano_modelo').options[1] = o;

			x= false;
			if(valor_ini == ano_fabricacao){ x = true; }
			var o = new Option(ano_fabricacao, ano_fabricacao, false, x);
			document.getElementById('ano_modelo').options[2] = o;
		}
		
	} catch (e) {}
}



/*
	@Função: LimpaSelect() -- Elimina registros do <Select>
	@params: 
		ID = id do Objeto
	Criado por: Joao Paulo Wodiani <joaopaulo@ecompleto.com.br>
	Data: 03/10/2008
*/
function LimpaSelect(id) {
	try {
		while (document.getElementById(id).options.length > 0) {
			document.getElementById(id).remove(document.getElementById(id).options.length-1);
		}
	} catch (e) {}
}




/*
Nome da Função: SuggestionPesquisa
	Parametro v: valor a ser passado para a pagina ajax
Descrição da Função: Montar Suggestion Search
Desenvolvido por: Joao Paulo Wodiani
Data: 08/12/2010
*/
function SuggestionPesquisa(v, id_obj, url)
{
	try {
		if (v!="") {
			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", url + '/ajax.suggestion.pesquisa.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function() {
				if (oHTTPRequest.readyState==4){
					v = oHTTPRequest.responseXML.getElementsByTagName('id'); //VALOR ID
					t = oHTTPRequest.responseXML.getElementsByTagName('nome'); //VALOR NOME
					r = oHTTPRequest.responseXML.getElementsByTagName('qtd_result'); //RESULT
					
					TextoSuggestion = "<ul>";
					for (i = 0 ; i < v.length ; i++) {
						TextoSuggestion = TextoSuggestion + "<li><a href=\"javascript: document.search.texto_pesquisa.value='"+ URLDecode(t[i].firstChild.nodeValue) +"'; document.search.submit();\">"+ URLDecode(t[i].firstChild.nodeValue) +" <span>("+ r[i].firstChild.nodeValue +")</span></a></li>";
					}
					if(v.length==0){
						TextoSuggestion = TextoSuggestion + "<li>Nenhuma sugestão encontrada</li>";
					}
					TextoSuggestion = TextoSuggestion + "<li class=\"sright\" style=\"text-align:right\">sugest&otilde;es</li></ul>";
					
					//carregando suggestion
					document.getElementById(id_obj).innerHTML = TextoSuggestion;
					
				}
				else
				{
					document.getElementById(id_obj).style.display = 'block';
					document.getElementById(id_obj).innerHTML = "<ul><li>carregando...</li><li class=\"sright\" style=\"text-align:right\">sugest&otilde;es</li></ul></ul>";
				}
			}
			oHTTPRequest.send("search=" + v);
		}else{
			document.getElementById(id_obj).style.display = 'none';
		}
	} catch(e) { alert(e); }
}


/*
Nome da Função:AdicionarCompradoListaPresentes
Descrição da Função: Adiciona mais um item na qtd_comprada no banco 
manualmete quando produto comprado na loja fisica 
	
*/
function AdicionarCompradoListaPresentes(id_lista, id_produto, div){
	quantidade = div.innerHTML;
	try {
			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", 'adicionaprodutolistapresente.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function(){
				if (oHTTPRequest.readyState==4){
					v = URLDecode(oHTTPRequest.responseText);					
					div.innerHTML = v;
					
				} 
			}
			oHTTPRequest.send("id_produto="+id_produto+"&id_lista="+id_lista+"&quantidade="+quantidade);
		
		
	} catch(e) { alert(e); }	

} 

function CarregaImposto(cep1, cep2, id_basket, id_formaentrega,exibe_imposto)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", 'carregaimposto.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function(){
			if (oHTTPRequest.readyState==4){
				imposto=URLDecode(oHTTPRequest.responseText);
				imposto=imposto.split('|');
				if(exibe_imposto){
					document.getElementById("valor_imposto").innerHTML = imposto[0];
				}
				
										
			} else {
				document.getElementById("valor_imposto").innerHTML = "<img src='http://www.ecompleto.com.br/i_padrao/loading.gif'>";					
			}
		}
		oHTTPRequest.send("cep1="+cep1+"&cep2="+cep2+"&id_basket="+id_basket+"&id_formaentrega="+id_formaentrega);
	
	} catch(e) { alert(e); }	
}


function EscondeBoxFone(idx, total){
	
	for(i=0;i<total;i++){
		if(i!=idx){
			$('#boxfone'+i).fadeOut(500);
		}
	}
	
}


/*
Nome da Função: GetCliqueFone(i, l, u)
	Parametro i: id_produto
			  l: id_loja
			  u: url_site
Descrição da Função: Grava Cliques Telefone
Desenvolvido por: João Paulo Wodiani <joaopaulo@ecompleto.com.br>
Data: 17/08/2011
*/
function GetCliqueFone(i, l, u)
{
	try {
		var oHTTPRequest = new createXMLHTTP(); 
		oHTTPRequest.open("post", u + '/libs/php/ajax/cliquefone.php', true);
		oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oHTTPRequest.onreadystatechange=function() {
			if (oHTTPRequest.readyState==4){
				//alert(oHTTPRequest.responseText);
			} else {
			}
		}
		
		oHTTPRequest.send("i="+ i +"&l="+ l);

	} catch(e) { alert(e); }	
}

function showDiv(div_id,classe)
{
	d = $('#'+div_id)
	if(d.is(':visible')){
		
		$('.'+classe).slideUp(100)
	
	}
	else
	{	
		$('.'+classe).slideUp(100)
		d.slideDown(100)

	}
	
}


/*
Nome da Função: CarregaCidade_Portais(v, id_el, id_inicial = 0, url)
	Parametro v: valor a ser passado para a pagina ajax
Descrição da Função: Carregar as cidades filtradas pelo estado
Desenvolvido por: Joao Paulo Wodiani
Data: 25/08/2011
*/
function CarregaCidade_Portais(v, id_el, id_inicial, url)
{
	try {
		if (v!="" && v!="0") {
			RemoveItensSelect(id_el);
			var o = new Option("- Selecione a Cidade -" ,"" , false, false);
			document.getElementById(id_el).options[0] = o;
			
			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", url + '/cidadePortal.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function() {
				if (oHTTPRequest.readyState==4){
					RemoveItensSelect(id_el);
					var o = new Option("- Selecione a Cidade -" ,"" , false, false);
					document.getElementById(id_el).options[0] = o;
					v = oHTTPRequest.responseXML.getElementsByTagName('id'); //VALOR DO ID DA CIDADE
					t = oHTTPRequest.responseXML.getElementsByTagName('nome'); //VALOR DO NOME DA CIDADE
					for (i = 0 ; i < v.length ; i++) {
						var o = new Option(URLDecode(t[i].firstChild.nodeValue),v[i].firstChild.nodeValue, false, false);
						document.getElementById(id_el).options[document.getElementById(id_el).options.length] = o;
					}
					
					//carregando cidade
					document.getElementById(id_el).value = id_inicial;
					
				}
				else
				{
					if (document.getElementById(id_el).options[0].text=="carregando.")
						document.getElementById(id_el).options[0].text = "carregando..";
					else if (document.getElementById(id_el).options[0].text == "carregando..")
						document.getElementById(id_el).options[0].text = "carregando...";
					else
						document.getElementById(id_el).options[0].text = "carregando.";
				}
			}
			oHTTPRequest.send("id=" + v);
		}
	} catch(e) { alert(e); }
}



/*
Nome da Função: CarregaLoja_Portais(v, id_el, id_inicial = 0, url)
	Parametro v: valor a ser passado para a pagina ajax
Descrição da Função: Carregar as cidades filtradas pelo estado
Desenvolvido por: Joao Paulo Wodiani
Data: 25/08/2011
*/
function CarregaLoja_Portais(v, id_el, id_inicial, url)
{
	try {
		if (v!="" && v!="0") {
			RemoveItensSelect(id_el);
			var o = new Option("- Selecione a Loja -" ,"" , false, false);
			document.getElementById(id_el).options[0] = o;
			
			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", url + '/lojaPortal.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function() {
				if (oHTTPRequest.readyState==4){
					RemoveItensSelect(id_el);
					var o = new Option("- Selecione a Loja -" ,"" , false, false);
					document.getElementById(id_el).options[0] = o;
					v = oHTTPRequest.responseXML.getElementsByTagName('id'); //VALOR DO ID DA LOJA
					t = oHTTPRequest.responseXML.getElementsByTagName('nome'); //VALOR DO NOME DA LOJA
					for (i = 0 ; i < v.length ; i++) {
						var o = new Option(URLDecode(t[i].firstChild.nodeValue),v[i].firstChild.nodeValue, false, false);
						document.getElementById(id_el).options[document.getElementById(id_el).options.length] = o;
					}
					
					//carregando loja
					document.getElementById(id_el).value = id_inicial;
					
				}
				else
				{
					if (document.getElementById(id_el).options[0].text=="carregando.")
						document.getElementById(id_el).options[0].text = "carregando..";
					else if (document.getElementById(id_el).options[0].text == "carregando..")
						document.getElementById(id_el).options[0].text = "carregando...";
					else
						document.getElementById(id_el).options[0].text = "carregando.";
				}
			}
			oHTTPRequest.send("id=" + v);
		}
	} catch(e) { alert(e); }
}



/*
	@Função: Ajax_CarregaCarroceria() -- Carrega cidades na combo via xml 'carrocerias filtradas por tipo de veículo
	@params: 
	Criado por: Joao Paulo Wodiani <joaopaulo@ecompleto.com.br>
	Data: 02/12/2010
*/
function Ajax_CarregaCarroceria(objeto, id, initval, label, url)
{

	try{
		if (id >= 0){
			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", url + '/ajax.carregacarroceria.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function() {
				if (oHTTPRequest.readyState==4){
					document.getElementById(objeto).innerHTML = URLDecode(oHTTPRequest.responseText);
				} else {
					document.getElementById(objeto).innerHTML = "carregando..";
				}
			}
			if(initval != ""){ oHTTPRequest.send("id=" + id + "&initval=" + initval + "&label="+ label); }else{ oHTTPRequest.send("id=" + id + "&label="+ label); }
		}
	}catch(e) { alert(e); }

}


/*
	@Função: ValidarBuscaAvancada() -- Adcarros
	@params: f = this.form
	Criado por: Joao Paulo Wodiani <joaopaulo@ecompleto.com.br>
	Data: 26/08/2011
*/
function ValidarBuscaAvancada(f){
	
	try{
		obj = f.opcionais;
		f.texto_pesquisa.value = '';
		for(i=0;i<obj.length;i++){
			if(obj[i].checked){
				if(f.texto_pesquisa.value == ''){ 
					f.texto_pesquisa.value = obj[i].value;
				}else{ 
					f.texto_pesquisa.value = f.texto_pesquisa.value + ', ' + obj[i].value; 
				}	
			}
		}
		
	}catch(e){ alert(e); return false; }
	
}


/*
	@Função: gotoAnchor() - Ir para ancora determinada no contexto html
	@params: ancora = nome da ancora
	Criado por: Joao Paulo Wodiani <joaopaulo@ecompleto.com.br>
	Data: 29/08/2011
*/
function gotoAnchor(ancora){ 
	window.location.hash=ancora; 
}

/*
Fucao para pegar parametros via get;
*/

function get(parametro){
	
	var loc = document.location;
	loc = loc.substring(loc.indexOf('?')+1);
	//alert(loc)
	var param_value = false;
	var params = loc.split("&");
	 
	for (i=0; i<params.length;i++) {  
		param_name = params[i].substring(0,params[i].indexOf('='));  
		if (param_name == parametro) {                                         
			param_value = params[i].substring(params[i].indexOf('=')+1)  
		}  
	}
	 
	if(param_value) {  
		return param_value;  
	}  
	else{  
		return false;  
	} 

}
function utf8_decode ( str_data ) 
{
	var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
	str_data += '';
	
	while ( i < str_data.length ) {
		c1 = str_data.charCodeAt(i);
		if (c1 < 128) {
			tmp_arr[ac++] = String.fromCharCode(c1);
			i++;
		} else if ((c1 > 191) && (c1 < 224)) {
			c2 = str_data.charCodeAt(i+1);
			tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
			i += 2;
		} else {
			c2 = str_data.charCodeAt(i+1);
			c3 = str_data.charCodeAt(i+2);
			tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}
	}
	return tmp_arr.join('');
}
