//UTF-8 天诺
/**
 * @param {string} name Cookie字段名称
 */
function Trolley(name,domain,exp){
	this.name=name;
	this.max=50;		//cookie容量
	this.state=new ccl.State.Cookie({domain:domain,expires:exp});
	this.event=new ccl.Utility.Event();
	this.event.inject("full","newgood","change","remove","clear");

	var t1=[];		//编号
	var t2=this.state.get(name,[])||[];				//产品对象
	for(var i=0,j=t2.length;i<j;i++)t1.push(t2[i].id);
	this.count=t1.length;
	/**
	 * 将商品放入购物车
	 * @param {object} 商品对象
	 *	{mixed} id	商品唯一编号
	 *	{string} name 商品名称
	 *	{float} price 单价
	 *	{int} amount (optional) 数量默认为1
	 *	{string} thumb (optional) 缩略图
	 *	{string} property (optional) 商品其它属性
	 * @return {boolean}
	 */
	this.put=function(o){
		var i=0;
		if(++this.count>this.max){
			this.count=this.max;
			this.event.trigger("full",o);
			return false
		}
	
		if(o && o.id && (t1.indexOf(o.id)==-1)){
			o.amount=o.amount || 1;
			o.thumb=o.thumb || "";
			o.property=o.property || "";
			t1.push(o.id);
			t2.push(o);
			this.state.set(this.name,t2);
			this.event.trigger("newgood",o)
		}
		return true
	}

	/**
	 * @return {object/null}
	 */
	this.get=function(id){
		if(id){
			var i;
			if((i=t1.indexOf(id))!=-1)return t2[i]
		}
		return null
	}

	this.setAmount=function(id,a){
		if(id && (a=parseInt(a,10))){
			var i=t1.indexOf(id);
			if(i!=-1){
				t2[i].amount=a;
				this.state.set(this.name,t2);
				this.event.trigger("change",t2[i]);
				return true
			}
		}
	}

	this.remove=function(id){
		var i=t1.indexOf(id);
		if(i!=-1){
			t1.splice(i,1);
			var o=t2[i];
			t2.splice(i,1);
			if(t2.length==0){
				this.state.set(this.name,"");
				this.count=0;
			}else{
				this.state.set(this.name,t2);
				this.count--;
			}
			this.event.trigger("remove",o)
		}
	}

	this.clear=function(){
		t1=[];
		t2=[];
		this.count=0;
		this.state.remove(this.name);
		this.event.trigger("clear");
	}

	this.has=function(id){
		return t1.indexOf(id)!=-1
	}

	this.each=function(f,s){
		s=s || window;
		for(var i=0,j=t2.length;i<j;i++)f.call(s,t2[i]);
	}

	this.getTotal=function(){
		var i,j,t,a,price=0;
		for(i=0,j=t2.length;i<j;i++){
			a=parseInt(t2[i].amount,10)||1;
			t=parseFloat(t2[i].price)||0;
			price+=t*a
		}
		return price
	}
}