G.app.order={
	NORMAL_CART_KEY:"shoppingcart",
	init:function(a){
			this._opt=a||{};
			this.address.hide();
			this.invoice.hide();
			//this.address.init();
			G.app.order.products._init()
			//
			if(G.logic.login.ifLogin(this,arguments)===false){return}else{G.logic.login.getLoginUser(function(b){if(b&&b.data){G.app.order._user=b.data}})}
			$("#btn_order").click(G.app.order.submit);
			this.status.fetchIds(function(b){$.each(b,function(c,d){G.app.order.status.setSavedId(c,d)});G.app.order.products.init()})
	},
	_getYTipHtml:function(b,a){
			return'<div class="'+(a==undefined?"wrap_para":a)+'"><p class="para_inb"> <span class="para_tit">'+b+"</span></p></div>"
	},
	getNormalShoppingCart:function(){return G.app.order._localCart.getInstance(G.app.order.NORMAL_CART_KEY)},
	_localCart:(function(){
		var h=function(k,j,l){
			G.logic.constants.getWhId(function(o){
				var n=j.getItem(k)||[],m={};$.each(n.list||[],function(p,q){m[q[0]]={pid:q[0],pnum:q[1],main_product_id:q[2],price_id:q[3]||0,y_track:q[5]||""}});
				if($.isFunction(l)){l(m)}})
			},c=function(k,j,l,m){
					G.logic.constants.getWhId(function(o){var n=[];if(l){$.each(l,function(p,q){n.push([q.pid,q.pnum||1,q.main_product_id||0,q.price_id||0,q.y_track||""])})}j.setItem(k,{whId:o,list:n});if($.isFunction(m)){m()}})
			},a=function(k,j,l){
					if(!j.pid){return}G.util.localShare(function(m){h(k,m,function(n){n[j.pid]={pid:j.pid,pnum:j.pnum||1,main_product_id:j.main_product_id||0,price_id:j.price_id||0,y_track:j.y_track||""};c(k,m,n,function(){if($.isFunction(l)){l(n,m)}})})})
			},g=function(j,k,l){
						//G.util.localShare(function(m){h(j,m,function(n){$.each(k,function(p,o){n[o.pid]={pid:o.pid,pnum:o.pnum||o.num||1,main_product_id:o.main_product_id||0,price_id:o.price_id||0,y_track:o.y_track||""}});c(j,m,n,function(){if($.isFunction(l)){l(n,m)}})})})
				},f=function(k,j,l){
					e(k,function(n,m){if(n[j]){delete n[j];c(k,m,n,function(){if($.isFunction(l)){l(n,m)}})}})
				},d=function(j,k){
					//G.util.localShare(function(l){c(j,l,null,function(){if($.isFunction(k)){k(null,l)}})})
				},e=function(j,k){
					//G.util.localShare(function(l){h(j,l,function(m){if($.isFunction(k)){k(m,l)}})})
				},
				b=function(l,j,k,m){e(l,function(o,n){if(o[j]){o[j].pnum=k;c(n,o,function(){if($.isFunction(m)){m(o,n)}})}})};
				var i={};
				return{
					getInstance:function(j){
						if(!i[j]){i[j]={add:function(k,l){a(j,k,l)},addMulti:function(k,l){g(j,k,l)},remove:function(k,l){f(j,k,l)},clear:function(k){d(j,k)},getAll:function(k){e(j,k)},setNum:function(k,l,m){b(j,k,l,m)}}}
						
						return i[j]
					}
				}
		
	})(),
	putPointOrCouponChange:function(){
			//var g=G.app.order.coupon,n=g._view,m=g._mod,
			var a=G.app.order.status.get("shippingtype"),b=G.app.order.status.get("prstatus"),k=G.app.order.price.get("centcut")*100,o=G.app.order.status.get("product");
			if(!a){return}var e=[],p=k;
			$.each(a.subOrder,function(l,i){e.push(l)});
			e.sort();
			var j=0,f=e.length;
			for(;j<f;j++){
				var d=e[j];if(!a.subOrder[d]||!o.items[d]){continue}
				var h=10*Math.round(((o.items[d].totalAmt-o.items[d].totalCut)*k)/(10*(o.totalAmt-o.totalCut)));//o.items[d].pointamt=h;p-=h
			}
			j=0;
			for(;p>0&&j<f;j++){
				//-o.items[d].couponamt-o.items[d].pointamt
				var d=e[j],h=o.items[d].totalAmt;//if(h>0){var c=(h<p?h:p)-0;o.items[d].pointamt+=c;p-=c}
			}
			$.each(a.subOrder,function(q,i){
				if(!o.items[q]){return}
				//-(b&&b[q]?b[q].coupon_amt:0)-o.items[q].pointamt-o.items[q].totalCut-o.items[q].rule_benefits
				var l=(o.items[q].totalAmt)/100;l=(l<0)?0:l;//+(i.shippingPrice-0)
				$("#cartinfo p[psubid="+q+"]").html("&yen;"+l.toFixed(2))
			})
	},
	price:{
			set:function(d,b,e){
				var a=G.app.order.price;
				if(arguments.length==1){$.each(d,function(g,f){a.set(g,f,true)})}else{
					b-=0;var c=$((d=="totalprice"?"strong":"span")+"[t="+d+"]",a._dom()).html('<span class="i_yuan">&yen;</span>'+b.toFixed(2));
					if(c.length>0){c[0].parentNode.className=b<=0?"none":""}
				}
				if(!e){a.calcu()}
			},get:function(a){
				return parseFloat($((a=="totalprice"?"strong":"span")+"[t="+a+"]",G.app.order.price._dom()).html().replace(/^<span[^>]*?>[^<]*?<\/span>/i,"")).toFixed(2)
			},calcu:function(e){
					var b=0,f=[["shippingprice","goodsprice"],["prizePrice","prcode"]],c=G.app.order.price;
					//var totalprice=parseFloat(G.app.order.price.get('totalprice'));
					//var prcode=parseFloat(G.app.order.price.get('prcode'));
					//if(!totalprice){
						//["shippingprice","goodsprice"],["discount","centcut","prcode","benefits"]
						//alert(c.get("goodsprice"));
						$.each(f,function(i,g){
							var h=i==0?1:-1;
							$.each(g,function(j,k){
									var p=c.get(k);if(isNaN(p)){p=0;}
									b+=h*p*100-0;
							})
						});
						var a=c.get("shippingprice")*100;
						if(!e&&b<=a){b=a}
						b=Math.round(b)/100;
						var d=G.app.order.status.get("paytype");
						//if(d&&d.pay_type==1){b=(Math.round(b*10)/10)}
						if(e){return b}
						//alert(c.get("prizePrice"));
						c.set("totalprice",b.toFixed(2),true);
						var goodsprice = parseFloat(G.app.order.price.get("goodsprice"));
						var DivideNum = parseInt(G.app.order.status.get('DivideNum'));
						if(DivideNum && DivideNum>1 && DivideNum<13 && goodsprice<=7000){
							var d=G.app.order.paytype;
							if(goodsprice<3000){ var shou=0.3,dai=0.7; }else{ var shou=0.5,dai=0.5; }
							totalprice = goodsprice*shou+(d.decimalTwo(goodsprice*dai*0.008)+d.decimalTwo(goodsprice*dai/DivideNum))*DivideNum+parseFloat(G.app.order.price.get('shippingprice'));
							prcode=c.get('prcode');if(!prcode || isNaN(prcode)){prcode=0;}
							c.set("totalprice",totalprice-prcode,true);
						}
					//}else{
					//	if(prcode){ totalprice=totalprice-prcode;}
					//	c.set("totalprice",totalprice,true);					
					//}
		},_con:null,_dom:function(){var a=G.app.order.price;if(!a._con){a._con=$("#summary")}return a._con}
	},
	event:{
				allinpay:{
					skipInvoice:true,
					process:function(){
						if(G.app.order._user){
							if(G.app.order._user.icsonid.toString().toLowerCase().indexOf("login_shauto_")==0){var a=G.app.order.status.get("paytype");if($.isPlainObject(a)&&"pay_type" in a&&73==a.pay_type){G.app.order.invoice._view.getDom().hide();G.app.order.invoice._view.clear();this.skipInvoice=true;return}}
						}
						this.skipInvoice=true;
						//G.app.order.invoice._view.getDom().show();
						//G.app.order.invoice.init()
					}
			}
	},
	submit:function(s){
			$("#btn_order")[0].disabled=true;
			var v=function(){$("#btn_order")[0].disabled=false};
			if(G.logic.login.ifLogin(this,arguments)===false){return v()}
			//,r=p.verifycode.get() ,verifycode:r
			var p=G.app.order,f=p.status.get("address"),b=p.status.get("product"),w={uid:G.logic.login.getLoginUid()};
			//if(r!==false&&r.length<4){G.ui.popup.showMsg("请输入验证码",1,function(){p.verifycode.focus()},$.noop,$.noop);return v()}
			if(!f||f.uediting){G.ui.popup.showMsg("请选择并确认收货地址信息");return v()}
			$.extend(w,{aid:f.aid,receiver:f.name,receiveAddrId:f.district,receiveAddrDetail:f.address,receiverTel:f.phone,receiverMobile:f.mobile,zipCode:f.zipCode});
			var n=p.status.get("shippingtype");
			if(!n||n.uediting){G.ui.popup.showMsg("请选择并确认配送方式信息");return v()}
			w.shipType=n.ShippingId;
			w.sign_by_other=n.sign_by_other==1?1:0;
			var g=Math.round(G.app.order.price.get("prcode")*100);
			$.extend(w,{Price:Math.round(G.app.order.price.get("goodsprice")*100-G.app.order.price.get("discount")*100)});
			var m=g,u=G.app.order.status.get("point"),o=p.status.get("paytype"),k=u,q=[],j=false,e=[];
			if(!o||o.uediting){G.ui.popup.showMsg("请选择并确认支付方式信息");return v()}
			w.payType=o.pay_type;n=G.app.order.shippingtype._encode(n);
			$.each(b.items,function(A,C){
				var z={deptId:A,price:C.totalAmt-C.totalCut,shipPrice:0,expectDate:"",expectSpan:"",arrived_limit_time:"",couponAmt:0,point:0},y=[];
				$.each(C.items,function(D,F){
					var E=[];
					$.each(F.gift||[],function(H,I){E.push(I.product_id)});
					E="["+E.join(",")+"]";
					y.push('{"product_id":'+D+',"num":'+F.buy_count+',"gift":'+E+"}")
				});
				z.itemJsonStr="["+y.join(",")+"]";
				if(n.subOrder&&n.subOrder[A]){
					var x=n.subOrder[A];
					if(x.shipRange){
						if(x.sDate>0&&x.shipRange[x.sDate]){
							z.expectDate=x.sDate.substr(0,4)+"-"+x.sDate.substr(4,2)+"-"+x.sDate.substr(6,2);
							if(x.isArrivedLimitTime==true){
								if(x.sTime>0&&x.shipRange[x.sDate]&&x.shipRange[x.sDate].list[x.sTime]){z.arrived_limit_time=G.app.order.shippingtype.SHIP_TIME_LIMIT_LIST_TRIPLE[x.sTime]}else{G.app.order.shippingtype._view.list();G.ui.popup.showMsg("请选择收货时间");j=true;return false}
							}else{
								if(x.once==1){
									var B=0;$.each(x.shipRange[x.sDate].list||[],function(E,D){B=E;return false});z.expectSpan=B
								}else{
										if(x.sTime>0&&x.shipRange[x.sDate]&&x.shipRange[x.sDate].list[x.sTime]){z.expectSpan=x.sTime}else{G.app.order.shippingtype._view.list();G.ui.popup.showMsg("请选择收货时间");j=true;return false}
								}
							}
						}else{
							G.app.order.shippingtype._view.list();
							G.ui.popup.showMsg("请选择收货日期");
							j=true;return false
						}
					}
					z.shipPrice=x.shippingPrice
				}
				if(o.pay_type==1){z.price=Math.floor(z.price/10)*10}
				e.push(z)
			});
			$.each(e,function(x,y){var z=y.deptId;q.push('"'+z+'":{"price":'+y.price+',"shipPrice":'+y.shipPrice+',"expectDate":"'+y.expectDate+'", "expectSpan":"'+y.expectSpan+'","arrived_limit_time":"'+y.arrived_limit_time+'","items":'+y.itemJsonStr+"}")});
			q="{"+q.join(",")+"}";
			if(!G.app.order.event.allinpay.skipInvoice){var h=p.status.get("invoice");if(!h||h.uediting){G.ui.popup.showMsg("请选择并确认发票信息");return v()}if(h.type==2){h.title=h.name}$.extend(w,{invoiceId:h.iid,invoiceType:h.type,invoiceTitle:h.title,invoiceContent:b.contentOpt[h.invoiceContentIdx]||"商品明细"});if(h.type==2){$.extend(w,{invoiceCompanyName:h.name,invoiceCompanyAddr:h.addr,invoiceCompanyTel:h.phone,invoiceTaxno:h.taxno,invoiceBankNo:h.bankno,invoiceBankName:h.bankname})}else{$.extend(w,{invoiceCompanyName:"",invoiceCompanyAddr:"",invoiceCompanyTel:"",invoiceTaxno:"",invoiceBankNo:"",invoiceBankName:""})}}
			$.extend(w,{point:Math.round((G.app.order.status.get("point")||0)*10),shippingPrice:""+Math.round(G.app.order.price.get("shippingprice")*100)});
			var t=G.app.order.status.get("tms"),l=G.app.order.status.get("prule"),d=G.util.parse.url();
			if(l&&t){$.extend(w,{rule_id:l,applytimes:t})}else{if(d.search.prule){$.extend(w,{rule_id:d.search.prule,applytimes:-d.search.tms})}
			//alert(G.app.order.status.get("coupon"))
			$.extend(w,{couponCode:G.app.order.status.get("coupon")||""})}
			var c=Math.round(G.app.order.price.calcu(true)*100)+"";
			if(c-0<w.shippingPrice-0){if(!(G.app.order.price.get("centcut")==0&&G.app.order.price.get("prcode")!=0)){G.ui.popup.showMsg("抱歉，您积分和优惠券/促销优惠抵扣的金额已超过了订单商品金额，无法下单。建议您先使用优惠券抵扣，再使用适量积分抵扣");return v()}}
			if(w.payType==1){w.Price=Math.floor(w.Price/10)*10}
			var a=$("textarea[name=desc]").val();
			if(a==G.app.order._ORDER_DESC){a=""}if($.strlen(a)>800){G.ui.popup.showMsg("备注内容太长，请适当删除部分内容后继续");return v()}
			$.extend(w,{comment:a,suborders:q});
			var i=G.util.cookie.get("backurl");
			if(2==d.search.ism){w.ism=2;if(p._isES){$.extend(w,p._esInfo)}}
			/*
			tmp=""
			for(var key in w){
				tmp +="&"+key+"="+(w[key])
			}
				window.clipboardData.setData("text",tmp);
				alert(tmp);
			return;
			*/
			w.divideTypeId=G.app.order.status.get('DivideId');
			w.divideNum=G.app.order.status.get('DivideNum');
			p._postNewOrderData(w);
			return false
	},
	_postNewOrderData:function(a){
				G.app.order.loading.open();
				a.act="finish";
				
				G.util.post("/purchase/order/",a,function(e){
					G.app.order.loading.close();
					if(!e.success){
					//alert(e.message+e.info);
					}
					$("#btn_order")[0].disabled=false;
					if(e&&e.errno==0){
						G.ui.popup.showMsg("订单提交成功",{okFn:(function(f){return function(){
							location.href=e.url;
						}})(a),btns:3,okText:"支付订单"});return
						//G.app.order.processRecommendProducts(a.suborders||null);
						///var c={uid:a.uid,order_id:e.data,url:a.url},b=[];
						//$.each(c,function(g,f){b.push('<input type="hidden" name="'+g+'" value="" />')});
						//var d=$('<form action="http://buy.51buy.com/index.php?mod=order&act=succ" method="post" target="_self">'+b.join("")+"</form>");
						//$.each(c,function(g,f){d.find("input[name="+g+"]").val(f)});
						//G.app.order._edmCookie.remove();
						//G.util.localShare(function(f){f.removeItem("esshoppingcart_info");f.removeItem("ordertmpids");f.setItem("last_order_info",{order_id:e.data,create_time:new Date().getTime()},3600*1000*24*3);d.appendTo($("body")).submit()})
					}else{
						if(e&&e.errno==6002){
							$("#btn_order")[0].disabled=false;
							if(e.data.errCode==-100){G.ui.popup.showMsg(e.data.errMsg,{okFn:(function(f){return function(){f.ingoreLackOfGift=1;G.app.order._postNewOrderData(f)}})(a),btns:3,okText:"继续下单",cancelText:"取消下单"});return}
							G.ui.popup.showMsg(e.data.errMsg,{okFn:(function(f){return function(){if(f.errCode==-11){location.reload()}}})(e.data)})
						}else{
							if(e&&e.errno==6003){
								$("#btn_order")[0].disabled=false;
								G.ui.popup.showMsg("抱歉，由于长时间未操作等原因，订单中的商品价格已有所变化，暂时无法提交订单。点击确定按钮后商品价格信息会进行更新，请您检查后重新提交订单",1,function(){location.reload()},null,null,"确定","取消")
							}else{
								if(e&&e.errno==6004){
									$("#btn_order")[0].disabled=false;
									G.ui.popup.showMsg("抱歉，您购物车中的商品与订单商品不一致，请刷新订单页面重新提交！",1,function(){location.reload()},null,null,"确定","取消")
								}else{
										if(e&&e.errno==6005){
											$("#btn_order")[0].disabled=false;G.ui.popup.showMsg("抱歉，您的验证码输入有误，请您核对后重新输入",1,function(){G.app.order.verifycode.focus()},$.noop,$.noop)
										}else{

												$("#btn_order")[0].disabled=false;
												if(e.message){G.ui.popup.showMsg(e.message)}else{G.ui.popup.showMsg("系统繁忙，请稍候再试");}
										}
								}
							}
						}
					}
				})
	},
	loading:(function(){
			var a=null;
			function b(){
				if(!a){a=G.ui.popup.create({title:"正在提交中...",width:500});
				a.paint(function(c){$(c.content).empty().html('<span class="loading_58_58">正在加载中</span>')})
				}
				return a
			}
			return{open:function(){b().show()},close:function(){b().close()}}
	})()
};

G.app.order._encode = function(a){var b={};$.each(a,function(d,c){b[d]=typeof c=="string"?G.util.parse.encodeHtml(c):c});return b};
G.app.order.coupon = {
	get:function(a,c){
		if(G.logic.login.ifLogin(this,arguments)===false){return false}
		var b=G.logic.login.getLoginUid();
		$.post("/purchase/order/",{act:"getcoupon",inajax:1},function(d){if(d&&d.errno==0){;$.isFunction(a)&&a(d.data)}else{$.isFunction(c)&&c(d)}},"json")
	},
	fillCode:function(a){
		if(G.app.order.coupon.status!="check"){
			G.ui.popup.showMsg("您已使用了其他优惠券，确定更换？",{okFn:function(){
				G.app.order.coupon.uncheck();
				G.app.order.coupon.fillCode(a);
				$("#user_coupon").click()
			},btns:3});
			return false
		}
		$("input[name=couponcode]").val(a)
	},
	check:function(){
		if(G.logic.login.ifLogin(this,arguments)===false){return false}G.app.order.status.set("coupon","");
		var c=G.logic.login.getLoginUid(),e=$("input[name=couponcode]").val();
		if(!e){G.ui.popup.showMsg("您尚未填写优惠券");return}
		var a=G.app.order.status.get("address");
		if(!a){G.ui.popup.showMsg("请先选择收货地址")}
		var b=G.app.order.status.get("shippingtype"),d=G.app.order.status.get("paytype");
		if(!b||!d){G.ui.popup.showMsg("请先选择配送方式/支付方式");return}
		G.app.order.coupon.setBtnStatus("disable");
		G.util.post("/purchase/order/",{act:"checkcoupon",inajax:1,code:e,district:a.district,paytype:d.pay_type},function(f){
			if(f&&f.errno==0){
				G.app.order.status.set("coupon",f.data.number);
				G.app.order.price.set("prcode",(f.data.money).toFixed(2));
				G.app.order.status.set("prstatus",f.data.subOrders);
				G.app.order.putPointOrCouponChange();
				G.app.order.coupon.setBtnStatus("uncheck")
			}else{
				$("input[name=couponcode]").val("");
				G.ui.popup.showMsg(f.data||"系统繁忙，请稍候再试");G.app.order.coupon.setBtnStatus("check")}
			}
		)
	},
	uncheck:function(){
		G.app.order.status.set("coupon","");G.app.order.price.set("prcode",0);G.app.order.status.set("prstatus",{});G.app.order.putPointOrCouponChange();
		G.app.order.coupon.setBtnStatus("check")
	},
	setBtnStatus:function(a){
		var b=G.app.order.coupon;b.status=a;
		if(a=="uncheck"){
			$("input[name=couponcode]").attr("disabled",true);
			$("#user_coupon").empty().html("<span>取消</span>").unbind().click(b.uncheck)
		}else{
			if(a=="check"){
				$("input[name=couponcode]").removeAttr("disabled");$("#user_coupon").empty().html("<span>使用</span>").unbind().click(b.check)
			}else{
				if(a=="disable"){$("input[name=couponcode]").attr("disabled",true);$("#user_coupon").unbind()}
			}
		}
	},
	init:function(){
		var a=$("div .id_order_check");
		G.ui.tips.swapInput({target:$("textarea[name=desc]",a),defaultValue:G.app.order._ORDER_DESC,blurClass:"nor"}).blur();
		G.app.order.coupon.get(function(d){
			var c=[];
			$.each(d,function(f,e){e=G.app.order._encode(e);c.push("<tr><td>"+e.code+"</td><td>"+e.content+"</td><td>"+e.endtime+'</td><td><a href="#" onclick="G.app.order.coupon.fillCode(\''+e.code+"');return false\">选择</a></td></tr>")});
			var b=$("#my_coupon");
			if(c.length>0){
				b.hide();
				$("#coupon_my_p").after("<p id='show_coupon'><a id='show_coupon_a' class='todo_link' href='#'>显示全部优惠券</a></p>");
				$("#show_coupon").toggle(function(){
						b.find("table tbody").empty().html(c.join(""));
						b.show();$("#show_coupon_a").text("收起全部优惠券")
					},function(){
						b.hide();$("#show_coupon_a").text("显示全部优惠券")
					}
				);
			}else{b.hide()}
			$("#prbox").show()
		},function(b){
			if(parseInt(b.errno)==2){$("#prbox").html("您属于炒货商用户，不能使用优惠券。")}else{$("#my_coupon").hide()}
			$("#prbox").show()
		});
		G.app.order.coupon.uncheck()
	}
};