// JavaScript Document

function readCookie(Loja)
{
  var cookieValue = "";
  var search = Loja +"=";
  if(document.cookie.length > 0)
  { 
    offset = document.cookie.indexOf(search);
    if (offset != -1)
    { 
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end))
    }
  }
  return cookieValue;
}


function writeCookie(Loja,Ref,Prod,preco)
{
  if (readCookie(Loja) != null) {compra=readCookie(Loja);}

  value=compra + Ref + "||" + Prod + "||" + preco + "||";
  var expire = "";
  expire = new Date((new Date()).getTime() + 24 * 3600000);
  expire = "; expires=" + expire.toGMTString();
  document.cookie = Loja + "=" + escape(value) + expire;
  totais(Loja);
}

function limpar_cesto(name)
{
  value="";
  var expire = "";
  expire = new Date((new Date()).getTime());
  expire = "; expires=" + expire.toGMTString();
  document.cookie = name + "=" + escape(value) + expire;
  cesto_qdd=0;
  cesto_preco = 0.00;
}

function le(name) {
resto=readCookie(name)
i=0
ref=new Array()
prod=new Array()
preco=new Array()
while (resto!="") {
posicao=resto.indexOf('||');
ref[i]=resto.substring(0,posicao);
resto=resto.substring(posicao+2,resto.length);
posicao=resto.indexOf('||');
prod[i]=resto.substring(0,posicao);
resto=resto.substring(posicao+2,resto.length);
posicao=resto.indexOf('||');
preco[i]=resto.substring(0,posicao);
resto=resto.substring(posicao+2,resto.length);
posicao=resto.indexOf('||');
i++;
}
}

function totais(name) {
le(name);
total_qdd=prod.length;
total_preco=0.00;
for(n=0;n<prod.length;n++){
total_preco+=parseFloat(preco[n]);
}
cesto_qdd = total_qdd;
cesto_preco = String((Math.round(total_preco*100))/100);
if (cesto_preco.lastIndexOf('.')==-1) cesto_preco=cesto_preco+ ".00";
if ((cesto_preco.length - cesto_preco.lastIndexOf('.'))==2) cesto_preco=cesto_preco+ "0";
valor=cesto_preco.substring(0,cesto_preco.lastIndexOf('.')) + "," + cesto_preco.substring(cesto_preco.lastIndexOf('.')+1, cesto_preco.length)

if (valor.length  > 6) {
valor=valor.substring(0,valor.length -6) + "." + valor.substring(valor.length-6,valor.length);
if (valor.length  > 10) {
valor=valor.substring(0,valor.length -9) + "." + valor.substring(valor.length-10,valor.length);
if (valor.length  > 14) {
valor=valor.substring(0,valor.length -12) + "." + valor.substring(valor.length-14,valor.length);
if (valor.length  > 18) {
valor=valor.substring(0,valor.length -15) + "." + valor.substring(valor.length-18,valor.length);
}}}}

if (document.cesta.compras) document.cesta.compras.value = cesto_qdd + " - € " + valor;
escreve_cesto()
}


