function GetCookie (name) {
  if(!cookieEnabled())return;
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
  var j = i + alen;
  if (document.cookie.substring(i, j) == arg)
  return getCookieVal (j);
  i = document.cookie.indexOf(" ", i) + 1;
  if (i == 0) break;
  }
  return null;
}

function SetCookie (name, value) {
  if(!cookieEnabled())return;

  var argv = SetCookie.arguments;
  var argc = SetCookie.arguments.length;
  var exp = new Date();
  exp.setTime(exp.getTime()+86400000);
  var expires = '; expires=" + exp.toGMTString())';
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;
  document.cookie = name + "=" + escape (value) +
   '; expires=Mon, 1 Jan 2100 00:00:00 UTC' +
  ((path ==   null) ? "" : ("; path=  " + path)) +
  ((domain == null) ? "" : ("; domain=" + domain)) +
  ((secure == true) ? "; secure" : "");
}

function DeleteCookie (name) {
  var exp = new Date();
  exp.setTime(exp.getTime()-1);
  var cval = GetCookie (name);
  document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

function getCookieVal(offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function cookieEnabled(){
  if(window.navigator.cookieEnabled){
    return true;
  }else{
    alert('您的瀏覽器不支援cookie, 無法使用購物車!!');
    return false;
  }
}
function newCart(){
  this.order=new Array;
  //this.cart=new Array;
  this.ItemCount=0;
  this.getTotalItemCount=function(){
         var totalItemCount=0;
         for(var i in this.order){
           totalItemCount+=this.order[i]['itemcount'];
         }
         return totalItemCount;
       };
  this.getProductTypeCount=function(){
         var productTypeCount=0;
         for(var i in this.order){
           productTypeCount++;
         }
         return productTypeCount;
       };
  this.getTotalPrice=function(){
  	     var is_member=(typeof(memberdata['name'])!=='undefined')?true:false;
         var discount=(is_member)?(memberdata['discount']/100):1;
         //alert('is_member ?'+is_member);
         //alert('discount ?'+discount);
         var totalPrice=0;
         for(var i in this.order){
         	 //alert('hasDiscount?'+this.order[i]['hasDiscount']);
           //totalPrice+=parseInt(this.order[i]['itemprice'])*parseInt(this.order[i]['itemcount']);
           var discountBase=(this.order[i]['hasDiscount']==1)?discount:1;
           //alert(parseInt(this.order[i]['itemprice'])*parseInt(this.order[i]['itemcount'])*discountBase);
           //alert('discountBase='+discountBase+', this item costs:'+parseInt(this.order[i]['itemprice'])*parseInt(this.order[i]['itemcount'])*discountBase);
           totalPrice+=parseInt(this.order[i]['itemprice'])*parseInt(this.order[i]['itemcount'])*discountBase;
         }
         return totalPrice;
       };
  this.getDiscount=function(){
         var is_member=(typeof(memberdata['name'])!=='undefined')?true:false;
         var discount=(is_member)?(memberdata['discount']/100):1;
         return discount;
       };
}

function initCart(){
  //FlushCart();return;
  ShoppingCart=new newCart;
  extractCookieString();
  //updateDiv();
  try{
    pageAction();
  }catch(e){
    alert('cannot excute pageAction!');
  }
}

function updateCart(){
  drawCartForm();
}

function init(){
  if(!cookieEnabled()){
    var data='親愛的客戶, 您好!\n\n我們偵測到您的瀏覽器不支援 cookies, 或是您已將 cookies 關閉\n為了繼續在網路上購物，我們建議您啟動瀏覽器的 cookies\n\n若您使用Internet Explorer 的瀏覽器，請依下列步驟：\n\n按 工具列 \/ Internet選項\n\n選取安全性標籤 \/ 重設為中安全性\n\n';
    alert(data);
  }else{
    setTimeout('initCart()',50);
  }
}
function order_data(item_id,itemID,itemname,itemprice,itemcount,hasDiscount){
  this.item_id=item_id;
  this.itemID=itemID
  this.itemname=itemname;
  this.itemprice=itemprice;
  this.itemcount=itemcount;
  this.hasDiscount=hasDiscount;
}
function Item(item_id, itemID, itemname, price, count, hasDiscount){
  this.item_id=item_id;
  this.itemID=itemID;  
  this.itemname=itemname;
  this.price=price;
  this.count=count;
  this.hasDiscount=hasDiscount;
}

//function Addcart(item_id, itemname, price, count, size, color){
function Addcart(item_id,itemID,itemname,itemprice,itemcount,hasDiscount){
  //alert("item_id="+item_id+",itemID="+itemID+",itemname="+itemname+",itemprice="+itemprice+",itemcount="+itemcount);
  if(!cookieEnabled()){return;}

  //_insertCart(item_id, itemname, price, count, size, color, 0);
  _insert_newOrder(item_id,itemID,itemname,itemprice,itemcount,hasDiscount,0)

  var str=GenerateCookieString();
  //alert(str);
  //return;
  SetCookie('cart',str);
  //self.location.replace('./items.php');
  self.location.replace('./shopdetail.php');
}
function _insert_newOrder(item_id,itemID,itemname,itemprice,itemcount,hasDiscount){
  var found=0;
  //alert('ShoppingCart.getTotalItemCount()='+ShoppingCart.getTotalItemCount());
  var Orders=ShoppingCart.order;
  for(var i in ShoppingCart.order){
    //alert('loop '+i);
    if(Orders[i].item_id==item_id){
      ShoppingCart.order[i].itemcount=parseInt(Orders[i].itemcount)+itemcount;
      found=1;
      break;
    }
  }
  if(!found){
    //alert(ShoppingCart.getTotalItemCount());
    //document.getElementById('aa').innerHTML+='not found, new record<br>';
    //alert("not found, new order");
    ShoppingCart.order[(ShoppingCart.getTotalItemCount()+1)]=new order_data(item_id,itemID,itemname,itemprice,itemcount,hasDiscount);
  }
  //updateDiv();
}

function GenerateCookieString(){
  var cookieString='';
  var cartString='"cart":{';
  //alert(ShoppingCart.getProductTypeCount());
  for(var i in ShoppingCart.order){
    cartString+='"'+i+'":["'+ShoppingCart.order[i].item_id+'","'+ShoppingCart.order[i].itemID+'","'+ShoppingCart.order[i].itemname+'",'+ShoppingCart.order[i].itemprice+','+ShoppingCart.order[i].itemcount+','+ShoppingCart.order[i].hasDiscount+'],';
  }
  cartString=cartString.substring(0,cartString.length-1);
  cartString+='}';
  //cookieString='{'+cartString+',"totalItemCount":'+ShoppingCart.getTotalItemCount()+',"productTypeCount":'+ShoppingCart.getProductTypeCount()+'}';
  cookieString='{'+cartString+',"totalItemCount":'+ShoppingCart.getTotalItemCount()+',"productTypeCount":'+ShoppingCart.getProductTypeCount()+',"discount":'+ShoppingCart.getDiscount()+'}';
  //alert('composed cookieString='+cookieString);
  return cookieString;
}

function extractCookieString(){
  //FlushCart();return;
  //alert('extractCookieString() called.');
  var cartdata=GetCookie('cart');
  //alert(cartdata);
  if(undefined==cartdata){
    return;
  }
  //alert("temp="+cartdata+";");
  eval("temp="+cartdata+";");
  for(var i in temp['cart']){
    //alert('hihi');
    //alert(temp['cart'][i][4]);
     //_insert_newOrder(temp['cart'][i][0],temp['cart'][i][1],temp['cart'][i][2],temp['cart'][i][3],temp['cart'][i][4],temp['cart'][i][5],temp['cart'][i][6],1);
    _insert_newOrder(temp['cart'][i][0],temp['cart'][i][1],temp['cart'][i][2],temp['cart'][i][3],temp['cart'][i][4],temp['cart'][i][5],1);
   //alert('id='+temp['cart'][i][0]+' '+temp['cart'][i][1]+' '+temp['cart'][i][2]+' '+temp['cart'][i][3]+' '+temp['cart'][i][4]+' '+temp['cart'][i][5]+' '+temp['cart'][i][6]);
  }
  //updateDiv();
  return;
}

function drawCartFormSubtotal(){
  var is_member=(typeof(memberdata['name'])!=='undefined')?1:0;
  var discount=(is_member)?(memberdata['discount']/100):1;
  var str='<table class=cartDivForm width="100%" cellspacing=1 cellpadding=5>';
  if(ShoppingCart.getTotalItemCount()>0){
    var temp=ShoppingCart.order;
    var sortedCart=new Array;
    for(var i in temp){
      sortedCart.push(i);
    }
    sortedCart.sort();
    str+='<tr class=cartDivFormTitle><td align=center nowrap>代碼</td><td>商品名稱</td><td align=center>數量</td><td align=right>單價</td><td align=right>金額</td></tr>';
    for(var i in sortedCart){
    	//alert(temp[sortedCart[i]]['hasDiscount']);
      var discountSeed=(temp[sortedCart[i]]['hasDiscount']==1)?discount:1;    	
      str+='<tr class=cartDivFormRow><td align=center>'+temp[sortedCart[i]]['itemID']+'</td><td width="40%">'+temp[sortedCart[i]]['itemname']+'</td><td width="19%" align=center>';
      //alert(temp[sortedCart[i]]['itemID']);
      str+='<input type=hidden name=order['+i+'][itemID] value="'+temp[sortedCart[i]]['itemID']+'">';
      str+='<input type=hidden name=order['+i+'][itemname] value="'+temp[sortedCart[i]]['itemname']+'">';
      str+='<input type=hidden name=order['+i+'][itemprice] value="'+parseInt(temp[sortedCart[i]]['itemprice']*discountSeed)+'">';
      str+='<input type=hidden name=order['+i+'][itemcount] value="'+temp[sortedCart[i]]['itemcount']+'">';
      str+=temp[sortedCart[i]]['itemcount'];
      str+='</td><td width="19%" align=right>'+formatCurrency(temp[sortedCart[i]]['itemprice'])+'</td><td width="19%" align=right>'+formatCurrency(temp[sortedCart[i]]['itemprice']*temp[sortedCart[i]]['itemcount']*discountSeed)+'&nbsp;元</td></tr>';
    }
    if(is_member){
      str+='<tr class=cartFormSubtotal><td colspan=4 class=memberdiscount align=right>會員折扣</td><td colspan=2 class=memberdiscount align=right>'+memberdata['discount']+'&nbsp;折</td></tr>';
    }
    str+='<tr class=cartFormSubtotal><td colspan=4 align=right>小計</td><td colspan=2 align=right>'+formatCurrency(parseInt(ShoppingCart.getTotalPrice()))+'&nbsp;元</td></tr>';
    str+='<tr class=cartFormSubtotal><td colspan=4 class=shippingfee align=right>運費</td><td colspan=2 class=shippingfee align=right>';
    var shippingfee=(ShoppingCart.getTotalPrice()>=2000)?0:150;

    str+='<input type=hidden name=is_member value="'+is_member+'">';
    str+='<input type=hidden name=shippingfee value="'+shippingfee+'">';

    str+=(shippingfee==0)?'免運費':shippingfee+'&nbsp;元';
    str+='</td></tr>';
    str+='<tr class=cartFormSubtotal><td colspan=4 align=right>合計</td><td colspan=2 align=right>'+formatCurrency(ShoppingCart.getTotalPrice()+shippingfee)+'&nbsp;元</td></tr>';
    str+='<input type=hidden name=subtotal value="'+(ShoppingCart.getTotalPrice()+shippingfee)+'">';

    str+='</table>';
    str+='<br><table width=100%>';
    str+='<tr><td align=right><a href="./items.php"><img src="img/continueshop.jpg" width="73" height="24" border="0"></a>&nbsp;<a href="./shopdetail.php"><img src="img/back.jpg" width="73" height="24" border="0"></a></td></tr>';
    str+='</table>';
    document.getElementById('submit').disabled=false;
  }else{
    str+='<tr class=cartDivFormTitle><td colspan=4 align=center><br>目前購物車裡沒有選購商品<br><br></td></tr>';
    str+='</table>';
    setTimeout('hopToItems()',1000);
  }
  document.getElementById('shoppingsummerize').innerHTML=str;
}

function drawCartForm(){
//alert(ShoppingCart.getTotalItemCount());return;
  var is_member=(typeof(memberdata['name'])!=='undefined')?true:false;
  var discount=(is_member)?(memberdata['discount']/100):1;
  //alert(is_member);
  var str='<table class=cartDivForm width="100%" cellspacing=1 cellpadding=5>';
  if(ShoppingCart.getTotalItemCount()>0){
    var temp=ShoppingCart.order;
    var sortedCart=new Array;
    for(var i in temp){
      sortedCart.push(i);
    }
    sortedCart.sort();
    str+='<tr class=cartDivFormTitle><td align=center nowrap>代碼</td><td>商品名稱</td><td align=center>數量</td><td align=right>單價</td><td align=right>金額</td></tr>';
    for(var i in sortedCart){
      var discountSeed=(temp[sortedCart[i]]['hasDiscount']==1)?discount:1;    	
      str+='<tr class=cartDivFormRow><td align=center width="10%">'+temp[sortedCart[i]]['itemID']+'</td><td width="40%" nowrap>'+temp[sortedCart[i]]['itemname']+'</td><td width="10%" align=right nowrap>'
         +'<form style="margin:0;spacing:0;"><input type=hidden name=itemId value="'+sortedCart[i]+'">'
         +'<input type=hidden name=itemID value="'+temp[sortedCart[i]]['itemID']+'">'
         +'<input type=hidden name=itemname value="'+temp[sortedCart[i]]['itemname']+'">'
         +'<select class=cartDivFormRow name=itemCount onChange="updateCount(this);">';
      for(var j=1;j<=10;j++){
        var selectedTag=(j==temp[sortedCart[i]]['itemcount'])?' selected':'';
        str+='<option value="'+j+'"'+selectedTag+'>'+j+'</option>';
      }
      str+='</select>&nbsp;<input style="vertical-align:middle;" class=cartFormColor type=image src="./img/delete.gif" onClick="deleteItem(this);return false;" title="取消購買此產品"></form></td><td width="19%" align=right>'+formatCurrency(temp[sortedCart[i]]['itemprice']*discountSeed)+'&nbsp;元</td><td width="10%" align=right nowrap>'+formatCurrency(temp[sortedCart[i]]['itemprice']*temp[sortedCart[i]]['itemcount']*discountSeed)+'&nbsp;元</td></tr>';

    }
    if(is_member){
      str+='<tr class=cartFormSubtotal><td colspan=4 class=memberdiscount align=right>會員折扣</td><td colspan=2 class=memberdiscount align=right>'+memberdata['discount']+'&nbsp;折</td></tr>';
    }else{
      document.getElementById('tologin').style.display='block';
    }
    str+='<tr class=cartFormSubtotal><td colspan=4 align=right>小計</td><td colspan=2 align=right>'+formatCurrency(parseInt(ShoppingCart.getTotalPrice()))+'&nbsp;元</td></tr>';
    str+='<tr class=cartFormSubtotal><td colspan=4 class=shippingfee align=right>運費</td><td colspan=2 class=shippingfee align=right>';
    var shippingfee=(ShoppingCart.getTotalPrice()>=2000)?0:150;
    str+=(shippingfee==0)?'免運費':shippingfee+'&nbsp;元';
    str+='</td></tr>';
    str+='<tr class=cartFormSubtotal><td colspan=4 align=right>合計</td><td colspan=2 align=right>'+formatCurrency(parseInt(ShoppingCart.getTotalPrice())+shippingfee)+'&nbsp;元</td></tr>';

    str+='</table>';
    str+='<br><table width=100%>';
    str+='<tr><td align=right><a href="#" onClick="doFlush();return false;"><img src="img/deleteall.jpg" width="61" height="24" border="0" /></a>&nbsp;<a href="./items.php"><img src="img/continueshop.jpg" width="73" height="24" border="0" /></a>&nbsp;<a href="./checkout.php"><img src="img/checkout.jpg" width="73" height="24" border="0"></a></td></tr>';
    str+='</table>';
  }else{
    str+='<tr class=cartDivFormTitle><td colspan=4 align=center><br>目前購物車裡沒有選購商品<br><br></td></tr>';
    str+='</table>';
    setTimeout('hopToItems()',1000);
  }
  document.getElementById('cartFormContent').innerHTML=str;
}

function formatCurrency(num) {
  num=num.toString();
  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));
  }
  return (num);
}

function doFlush(){
  if(confirm('您確定要取消您目前所選購的所有商品嗎?')){
    FlushCart();
    hopToItems();
  }
}

function hopToItems(){
  self.location.replace('./items.php');
}

function FlushCart(){
  if(!cookieEnabled()){return;}

  DeleteCookie('cart');
  delete ShoppingCart;
  ShoppingCart=new newCart;
}

function updateCount(obj){
  if(!cookieEnabled()){return;}
  var item_id=obj.form.itemId.value;
  ShoppingCart.order[item_id]['itemcount']=parseInt(obj.options[obj.selectedIndex].value);
  var str=GenerateCookieString();
  SetCookie('cart',str);
  drawCartForm();
}

function deleteItem(obj){
  if (confirm('您確定要刪除此項產品的訂購?\n\n產品代碼 : '+obj.form.itemID.value+'\n\n品名 : '+obj.form.itemname.value)){
    var item_id=obj.form.itemId.value;

    delete ShoppingCart.order[item_id];

   if(ShoppingCart.getTotalItemCount()==0){
     FlushCart();
     updateCart();
     return
   }
   var str=GenerateCookieString();
   SetCookie('cart',str);
   updateCart();
  }
}

function orderItem(obj,token){//從首頁進token為0, 其餘為1
  var itemcount=(token==0)?1:parseInt(obj.form.itemcount.options[obj.form.itemcount.selectedIndex].value);
  var itemprice=parseInt(obj.form.itemprice.value);
  var item_id=obj.form.item_id.value;
  var itemID=obj.form.itemID.value;
  var itemname=obj.form.itemname.value;
  var hasDiscount=obj.form.hasDiscount.value;
  //alert('itemprice='+itemprice+', item_id='+item_id+', itemID='+itemID+', itemname='+itemname);
  try{
    Addcart(item_id,itemID,itemname,itemprice,itemcount,hasDiscount);
  }catch(e){
    setTimeout(function(){
    Addcart(item_id,itemID,itemname,itemprice,itemcount,hasDiscount);
    },40);
  }
  //updateDiv();
}

function updateDiv(){
  var str='';
  str+='Current Order data:';
  str+='<table cellspacing=1 cellpadding=4 border=1>';
  str+='<tr bgcolor=#ffccff><td>i</td><td>item_id</td><td>itemname</td><td>itemprice</td><td>itemcolor</td></tr>';
  var Orders=ShoppingCart.order;
  for(var i in Orders){
    str+='<tr>';
    str+='<td>'+(parseInt(i)+1)+'</td>';
    str+='<td>'+Orders[i].item_id+'</td>';
    str+='<td>'+Orders[i].itemname+'</td>';
    str+='<td>'+Orders[i].itemprice+'</td>';
    str+='<td>'+Orders[i].itemcount+'</td>';
    str+='</tr>';
  }
  str+='</table>';
  str+='<br><br>';
  document.getElementById('aa').innerHTML+=str;
}

//alert('hihihi');
//for(var i in memberdata){
//  alert(i);
//}
//FlushCart();
