// JavaScript Document
var codUltimoProdAberto="";

Number.prototype.times = function(block) {
  for (var i = 0; i < this; i++) block(i)
}

Array.prototype.remove=function(s)
{
  for(i=0;i<this.length;i++){
    if(s==this[i]) this.splice(i, 1);
  }
}

Array.prototype.somar=function()
{
  aux = 0;
  for(i=0;i<this.length;i++)
  {
    aux += this[i];
  }
  return aux;
}

Array.prototype.clear = function() {
  var obj = this
  this.length.times(function(index) {
    delete obj[index]
  })
  this.length = 0
}

Array.prototype.contains = function (element) 
{
	for (var i = 0; i < this.length; i++) 
    {
    	if (this[i] == element) 
        {
        	return true;
        }
    }
    return false;
}

Array.prototype.isEmpty = function() {
    return this.length == 0;
}

function mostrar_prod(cod_prod, opc)
{
	idPF = 'prodA_' + cod_prod;
	idPA = 'prodF_' + cod_prod;
	
	if(opc==0) //fechar
	{
		document.getElementById(idPA).style.display = "none";
		document.getElementById(idPF).style.display = "block";
	}
	else //abrir =1 
	{
		document.getElementById(idPF).style.display = "none";
		document.getElementById(idPA).style.display = "block";
	}

	if(codUltimoProdAberto!='' && codUltimoProdAberto!=cod_prod)
	{
		idPFUlt = 'prodA_' + codUltimoProdAberto;
		idPAUlt = 'prodF_' + codUltimoProdAberto;						
		
		document.getElementById(idPAUlt).style.display = "none";
		document.getElementById(idPFUlt).style.display = "block";					
	}
	
	codUltimoProdAberto = cod_prod;

}

function show(id)
{
	var obj = document.getElementById(id).style;

	if (obj.display == "none") 
		obj.display = "block";
	else
		obj.display = "none";
}

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 calcular_totais(embalagem, unidade, preco_emb, aliq_IPI, qtd, cod_prod, cod_emb, prods, tipo_consulta)
{ 
	divTotal = 'qtd_total_' + cod_prod + '_' + cod_emb;
	divPreco = 'preco_total_' + cod_prod + '_' + cod_emb;
		
	preco_emb = parseFloat(preco_emb);
	aliq_IPI = parseFloat(aliq_IPI);
	
	if(unidade == 'MIL')
		unidade = 1000;
	else if(unidade == 'UN' || unidade == 'KG' || unidade == 'L')
		unidade = 1;
	else
		unidade = 1;
			
	qtd_produtos = embalagem * unidade * qtd;
	preco_total = (qtd * preco_emb)*(1+(aliq_IPI/100));
	//preco_total = float2moeda(preco_total);

	//html qtd total e hidden
	document.getElementById(divTotal).innerHTML = qtd_produtos;
	document.getElementById('HD'+divTotal).value = qtd_produtos;

	//html preco total e hidden
	document.getElementById(divPreco).innerHTML = "R$ " + float2moeda(preco_total);	
	document.getElementById('HD'+divPreco).value = preco_total;
	
	//totais do produto aberto
	if(tipo_consulta == 1)
	{
		document.getElementById('qtd_'+cod_prod).innerHTML = somar_campos('HDqtd_total_',cod_prod, prods);
		document.getElementById('qtdP_'+cod_prod).innerHTML = float2moeda(somar_campos('HDpreco_total_',cod_prod, prods));
	}

	//totais do carrinho de compras
	if(tipo_consulta == 2)
	{
		//document.getElementById('ct_PTotal').innerHTML = float2moeda(somar_campos('HDpreco_total_',cod_prod, prods));
	}
}

function somar_campos(prefixo, cod_prod, cod_emb)
{

	aux = 0;
	for(i=0;i<cod_emb.length;i++)
	{
		if(document.getElementById(prefixo+cod_prod+'_'+cod_emb[i]).value)
			aux += parseFloat(document.getElementById(prefixo+cod_prod+'_'+cod_emb[i]).value);
	}
	return aux;

}

function zerar_campo(cod_prod, emb_prod, prods)
{
	//input qtd
	document.getElementById('qtd_'+cod_prod+'_'+emb_prod).value = 0;
	
	//html qtd total e hidden
	document.getElementById('qtd_total_'+cod_prod+'_'+emb_prod).innerHTML = '0';	
	document.getElementById('HDqtd_total_'+cod_prod+'_'+emb_prod).value = 0;
	
	//html preco total e hidden
	document.getElementById('preco_total_'+cod_prod+'_'+emb_prod).innerHTML = 'R$ 0,00';	
	document.getElementById('HDpreco_total_'+cod_prod+'_'+emb_prod).value = 0;
	
	//totais do produto aberto
	document.getElementById('qtd_'+cod_prod).innerHTML = somar_campos('HDqtd_total_',cod_prod, prods);
	document.getElementById('qtdP_'+cod_prod).innerHTML = float2moeda(somar_campos('HDpreco_total_',cod_prod, prods));

	
}

/* ####### carrinho ##########*/

function fechar_compra(cod_prod, cod_emb, tipo_insercao)
{
	prefixo = 'qtd_';
	
	compra = 0;
	for(i=0;i<cod_emb.length;i++)
		if(document.getElementById(prefixo+cod_prod+'_'+cod_emb[i]).value && document.getElementById(prefixo+cod_prod+'_'+cod_emb[i]).value>=0)
			compra=1;
			
	if(compra==1)
	{
		compra = 0;
		/*criando dados para POST*/
		campos = "action=add";
		for(i=0;i<cod_emb.length;i++)
		{
	
			if(document.getElementById(prefixo+cod_prod+'_'+cod_emb[i]).value)
			{
				campos = "action=add";
				campos += "&cod_prod="+cod_prod;
				campos += "&embprod="+cod_emb[i];
				campos += "&qtd_prod=" + parseInt(document.getElementById(prefixo+cod_prod+'_'+cod_emb[i]).value);
				campos += "&qtd_prod_total=" + document.getElementById('HDqtd_total_'+cod_prod+'_'+cod_emb[i]).value;												
				campos += "&preco_prod=" + document.getElementById('HDpreco_total_'+cod_prod+'_'+cod_emb[i]).value;												
				campos += "&preco_emb=" + document.getElementById('HDpreco_emb_'+cod_prod+'_'+cod_emb[i]).value;												
				campos += "&ipi=" + document.getElementById('HDipi_'+cod_prod+'_'+cod_emb[i]).value;
				
				//faltava
				campos += "&emb=" + document.getElementById('HDemb_'+cod_prod+'_'+cod_emb[i]).value;
				campos += "&unid=" + document.getElementById('HDunid_'+cod_prod+'_'+cod_emb[i]).value;
				campos += "&preco_unit=" + document.getElementById('HDpreco_unit_'+cod_prod+'_'+cod_emb[i]).value;				

				//alert(campos);
				HttpRequest("carrinho.php", "POST", true, campos, retornoInserir);
				
				if(document.getElementById(prefixo+cod_prod+'_'+cod_emb[i]).value > 0)
					compra=1;
			}
			
		}
		
		if(tipo_insercao==1)	//bt comprar (1), fecha o produto | bt atualizar (2) não fecha
			mostrar_prod(cod_prod, 0);
	
		if(compra==1)
		{
			document.getElementById('imgC_' + cod_prod).style.display = "block";
			document.getElementById('imgA_'+cod_prod).style.display = "block";			
			document.getElementById('imgD_'+cod_prod).style.display = "block";			
		}
		else
		{
			document.getElementById('imgC_' + cod_prod).style.display = "none";
			document.getElementById('imgA_'+cod_prod).style.display = "none";			
			document.getElementById('imgD_'+cod_prod).style.display = "none";			
		}
		
	}
	else
	{
		alert('Erro ao incluir compra: entre com ao menos uma quantidade nos produtos')	
	}

}

function retornoInserir()
{
	if (req.readyState == 4) 
	{
		//alert(req.responseText);
		if (req.status == 200) 
		{
			valor_carrinho('preco_carrinho');			
		} 
	}
}

function preencher_produto(qtd, cod_prod, cod_emb)
{
	
	document.getElementById('qtd_'+cod_prod+'_'+cod_emb).value = qtd;
	document.getElementById('imgC_'+cod_prod).style.display = "block";
	document.getElementById('imgA_'+cod_prod).style.display = "block";
	document.getElementById('imgD_'+cod_prod).style.display = "block";

	document.getElementById('qtd_'+cod_prod+'_'+cod_emb).onkeyup();
}

// funções do carrinho
function desfazer(campo, valor)
{
	document.getElementById(campo).value = valor;
}

function atualizar()
{
	var frm = document.frmCart;

	//frm.action.value = "update";
	frm.submit();
}

function limpar_carrinho()
{
	var frm = document.frmCart;

	frm.action.value = "clean";
	frm.submit();
}

function remover(id, desc)
{
	var frm = document.frmCart;

	if(confirm("Deseja realmente excluir o item \'"+desc+"\'? \n Clique em \'Ok\' para excluir ou \'Cancelar\' para cancelar"))
	{
		frm.action.value = "delete";
		frm.idItem.value = id;	
		frm.submit();	
	}
}

function valor_carrinho(idItem) 
{
	var xml = new xmlConnection();
	if (xml.create()) 
	{
		xml.setMethod('POST');
		xml.setURL('xml_carrinho_valor.php');
		xml.setChildName('return');
		
		//xml.addParameters('campo01',vCampo01);
		
		xml.onComplete = function() 
		{
			document.getElementById(idItem).innerHTML = "R$ " + float2moeda(this.getAttByName('retorno',0));
			document.getElementById(idItem+'_baixo').innerHTML = "R$ " + float2moeda(this.getAttByName('retorno',0));
		};
		xml.execute();
	}
};
