function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate());
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) + ";path=/";
}

function removeCookie(c_name)
{
var exdate=new Date();
exdate.setDate(exdate.getDate());
document.cookie=c_name+ "=0;expires=Fri, 27 Jul 2001 02:47:11 UTC;path=/";
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function checkCookie()
{
username=getCookie('username');
if (username!=null && username!="")
  {
  alert('Welcome again '+username+'!');
  }
else
  {
  username=prompt('Please enter your name:',"");
  if (username!=null && username!="")
    {
    setCookie('username',username,365);
    }
  }
}

function addToCart(id) {
    if (getCookie('shoppingCart['+id+']')>0)
        setCookie('shoppingCart['+id+']',parseInt(getCookie('shoppingCart['+id+']'))+1);
    else
        setCookie('shoppingCart['+id+']',1);

}

function add2cart(id) {
    addToCart(id);
    updateQuantity(id);
}

function removeFromCart(id) {
    if (parseInt(getCookie('shoppingCart['+id+']'))-1>0)
        setCookie('shoppingCart['+id+']',parseInt(getCookie('shoppingCart['+id+']'))-1);
    else
        removeCookie('shoppingCart['+id+']');
    
    updateQuantity(id);
}

function updateQuantity(id) {
    var q=getCookie("shoppingCart["+id+"]");
    if (q=='') q=0;
    $('#'+id+' .quantity').html('['+q+']');
    displayTotal();
    if (q!=0) location.reload();
}

function displayTotal() {
    var total=0;

    $('.product').each(
        function(){
            var b=new RegExp('[^0-9.]','g');
            var price=($(this).find('.price').html()).replace(b,'');
            var quantity=($(this).find('.quantity').html());
            quantity=quantity.substring(1,quantity.length-1);
            total+=parseInt(quantity)*parseFloat(price);
        })
    $('#totalprice').html('$'+total.toFixed(2));
}