
var numArticulos = 0;
var html = "";
var html2 = "";

//Instantiate cookie class
var myCookie = new Cookie();


function iniCookies()
{
	//Cookies didn't exist, create new cookies
	if(!myCookie.Load())
	{
	  myCookie.Create("articles", 10);
	  myCookie.Create("artidesc", 10);
	
	  //Add sub-item(s) to named cookie(s)
	  //myCookie.AddItem("articles", "3636");
	
	  //Store cookies
	  myCookie.Save();
	}
	else
	{ 	//Cookies were available so ignore 
	    //creating new ones and just load previous
	    //This is web site persistence at it's best
			//alert(document.cookie);

		try{
			numArticulos = myCookie.GetCount("articles");
			carrito.innerHTML = "Hay " + numArticulos + " artículos";
		}catch(e){
		  myCookie.Create("articles", 10);
		  myCookie.Create("artidesc", 10);
		  return;		
		}
		
		/*
		var htmlTemp = "";
	  //Pintam els articles:
	  for(j=numArticulos-1; j>=0; j--)
	  {
	  	htmlTemp = htmlTemp + "<LI> " + unescape(myCookie.GetItem("artidesc",j));
	  	if (j==numArticulos-5){
	  		htmlTemp = htmlTemp + "<br> ..."; 
	  		break;
	  	}
	  }
	
	  carrito2.innerHTML = htmlTemp;
	  */
	}
}


function addCart(codi, desc)
{
	/*
	html2 = carrito2.innerHTML;
	
	if (numArticulos==0) html2 = "";
	
	html2 = "<LI> " + desc + html2;
	
	if (numArticulos>5){
		alert(html2)
		lio = html2.lastIndexOf("<LI>");
		alert(lio)
		html2=html2.substr(0,lio);
		html2=html2 + "<br> ...";
	}
	
	alert(html2)
	
	carrito2.innerHTML = html2;
	*/
	
	if (testInCart(codi, desc))
	{
		alert("El artículo ya está en el carrito, si desea más unidades indiquelo en el campo comentario cuando envie su petición");
		return;
	}
	
	numArticulos++;
	carrito.innerHTML = "Hay " + numArticulos + " artículos";
	
	//Add Cookie
	myCookie.AddItem("articles",escape(codi));
	myCookie.AddItem("artidesc",escape(desc));
	myCookie.Save();
}


function delCart(codi, index)
{
	numArticulos--;
	carrito.innerHTML = "Hay " + numArticulos + " artículos";
	
	//Add Cookie
	myCookie.DelItem("articles",index);
	myCookie.DelItem("artidesc",index);
	myCookie.Save();
}


function deleteCart()
{
	for(var j=0; j<=numArticulos - 1; j++)
  {
  	
  	//alert(myCookie.GetItem("articles",j) + " - " + myCookie.GetItem("artidesc",j))
  	
  	myCookie.DelItem("articles",j);
  	myCookie.DelItem("artidesc",j);
  }

	myCookie.Delete("articles");
	myCookie.Delete("artidesc");
	myCookie.Save();
}


function testInCart(codi, desc)
{
	var temp = "";
	for(var j=0; j<=numArticulos; j++)
  {
		temp = unescape(myCookie.GetItem("articles",j));
  	if (temp == codi)
  		return true;
  }
  return false;
}
