var Cart={
	bindView:function(el){
		var topbarWrap = el.getParent().getParent();
		new QMenu(el,new Element('div',{'class':'fmenu','style':'text-align:left;top:20;right:0;width:100px;display:none;height:100px;'}).inject(topbarWrap)).addEvent('firstshow',function(e){
			new Ajax(Shop.url.viewcart,{update:e.target,onSuccess:function(){
				this.setStyles({'width':null,'height':null});
			}.bind(e.target)}).request();
		}.bind(this));
	},
	_update:function(gid,opt){
		try{
			var oStr = Cookie.get('S[CART]');
			if(oStr){
				var oLs = oStr.split('-');
				var t = false;
				for(var i=0;i<oLs.length;i++){
					var v = oLs[i].split('_');
					if(v[0]==gid){
						if(!v[1])v[1]=1;
						oLs[i] = gid+'_'+(Number(v[1])+1);
						t = true;
						break;
					}
				}
				if(!t){
					oLs.push(gid);
				}
			}else{
				var oLs = [gid];
			}
			Cookie.set('S[CART]',oLs.join('-'));
		}catch(e){throw e}
	},
	countItem:function(item,obj){
		if(item.getAttribute('price'))
			$E('.itemTotal',obj).innerHTML = Cart.moneyFormat(item.getAttribute('price').toFloat() * $E('input[name^=cartNum[]',obj).value);
		if(item.getAttribute('point'))
			$E('.itemTotal',obj).innerHTML = item.getAttribute('point').toFloat() * $E('input[name^=cartNum[]',obj).value;
	},
	update:function(URL,num,rowObj,numObj,butObj){
       if(this.updateRequest&&this.updateRequest.cancel)
       this.updateRequest.cancel();
	   this.updateRequest=new Request({method:'post',
                         data:$('form-cart'),
                         onRequest:function(){
                         var fc=$('fix-CartBtn')||new Element('div',{'id':'fix-CartBtn'})
                         .inject(document.body).setStyles({
                             'position':'absolute',
                             'background':'#ffffff',
                             'visibility':'hidden',
                             'zIndex':2000,
                             'opacity':.3
                         });
                          fc.setStyles($E('.CartBtn','form-cart').getCis()).setStyle('visibility','visible');
                         },
                         onSuccess:function(a){
								window.location = "?cart.html";
    							if(a.contains('totalprice')){
    								rowObj.setProperty('number',numObj.value);
    								$('cartTotal').setHTML(a);
    								Cart.countItem(butObj,rowObj);
    							}else{
    								numObj.value = rowObj.getProperty('number');
    								//new Dialog(new Element('div').setText(a),{title:'Updating failed!'}); //翻译 更新失败
    								MessageBox.error(a);
    							}
                              $('fix-CartBtn').setStyle('visibility','hidden');  
    						}
						}).send({url:URL});
	},
	inputUpdate:function(e){
		e=new Event(e);
		var ipt = $(e.target);
		for(obj=ipt.getParent(); !obj.getAttribute('urlupdate'); obj=obj.getParent()){;}
		if(obj.getProperty('number').toInt() > ipt.value){
			ipt.value = ipt.value.toInt() + 1;
			var butObj = $E('.decrease',obj);
		}else{
			ipt.value = ipt.value.toInt() - 1;
			var butObj = $E('.increase',obj);
		}
		e.target = butObj;
		butObj.fireEvent('click', e);
	},
	load:function(){
		Cart.els = $E('.CartInfoWrap');
		if(Cart.els.length>0){
			//Cart.update = Cart.update;
			if(Cookie.get("S[CART]")&&Cookie.get("S[CART]").length>0){
				var a = new Ajax(Shop.url.viewcart, {method: 'get'});
				a.addEvent('onComplete',Cart.updateView);
				a.request();
			}else{
				for(var i=0;i<Cart.els.length;i++){
					Cart.els[i].style.visibility='';
				}
			}
		}
	},
	add:function(e){
		new Event(e).stop().target;
		var p = this.getAttribute('buy');
		if(p){
			var o = Cart.els.length>0?Cart.els[0]:$E('.s-menu-cart');
			if(o){
				new Event(e).stop();
				var a= new Ajax(Shop.url.addcart,{method:'post',data:'gid='+p});
				if(Cart.els)a.addEvent('onComplete',Cart.updateView);
				a.request();
			}
		}
	},
	updateView:function(c){
		for(var i=0;i<Cart.els.length;i++){
			Cart.els[i].innerHTML=c;
			Cart.els[i].style.visibility='';
		}
	},
	selectbuy:function(key){
		new Ajax(key,{method:'post'}).request();
		alert('Adding to shopping cart succeeded!');  //翻译：加入购物车成功！
	},
	shipping_id:0,
	d_pay:0,
	is_protect:'false',
	payment:0,
	checkout:{
		shipping:function(o){
			if(o&&o.value){
               new Request.HTML({url:Shop.url.shipping,update:'shipping',onRequest:function(){
                  $('shipping').set('text','loading...');
               }}).post({area:o.value});
			}
		},
		setShipping:function(o,t){
			if(o.id){
				var strid = o.id, ss;
				ss = strid.split('_');
				var oInput = $('shipping').getElementsByTagName('INPUT');
				for(var i=0; i<oInput.length; i++){
					if(ss[0] == 'shipping'){
						if(oInput[i].id != 'protect_'+ss[1] && oInput[i].id != strid){
							oInput[i].checked = false;
						}
						if(oInput[i].id == 'protect_'+ss[1]){
						    if(Cart.is_protect == 'true')
            					oInput[i].checked = true;
            				else
            					oInput[i].checked = false;
						}
					}else{
						if(o.checked){
							if(oInput[i].id != 'protect_'+ss[1]){
								oInput[i].checked = false;
							}
							if(oInput[i].id == 'shipping_'+ss[1]){
								oInput[i].checked = true;
								Cart.shipping_id = oInput[i].value;
							}
						}
					}
				}
			}
			if(t == 1){
				if(o.checked == true)
					Cart.is_protect = 'true';
				else
					Cart.is_protect = 'false';
			}else{
				Cart.shipping_id = o.value;
			}
			if($('shipping_'+Cart.shipping_id).getAttribute('has_cod') == 1){
				$('_pay_cod').style.display = '';
				Cart.d_pay = 1;
			}else{
				$('_pay_cod').style.display = 'none';
				if( $('_pay_cod').getElement('#payment_bank').checked == true ){
					$('_pay_cod').getElement('#payment_bank').checked = false;
				}
				Cart.d_pay = 0;
			}

			Cart.checkout.total();
			return;
		},
		setCurrency:function(o){
			if(o.value){
				new Ajax(Shop.url.payment,{method:'post',onComplete:function(){
						if($('shipping_'+Cart.shipping_id).getAttribute('has_cod') == 1){
							$('_pay_cod').style.display = '';
						}
					},update:'payment',data:'cur='+o.options[o.selectedIndex].value+'&d_pay='+Cart.d_pay+'&payment='+Cart.payment
					,onComplete:function(a,b,c){
						$ES('input.x-payMethod','payment').addEvent('click',Cart.checkout.setPayment);
					}.bind(this)}
					).request();
			}
			Cart.payment = 0;
			return;
		},
		setPayment:function(o,b){
			Cart.payment = new Event(o).target.value;
			Cart.checkout.total();
		},
		total:function(){
			if($('is_tax') && $('is_tax').checked == true){
				var is_tax = 'true';
			}else{
				var is_tax = 'false';
			}
			var data = 'shipping_id='+Cart.shipping_id
					+'&is_protect='+Cart.is_protect
					+'&payment='+Cart.payment
					+'&cur='+$('payment-cur').getValue()
					+'&is_tax='+is_tax;
			if($E('input[name^=delivery[ship_area]')){
				data+='&area='+$E('input[name^=delivery[ship_area]').getValue()
			}
			new Ajax(Shop.url.total,{
				method:'post',
				update:$('amountInfo'),
				'data':data,onComplete:function(a,b,c){
					if(window.ie){
						$('amountInfo').setHTML(a);
					}
					}
			}).request();
		}
	},
	dlgHandler:{},
	getReceiverList:function(e){
		e=new Event(e).stop();
		
		Cart.dlgHandler = new Dialog(e.target.href,{title:'Please choose receiving address!'});  //翻译：选取收获地址
	},
	checkAddr:function(e){
		e=new Event(e).stop();
		var oInput = $('addrList').getElementsByTagName('INPUT');
		for(var i=0; i<oInput.length; i++){
			if(oInput[i].checked) break;
		}
		if(!!!oInput[i])return alert('Please choose receiving address!'); //翻译：选取收获地址
		var tdObj = oInput[i].parentNode.parentNode;
		var tdElement = tdObj.getElementsByTagName('TD');
		for(var i=0; i<tdElement.length; i++){
			if(tdElement[i].className){
				if($(tdElement[i].className))
				$(tdElement[i].className).value = tdElement[i].innerHTML;
			}
		}
		Cart.dlgHandler.close();
	},
	moneyFormat:function(num){
		num = num.toFloat();
		num = num.round(moneyFormat.decimals)+'';
		var p =num.indexOf('.');
		if(p<0){
			p = num.length;
			part = '';
		}else{
			part = num.substr(p+1);
		}
			while(part.length<moneyFormat.decimals){
				part+='0';
			}
		var c=[];
		while(p>0){
			if(p>2){
				c.unshift(num.substr(p-=3,3));
			}else{
				c.unshift(num.substr(0,p));
				break;
			}
		}
		return moneyFormat.sign+c.join(moneyFormat.thousands_sep)+moneyFormat.dec_point+part;
	}
}

if($('form-cart')){
    $ES('.increase','form-cart').each(function(item){
        item.addEvent('click',function(e){
            e=new Event(e).stop();
            var ipt=e.target;
            for(obj=ipt.getParent(); !obj.getAttribute('urlupdate'); obj=obj.getParent()){;}
            $E('input[name^=cartNum[]',obj).value = $E('input[name^=cartNum[]',obj).value.toInt() + 1;
            Cart.update(obj.getAttribute('urlupdate'),null,obj,$E('input[name^=cartNum[]',obj),ipt);
        });
    });
    $ES('.decrease','form-cart').each(function(item){
        item.addEvent('click',function(e){
            e=new Event(e).stop();
            var ipt=e.target;
            for(obj=ipt.getParent(); !obj.getAttribute('urlupdate'); obj=obj.getParent()){;}
            if($E('input[name^=cartNum[]',obj).value.toInt() > 1){
                $E('input[name^=cartNum[]',obj).value = $E('input[name^=cartNum[]',obj).value.toInt() - 1;
              Cart.update(obj.getAttribute('urlupdate'),null,obj,$E('input[name^=cartNum[]',obj),ipt);
            }
        });
    });


    $ES('.quiet','form-cart').each(function(item){
        item.addEvent('click',function(e){
            e=new Event(e).stop();
            var ipt=e.target;
            for(obj=ipt.getParent(); !obj.getAttribute('urlremove'); obj=obj.getParent()){;}
            var url = obj.getAttribute('urlremove');
            obj.remove();
            new Ajax(url,{method:'post',update:'cartTotal',data:$('form-cart')}).request();
        });
    });
}
if($('clearCart')){
	$('clearCart').addEvent('click',function(e){

		e=new Event(e).stop();
        if(window.confirm('Are you sure to empty the shopping cart?')){   //翻译：确定要清空吗?
            var ipt=e.target;
            var url = ipt.getAttribute('url');
            $('cartItems').remove();
            new Ajax(url,{method:'post',data:'a=a',onComplete:function(a){
                                $('cart-items').remove();
                                $('cart-coupon').remove();
                                $('cart-none-msg').style.display = 'inline';
                            }}).request();
        }
	});
}


Order = {
	url:{},
	updateTotal:function(){
		new Ajax(Shop.url.ordertotal,{method:'post',update:'order-total',data:$('order-create')}).request();
	},
	applyCoupon:function(coupon){
		$('order-main').set('html','loading...');
		coupon = coupon?'coupon='+coupon:'';
		new Ajax(Shop.url.applycoupon,{method:'post',update:'order-main',data:coupon}).request();
	}
};

if($('anonymityBuy')){
	$('anonymityBuy').addEvent('click',function(e){
		Cookie.set('S[ST_ShopEx-Anonymity-Buy]', 'true');
	});
}

$ES('.cal').each(function(cal){
cal.makeCalable();
});
