/*
请保留此信息，不会影响程序的执行。试用于ff2.0和ie6，其他浏览器没测试。
            --2008-4-16,ShowBo
*/
//扩展string原型
String.prototype.trim=function(reg){  if(reg) return this.replace(reg,""); else return this.replace(/^\s*|\s*$/g,"");}
function regInput(obj, reg, inputStr)
	{
		var docSel	= document.selection.createRange()
		if (docSel.parentElement().tagName != "INPUT")	return false
		oSel = docSel.duplicate()
		oSel.text = ""
		var srcRange	= obj.createTextRange()
		oSel.setEndPoint("StartToStart", srcRange)
		var str = oSel.text + inputStr + srcRange.text.substr(oSel.text.length)
		return reg.test(str)
	}
function Product(CookieName)
{
  this.Product=new Array();  
  this.Init=function()
  {
    //生成数组
    var match=document.cookie.match(new RegExp(CookieName+"=([^;]+);?","i"));
    var cookieStr=match?match[1]:"";
    if(cookieStr.trim()!="")
    {
      var ps=cookieStr.split("|");
      var p;
      for(var i=0;i<ps.length;i++)
      {
         p=ps[i].split(",");
         this.Product.push(this.createObj(p[0],unescape(p[1]),parseFloat(p[2]),parseInt(p[3],10)));
      }
    }
  }
  //重写toString方法
  this.toString=function()
  {
     var Str="",o;
     for(var i=0;i<this.Product.length;i++)
     {
       o=this.Product[i];
       Str+=o.id+","+escape(o.name)+","+o.price+","+o.count+"|";
     }
     return Str.trim(/\|$/);
  }
  //产品对象
  this.createObj=function(id,name,price,count)
  {
     var o=new Object();
     o.id=id;
     o.name=name;
     o.price=price;
     o.count=count;
     return o;
  }
}
function Car(CookieName,txtTotalMoney)
{
   this.expires=7;//存活期限7天
   this.Product=new Product(CookieName);//产品对象
   this.Product.Init();//初始化
   this.RefreshCar=function()
   {
     this.Product=new Product(CookieName);
     this.Product.Init();
   }
   this.Add=function(id,name,price,count)
   {    
      if(!id||!name||!price||isNaN(price))
      {
        alert('参数不正确！');
        return;
        }
      if(!count||isNaN(count)||parseInt(count,10)<1)count=1;else count=parseInt(count,10);
      var o=this.FindProductObj(id.trim());
      if(o)//存在这个id物品，则在原来基础上加1
      {
         o.count=o.count+count;
         alert('已经更新购物车,当前物品数量为'+o.count+'！');
      }
      else
      {
        this.Product.Product.push(this.Product.createObj(id,name,price,count));//添加新产品
        alert('已经放入购物车！');
      }
      this.Save();//保存cookie
   }
   this.UpdateProduct=function(id,NowObj,Final)//Final参数指定是否输出“更新成功”提示
   {
     var tr=NowObj.tagName=="A"?NowObj.parentNode.parentNode:NowObj;
     var countTxt=tr.cells[2].getElementsByTagName("input")[0];
     if(!countTxt){alert('找不到数量输入框！');return;}
     if(countTxt.value.trim()==""||isNaN(countTxt.value))
     {
       alert('数量不正确，为整数！');
       countTxt.select();
       return;
     }  
     if(parseInt(countTxt.value,10)<1)
     {
         this.DeleteProduct(id,NowObj,'数量小于0时将删除这个物品，确定删除？！');
         return;
     }
     var count=countTxt.value;
     var o=this.FindProductObj(id);
     if(!o){alert('产品不存在，请确认！');return false;}
     if(!count||isNaN(count)||parseInt(count,10)<1) count=1;else count=parseInt(count,10);
     var tm=parseFloat($(txtTotalMoney).value)+(count-o.count)*o.price;
     o.count=count;
	 var itemPrice=tr.cells[3].getElementsByTagName("input")[0];
	 itemPrice.value = o.count*o.price;
     this.Save();//保存cookie
     $(txtTotalMoney).value=tm;//更新总价钱
     if(Final==false) alert('更新成功！');
   }
   this.DeleteProduct=function(id,NowObj,Msg)
   {
     if(confirm(Msg?Msg:'确认删除？！'))
     {
       var Index=this.FindProductObj(id,true);//注意是获取索引位置，而且要注意返回null，要不删除第1个物品时index为0，!0在js中是true
       if(Index==null){alert('产品不存在，请确认！');return false;}
       var o=this.Product.Product[Index];//得到原来的对象
       //计算剩下的总价钱
       var tm=parseFloat($(txtTotalMoney).value)-o.price*o.count;
       this.Product.Product.splice(Index,1); //从数组中删除该物品      
       this.Save();//保存cookie
       var tr=NowObj.tagName=="A"?NowObj.parentNode.parentNode:NowObj;//注意这里判断是否是结帐时传递来的行或者是删除/修改时传递来的连接对象      
       tr.parentNode.removeChild(tr);
       $(txtTotalMoney).value=tm;//更新总价钱
	   $("all").innerHTML = tm;
       if(!Msg) alert('删除成功！');
       return true;       
     }
     else
       return false;
   }
   this.Save=function()
   {      
      var d=new Date();
      d.setDate(d.getDate()+this.expires);
      document.cookie=CookieName+"="+this.Product.toString()+";expires="+d.toGMTString();
   }
   this.FindProductObj=function(id,NeedIndex)
   {
      var o;
      for(var i=0;i<this.Product.Product.length;i++)
      {
         o=this.Product.Product[i];
         if(o.id==id)
         {
           if(NeedIndex)//需要索引位置
              return i;
           return o;
         }
      }
      return null;
   }
   this.Read=function()
   {
      var Str="";
      if(this.Product.Product.length==0)
      {
         Str="<tr><td colspan='5' align='center'><font color='red'>没有记录！</font></td></tr>";
      }
      else
      {
        var o,tm=0;      
        for(var i=0;i<this.Product.Product.length;i++)
        {
           o=this.Product.Product[i];
        Str+="<tr bgcolor='#999999'><td align='center' valign='middle'>"+o.name+"<input type='hidden' name='goodsid' value='"+o.id+"'/></td>"
			+"<td align='center' valign='middle'>"+o.price+"</td>"
			+"<td align='center' valign='middle'><input type='text' name='gcount' value='"+o.count+"' style='width:40px' onKeyPress	= \"return regInput(this,	/^[0-9]*$/,		String.fromCharCode(event.keyCode))\""
            +"     onpaste		= \"return regInput(this,	/^[0-9]*$/,		window.clipboardData.getData('text'))\""
            +"     ondrop		= \"return regInput(this,	/^[0-9]*$/,		event.dataTransfer.getData('text'))\"/></td>"       
            +"<td align=\"center\" valign=\"middle\" ><input type='text' name='gprice' value='"+o.count*o.price+"' readonly='readonly' style='width:100%' class='underline'></td>"
			+"<td align='center' valign='middle'><a href='#' id='link"+o.id+"' onclick=\"CarObj.UpdateProduct('"+o.id+"',this,false);getSum();return false;\">更新</a> <a href='#' onclick=\"CarObj.DeleteProduct('"+o.id+"',this);getSum();return false;\"><img src='images/trash.gif'  border='0' width='15' height='17'></a></font></td></tr>";
           tm+=o.price*o.count;
        }
        $(txtTotalMoney).value=tm;       
      }
      return Str;
   }
   this.CheckOut=function(NowObj,Url)
   {
      //alert('正在更新购物车！');
      //               td         tr         tfoot      table               tbody

      //var tbody=NowObj.parentNode.parentNode.parentNode.parentNode.getElementsByTagName("tbody")[0];
	  var tbody = document.getElementById("trs");
      var txtCount;
      for(var i=0;i<tbody.rows.length;/*i++*/)//注意不要在这里控制循环变量，要不有小于1的数量时删除不全
      {
		if(tbody.rows[0].cells.length<2)
		{
			alert('您还没有选择任何物品！');
			return;
		 }
        txtCount=tbody.rows[i].cells[2].getElementsByTagName("input")[0];
		
        if(txtCount.value.trim()==''||isNaN(txtCount.value))
        {
           alert('输入的数量不正确，请检查后在结帐！');
           txtCount.select();
           return ;
        }
        if(parseInt(txtCount.value,10)<1)
        {
           if(!this.DeleteProduct(tbody.rows[i].cells[0].getElementsByTagName("input")[0].value,tbody.rows[i],'有数量小于0的物品，您是要删除该物品？！'))
           {
             txtCount.select();
             return;
           }           
        }
        else
        {
          this.UpdateProduct(tbody.rows[i].cells[0].getElementsByTagName("input")[0].value,tbody.rows[i],true);//更新这个物品的数量
          i++;
        }
      }
      if(confirm('您确定要提交订单？'))
      {
        if(CarObj.Product.Product.length>0)
		  {
			if(self.opener==null)
			  {
				top.location=Url;
			  }
			 else
			  {
				self.opener.top.location=Url;
				window.close();
			  }
		  }
        else
          alert('没有物品！');
      }
   }
}



//参数名称为cookie的名称和接收总价钱的控件的id 
var CarObj=new Car('ProductList','TotalMoney');