/* --- inicio funcoes fixas do carrinho --- */

function limpa_frete(form){
	document.getElementById('cep1').value = '';
	document.getElementById('cep2').value = '';
}

function cal_inc(form){
	var x;
	x =	document.getElementById('calcular_impostos').value;
	
	if(x==1){
		x=0;
	}else{
		x=1;
	}

	document.getElementById('calcular_impostos').value = x;
}

function abre_janela(width, height, nome, scrollbars){
	var top; var left;
	top = ((screen.height/2) - (height/2))
	left = ((screen.width/2) - (width/2))
	window.open('',nome,'width='+width+',height='+height+',scrollbars='+scrollbars+',toolbar=no,location=no,status=no,menubar=no,resizable=no,left='+left+',top='+top);
}

function arredonda(valor){
	valor  = valor.toString();       // transforma em strings
	valor  = valor.replace(",","");  // transforma em strings
	nponto = valor.indexOf(".");     // pega a posição do ponto

	if(nponto == -1){
		//nfinal=valor.substring(0,valor.length-2 )+"."+valor.substring(valor.length - 2,valor.length);
		nfinal = valor+".00";
	}else{
		nfinal = valor.substring(0,nponto+3);
	}
	
	return nfinal;
}

function formata_rs(valor){
	var indice;
	var j=0;
	
	valor = arredonda(valor); 				// arredonda valor
	//alert('arredondado '+valor);
	nponto = valor.indexOf(".");  			// pega a posicao do ponto
	tamanho= valor.length;        			// tamanho
	v1 = valor.substring(0,nponto); 		// separa a strings
	v2 = valor.substring(nponto+1,tamanho); // separa a outra parte

	for(indice = v1.length; indice > 0 ; indice-- ){
		if( j== 3 || j== 6 || j== 9 || j== 12 || j==16 || j==19){
			v1=v1.substring(0,indice)+"."+v1.substring(indice,v1.length);
		}
		j++;
	}

	if(v2.length<2){ v2 = v2+'0'; }
	valor = (v1+","+v2);
	return valor;
}

function float2moeda(num){

	x = 0;

	if(num<0) {
		num = Math.abs(num);
		x = 1;
	}

	if(isNaN(num)) num = "0";
	cents = Math.floor((num*100+0.5)%100);
	num = Math.floor((num*100+0.5)/100).toString();

	if(cents < 10) cents = "0" + cents;
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'
		+num.substring(num.length-(4*i+3));
		ret = num + ',' + cents;
		if (x == 1) ret = ' - ' + ret;

	return ret;
}

function valor_frete(valor,subtotal, imposto_pedido, desconto_pedido){
	if (imposto_pedido=='') imposto_pedido = 0;
	imposto = imposto_pedido;
	imposto = imposto*1;
	if (desconto_pedido=='') desconto_pedido = 0;
	var desconto = desconto_pedido;
	desconto = desconto*1;

	if(valor>0){
		valor_total = subtotal+valor+imposto-desconto;
	}else{
		valor_total = subtotal+imposto-desconto;
	}

	valor_total = float2moeda(valor_total);

	if (document.getElementById('frete7')){
		if (valor==-1) valor = 0;
		document.getElementById('frete7').innerHTML = formata_rs(valor);
	}

	document.getElementById('mostra_total').innerHTML = valor_total;
}

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;
}

function mudar_cor(linha,id){
   if (document.getElementById('tab')) {
	var tabela = document.getElementById('tab').getElementsByTagName('tr');
	var total = tabela.length;

	for(i=0;i<total;i++){
		tabela[i].className = "";
	}

	linha.className = "trOver"
	document.getElementById(id).checked = true;
   }            
}

/* --- fim funcoes fixas do carrinho --- */





/* --- inicio funcoes que estavam no 'script.js' --- */


//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>Atualizando formas de pagamento...</p></center>';
}

function ajaxRead(file,destino){
  
  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){
	document.getElementById(obj).innerHTML = data;
}


//funcao que faz a alternacao de abas na pagina de produtos
function AbrirAbas(id_div,id_li){

	if(document.getElementById(id_div).style.display == ''){
		}else{
		var ar = document.getElementById('AbasBlock').getElementsByTagName('div');
		for(var i=0;i<ar.length;i++){
			if(ar[i].className == 'cont'){
				ar[i].style.display = 'none';
				}
			}
		var ar = document.getElementById('AbasBlock').getElementsByTagName('li');
		for(var i=0;i<ar.length;i++){
			if(ar[i].className == 'aberta tit_lateral'){
				ar[i].className = 'tit_lateral';
				}
			}
		document.getElementById(id_div).style.display = '';
		document.getElementById(id_li).className = "aberta tit_lateral";
	}
}


//funcoes usadas no '/loja/finalizar_pagamento.php'
function esconde_div_erro1(){
	document.getElementById('erro1').style.display = 'none';
}


function esconde_div_erro2(){
	document.getElementById('erro2').style.display = 'none';
}


function checa(campo){
	document.getElementById(campo).checked = true;
	esconde_div_erro1();
}


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 valida_formas_pagamento(flag_contrato){

	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();
	}
}


function valida_contrato_pagamento(){

	if (document.getElementById('contrato').checked == false){
		document.getElementById('erro2').style.display = '';
		return false;
	}
}

// ---------- Funcoes para validar os comentarios ---------- //

function validaComent(Form){
		
	if (document.getElementById('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 (document.getElementById('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 (document.getElementById('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 ((document.getElementById('email_cliente').value.indexOf("@") == -1 )&&( document.getElementById('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 (document.getElementById('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 (document.getElementById('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  ---------- //


// ---------- Funcoes para validar email dos clientes da lista de espera  ---------- //
function validaEmail(Formulario,campo,erro){	

	if (document.getElementById(campo).value == "")  	{
	    document.getElementById(erro).style.display = '';
	    document.getElementById(erro).innerHTML = '<img src="img01/alert.png" width="25" height="25"> Digite o email.';
	    document.getElementById(campo).focus();
	    return (false);
	}
	if ( (document.getElementById(campo).value.indexOf("@") == -1 )&&( document.getElementById(campo).value != "" ) ) {
	   document.getElementById(erro).style.display = '';
	   document.getElementById(erro).innerHTML = '<img src="img01/alert.png" width="25" height="25"> Formato de e-mail inv&aacute;lido.';
	   document.getElementById(campo).focus();
	   return (false);
	}
	
	
}

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 removeAlertErro(erro){
	document.getElementById(erro).innerHTML = '';
	document.getElementById(erro).style.display = 'none';
}

// ---------- FIM Funcoes para validar email dos clientes da lista de espera  ---------- //


//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: ');
	}

	for(var i=0;i<paginas_prod;i++){
		
		if(total<=por_pag){
			cont=0;
		}
		
		url_link=url+'&cont='+cont+'&prod_visitados='+total+'&id='+id;
		document.write(' <a id="linkPag" class="linkPag" href="javascript:void(0)" onclick="geraLinkPaginacao(\''+div+'\',\''+url_link+'\');">'+(i+1)+'</a> ');
		cont=cont-3;
		total=total-3;
	}
}

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 verifica_cep_keypress(e,form,escolha){
	if (e == null)
        e = window.event 
    if (e.keyCode == 13)
    	verifica_cep(form,escolha);
}

/* --- fim funcoes que estavam no 'script.js' --- */
