// Criando o objeto xmlhttp(AJAX)
try{
	xmlhttp = new XMLHttpRequest();
}catch(ee){
	try{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(E){
			xmlhttp = false;
		}
	}
}

//Marcar radio
function verifica_selecionado(p,num){
	var seleciona_primeira_opcao = 0;
	var inputs = document.getElementById(id).getElementsByTagName('input');
	var total = inputs.length;
	for(var v=0;v<total;v++){
		parcelas_radios = 'p_'+p+'.'+v;
		if (document.getElementById(parcelas_radios).checked == true){
			seleciona_primeira_opcao = 1;
			break;
		}
	}
	if (seleciona_primeira_opcao == 0){
		document.getElementById('p_'+p+'.0').checked = true;
		document.getElementById('parcelas_'+p).value = document.getElementById('p_'+p+'.0').value;
	}
}
//Selecionar forma de pagamento
function Selecionar(id_tr){
	if(document.getElementById(id_tr).className == 'selected'){
	}else{
		var ar = document.getElementById('FormasPagamento').getElementsByTagName('fieldset');
		for(var i=0;i<ar.length;i++){
			if(ar[i].className == 'selected'){
				ar[i].className = '';
			}
		}
		document.getElementById(id_tr).className = 'selected';
		document.getElementById('Formas').value = id_tr;
	}
}
//Ranking
var numStar=0;
function setStar(img) {
	document.voto.src = 'img01/star'+img+'.gif';
} 
function MostrarStar(variavel,number){
	document.getElementById('rate').innerHTML=variavel;
	document.getElementById('nota_comentario').value=number;
	if (number == 1){
		numStar = 1;
	}
	if (number == 2){
		numStar = 2;
	}
	if (number == 3){
		numStar = 3;
	}
	if (number == 4){
		numStar = 4;
	}
	if (number == 5){
		numStar = 5;
	}
}
//Função do CEP
var VerifiqueTAB=true;
function Mostra(quem, tammax) {
	if ((quem.value.length == tammax) && (VerifiqueTAB)){ 
		var i=0,j=0, indice=-1;
		for (i=0; i<document.forms.length; i++){
			for (j=0; j<document.forms[i].elements.length; j++){
				if (document.forms[i].elements[j].name == quem.name){
					indice=i;
					break;
				}
			}
			if (indice != -1){
				break;
			}
		}
		for (i=0; i<=document.forms[indice].elements.length; i++){
			if (document.forms[indice].elements[i].name == quem.name){
				while ((document.forms[indice].elements[(i+1)].type == "hidden") && (i < document.forms[indice].elements.length)){
					i++;
				}
				document.forms[indice].elements[(i+1)].focus();
				VerifiqueTAB=false;
				break;
			}
		}
	}
}
function PararTAB(quem)
{ VerifiqueTAB=false; }
function ChecarTAB()
{ VerifiqueTAB=true; }
//preenchimento de data
function barra(objeto){
	if (objeto.value.length == 2 || objeto.value.length == 5 ){
		objeto.value = objeto.value+"/";
	}
}
//Abre e fecha formas de pagto
function AlternarOpcao(conteudo){
	if (document.getElementById(conteudo).style.display=='')
	{document.getElementById(conteudo).style.display='none';
	}else{
	document.getElementById(conteudo).style.display='';}
	}
//Limpa o conteúdo dos input ao clicar do mouse
function Limpar(id){
	document.getElementById(id).value='';
}
//Trocar fotos Ampliadas
function Abrirfotoabas(id_span){
	if(document.getElementById(id_span).style.display == ''){
		}else{
		var ar = document.getElementById('fotoBlock').getElementsByTagName('div');
		for(var i=0;i<ar.length;i++){
			if(ar[i].className == 'view'){
				ar[i].style.display = 'none';
				}
			}
		document.getElementById(id_span).style.display = '';		
	}
}
//Trocar as Abas das Informações do Produto
function AbrirAbas(id_span,id_li,tipo,pagina,inputHidden){
	if(document.getElementById(id_span).style.display == ''){
		}else{
		var ar = document.getElementById('ProdBlock').getElementsByTagName('div');
		for(var i=0;i<ar.length;i++){
			if(ar[i].className == 'prodBox'){
				ar[i].style.display = 'none';
			}
		}
		var ar = document.getElementById('ProdBlock').getElementsByTagName('li');
		for(var i=0;i<ar.length;i++){
			if(ar[i].className == 'aberta'){
				ar[i].className = '';
			}
		}
		document.getElementById(id_span).style.display = '';
		document.getElementById(id_li).className = "aberta";		
	}
	if(tipo==1)
	{
		if($(inputHidden).value==0)
		{
			$(id_span).innerHTML = '<img src="img01/ajax-loading.gif" alt="Loading" title="Loading" />';
			atualizaDiv(pagina,id_span);
			$(inputHidden).value=1;
		}
	}
}
// Troca as abas da visualização do produto
function TrocarAba(col_id,aba_id){
	if(document.getElementById(col_id).style.display == ''){
		}else{
		var ar = document.getElementById('visualBlock').getElementsByTagName('div');
		for(var i=0;i<ar.length;i++){
			if(ar[i].className == 'conteudo'){
				ar[i].style.display = 'none';
				}
			}
		var ar = document.getElementById('visualBlock').getElementsByTagName('li');
		for(var i=0;i<ar.length;i++){
			if(ar[i].className == 'aberta'){
				ar[i].className = '';
				}
			}
		document.getElementById(col_id).style.display = '';
		document.getElementById(aba_id).className = "aberta";		
	}
}
//Função que mostra e oculta o ítem selecionado
function mostrarItem(item)
{
	var elemento = document.getElementById(item);
	if(elemento.style.display == '')
	{
		elemento.style.display = 'none';
	}
	else
	{
		elemento.style.display = '';
	}
}
//Trocar modo de visualização de Lista para Galeria
function setList(css, loja)
{
   if(css=='galeria' && loja>0) { href = '../includes/' + loja + '/' + loja + '_galeria.css'; }
   else                         { href = 'view/css/' + css + '.css'; }
   
   document.getElementById('bodyCSS').href=href;
   atualizaDiv('funcoes/atualiza_css.php?visualizar='+css,'atualizaCSS');
   return null;
}
//funcoes para o ajax
var req;
function loadXMLDoc(url,valor){
    req = null;
    // Procura por um objeto nativo (Mozilla/Safari)
   if(window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url+'?criterio='+valor, true);
        req.send(null);
    // Procura por uma versao ActiveX (IE)
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
       if(req) {
            req.onreadystatechange = processReqChange;
            req.open("POST", url+'?criterio='+valor, true);
            req.send();
        }
    }
}
function processReqChange(){
    // apenas quando o estado for "completado"
    if(req.readyState == 4) {
        // apenas se o servidor retornar "OK"
        if(req.status == 200) {
            // procura pela div id="atualiza" e insere o conteudo
            // retornado nela, como texto HTML
            document.getElementById('atualiza').innerHTML = req.responseText;
        }else{
            alert("Houve um problema ao obter os dados:\n" + req.statusText);
        }
    }
}

function Atualiza(url,valor){
   loadXMLDoc(url+'.php',valor);
   document.getElementById('atualiza').innerHTML = '<BR><BR><center><p class=title>Aguarde...atualizando formas de pagamento.</p></center>';
}
function ajaxRead(file,destino){  
	alert(file);
  var xmlObj = null;
  if(window.XMLHttpRequest){
      xmlObj = new XMLHttpRequest();
  }else if(window.ActiveXObject){
      xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
  }else{
      return;
  }
	xmlObj.onreadystatechange = function(){   
	if(xmlObj.readyState == 1){
		//**** USAR PARA ARQUIVOS HTML *****
		//updateObj(destino,"Aguarde...");
  }
	if(xmlObj.readyState == 4){
		if(xmlObj.status == 200){ //se nao ocorreu nenhum erro
			//**** USAR PARA ARQUIVOS HTML *****
			texto=unescape(xmlObj.responseText.replace(/\+/g," "));
			updateObj(destino, xmlObj.responseText);
			/* extraindo script e executando */			
		}else{
			alert("Houve um problema ao obter os dados:\n" + xmlObj.statusText);
		}
	}
}
xmlObj.open ('GET', file, true);
xmlObj.send ('');
}
function updateObj(obj, data){
	$(obj).innerHTML = data;
}
//funcoes usadas no '/loja/finalizar_pagamento.php'
function esconde_div_erro1(){
	$('erro1').style.display = 'none';
}
function esconde_div_erro2(){
	$('erro2').style.display = 'none';
}
function checa(campo){
	$(campo).checked = true;
	esconde_div_erro1();
}

function checa_pd(campo,campo2){
	$(campo).checked = true;
	esconde_div_erro1();
	$('meio_pagamento').value = campo2;
}

function unchecked(nome)
{
	var inputs = document.getElementsByTagName('input');
	var total = inputs.length;	
	for (i=0;i<total;i++)
	{
		if(inputs[i].type != 'radio')
		{
			continue;
		}
		else
		{
			if (inputs[i].checked == true) 
			{
				inputs[i].checked = false;
			}
		}
	}
}

function verifica_selecionado(p,num){
	var seleciona_primeira_opcao = 0;
	for(var v=0;v<num;v++){
		parcelas_radios = 'p_'+p+'.'+v;
		if (document.getElementById(parcelas_radios).checked == true){
			seleciona_primeira_opcao = 1;
			break;
		}
	}
	if (seleciona_primeira_opcao == 0){
		document.getElementById('p_'+p+'.0').checked = true;
		document.getElementById('parcelas_'+p).value = document.getElementById('p_'+p+'.0').value;
	}
}

function abre_popup_boleto(nome_janela){
	window.open("",nome_janela,"toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,screenX=0,screenY=0,left=0,top=0,width=750,height=600");
}

function valida_formas_pagamento(flag_contrato,flag_abre_pop,nome_janela){
	cont_pagamento = 0;
	for (i=0;i<document.getElementsByName('pagamento').length;i++){
		id_pagamento = 'pagamento_'+i;		
		if (document.getElementById(id_pagamento).checked == true) {
			cont_pagamento = 1;
			break;
		}
	}
	if (cont_pagamento == 0){
		document.getElementById('erro1').style.display = '';
		return false;
	}
	if (flag_contrato == 1){
		return valida_contrato_pagamento(flag_abre_pop,nome_janela);
	}else{
		if(flag_abre_pop==1){
			abre_popup_boleto(nome_janela);
		}
	}
}

function valida_contrato_pagamento(flag_abre_pop,nome_janela){
	if (document.getElementById('contrato').checked == false)
	{
		document.getElementById('erro2').style.display = '';
		document.getElementById('contrato').focus();
		return false;
	}
	if(flag_abre_pop==1){
		abre_popup_boleto(nome_janela);
	}
}

// ---------- Funcoes para validar os comentarios ---------- //
function validaComent(Form) {		
	if (Form.nota.value == ''){
		document.getElementById('erro').style.display = '';
		document.getElementById('erro').innerHTML = '<img src="img01/alert.png">Avalia&ccedil;&atilde;o sobre o produto obrigat&oacute;ria.';
	    return (false);
	}	
	if (Form.nome_cliente.value == "")  	{
		document.getElementById('erro').style.display = '';
		document.getElementById('erro').innerHTML = '<img src="img01/alert.png"> Campo nome obrigat&oacute;rio.';
	    return (false);
	}
	if (Form.email_cliente.value == "")  	{
	    document.getElementById('erro').style.display = '';
	    document.getElementById('erro').innerHTML = '<img src="img01/alert.png">Campo email obrigat&oacute;rio.';
	    return (false);
	}
	if ( (Form.email_cliente.value.indexOf("@") == -1 )&&( Form.email_cliente.value != "" ) ) {
	   document.getElementById('erro').style.display = '';
	   document.getElementById('erro').innerHTML = '<img src="img01/alert.png">Formato de e-mail inv&aacute;lido.';
	   return (false);
	}
	if (Form.titulo.value == "")  	{
	    document.getElementById('erro').style.display = '';
	    document.getElementById('erro').innerHTML = '<img src="img01/alert.png">Campo t&iacute;tulo obrigat&aacute;rio.';
	    return (false);
	}
	if (Form.comentario.value == "")  	{
	    document.getElementById('erro').style.display = '';
	    document.getElementById('erro').innerHTML = '<img src="img01/alert.png">Campo coment&aacute;rio obrigat&aacute;rio.';
	    return (false);
	}		
}	
function removeAlert(){
	document.getElementById('erro').style.display = 'none';
}
function caracterRestante(id,total, max){
	var rest = max - total;	
	if(rest < 0 ){
		valor = document.getElementById(id).value;
		valor = valor.substring(0,max);
		document.getElementById(id).value = valor;
		return (false); 
	}	
	document.getElementById('restante').innerHTML=rest;
}
// ---------- FIM Funcoes para validar os comentarios ---------- //
// ---------- Funcoes para colocar nota na avalialçao dos comentarios ---------- //
function Marcar(id1,id2,id3,id4,id5){
	document.getElementById('id1').className = 'star';
	document.getElementById('id2').className = 'star';
	document.getElementById('id3').className = 'star';
	document.getElementById('id4').className = 'star';
	document.getElementById('id5').className = 'star';	
	//alert(id1+' '+id2+' '+id3+' '+id4+' '+id5+'iu');	
	document.getElementById(id1).className = 'starOK';
	document.getElementById(id2).className = 'starOK';
	document.getElementById(id3).className = 'starOK';
	document.getElementById(id4).className = 'starOK';
	document.getElementById(id5).className = 'starOK';
}
function Mostrar(variavel){
	document.getElementById('rate').innerHTML = variavel;
}
function setNota(valor){
	document.getElementById('nota').value = valor;
}
// ---------- FIM Funcoes para colocar nota na avalialçao dos comentarios  ---------- //
// ---------- INICIO Funcoes para validar campos de formularios, como telefone, email, cep, etc  ---------- //
function mascara(o,f){
    v_obj=o;
    v_fun=f;
    setTimeout("execmascara()",1);
}
function execmascara(){
    v_obj.value=v_fun(v_obj.value);
}
function valorBr(v)
{
 	v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
	v=v.replace(/(\d)(\d{11})$/,"$1.$2") //Coloca ponto antes dos 9 últimos digitos
	v=v.replace(/(\d)(\d{8})$/,"$1.$2") //Coloca ponto antes dos 7 últimos digitos
	v=v.replace(/(\d)(\d{5})$/,"$1.$2") //Coloca ponto antes dos 5 últimos digitos
	v=v.replace(/(\d)(\d{2})$/,"$1,$2") //Coloca virgula antes dos 2 últimos digitos
	return v
}
function numeros(v)
{
    return v.replace(/\D/g,"")
}
function telefone(v)
{
    v=v.replace(/\D/g,"");               //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2"); //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígito
    return v;
}
function numeros2(v){
    return v.replace(/\D/g,"")
}	
function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}
function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}
function data(v){
	v=v.replace(/\D/g,"") 
	v=v.replace(/(\d{2})(\d)/,"$1/$2") 
	v=v.replace(/(\d{2})(\d)/,"$1/$2") 
	return v
}

function data2(v){
	v=v.replace(/\D/g,"") 
	v=v.replace(/(\d{2})(\d)/,"$1/$2") 
	v=v.replace(/(\d{2})(\d)/,"$1/$2") 
	return v
}

function cnpj2(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    return v
}
function romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}
//Paginação AJAX para listar os produtos visitados
function geraPaginacaoAjax(por_pag, total, div, id, loja, url){	
	var paginas_prod = total/por_pag;
	paginas_prod = Math.floor(paginas_prod);
	if(total%por_pag != 0){
		paginas_prod = paginas_prod+1;
	}	
	//Verifica se tem mais de três produtos na $_SESSION
	if(total>por_pag){
		produtos_exibir = total;
		cont = produtos_exibir-por_pag;
	}else{
		cont = 0;
	}	
	url_link=url+'&cont='+cont+'&prod_visitados='+total+'&id='+id;
	geraLinkPaginacao(div,url_link);	
	if (total>0){
		//document.write('P&aacute;ginas: ');
		url_link=url+'&cont='+cont+'&prod_visitados='+total+'&id='+id;
		document.write('<span id="linksPag"> <a id="pag1" class="pageON" href="javascript:void(0)" onclick="geraLinkPaginacao(\''+div+'\',\''+url_link+'\');changeClass(\'linksPag\', this.id,\'pageON\');">'+1+'</a> ');
		cont=cont-por_pag;
		total=total-por_pag;
	}
	for(var i=1;i<paginas_prod;i++){		
		if(total<=por_pag){
			cont=0;
		}		
		url_link=url+'&cont='+cont+'&prod_visitados='+total+'&id='+id;
		document.write(' <a id="pag'+(i+1)+'" class="" href="javascript:void(0)" onclick="geraLinkPaginacao(\''+div+'\',\''+url_link+'\');changeClass(\'linksPag\', this.id,\'pageON\');">'+(i+1)+'</a> ');
		cont=cont-por_pag;
		total=total-por_pag;
	}
	document.write('</span>');
}
function changeClass(idMestre, id, classe){
	var ar = document.getElementById(idMestre).getElementsByTagName('a');
	var total = ar.length;
	for(var i=0;i<total;i++){
		ar[i].className = '';
	}
	document.getElementById(id).className=classe;
}
function geraLinkPaginacao(div, url){
	new Ajax.Updater(div,url, {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});
}
function limpaInput(id){
	document.getElementById(id).value = '';
}
function Trim(str){
	return str.replace(/^\s+|\s+$/g,"");
}
function Verify(CNUMB,CTYPE){
	CNUMB=ParseNumb(CNUMB)
	if(CNUMB == 0){
		return(false);
	}else{
		g=CNUMB.length-2;
		if(TestDigit(CNUMB,CTYPE,g)){
			g=CNUMB.length-1;
			if(TestDigit(CNUMB,CTYPE,g)){
				return(true);
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}
}
function TestDigit(CNUMB,CTYPE,g){	
	var dig=0;
	var ind=2;
	for(f=g;f>0;f--){
		dig+=parseInt(CNUMB.charAt(f-1))*ind;
		if (CTYPE=='CNPJ'){
			if(ind>8){
				ind=2
			}else{
				ind++
			}
		}else{
			ind++
		}
	}	
	dig%=11;
	if(dig<2){
		dig=0;
	}else{
		dig=11-dig;
	}
	if(dig!=parseInt(CNUMB.charAt(g))){
		return(false);
	}else{
		return(true);
	}
}
function ShowCep(){
	open('http://www.correios.com.br/servicos/cep/cep_default.cfm','ShowCep','location=no,resize=no, width=730,height=600,left=18,top=18,maximized=0,scrollbars=1');
}
function select_drop(sel_name, abbr_name){
	if(abbr_name!=''){
		if(sel_name.length > 0){
			var maxIndex = sel_name.length;
			for(var i=0; i<maxIndex; i++){
				if(abbr_name== sel_name.options[i].value){
					sel_name.selectedIndex = i;
					break;
				}
			}
		}
	}
	return true;
}
function formatar(src, mask){
    var Form;
    Form = document.frm2;
  	var i = src.value.length;
  	var saida = mask.substring(0,1);
  	var texto = mask.substring(i)
	if (texto.substring(0,1) != saida){
   		src.value += texto.substring(0,1);
	}
   if(Form.cep_1.value.length == 6){
        Form.cep_2.focus();
    }
}
function somente_numeros(e) {
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = e.which;
		if (tecla > 47 && tecla < 58) // numeros de 0 a 9
			return true;
	else {
		if (tecla != 8) // backspace
			event.keyCode = 0;
			//return false;
		else
			return true;
    }
}
function limpaDiv(div) {
	document.getElementById(div).innerHTML = '';
	document.getElementById(div).style.display = 'none';
}
function volta_input_classe(id,classe){
	document.getElementById(id+'_erro').innerHTML = '';
	document.getElementById(id+'_erro').style.display = 'none';
	document.getElementById(id).className = classe;
}
function volta_span(id,id2)
{
	document.getElementById(id2).innerHTML = '';
	document.getElementById(id2).style.display = 'none';
	document.getElementById(id).className = 'table obriga';	
	return false;
}
function volta_span2(id,id2,id3)
{
	if (Trim(id.value)=='') 
	{
		document.getElementById(id2).innerHTML = '';
		document.getElementById(id2).style.display = 'none';
		document.getElementById(id3).className = 'obriga table';	
		return false;
	}
}
function volta_input(id){

	document.getElementById(id+'_erro').innerHTML = '';
	document.getElementById(id+'_erro').style.display = 'none';
	document.getElementById(id).className = 'text obriga';	
}
function volta_textarea(id){
	document.getElementById(id+'_erro').innerHTML = '';
	document.getElementById(id+'_erro').style.display = 'none';
	document.getElementById(id).className = 'textarea obriga';
	document.getElementById('spanTextarea').className = 'obriga table';
}
function verifica_formato_email(id){
	var teste_mail = strpos(id,'email');	
	if (teste_mail !== false){	
		if (document.getElementById(id).value.indexOf("@") == -1){
			document.getElementById(id + '_erro').style.display = '';
			document.getElementById(id + '_erro').innerHTML = document.getElementById(id + '_mensagem_invalido').value;
			document.getElementById(id).className = 'text inputErro';
			document.getElementById(id).focus();
			return false;
		}
	}
}
function valida_formularios(){
	var cont = document.getElementsByName('campo_obrigatorio[]').length;
	for (r = 0; r < cont; r++){
		var id_input_obrigatorio = document.getElementById('campo_obrigatorio_' + r).value;
		var teste = document.getElementById(id_input_obrigatorio);		
		if (Trim(teste.value)=='' || teste.value=='0'){
			document.getElementById(id_input_obrigatorio + '_erro').style.display = '';
			document.getElementById(id_input_obrigatorio + '_erro').innerHTML = document.getElementById('mensagem_erro_' + r).value;			
			if((teste.className == 'textarea') || (teste.className == 'textarea obriga')){
				document.getElementById('spanTextarea').className = 'table inputErro';
			}else{
				document.getElementById(id_input_obrigatorio).className = 'text inputErro';
			}
			document.getElementById(id_input_obrigatorio).focus();			
			return false;
		}else{
			var retorno = verifica_formato_email(id_input_obrigatorio);
			if (retorno == false){	return false;	}
		}
	}
}
function verifica_campos_iguais(id1,id2){
	if (document.getElementById(id1).value != '') {
		if (document.getElementById(id2).value == '') {		
			document.getElementById(id2+'_erro').style.display = '';
			document.getElementById(id2+'_erro').innerHTML = document.getElementById(id2+'_mensagem_novamente').value;
			document.getElementById(id2).className = 'text inputErro';
			document.getElementById(id2).focus();			
			return false;			
		}else{		
			if (document.getElementById(id1).value != document.getElementById(id2).value) {
				document.getElementById(id2+'_erro').style.display = '';
				document.getElementById(id2+'_erro').innerHTML = document.getElementById(id2+'_mensagem_erro').value;
				document.getElementById(id2).className = 'text inputErro';
				document.getElementById(id2).focus();				
				return false;
			}
		}
	}
}
function strpos(haystack, needle){
	var i = (haystack + '').indexOf(needle);
	return i === -1 ? false : i;
}
function atualizaDiv(url,div){
	new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});
}
function atualizaLinkPagParcelado(id,idSpan,id_produto,loja,texto){
	var valores = document.getElementById(id).value;
	var valor = valores.split("|");
	valor[0] = valor[0].replace(".", "");
	valor[0] = valor[0].replace(",", ".");
	document.getElementById(idSpan).href = 'pag_parcelado.php?IdProd='+id_produto+'&preco='+valor[0]+'&loja='+loja;
}

/**
 *			Muda o valor do produto qndo houver variacao no mesmo(simples) 
 * @param 	Integer : id
 * @param 	Float   : idSpanPreco
 * @param 	String  : idSpanErro
 * @param 	String  : url
 * @param   String  : div
 */
function mudaVariacaoSimples(id,idSpanPreco,idSpanErro,url,div){

	var valores = $(id).value;

	var antVariacao = $('antVariacao').value;
	
	var valor = valores.split("|");
	
	var valor_anterior = valor[0];
	
	var valor_desconto_especial = 0;
	
	if(valor[0] == 'null' && valor[2] == 'null'){
		mudaVariacaoSimples_clientesAguardando(valor[1],id);
		return false;
	}
	
	var valor_adicional = calcula_total_adicionais();

	valor[0] = verificaValoresTextoVariacao(valor[0]);
	
	var verifica_clientes_aguardando= $('verifica_clientes_aguardando').value;
	var verifica_estoque_venda = $('verifica_estoque_venda').value;
	
	if(verifica_clientes_aguardando == 1 && verifica_estoque_venda == 0){

		$('produto_preco').style.display = '';
		$('cepbox').style.display = '';
		$('cepbox').style.display = '';
		$('quantidade').style.display = '';
		$('info').style.display = '';
		$('bt_comprar').style.display = '';
		$('Aba4').style.display = '';
		$('nao_disp').style.display = 'none';
		$('img_nao_disp').style.display = 'none';
		$('verifica_variacao').value = '';
		$('bonus_cupom').style.display = '';

	}	
	
	if(valor_adicional > 0){
		valor_exibicao_preco = valor[0].replace(".","");
		valor_exibicao_preco = valor_exibicao_preco.replace(",",".");
		valor_exibicao_preco = parseFloat(valor_exibicao_preco);
		
		valor_exibicao_preco += valor_adicional;
		valor_exibicao_preco = valor_exibicao_preco.toFixed(2);
		valor_exibicao_preco = number_format(valor_exibicao_preco,2,",",".");
	}else{
		valor_exibicao_preco = valor[0];
	}
	
	$(idSpanPreco).innerHTML = valor_exibicao_preco;
	
	$('variacao').value=valor[1];
	
	var hiddenVars  = $('hidden'+valor[1]).value;
	var estoqueVars = $('estoque_'+valor[1]).value;
	var precoDeVars     = $('precoDeVar'+valor[1]).value;
	var precoDeVarDif   = $('precoDeVarDif'+valor[1]).value;
	var precoDeOriginal = $('precoDeOriginal').value;
	var precoDeDif = $('precoDeDif').value;
	
	if(hiddenVars!='')
		$('imgView').src = hiddenVars;
	else
		$('imgView').src = antVariacao;
	
	var imagem_atual = $('imgView').src;
	
	var zoom = variacaoZoom(imagem_atual);
	
	if(estoqueVars != ""){
		$('estoque_variacao').innerHTML = ' / '+estoqueVars; 
	}else{
		$('estoque_variacao').innerHTML = ""; 
	}
	
	changeLangVar('a_partir');
	
	if(zoom == false){
		swapImage('imageL_1','imageH_1');
	}
	
	$(idSpanErro).innerHTML = '';
	$(idSpanErro).style.display = 'none';
	$('span_erro_cep').innerHTML = '';
	$('span_erro_cep').style.display = 'none';
	
	if(valor[0] == valor_anterior){
	
		if(valor[2] == 1){
	
			if(parseFloat(precoDeVars)>0 && precoDeVars != valor[0]){

				$('precoDe').style.display      = '';
				$('precoDeValor').style.display = '';
				$('economize').style.display    = '';
				$('precoDeValor').innerHTML     = precoDeVars;
				$('valorDeDif').innerHTML       = precoDeVarDif;

			}else{

				$('precoDe').style.display      = 'none';
				$('precoDeValor').style.display = 'none';
				$('economize').style.display    = 'none';

			}

			$('info_preco').style.display   = 'none';
	
		}else{
	
			if(parseFloat(precoDeVars)>0 && precoDeVars != valor[0]){

				$('precoDe').style.display    	= '';	
				$('precoDeValor').style.display   = '';
				$('precoDeValor').innerHTML   	= precoDeOriginal;
				$('valorDeDif').innerHTML   		= precoDeDif;
				$('economize').style.display  	= '';
				$('info_preco').style.display 	= '';

			}else{

				$('precoDe').style.display    	= 'none';	
				$('precoDeValor').style.display   = 'none';
				$('economize').style.display  	= 'none';
				$('info_preco').style.display 	= '';

			}

		}
	
	}else{

		$('precoDe').style.display      = 'none';
		$('precoDeValor').style.display = 'none';
		$('economize').style.display    = 'none';
		$('info_preco').style.display   = 'none';

	}
	
	var preco_calculo = valor[0].replace(".", "");
	var preco_calculo = preco_calculo.replace(",", ".");
	
	var variaveis      = url.split('&');
	var url_loja       = variaveis[0].split('?');
	var url_id_loja    = url_loja[1];
	var url_id_produto = variaveis[1];

	if(valor_desconto_especial != 'null'){
	
		if(valor_adicional>0){
			valor_desconto_especial = parseFloat(valor_desconto_especial) + valor_adicional;
		}

		$('valor_desconto_especial').value = valor_desconto_especial;

	}

	var preco_especial = $('valor_desconto_especial').value;

	if(preco_especial>0){
		preco_calculo = preco_especial;
	}
	
	$('preco_atual').value = preco_calculo;
	
	if(valor_adicional>0){
		preco_calculo = parseFloat(preco_calculo) + valor_adicional;
	}

	url=url+'&preco_calculo='+preco_calculo+'&atualiza=1';
	
	$(div).innerHTML = '<img src="img01/ajax-loading.gif" alt="Loading" title="Loading" />&nbsp;Carregando Formas de Pagamento';
	
	$('aba_formas').value=1;

	if(valor_desconto_especial > 0){
		
		valor_desconto_especial = valor_desconto_especial.replace(".", ",");
		$('desconto_especial').innerHTML = valor_desconto_especial;
	}

	atualizaDiv('detalhes_formas.php?'+url_id_loja+'&'+url_id_produto+'&preco_calculo='+preco_calculo,'detalhes_formas');
	atualizaDiv(url,div);
}

function mudaVariacaoSimples_clientesAguardando(id_variacao,id){	
	var verifica_clientes_aguardando = $('verifica_clientes_aguardando').value;
	var verifica_estoque_venda 		 = $('verifica_estoque_venda').value;
	
	//-----------------------------------------------------------------------
	var layout_variacao 		= $('layout_variacao').value;
	var variacao_dupla 			= $('variacao_tipo2').innerHTML;
	var define_radio_select		= $('define_radio_select').value;
	
	if(layout_variacao == '1'  || (layout_variacao == '4' && define_radio_select == 0))//RADIO
	{
		//alert(alert(define_radio_select););
		if(variacao_dupla == "")
		{	 
			$('variacao_valor1').innerHTML = $('label_valor1_'+id).innerHTML;			
		}
		else
		{
			$('variacao_valor1').innerHTML = $('label_valor1_'+id).value;		
			$('variacao_valor2').innerHTML = $('label_valor2_'+id).innerHTML;		
		}


	}
	else if(layout_variacao == '2' || (layout_variacao == '4' && define_radio_select == 1))// SELECT
	{	
		var valor_escolhido = $(id).options[$(id).selectedIndex].text;
		
		if(variacao_dupla == "")
		{	
			$('variacao_valor1').innerHTML = valor_escolhido;
		}
		else
		{				
			var variacao_dupla_valor = $('verifica_variacao_dupla_valor').value;
			$('variacao_valor1').innerHTML = variacao_dupla_valor;
			$('variacao_valor2').innerHTML = valor_escolhido;		
		}
	}
	//-----------------------------------------------------------------------
	
	if(verifica_clientes_aguardando == 1 && verifica_estoque_venda == 0){
		$('produto_preco').style.display = 'none';
		$('cepbox').style.display = 'none';
		$('cepbox').style.display = 'none';
		$('quantidade').style.display = 'none';
		$('info').style.display = 'none';
		$('bt_comprar').style.display = 'none';
		$('Aba4').style.display = 'none';
		$('nao_disp').style.display = '';
		$('img_nao_disp').style.display = '';
		$('span_erro_cep').innerHTML = '';
		$('span_erro_cep').style.display = 'none';
		$('verifica_variacao').value = id_variacao;
		$('bonus_cupom').style.display = 'none';
	}
}

function mudaVariacaoDupla(div,tipo,loja,id_produto,idSelect,idSpanPreco,divClasse,cont,preco_prod,pagamento,tipo1,preco_desconto_especial){	
	
	var valor = $(idSelect).value;
	valor_url = encodeURIComponent(valor);
	
	var antVariacao = document.getElementById('antVariacao').value;
	
	var valor_adicional = calcula_total_adicionais();
	
	preco_calculo = preco_prod.replace(",",".");

	if(preco_desconto_especial){

		var valor_desconto_especial = parseFloat(preco_calculo)*(1-parseFloat(preco_desconto_especial));
		valor_desconto_especial = valor_desconto_especial.toFixed(2);
		
		if(valor_adicional>0){
			valor_desconto_especial += valor_adicional;
		}

		$('valor_desconto_especial').value = valor_desconto_especial;

		preco_produto = valor_desconto_especial;

		preco_produto = preco_produto.toString();
		preco_produto = preco_produto.replace(".", ",");
		
		preco_calculo = valor_desconto_especial;

	}else{

		preco_produto = preco_prod;

	}
	
	$('preco_atual').value = preco_calculo;
	
	if(valor_adicional>0){

		preco_calculo = parseFloat(preco_calculo) + valor_adicional;

		valor_exibicao_preco = preco_prod.replace(".","");
		valor_exibicao_preco = valor_exibicao_preco.replace(",",".");
		valor_exibicao_preco = parseFloat(valor_exibicao_preco);
		
		valor_exibicao_preco += valor_adicional;
		valor_exibicao_preco = valor_exibicao_preco.toFixed(2);
		valor_exibicao_preco = number_format(valor_exibicao_preco,2,",",".");

	}else{

		valor_exibicao_preco = preco_prod;

	}

	document.getElementById('variacao').value='';
	document.getElementById('imgView').src = antVariacao;
	document.getElementById('estoque_variacao').innerHTML = ""; 
	document.getElementById('precoDe').style.display = '';

	if(preco_desconto_especial > 0){
		document.getElementById('desconto_especial').innerHTML = preco_produto; 
	}

	if (valor == ''){
		document.getElementById(divClasse).className = 'varTit';
		atualizaDiv('abas_produto.php?loja='+loja+'&aba=formas&id_produto='+id_produto+'&preco_calculo='+preco_calculo,'atualizaFormas');
	}else{

		document.getElementById(divClasse).className = 'varTit onVar';
	}
	
	document.getElementById(idSpanPreco).innerHTML 					= valor_exibicao_preco;	
	document.getElementById('verifica_variacao_dupla_valor').value 	= valor;

	var url='funcoes/executa_variacao_dupla.php?loja='+loja+'&id_produto='+id_produto+'&tipo='+tipo+'&valor='+valor_url+'&cont='+cont+'&preco_prod='+preco_prod+'&pagamento='+pagamento+'&tipo1='+tipo1+'&preco_desconto_especial='+preco_desconto_especial;
	new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});
}

function mudaVariacaoDuplaCores(div,tipo,loja,id_produto,idSelect,idSpanPreco,cont,preco_prod,pagamento,tipo1,preco_desconto_especial,tipo2,preco_v){	

	var valor = $(idSelect).value;
	valor_url = encodeURIComponent(valor);
	
	var antVariacao = document.getElementById('antVariacao').value;
	
	var valor_adicional = calcula_total_adicionais();
	
	preco_calculo = preco_prod.replace(",",".");

	if(preco_desconto_especial){

		var valor_desconto_especial = parseFloat(preco_calculo)*(1-parseFloat(preco_desconto_especial));
		valor_desconto_especial = valor_desconto_especial.toFixed(2);
		
		if(valor_adicional>0){
			valor_desconto_especial += valor_adicional;
		}

		$('valor_desconto_especial').value = valor_desconto_especial;

		preco_produto = valor_desconto_especial;

		preco_produto = preco_produto.toString();
		preco_produto = preco_produto.replace(".", ",");
		
		preco_calculo = valor_desconto_especial;

	}else{

		preco_produto = preco_prod;

	}
	
	$('preco_atual').value = preco_calculo;
	
	if(valor_adicional>0){

		preco_calculo = parseFloat(preco_calculo) + valor_adicional;

		valor_exibicao_preco = preco_prod.replace(".","");
		valor_exibicao_preco = valor_exibicao_preco.replace(",",".");
		valor_exibicao_preco = parseFloat(valor_exibicao_preco);
		
		valor_exibicao_preco += valor_adicional;
		valor_exibicao_preco = valor_exibicao_preco.toFixed(2);
		valor_exibicao_preco = number_format(valor_exibicao_preco,2,",",".");

	}else{

		valor_exibicao_preco = preco_prod;

	}

	document.getElementById('variacao').value='';
	
	document.getElementById('imgView').src = antVariacao;
	document.getElementById('estoque_variacao').innerHTML = ""; 
	document.getElementById('precoDe').style.display = '';

	if(preco_desconto_especial > 0){
		document.getElementById('desconto_especial').innerHTML = preco_produto; 
	}

	if (valor == ''){
		atualizaDiv('abas_produto.php?loja='+loja+'&aba=formas&id_produto='+id_produto+'&preco_calculo='+preco_calculo,'atualizaFormas');
	}
	
	document.getElementById(idSpanPreco).innerHTML 					= valor_exibicao_preco;	
	document.getElementById('verifica_variacao_dupla_valor').value 	= valor;

	var url='funcoes/variacao_dupla_cores.php?loja='+loja+'&id_produto='+id_produto+'&tipo='+tipo+'&valor='+valor_url+'&cont='+cont+'&preco_prod='+preco_prod+'&pagamento='+pagamento+'&tipo1='+tipo1+'&preco_desconto_especial='+preco_desconto_especial+"&tipo2="+tipo2;
	new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});
}

function mudaVariacaoDuplaCompreJunto(div,loja,id_produto,id_produto_principal,id_compre_junto,idSelect,divClasse){	

	var id_hidden = 'variacao'+id_compre_junto+'_'+id_produto;
	var valor = $(idSelect).value;	
	var idForm = "form"+id_compre_junto;
	
	valor_url = encodeURIComponent(valor);
	
	$(id_hidden).value = '';
	
	if (valor == ''){
		$(divClasse).className = 'varTit';
	}else{
		$(divClasse).className = 'varTit onVar';
	}
	
	
	var url='funcoes/variacao_dupla_compre_junto.php?loja='+loja+'&id_produto='+id_produto+'&id_produto_principal='+id_produto_principal+'&id_compre_junto='+id_compre_junto+'&valor='+valor_url;
	new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});

	sendDataBuyTogether(idForm,id_compre_junto,loja);
}


function mudaVariacaoDuplaBrinde(div,loja,id_produto,id_produto_principal,id_compre_junto,idSelect,divClasse){	

	var id_hidden = 'brinde';
	var id_hidden_variacao = 'variacao_brinde';
	var valor = $(idSelect).value;	
	
	valor_url = encodeURIComponent(valor);
	
	$(id_hidden).value = '';
	$(id_hidden_variacao).value = '';
	
	if (valor == ''){
		$(divClasse).className = 'varTit';
	}else{
		$(divClasse).className = 'varTit onVar';
	}
	
	
	var url='funcoes/variacao_dupla_compre_junto.php?loja='+loja+'&id_produto='+id_produto+'&id_produto_principal='+id_produto_principal+'&id_compre_junto='+id_compre_junto+'&valor='+valor_url;
	new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});

}

function mudaVariacaoCompreJunto(idSelect,idCompreJunto,idProduto,idLoja){	

	var id_hidden = 'variacao'+idCompreJunto+'_'+idProduto;
	var valores = document.getElementById(idSelect).value;
	valor = valores.split('|');

	$('erroCompreJunto'+idCompreJunto).hide();
	var idForm = "form"+idCompreJunto;

	document.getElementById(id_hidden).value = valor[0];
	
	sendDataBuyTogether(idForm,idCompreJunto,idLoja);

}

function mudaVariacaoBrinde(idSelect,idCompreJunto,idProduto,idLoja){	

	var id_hidden_variacao = 'variacao_brinde';
	var valores = $(idSelect).value;
	valor = valores.split('|');

	$(id_hidden_variacao).value = valor[0];
	
	$('erro_brinde_var').hide();
	
}

function mudaVariacaoSimplesFrete(id,div){
	var valor = document.getElementById(id).value;
	document.getElementById('variacao').value=valor;
	document.getElementById(div).innerHTML = '';
	document.getElementById(div).style.display = 'none';
}
function mudaVariacaoDuplaFrete(div,loja,id_produto,idSelect,divClasse,cont){	
	var valor = document.getElementById(idSelect).value;
	valor_url = encodeURIComponent(valor);
	
	document.getElementById('variacao').value='';
	document.getElementById('valor_var').value=valor;	
	if (valor == ''){
		document.getElementById(divClasse).className = 'varTit';
	}else{
		document.getElementById(divClasse).className = 'varTit onVar';
	}
	var url='funcoes/variacao_simular_frete.php?loja='+loja+'&id_produto='+id_produto+'&atualiza_variacao=1&valor='+valor_url+'&cont='+cont;
	new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});
}
function ParseNumb(c){	
	c=ClearStr(c,'-');
	c=ClearStr(c,'/');
	c=ClearStr(c,',');
	c=ClearStr(c,'.');
	c=ClearStr(c,'(');
	c=ClearStr(c,')');
	c=ClearStr(c,' ');
	if((parseFloat(c) / c != 1)){
		if(parseFloat(c) * c == 0){
			return(c);
		}else{
			return(0);
		}
	}else{
		return(c);
	}
}
function enviaForm(Form,div,campo,erro,url){
	
	var Form = document.getElementById(Form);
	var retorno = validaEmail(Form,campo,erro);
	if(retorno != false){
		new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});
	}else{
		return (false);
	}	
}
function enviaFormulario(idForm){
	document.getElementById(idForm).submit();
}
function enviaComent(div,erro,url){
	var retorno = validaNome("","nome_coment",erro);
	if(retorno == false){
		return (false);
	}	
	retorno = validaEmail("","email_coment",erro);
	if(retorno == false){
		return (false);
	}
	retorno = validaMensagem("","mensagem_coment",erro);
	if(retorno == false){
		return (false);
	}	
	retorno = validaVoto("","voto",erro);
	if(retorno == false){
		return (false);
	}	
	var nota = document.getElementById('nota_comentario').value;
	var exibe_email = document.getElementById('exibe_email').checked;
	if(exibe_email == true)
		exibe_email = 1;
	else
		exibe_email = 0;
	var comentario = document.getElementById('mensagem_coment').value;
	url = url+'&nota='+nota+'&exibe_email='+exibe_email+'&comentario='+comentario;
	new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});
}
function exibeBotao(id_forma_pagamento){
	var tot = document.getElementsByTagName('input');
	for(var i=0; i<tot.length; i++){
		if(tot[i].name=='imageSend'){
			tot[i].style.display='none';
		}
	}
	document.getElementById(id_forma_pagamento).style.display = '';
}
function limparFrete(id_produto, loja){
	window.location.href='?loja='+loja+'&id_produto='+id_produto;
}
// ENVIA DADOS POR SELECT TAGS "catalogo.php"
function enviaDadosOnChange(id,loja,link){   
	var dep = document.getElementById(id).value;
	window.location.href = "catalogo.php?loja="+loja+'&IdDep='+dep+link;   
}
function enviaDadosOrdem(id,loja,link,dep){   
	var ordem = document.getElementById(id).value;
	window.location.href = "catalogo.php?loja="+loja+link+"&filtrar_ordem="+ordem;   
}
function enviaDadosMarca(item,loja,link,dep){   
	var marca = item.value;
	window.location.href = "catalogo.php?loja="+loja+link+"&filtrar_marca="+escape(marca);   
}



function enviaDadosDisponibilidade(item,loja,link,dep){
	var disponilibidade = item.value;
	window.location.href = "catalogo.php?loja="+loja+link+"&filtrar_disponibilidade="+escape(disponilibidade); 
}



// ENVIA DADOS POR SELECT TAGS "pronta_entrega.php"
function enviaDadosOnChangePE(id,loja,link){   
	var dep = document.getElementById(id).value;
	window.location.href = "pronta_entrega.php?loja="+loja+link;   
}
function enviaDadosOrdemPE(id,loja,link,dep){   
	var ordem = document.getElementById(id).value;
	window.location.href = "pronta_entrega.php?loja="+loja+link+"&filtrar_ordem="+ordem;   
}
function enviaDadosMarcaPE(item,loja,link,dep){   
	var marca = item.value;
	window.location.href = "pronta_entrega.php?loja="+loja+link+"&filtrar_marca="+escape(marca);   
}
// ENVIA DADOS POR SELECT TAGS "busca.php"
function enviaDadosOnChangeBusca_1(item,loja,linkpag){   
	var id = item.value;
	window.location.href = "busca.php?loja="+loja+"&filtrar_marca="+escape(id)+"&avancada=1&linkpag="+linkpag;   
}
function PrintPage(){
	if (window.print){
    window.print();
	}else{
    alert("O script não conseguiu enviar o documento diretamente para impressão,\nPressione Ctrl+P ou selecione Imprimir no menu Arquivo para imprimir esta página.");
	}
}
function enviaDadosOnChangeBusca_2(item,loja,linkpag){   
	var id = item.value;
//	window.location.href = "busca.php?loja="+loja+"&filtrar_ordem="+id+"&linkpag="+linkpag;
	window.location.href = "busca.php?loja="+loja+"&filtrar_marca=&filtrar_ordem="+id+"&linkpag="+linkpag;   
} 
///** */
function Limpar(valor, validos){
	// retira caracteres invalidos da string
	var result = "";
	var aux;
	for (var i=0; i < valor.length; i++){
		aux = validos.indexOf(valor.substring(i, i+1));
		if (aux>=0) {	result += aux;	}
	}
	return result;
}
//Formata número tipo moeda usando o evento onKeyDown
function Formata(campo,tammax,teclapres,decimal){
	var tecla = teclapres.keyCode;
	vr 	= Limpar(campo.value,"0123456789");
	tam = vr.length;
	dec	=decimal
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	if (tecla == 8 ){	tam = tam - 1 ; }
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= dec ){ campo.value = vr ; }
		if ( (tam > dec) && (tam <= 5) ){	campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }		
		if ( (tam >= 6) && (tam <= 8) ){	campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }	
		if ( (tam >= 9) && (tam <= 11) ){	campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
		if ( (tam >= 12) && (tam <= 14) ){	campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }		
		if ( (tam >= 15) && (tam <= 17) ){	campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;}
	} 
}
function openLightWindow(url,titulo,altura,largura, iframeNome){
	
	var myLightWindow = new lightwindow();
	
	myLightWindow.activateWindow({
		href: url,
		title: titulo,
		width: largura,
		height: altura,
		iframeNome: iframeNome,
		type: 'external'
	});
	
	return false;
}
//Variavel que recebera o comentario para depois poder devolve-lo
var comentario = '';
//Função utilizada para editar comentario do cliente por ajax
function editarComentario(link,div)
{
	if(comentario!='')
	{
		return false;
	}
	comentario = document.getElementById(div).innerHTML;
	url = link.href;
	atualizaDiv(url,div);
}
//Função utilizada para cancelar alteração do comentario do cliente por ajax
function cancelarComentario(div)
{
	document.getElementById(div).innerHTML = comentario;
	comentario = '';
}
//Função utilizada para atualizar comentario do cliente por ajax
function atualizaComentario(link,div,idComent,idNota)
{
	var retorno = valida_formularios();	
	if (retorno == false)
	{
		return false;
	}
	var coment = document.getElementById(idComent).value;
	var nota = document.getElementById(idNota).value;
		
	url = link.href+'&comentario='+coment+'&nota='+nota;
	atualizaDiv(url,div);
	comentario = '';
}
//Função que exibe uma confirmação de uma ação
function confirmSent(link, mensagem)
{
	var confirmation = confirm(mensagem);
	if(confirmation == true)
		window.location=link.href;
	else
		return false;
}
function cleanVisited(Link,div)
{
	url=Link.href;
	atualizaDiv(url,div);
	document.getElementById(div).style.display='none';
}
function clearItem(tipo,id)
{
	var div = tipo+id;
	var	url='funcoes/atualiza_navegacao.php?tipo='+tipo+'&id='+id;
	atualizaDiv(url,div);
	document.getElementById(div).style.display='none';
}
function swapImage(imgP,imgG)
{
	var bigs = document.getElementById('foto_p').getElementsByTagName('span');
	var smalls = document.getElementById('foto_a').getElementsByTagName('span');
	var totBigs = bigs.length;
	for(i=0;i<totBigs;i++)
	{
		bigs[i].style.display='none';
		smalls[i].style.display='';
	}
	document.getElementById(imgP).style.display='none';
	document.getElementById(imgG).style.display='';
}
//Função para colocar na sessao o produto a ser comparado
function inserirComparacao(link,qtd,div,loja)
{
	atualizaDiv(link.href,div);
	if(qtd)
		window.location.href='comparador-'+loja;
}
//Função para retirar da sessao o produto a ser comparado
function removerComparacao(link,div)
{
	atualizaDiv(link.href,div);
}
function atualizaFromas(url,inputHidden,div)
{
	if ($(inputHidden).value == 0) {
		$(inputHidden).value = 1;
		$(div).innerHTML = '<img src="img01/ajax-loading.gif" alt="Loading" title="Loading" />&nbsp;Carregando Formas de Pagamento';
		atualizaDiv(url, div);
	}
}

function enviaFormularioContatoAjax(Form,divAt,msg)
{
	var retorno = valida_formularios();	
	if (retorno == false)
	{
		return (false);
	}
	
	Form.request({
		onSuccess:function(transport)
		{
			$(divAt).innerHTML="<div class='blocoSucesso'>"+msg+"</div>";
			$(divAt).style.display = '';
		}
	});
	return (false);
}

function calculaFrete()
{
	validaCalculoFrete('cep1','cep2','quant','span_erro_cep');
	return false;
}

function enviaDepLoja(Form)
{
	var nome = $('nome_depoimento');
	var email = $('email_depoimento');
	var depo = $('msg_depoimento');

	if(nome.value == "")
	{
		$('aviso_depoimento').innerHTML="<div class='blocoAlerta'>Campo nome obrigatório. Digite o seu nome completo por favor.</div>";
		$('aviso_depoimento').style.display = '';
		return (false);
	}

	if(email.value == "")
	{
		$('aviso_depoimento').innerHTML="<div class='blocoAlerta'>Campo email obrigatório. Digite o seu email por favor.</div>";
		$('aviso_depoimento').style.display = '';
		return (false);
	}

	if(email.value.indexOf("@") == -1 || email.value.indexOf(".") == -1)
	{
		$('aviso_depoimento').innerHTML="<div class='blocoAlerta'>Formato de e-mail inválido. Digite o seu email por favor.</div>";
		$('aviso_depoimento').style.display = '';
		return (false);
	}

	if(depo.value == "")
	{
		$('aviso_depoimento').innerHTML="<div class='blocoAlerta'>Campo depoimento obrigatório. Digite o depoimento por favor.</div>";
		$('aviso_depoimento').style.display = '';
		return (false);
	}

	Form.request({
		onSuccess:function(transport)
		{
			$('aviso_depoimento').innerHTML="<div class='blocoSucesso'>Depoimento enviado com Sucesso!</div>";
			$('aviso_depoimento').style.display = '';
            Form.reset();
		}
	});
	return (false);
}

//Função que dimenciona o site do cliente se ele estiver com a resolução baixa
if(window.screen.width < 900)
{
	setTimeout("document.getElementById('Body').style.width = '1030px'",1000);
}

function fecharBannerFlutuante(op)
{
	document.getElementById(op).style.display = "none";
}

function atualizaSelectDepo(loja,select)
{
	window.location.href='depoimentos.php?loja='+loja+'&origem='+select.value;
}

function validaBonus(caixaTexto,max)
{
	max = parseInt(max);
	if(caixaTexto.value>max)
		caixaTexto.value = max;
}

//Abri as imagens nas categorias
function AbrirSub(menu){
	//new Effect.BlindDown(menu, {duration:0.2});
	$(menu).style.display = 'block';
}

//Fecha as imagens nas categorias
function FecharSub(menu){
	$(menu).style.display = 'none';
}

function setGift(loja,id_produto)
{
	new Ajax.Request('funcoes/produtos_presente.php?loja='+loja+'&id_produto='+id_produto+'&carrinho=1');
}

function exibeDetalheCartao(id_cartao,id_produto,loja)
{
	new Ajax.Request('funcoes/produtos_presente.php?loja='+loja+'&id_produto='+id_produto+'&cartao=1&id_cartao='+id_cartao);

	var divs = $('lista_'+id_produto).getElementsByTagName('div');
	
	var total = divs.length;
	for(var i=0;i<total;i++){
		if(divs[i].className == 'detalhe_cartao'){
			divs[i].style.display = 'none';
		}
	}

	//$('cartao_'+id_produto+'_'+id_cartao).style.display = '';
	new Effect.BlindDown('cartao_'+id_produto+'_'+id_cartao ,{duration:1.0});
}

function exibeDetalheEmbalagem(id_embalagem,id_produto,loja)
{
	new Ajax.Request('funcoes/produtos_presente.php?loja='+loja+'&id_produto='+id_produto+'&id_embalagem='+id_embalagem+'&embalagem=1');

	var divs = $('lista_'+id_produto).getElementsByTagName('div');

	var total = divs.length;
	for(var i=0;i<total;i++){
		if(divs[i].className == 'detalhe_embalagem'){
			divs[i].style.display = 'none';
		}
	}

	//$('emb_'+id_produto+'_'+id_embalagem).style.display = '';
	new Effect.BlindDown('emb_'+id_produto+'_'+id_embalagem ,{duration:1.0});
}

function gravaTextoCartao(id,id_cartao,id_produto,loja)
{
	var texto = $(id).value;
	new Ajax.Request('funcoes/produtos_presente.php?loja='+loja+'&id_produto='+id_produto+'&cartao_texto=1&id_cartao='+id_cartao+'&texto='+texto);

}

function changeDisplay(div1,div2){
		
	$(div1).show();
	$(div1+'_link').className = 'menu_esquerdo_ativado';	
	
	$(div2).hide();
	$(div2+'_link').className = '';
}

//funçao que abre o menu superior
function abreMenuSuperior(menu){

	var UL = menu.getElementsByTagName('ul');
	UL[0].style.display='block';

}

function fechaMenuSuperior(menu){

	var UL = menu.getElementsByTagName('ul');
	UL[0].style.display='none';

}

function fabreWinPagamento(){
	if(navigator.appName.indexOf("Netscape") != -1) {
		mpg_popup=window.open("","mpg_popup","toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=0,screenX=0,screenY=0,left=0,top=0,width=765,height=440");
	} else {
		mpg_popup=window.open("","mpg_popup","toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,screenX=0,screenY=0,left=0,top=0,width=765,height=440");
	}
}

function total_voce_quis_dizer(vocequisdizer,loja){

	//Abrindo arquivo externo
	xmlhttp.open("POST", "busca.php?rand="+Math.ceil ( Math.random() * 100000 ),true);
	
	//Setando o cabeçalho da requisição		
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");	
	
	//Enviando a requisição por POST (Não esquecer de fazer utf8_decode na página que irá receber)
	xmlhttp.send("palavra_busca="+vocequisdizer+"&ajax_voce_quis_dizer=1&loja="+loja);		
	
	//Recebendo a resposta da requisição
	xmlhttp.onreadystatechange=function(){	
		//Verificando o staus de terminado
		if (xmlhttp.readyState == 4){					
			//Verificando se enviou resposta
			if(xmlhttp.status == 200){						
				if(xmlhttp.responseText <= 1){
					var item = 'item';
				}else{
					var item = 'itens'; 
				}
				document.getElementById("total_voce_quis_dizer").innerHTML = vocequisdizer+'  ('+xmlhttp.responseText+' '+item+')';
				
			}			
		}			
	}
}

function validaCompreJunto(idForm,idCompreJunto){
	
	if(document.getElementById('variacoes_'+idCompreJunto).value == 1){

		var Form = document.getElementById(idForm);
		var compreJunto = document.getElementById('erroCompreJunto'+idCompreJunto);
		var inputs = Form.getElementsByTagName('input');
		var total = inputs.length;
		
		for(i=0;i<total;i++){
			if(inputs[i].type == 'hidden' && inputs[i].value == ''){
				compreJunto.style.display = 'block';
				return false;
			}
		}
	}
	
}

function sendDataBuyTogether(idForm,idCompreJunto,idLoja){
	
	var param = '';

	var Form = document.getElementById(idForm);
	var compreJunto = document.getElementById('erroCompreJunto'+idCompreJunto);
	var inputs = Form.getElementsByTagName('input');
	var total = inputs.length;
	
	for(i=0;i<total;i++){
		if(inputs[i].type == 'hidden' && inputs[i].value != ''){
			param += '&'+inputs[i].id+'='+inputs[i].value;
		}
	}
	
	var div = 'CompreJunto'+idCompreJunto;
	var url = 'funcoes/compre_junto.php?loja='+idLoja+param+'&id_compre_junto='+idCompreJunto;

	atualizaDiv(url,div);
}

function ativa_checkbox_variacao(loja,id,posicao,id_variacao,indice)
{
	if(document.getElementById(id).checked==false)
	{
		document.getElementById(id).checked = true;
	}

	$(posicao).hide();

	atualizaDiv('funcoes/variacao_texto_produto.php?loja='+loja+'&id='+id_variacao+'&posicao_lista='+posicao+'&i='+indice,posicao);
}

function ativa_checkbox_ie(select)
{
	if(navigator.appName == "Microsoft Internet Explorer"){
		var funcao = select.options[select.selectedIndex].onmouseup;
		setTimeout(funcao,1);
	}
}

function desativa_checkbox_variacao(id,posicao)
{
	if(document.getElementById(id).checked==true)
	{
		document.getElementById(id).checked = false;
	}

	$(posicao).hide();
	$(posicao).innerHTML = '';
}

var tamanho_brinde = 0;
var brinde_atual = 0;

function calculaTamanho(){
	
	var width = 0;
	
	var cont = 0;
	$$("#brindes li").each(function(p){
		width += 100;
	})
	
	tamanho_brinde = width;
	
	$("brindes").style.width = width+"px";
}

function rolar(sentido){
	
	var tamanho = $("brindes").style.width;
	tamanho = tamanho.replace("px","");
	
	if(sentido=='menos'){
		new Effect.Move('brindes', {duration: 0.5, x:100, transition: Effect.Transitions.sinoidal });
		brinde_atual += 100;
	}else{
		new Effect.Move('brindes', {duration: 0.5, x:-100, transition: Effect.Transitions.sinoidal });
		brinde_atual -= 100;
	}
	
	if(brinde_atual == 0){
		new Effect.Fade('btmenos', {duration: 1.0});
	}else if(brinde_atual < 0){
		new Effect.Appear('btmenos', {duration: 1.0});
	}
	
	if(brinde_atual == -(tamanho - 300)){
		new Effect.Fade('btmais', {duration: 1.0});
	}else{
		new Effect.Appear('btmais', {duration: 1.0});
	}
	
}

function selecionaBrinde(idCompreJunto,idProdutoBrinde,nomeProdutoBrinde,tem_variacao){

	var id_hidden = "brinde";
	var id_hidden_variacao = "variacao_brinde";
	var id_produto_brinde = "produto_brinde";
	var nome_brinde = "nomeBrinde";
	var imagem = $("imagem_"+idCompreJunto);
	var link = $("link_"+idCompreJunto);
	var variacao = $("variacao_brinde");
	var valida = true;

	$("span_erro_carrinho").hide();
	$("span_erro_carrinho").innerHTML = '';

	if(tem_variacao==1){
	
		$$(".variacao select").each(function(e){
			if(e.selectedIndex == 0){
				valida = false;
				$(id_hidden_variacao).value = "";
			}
		});
		
	}else{

		$(id_hidden_variacao).value = "";

	}
	
	if(valida == true){

		$(id_hidden).value = idCompreJunto;
		$(id_produto_brinde).value = idProdutoBrinde;
		$(nome_brinde).innerHTML = "Seu Brinde: "+nomeProdutoBrinde;
	
		$$("#brindes .imagem_produto").each(function(e){
			e.setStyle({
				border: "none"
			});
		});
		
		imagem.setStyle({
			border: "2px solid #f00"
		});
	
		myLightWindow.deactivate();

	}else{

		$("erro_brinde_var").show();

	}

}

function desativaBrinde(idCompreJunto,idProdutoBrinde,nomeProdutoBrinde){
	
	var id_hidden = 'brinde';
	var id_hidden_variacao = 'variacao_brinde';
	var id_produto_brinde = "produto_brinde";
	var imagem = $("imagem_"+idCompreJunto);
	var link = $("link_"+idCompreJunto);
	var nome_brinde = "nomeBrinde";
	
	if($(id_hidden).value == idCompreJunto){

		$(id_hidden).value = "";
		$(id_hidden_variacao).value = "";
		$(id_produto_brinde).value="";
		$(nome_brinde).innerHTML = nomeProdutoBrinde;
		
		var imagem = $("imagem_"+idCompreJunto);
		
		imagem.setStyle({
			border: "none"
		});

	}
	
	return false;
	
}

function validaSuperPay(flag_contrato,loja,id_forma_pagamento){
	
	var url = "funcoes/dadosCartaoSuperPay.php?loja="+loja+"&flag_contrato="+flag_contrato+"&id_forma_pagamento="+id_forma_pagamento;
	
	openLightWindow(url,"Dados do Cartão",360,600);
	
	return false;
}

function enviaDadosCartao(flag_contrato) {

	var valida 			=  valida_formularios();
	
	if(valida != false){
		
		if($("dadosNumeroCartaoCredito").value.length < 16){

			$("dadosNumeroCartaoCredito").className = 'text inputErro';
			$("dadosNumeroCartaoCredito_erro").style.display = '';
			$("dadosNumeroCartaoCredito_erro").innerHTML = $("mensagem_erro_1").value;
			
			return false;

		}else if($("dadosCodigoSeguranca").value.length < 3){

			$("dadosCodigoSeguranca").className = 'text inputErro';
			$("dadosCodigoSeguranca_erro").style.display = '';
			$("dadosCodigoSeguranca_erro").innerHTML = $("mensagem_erro_2").value;
			
			return false;

		}else if($("mesDataValidadeCartao").value.length < 2){

			$("mesDataValidadeCartao").className = 'text inputErro';
			$("mesDataValidadeCartao_erro").style.display = '';
			$("mesDataValidadeCartao_erro").innerHTML = $("mensagem_erro_3").value;
			
			return false;

		}else if($("anoDataValidadeCartao").value.length < 2){

			$("anoDataValidadeCartao").className = 'text inputErro';
			$("anoDataValidadeCartao_erro").style.display = '';
			$("anoDataValidadeCartao_erro").innerHTML = $("mensagem_erro_4").value;
			
			return false;

		}else{
		
			var nomeTitular  	 =  $("dadosNomeTitularCartaoCredito").value;
			var mesValidade 	 =  $("mesDataValidadeCartao").value;
			var anoValidade 	 =  $("anoDataValidadeCartao").value;
			var numeroCartao 	 =  $("dadosNumeroCartaoCredito").value;
			var codigoSeguranca  =  $("dadosCodigoSeguranca").value;
		
			var validade = mesValidade.toString() + '/' + anoValidade.toString();
		
			parent.$("NomeTitularCartaoCredito").value  = nomeTitular;
			parent.$("DataValidadeCartao").value 		= validade;
			parent.$("NumeroCartaoCredito").value 		= numeroCartao;
			parent.$("CodigoSeguranca").value 			= codigoSeguranca;
		
			parent.$("pag").submit(flag_contrato);
			
		}

	}else{
		return false;
	}
}

function validaFormPagamento(){

	var valida 			=  valida_formularios();
	
	if(valida != false){
		
		if($("dadosNumeroCartaoCredito").value.length < 16){

			$("dadosNumeroCartaoCredito").className = 'text inputErro';
			$("dadosNumeroCartaoCredito_erro").style.display = '';
			$("dadosNumeroCartaoCredito_erro").innerHTML = $("mensagem_erro_1").value;
			
			return false;

		}else if($("dadosCodigoSeguranca").value.length < 3){

			$("dadosCodigoSeguranca").className = 'text inputErro';
			$("dadosCodigoSeguranca_erro").style.display = '';
			$("dadosCodigoSeguranca_erro").innerHTML = $("mensagem_erro_2").value;
			
			return false;

		}else if($("mesDataValidadeCartao").value.length < 2){

			$("mesDataValidadeCartao").className = 'text inputErro';
			$("mesDataValidadeCartao_erro").style.display = '';
			$("mesDataValidadeCartao_erro").innerHTML = $("mensagem_erro_3").value;
			
			return false;

		}else if($("anoDataValidadeCartao").value.length < 2){

			$("anoDataValidadeCartao").className = 'text inputErro';
			$("anoDataValidadeCartao_erro").style.display = '';
			$("anoDataValidadeCartao_erro").innerHTML = $("mensagem_erro_4").value;
			
			return false;

		}

	}else{
		return false;
	}
}

function define_opcao_valor_select(value_option,pos){

	var valores = value_option;
	var valor = valores.split("|");

	var select_opcao = valor[0];
	var select_valor = valor[1];

	if(value_option==0){
		select_valor = "0.00";
	}

	$('informacao_adicional_opcao_'+pos).value = select_opcao;
	$('informacao_adicional_valor_'+pos).value = select_valor;
}


function calcula_total_adicionais(){

	var valor_adicional = 0.00;
	var input = "";

	$$(".valor_hidden").each(function(e){
		
		if(e.value == ""){
			e.value = 0;
		}

		if(e.className == "valor_hidden text"){
		
			id_input = e.id.replace("valor","opcao");
			
			input = $(id_input);
			
			if(input.value!=""){
			
				valor_adicional += parseFloat(e.value);

			}
			
		}else{
			valor_adicional += parseFloat(e.value);
		}
		
	});
	
	return parseFloat(valor_adicional);
}

function valoresAdicionais(id_produto,loja,pagamento,detalhes,calculoPontos,bonusValor){

	var valor_atual = $("preco_atual").value;
	var valor_adicionais = calcula_total_adicionais();
	var calculoPontos = calculoPontos;	// Vindo por Session			
	var bonusValor 	  = bonusValor;		// Vindo por Session
	
	var total = parseFloat(valor_atual) + valor_adicionais;
	total_formatado = number_format(total,2,",",".");
	
	$("variacaoPreco").innerHTML = total_formatado;
	
	url = "formas_pagamento.php?loja="+loja+"&id_produto="+id_produto+"&pagamento="+pagamento+"&preco_calculo="+total+"atualiza=1";
	url2 = "detalhes_formas.php?loja="+loja+"&id_produto="+id_produto+"&preco_calculo="+total;

	$("atualizaFormas").innerHTML = '<img src="img01/ajax-loading.gif" alt="Loading" title="Loading" />&nbsp;Carregando Formas de Pagamento';
	$('aba_formas').value=1;

	atualizaDiv('abas_produto.php?loja='+loja+'&aba=formas&id_produto='+id_produto+'&preco_calculo='+total,'atualizaFormas');
	atualizaDiv(url2,"detalhes_formas");
	$("linkPagParcelado").href = 'pag_parcelado.php?IdProd='+id_produto+'&preco='+total+'&loja='+loja;
	
	$("info_preco").innerHTML = "";
	
	limpa_erro_carrinho();
	
	//fernando
	calculaBonusVariacao(calculoPontos,total_formatado,bonusValor);
}

function limpa_erro_carrinho(){
	$('span_erro_carrinho').innerHTML = '';
	$('span_erro_carrinho').style.display = 'none';
}

function number_format(number,decimals,dec_point,thousands_sep) {
    // %     nota 1: Para 1000.55 retorna com precisão 1 no FF/Opera é 1,000.5, mas no IE é 1,000.6
    // *     exemplo 1: number_format(1234.56);
    // *     retorno 1: '1,235'
    // *     exemplo 2: number_format(1234.56, 2, ',', ' ');
    // *     retorno 2: '1 234,56'
    // *     exemplo 3: number_format(1234.5678, 2, '.', '');
    // *     retorno 3: '1234.57'
    // *     exemplo 4: number_format(67, 2, ',', '.');
    // *     retorno 4: '67,00'
    // *     exemplo 5: number_format(1000);
    // *     retorno 5: '1,000'
    // *     exemplo 6: number_format(67.311, 2);
    // *     retorno 6: '67.31'
 
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}

function calculaBonusVariacao(calculoPontos,variacaoPreco,bonusValor) {
	
	var variacaoPreco = parseFloat($('variacaoPreco').innerHTML);
	var calculoPontos = calculoPontos;	// Vindo por Session			
	var bonusValor 	  = parseFloat(bonusValor);		// Vindo por Session

	if(calculoPontos=='preco'){
		$('idBonusVariacao').innerHTML 	 = parseFloat(variacaoPreco/bonusValor);
	}	
}

function mudaSelecao(id){
	
	$$(".cor_variacao img").each(function(e){
		e.className = "";
	});
	
	$$(".lista_cor_variacao div").each(function(e){
		e.className = "";
	});
	
	$(id).className = "cor_selecionada";
	
	$("cor_nome").innerHTML = "( "+$(id).title+" )";
	
}

function mudaSelecao2(id){
	
	$$(".cor_variacao2 img").each(function(e){
		e.className = "";
	});
	
	$$(".lista_cor_variacao2 div").each(function(e){
		e.className = "";
	});
	
	$(id).className = "cor_selecionada";
	
	$("cor_nome2").innerHTML = "( "+$(id).title+" )";
	
}