/*
NEED Lib:
	JSON
*/
if(typeof lemon == 'undefined')var lemon = {};
if(typeof lemon.cx == 'undefined')lemon.cx = {};
lemon.cx.Item = function(){
	this.oItem={};
}
lemon.cx.Item.prototype={
	add:function(oItem){this.oItem = oItem;},
	modQty:function (Qty){this.oItem.Qty = Qty;},
	modMaxQty:function(Qty){this.oItem.maxQty = Qty;},
	maxQty:function(){return this.oItem.maxQty;},
	get:function(key){
		if(typeof eval('this.oItem.'+key) != 'undefined'){
			return (key=='ShowName')?unescape(eval('this.oItem.'+key)):eval('this.oItem.'+key);
		}else return null;
	},
	set:function(key,val){
		if(key=='ShowName')val=unescape(val)
		eval('this.oItem.'+key)=val;
	},
	getAmount:function(){
		return this.oItem.SellingPrice_All * this.oItem.Qty;
	}
}
/*
   loading==> lemon.cx.ShoppingCart().initialize()==>onSuccess()==>show();
   adding ==> lemon.cx.ShoppingCart().add()==>onSuccess()==>show();
*/
lemon.cx.ShoppingCart=function(auto){
	this.aList=[];
	this.iLength=0;
	this.iAmount=0;
	this.oShowObj=undefined;
	this.act='';
	this.sSessUrl='/json/ShoppingCart/sess_ShoppingCart.php?';
	this.sUrl='';this.active=false;
	this.sProto='http://';
	this.sHost='shop.chinatrust-hotel.com.tw';
	/* default loading not to reload init oAutoCulShipFee object, so set isSentSF to true.*/
	this.isSentSF=true;
	/* setting which function control call back Amount*/
	this.fnCallBackAmount=undefined;
	/*{fee:120,moreAmt:3000,autoCul:false,name:name,CatSn:0,PrdSn:0,SN:0}*/
	this.oAutoCulShipFee={SN:0,autoCul:false};
	if(auto==true)this.initialize();
}
lemon.cx.ShoppingCart.prototype={
	/*auto calculate Shipping Fee*/
	autoCulShipFee:function(o){this.oAutoCulShipFee=o;this.isSendSFInfo(false);},
	isSendSFInfo:function(is){if(is==undefined)return this.isSentSF;else this.isSentSF=is;},
	_getShipFeeUrl:function(){
		var sf='';
		if(!this.isSendSFInfo()){this.isSendSFInfo(true);sf='&sf='+JSON.stringify(this.oAutoCulShipFee);}
		return sf;
	},
	addShippingFee:function(oItem){
		if(this.oAutoCulShipFee!=undefined)
		if( this.getAmount() < this.oAutoCulShipFee.moreAmt){//should add shipping Fee
			this.add(oItem);
		}else{
			this.actBySn('del',oItem.SN);
		}
	},
	removeShippingFee:function(iSN){
		this.autoCulShipFee({SN:0,autoCul:false});
		this.actBySn('del',iSN);
	},
    initialize:function(){
        this.head = document.getElementsByTagName("head")[0];
        this.TRANS_ID=1000;
		this.sel();
    },
	isEmptyCart:function(){return this.iLength>0?false:true;},
	lengthItems:function(){	return this.iLength;},
	setCallBackAmount:function(fn){this.fnCallBackAmount=fn;},
	setProtocalHost:function(sProto,sHost){this.sProto=sProto;this.sHost=sHost;this.sUrl = this.sProto+this.sHost+this.sSessUrl;},
	setShowElement:function(sShowObj){if(document.getElementById(sShowObj))this.oShowObj = document.getElementById(sShowObj);},
	/*
		sPrdSn¬O¦b$_GET¶Ç¿éªº¹Lµ{¤¤¡A¥Î©ó©w¸qPrdSn©Ò¥Îªºkey­È¡C
		¥Î¥H¨ú±o¥Ø«e²{¦b¥¿¦b§e²{ªººô­¶¤¤¡A¬O¨º¤@­Ó²£«~ªº§Ç¸¹¡C
		this.iCurrPrdSn¬O¥Ø«e§e²{ºô­¶ªºProduct Sn¼Æ¦r¡C
	*/
	setShowCurrentPrdSnBy_GET:function(sPrdSn){
		if(location.search.length==0)return;var  as=p=sUrl='',s='';
		p=location.search.split("&");
		for(s in p){if(typeof p[s] == 'string'){as=p[s].split('=');
		if(as[0]=='PrdSn'){this.iCurrPrdSn=Number(as[1]);break;}}}
	},
	/*
	³]©w²£«~¥Ø«e¿ïªº¼Æ¶q©Ò¨Ï¥Îªºª«¥ó¡C
	*/
	setPrdNumSelElement:function(sSel){
		if(typeof sSel=='string'){
			try{
				this.oPrdNumSel = document.getElementById(sSel);
			}catch(e){
				return false;
			}
		}
	},
	/*
	¥Î©óºô­¶onLoad¤§«á¡A³]©w¥Ø«eºô­¶§e²{ªº°Ó«~ªº¿ï¾Ü¼Æ¶q¡C
	*/
	setPrdSelNum:function(){
		if(typeof(this.iCurrPrdSn) == 'number' && typeof(this.oPrdNumSel)=='object'){
			var iQtyNum = undefined;
			for(var i in this.aList)
				if(this.aList[i].get('SN')==this.iCurrPrdSn){
					iQtyNum = this.aList[i].get('Qty');break;
				}
			this.oPrdNumSel.selectedIndex = iQtyNum;
		}else{
			return undefined;
		}
	},
	setShopCartListElement:function(o){	this.oCartListObj = o;},
	/*
		µ²±b®ÉªºÁÊª«¨®¡A¥²»Ý­n³]©wÁ`­pªºÄæ¦ìId¦WºÙ¡A¤~¥i¥H¦Û°Ê­pºâ²{¦³Á`»ù¡C
	*/
	setCartListAmountElement:function(sAmountObj){
		if(typeof(document.getElementById(sAmountObj))=='object')
		this.oAmountObj = document.getElementById(sAmountObj);
	},
	onSuccess:function(a){
		this.iLength=0;
		this.aList=new Array();
		for(var i in a){
			//alert(unescape(o.aList[i].ShowName)+'/'+i+'/'+typeof(o.aList[i]));
			if(a[i].Qty>0){
			this.aList[this.iLength] = new lemon.cx.Item();
			this.aList[this.iLength].add(a[i]);
			++this.iLength;}
		}
		this.show();
		switch(this.act){
			case 'remv':
			case 'sel':
			if(typeof this.oCartListObj == 'object')
				this.showCartListAtPage(this.oCartListObj);
				this.setPrdSelNum();
			break;
			case 'add':
			case 'del':
			case 'mQty':
				//alert(this.act);
				aniShopList("open");
				this.showCartListAtPage(this.oCartListObj,this.act);
				this.setPrdSelNum();
				if(this.fnCallBackAmount!=undefined)this.fnCallBackAmount(this);
			break;
		}
		this.active=true;
		return true;
	},
	onFail:function(){alert('Shopping Cart Connection fail..');return false;},
	sel:function(){
		this.act='sel';
		this.loadUrl(this.sUrl,'act=sel'+this._getShipFeeUrl(),this,function(o){this.onSuccess(o);},function(){this.onFail();});
	},
	add:function(oItem){
		if(!this.active)return;
		//alert(oItem.ShowName);
		if(oItem.Qty>0){
			var iNo = undefined;
			for(var i in this.aList){
				if(typeof(this.aList[i])!='object')continue;
				//alert(this.aList[i].get('SN')+'/'+oItem.SN);
				if(this.aList[i].get('SN')==oItem.SN){iNo = i;break;}
			}
			if(iNo==undefined){
				this.act='add';
				this.loadUrl(this.sUrl,'act=add&Item='+JSON.stringify(oItem)+this._getShipFeeUrl(),this,function(o){this.onSuccess(o);},function(){this.onFail();});
			}else{
				this.modQty(iNo,oItem.Qty,oItem.maxQty);
			}
		}
	},
	actBySn:function(act,iSN){
		if(!this.active)return;
		for(var i in this.aList){
				if(typeof(this.aList[i])!='object')continue;
				if(this.aList[i].get('SN')==iSN){
					switch(act){
						case 'del':this.del(i);break;
					}
				}
					
		}
	},
	del:function(iNo){
		if(!this.active)return;
		if(this.aList[iNo]!=undefined){
			var SN = this.aList[iNo].get('SN');
			this.aList[iNo] = undefined;
			--this.iLength;
			this.act='del';
			this.loadUrl(this.sUrl,'act=del&SN='+SN+this._getShipFeeUrl(),this,function(o){this.onSuccess(o);},function(){this.onFail();});
		}
	},
	modQty:function(iNo,Qty,maxQty){
		if(!this.active)return;
		if(this.aList[iNo]!=undefined){
			var SN = this.aList[iNo].get('SN');
			this.aList[iNo].modQty(Qty);
			this.aList[iNo].modMaxQty(maxQty);
			this.act='mQty';
			this.loadUrl(this.sUrl,'act=mQty&SN='+SN+'&Qty='+Qty+'&maxQty='+maxQty+this._getShipFeeUrl(),this,function(o){this.onSuccess(o);},function(){this.onFail();});
		}
	},
	destroy:function(){
		this.aList.length = 0;
		this.iLength =this.iAmount= 0;
		this.act='remv';
		this.loadUrl(this.sUrl,'act=remv',this,function(o){this.onSuccess(o);},function(){this.onFail();});
	},
    loadUrl : function(url, params, caller,onComplete, onFailure){
       //transId=++ScriptTagProxy.TRANS_ID;
       transId = ++this.TRANS_ID;
        var trans ={
          id : transId,
          cb : "stcCallback"+transId,
          scriptId : "stcScript"+transId,
          url : url,
          params : params,
          caller : caller,
          onComplete : onComplete,
          onFailure :onFailure
        };
		var conn = this;
		window[trans.cb] = function(o){conn.handleResponse(o, trans);};
        params='callback='+trans.cb+'&'+params+'&ti='+new Date();
		//alert(url+'/'+params);
        var script = document.createElement("script");
        script.setAttribute("src", url+params);
        script.setAttribute("type", "text/javascript");
        script.setAttribute("id", trans.scriptId);
        //this.trans.timeoutId=setTimeout(this.handleFailure(trans), 10000);
        try{this.head.appendChild(script);}
		catch(e){setTimeout(this.head.appendChild(script), 10000);}
		//alert(script.id+'/'+trans.scriptId+'/'+transId+'/'+this.head.innerHTML);
	},
	handleResponse : function(o, trans){
		this.destroyTrans(trans, true);
		trans.onComplete.call(trans.caller||window, o);
	},
	handleFailure : function(trans){
		 this.destroyTrans(trans, false);
		 if(trans.onFailure){
			 trans.onFailure.call(trans.caller||window, null);
		 }else{alert('Load Timeout');}
	},
	destroyTrans : function(trans, isLoaded){
		//alert(trans.scriptId+'/'+document.getElementById(trans.scriptId));
		this.head.removeChild(document.getElementById(trans.scriptId));
		clearTimeout(trans.timeoutId);
		if(isLoaded){
			window[trans.cb] = undefined;
			try{delete window[trans.cb];}catch(e){}
		}else{
			window[trans.cb] = function(){
			  window[trans.cb] = undefined;
			  try{delete window[trans.cb];}catch(e){}
			};
		}
	},
	/*
	 Show Shopping Cart List in Element which you can define it.
	*/
	show:function(){
		this.oShowObj.innerHTML = '';
		for(var ino in this.aList){
			if(typeof(this.aList[ino])!='object' || this.aList[ino]==undefined)continue;
			var oItemDiv = document.createElement("div");
			if(this.aList[ino].get('PicSn')>0)
			oItemDiv.style.backgroundImage ='url('+this.sProto+this.sHost+'/tools/getPic/album.php?W=40&H=40&SN='+this.aList[ino].get('PicSn')+')';
			//var oSIcon = document.createElement('img');
			//with(oSIcon){src="tools/getPic/album.php?W=40&H=40&SN="+this.aList[ino].get('PicSn');}
			//oItemDiv.appendChild(oSIcon);
			/* ============= Del ================*/
			var oItemBtn = document.createElement("a");
			oItemBtn.ele = this.oShowObj;
			oItemBtn.href= '#';
			oItemBtn.iNo = ino;
			oItemBtn.parentObj = this;
			oItemBtn.innerHTML = 'åˆªé™¤';
			oItemBtn.onclick=function(){
				this.parentObj.del(this.iNo);
				this.parentObj.show(this.ele);
			}
			var oItemTitle = document.createElement("h3");
			oItemTitle.innerHTML = '<a href="?CatSn='+this.aList[ino].get('CatSn')+'&PrdSn='+this.aList[ino].get('SN')+'">'+this.aList[ino].get('ShowName')+'</a>';
			/* ============= Qty select ================*/
			var oItemSelect = document.createElement("select");
			oItemSelect.iNo=ino;
			oItemSelect.parentObj = this;
			oItemSelect.SellingPrice_All=this.aList[ino].get('SellingPrice_All');
			oItemSelect.onchange=function(){
				document.getElementById('CartItem_'+this.iNo).innerHTML = ' X '+twMoney(this.SellingPrice_All)+' = '+twMoney(this.SellingPrice_All*this.options[this.selectedIndex].value);
				this.parentObj.modQty(this.iNo,this.options[this.selectedIndex].value,this.options.length);
			}
			for(var i=1;i<=this.aList[ino].maxQty();i++){
				var oItemSelOption = document.createElement("option");
				oItemSelOption.text = oItemSelOption.value = i;
				try{oItemSelect.add(oItemSelOption,null);}
				catch(ex){oItemSelect.add(oItemSelOption);}
				if(i==this.aList[ino].get('Qty')){
					oItemSelOption.selected = true;
				}
			}
			/* ============= Sub Total ================*/
			var oItemSpan = document.createElement("span");
			oItemSpan.id='CartItem_'+ino;
			oItemSpan.innerHTML= ' X '+twMoney(this.aList[ino].get('SellingPrice_All'))+' = '+twMoney(this.aList[ino].getAmount());
			/* ============= Img ================*/
			var oItemDetail = document.createElement("p");
			oItemDetail.appendChild(oItemSelect);
			oItemDetail.appendChild(oItemSpan);
			if(!this.aList[ino].get("NoDel"))
			oItemDetail.appendChild(oItemBtn);
			oItemDiv.appendChild(oItemTitle);
			oItemDiv.appendChild(oItemDetail);
			//this.oShowObj.appendChild(oItemImg);
			this.oShowObj.appendChild(oItemDiv);
		}
	},
	showCartListAtPage:function(o,act){
		//alert(o+'/');
		/**/
		if(o!=null && typeof(o)=='object'){
			//if(act=='mQty')return;
		if(o.rows!=undefined && o.rows.length>0){
			var itotal = o.rows.length;
			for(var ii=0;ii<itotal;ii++){
				o.deleteRow(0);
			}
		}
		var str = '',i=0,iAmount=0;
		for(var ino in this.aList){
		if(typeof(this.aList[ino])!='object' )continue;
			/*str += '<tr>';
			str += '<td><img src="tools/getPic/album.php?W=40&H=40&SN='+this.aList[ino].get('PicSn')+'" /><a href="?CatSn='+this.aList[ino].get('CatSn')+'&PrdSn='+this.aList[ino].get('SN')+'">'+this.aList[ino].get('ShowName')+'</a></td>';
			str += '<td>'+this.aList[ino].get('ListPrice')+'</td>';
			str += '<td>'+this.aList[ino].get('SellingPrice_All')+'</td>';
			str += '<td>'+this.aList[ino].get('ShowName')+'</td>';
			str += '<td>'+this.aList[ino].get('ShowName')+'</td>';
			str += '<td>'+this.aList[ino].get('ShowName')+'</td>';
			str += '</tr>';
			*/
			var oTR = document.createElement('tr');
			oTR.className = 'tr'+(++i%2);
			var oTD0 = document.createElement('td');
			oTD0.className = 'ItemName';
			if(this.aList[ino].get('SN')>0)
			oTD0.innerHTML = '<img src="tools/getPic/album.php?W=40&H=40&SN='+this.aList[ino].get('PicSn')+'" />';
			oTD0.innerHTML += '<a href="?CatSn='+this.aList[ino].get('CatSn')+'&PrdSn='+this.aList[ino].get('SN')+'">'+this.aList[ino].get('ShowName')+'</a>';
			oTR.appendChild(oTD0);
			var oTD1 = document.createElement('td');
			oTD1.innerHTML = twMoney(this.aList[ino].get('SellingPrice_All'));
			oTR.appendChild(oTD1);
			var oTD2 = document.createElement('td');
			oTD2.innerHTML = twMoney(this.aList[ino].get('SellingPrice_All'));
			oTR.appendChild(oTD2);
			var oTD3 = document.createElement('td');
				/* ============= Qty select ================*/
				var oItemSelect = document.createElement("select");
				oItemSelect.iNo=ino;
				oItemSelect.parentObj = this;
				oItemSelect.SellingPrice_All=this.aList[ino].get('SellingPrice_All');
				oItemSelect.onchange=function(){
					document.getElementById('CartListId_'+this.iNo).innerHTML = twMoney(this.SellingPrice_All*this.options[this.selectedIndex].value);
					this.parentObj.modQty(this.iNo,this.options[this.selectedIndex].value,this.options.length);
					this.parentObj.countCartListAmount();
				}
				for(var i=1;i<=this.aList[ino].maxQty();i++){
					var oItemSelOption = document.createElement("option");
					oItemSelOption.text = oItemSelOption.value = i;
					try{oItemSelect.add(oItemSelOption,null);}
					catch(ex){oItemSelect.add(oItemSelOption);}
					if(i==this.aList[ino].get('Qty')){
						oItemSelOption.selected = true;
					}
				}
				/* ============= Qty select ================*/
			oTD3.appendChild(oItemSelect);
			oTR.appendChild(oTD3);
			var oTD4 = document.createElement('td');
			oTD4.id='CartListId_'+ino;
			oTD4.innerHTML = twMoney(this.aList[ino].get('SellingPrice_All')*this.aList[ino].get('Qty'));
			oTR.appendChild(oTD4);
			var oTD5 = document.createElement('td');
			oTD5.className = 'ItemDel';
			if(this.aList[ino].get('SN')>0){
				/* ============= Del ================*/
				var oItemBtn = document.createElement("button");
				oItemBtn.ele = this.oShowObj;
				//oItemBtn.href= '#';
				oItemBtn.iNo = ino;
				oItemBtn.parentObj = this;
				oItemBtn.innerHTML = 'åˆªé™¤';
				oItemBtn.onclick=function(){
					this.parentObj.del(this.iNo);
					this.parentObj.show(this.ele);
				}
				/* ============= Del ================*/
				oTD5.appendChild(oItemBtn);
			}
			oTR.appendChild(oTD5);
		o.appendChild(oTR);
		}
		this.countCartListAmount();
		//alert(str);
		/**/
		}
	},
	countCartListAmount:function(){
		if(this.oAmountObj==undefined)return;
		this.iAmount=0;
		for(var ino in  this.aList){
		if(typeof(this.aList[ino])!='object')continue;
			this.iAmount+=this.aList[ino].get('SellingPrice_All')*this.aList[ino].get('Qty');
		}
		this.oAmountObj.value=twMoney(this.iAmount);
	},
	getAmount:function(){return this.iAmount;	}
}
function twMoney(v){
	v = (Math.round((v-0)*100))/100;
	v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
	v = String(v);
	var ps = v.split('.');
	var whole = ps[0];
	var r = /(\d+)(\d{3})/;
	while (r.test(whole)) {whole = whole.replace(r, '$1' + ',' + '$2');}
	v = whole;
	if(v.charAt(0) == '-'){return '-$' + v.substr(1);}
	return "$" +  v;
};
