var WSTHook_beforeStatCartMoney = [],WSTHook_beforeStatGoodsMoney = [];
function driftTabs(){
    var offsetTop = $("#cartTabs").offset().top;
    $(window).scroll(function() {  
        var scrollTop = $(document).scrollTop();
        if (scrollTop < offsetTop-WST.pageHeight()){
        	$("#cartTabs").addClass("active");
        }else{
        	$("#cartTabs").removeClass("active");
        }  
    });
}
function checkChks(obj,cobj){
	if($(obj).attr('class').indexOf('active') == -1 ){
		$(obj).addClass('active');
		var n = 1;
	}else{
		$(obj).removeClass('active');
		var n = 0;
	}
	$(cobj).each(function(){
		if(n==1){
			$(this).addClass('active');
		}else{
			$(this).removeClass('active');
		}
		var cid = $(this).attr('value');
		if(cid!=''){
		    WST.changeCartGoods(cid,$('#buyNum_'+cid).val(),n);
		    statCartMoney();
	    }
	})
}
function statCartMoney(){
	var cartMoney = 0,goodsTotalPrice,id;
	$('.j-gchk').each(function(){
		id = $(this).attr('value');
		if(WSTHook_beforeStatGoodsMoney.length>0){
			for(var i=0;i<WSTHook_beforeStatGoodsMoney.length;i++){
				delete window['callback_'+WSTHook_beforeStatGoodsMoney[i]];
				window[WSTHook_beforeStatGoodsMoney[i]](id); 
				if(window['callback_'+WSTHook_beforeStatGoodsMoney[i]]){
					window['callback_'+WSTHook_beforeStatGoodsMoney[i]]();
					return;
				 }
			}
		}
		goodsTotalPrice = parseFloat($(this).attr('mval'))*parseInt($('#buyNum_'+id).val());
		$('#tprice_'+id).html(goodsTotalPrice.toFixed(2)+'元');
		if($(this).attr('class').indexOf('active') == -1){
		}else{
			cartMoney = cartMoney + goodsTotalPrice;
		}
	});
	var minusMoney = 0;
	if(WSTHook_beforeStatCartMoney.length>0){
		for(var i=0;i<WSTHook_beforeStatCartMoney.length;i++){
			delete window['callback_'+WSTHook_beforeStatCartMoney[i]];
			minusMoney = window[WSTHook_beforeStatCartMoney[i]](cartMoney); 
			if(window['callback_'+WSTHook_beforeStatCartMoney[i]]){
				window['callback_'+WSTHook_beforeStatCartMoney[i]]();
				return;
			 }
			cartMoney = cartMoney - minusMoney;
		}
	}
	$('#totalMoney').html(cartMoney.toFixed(2));
	checkGoodsBuyStatus();
}
function checkGoodsBuyStatus(){
	var cartNum = 0,stockNum = 0,cartId = 0;
	$('.j-gchk').each(function(){
		cartId = $(this).attr('value');
		cartNum = parseInt($('#buyNum_'+cartId).val(),10);
		stockNum = parseInt($(this).attr('sval'),10);;
		if(stockNum < 0 || stockNum < cartNum){
			if($(this).prop('checked')){
				$(this).parent().parent().css('border-top','1px solid #ff6700');
				$(this).parent().parent().css('border-bottom','1px solid #ff6700');
			}else{
				$(this).parent().parent().css('border-top','1px solid #e0e0e0');
				$(this).parent().parent().css('border-bottom','0px');
			}
			if(stockNum < 0){
				$('#gchk_'+cartId).attr('allowbuy',0);
				$('#err_'+cartId).css('color','#ff6700').html('库存不足');
			}else{
				$('#gchk_'+cartId).attr('allowbuy',1);
				$('#err_'+cartId).css('color','#ff6700').html('购买量超过库存');
			}
		}else{
			$('#gchk_'+cartId).attr('allowbuy',10);
			$(this).parent().parent().css('border-top','1px solid #e0e0e0');
			$(this).parent().parent().css('border-bottom','0px');
			$('#err_'+cartId).html('');
		}
	});
}
function toSettlement(){
	var isChk = false;
	var goodsCount = $('.j-gchk.active').length;
	if(goodsCount>0){
		isChk = true;
	}
	if(!isChk){
		WST.msg('请选择要结算的商品!',{icon:1});
		return;
	}
	var msg = '';
	$('.j-gchk').each(function(){
		if($(this).prop('checked')){
			if($(this).attr('allowbuy')==0){
				msg = '所选商品库存不足';
				return;
			}else if($(this).attr('allowbuy')==1){
				msg = '所选商品购买量大于商品库存';
				return;
			}
		}
	})
	if(msg!=''){
		WST.msg(msg,{icon:2});
		return;
	}
	location.href=WST.U('home/carts/settlement');
}

function setDeaultAddr(id){
	$.post(WST.U('home/useraddress/setDefault'),{id:id},function(data){
		var json = WST.toJson(data);
		if(json.status==1){
			getAddressList();
			changeAddrId(id);
		}
	});
}

function changeAddrId(id){
	$("#list_"+id).addClass('default').siblings('#addressList .list').removeClass('default');
	$.post(WST.U('home/useraddress/getById'),{id:id},function(data){
		var json = WST.toJson(data);
		if(json.status==1){
			$('#s_addressId').val(json.data.addressId);
			$('#s_areaId').val(json.data.areaId2);
			$('#addressin').html('<p class="info">'+json.data.userName+'&nbsp;'+json.data.userPhone+'<br/>'+json.data.areaName+'&nbsp;'+json.data.userAddress+'&nbsp;<a href="javascript:void(0);" onclick="javascript:toEditAddress('+json.data.addressId+',this,1,1,1)" class="modify">修改</a>');
	     	// 计算运费
			getCartMoney();
		}
	})
}
//更多地址
function moreAddr(){
	if($("#more2").attr('class').indexOf('hide') == -1 ){
		$("#more1").show();
		$("#more2").addClass('hide');
		$(".address-hide").addClass('hide');
	}else{
		$("#more1").hide();
		$("#more2").removeClass('hide');
		$(".address-hide").removeClass('hide');
	}
}

function delAddr(id){
	WST.confirm({content:'您确定要删除该地址吗？',yes:function(index){
		$.post(WST.U('home/useraddress/del'),{id:id},function(data,textStatus){
		     var json = WST.toJson(data);
		     if(json.status==1){
		    	 WST.msg(json.msg,{icon:1});
		    	 getAddressList();
		     }else{
		    	 WST.msg(json.msg,{icon:2});
		     }
		});
	}});
}

function getAddressList(){
	var load = WST.load({msg:'正在加载记录，请稍后...'});
	$.post(WST.U('home/useraddress/listQuery'),{rnd:Math.random()},function(data,textStatus){
		 layer.close(load);
	     var json = WST.toJson(data);
	     if(json.status==1){
	       json = json.data || [];
	 	    var gettpl = document.getElementById('address').innerHTML;
	 	    laytpl(gettpl).render(json, function(html){
	 	        $('#addressList').html(html);
	 	    });
	 	    if(json.length>3){
	 	    	$('#address-more').show();
	 			$("#more1").show();
	 			$("#more2").addClass('hide');
	 			$(".address-hide").addClass('hide');
	 	    }
	     }else{
	     	$('#addressList').empty();
	     }
	})
}

function inEffect(obj,n){
	$('div[id^="addr-"]').removeClass('j-selected');
	$(obj).addClass('j-selected');
}
function inEffect1(obj,n){
	$(obj).addClass('j-selected').siblings('.wst-frame'+n).removeClass('j-selected');
}
function editAddress(){
	var isNoSelected = false;
	$('.j-areas').each(function(){
		isSelected = true;
		if($(this).val()==''){
			isNoSelected = true;
			return;
		}
	})
	if(isNoSelected){
		WST.msg('请选择完整收货地址！',{icon:2});
		return;
	}
	layer.close(layerbox);
	var load = WST.load({msg:'正在提交数据，请稍后...'});
	var params = WST.getParams('.j-eipt');
	params.areaId = WST.ITGetAreaVal('j-areas');
	$.post(WST.U('home/useraddress/'+((params.addressId>0)?'toEdit':'add')),params,function(data,textStatus){
		layer.close(load);
		var json = WST.toJson(data);
	     if(json.status==1){
	    	 WST.msg(json.msg,{icon:1});
	    	 if(params.addressId==0){
	    		 changeAddrId(json.data.addressId);
	    	 }else{
	    		 changeAddrId(params.addressId);
	    	 }
	    	 getAddressList();
	     }else{
	    	 WST.msg(json.msg,{icon:2});
	     }
	});
}
var layerbox;
function showEditAddressBox(){
	getAddressList();
	toEditAddress();
}
function emptyAddress(obj,n){
	$('#addressForm')[0].reset();
	$('#addressId').val(0);
	$("select[id^='area_0_']").remove();

	layerbox =	layer.open({
					title:'用户地址',
					type: 1,
					area: ['580px', '400px'],
					content: $('.j-edit-box')
					});
}
function toEditAddress(id,obj,n,flag,type){
	id = (id>0)?id:$('#s_addressId').val();
	$.post(WST.U('home/useraddress/getById'),{id:id},function(data,textStatus){
	     var json = WST.toJson(data);
	     if(json.status==1){
	     	if(flag){
		     	layerbox =	layer.open({
					title:'用户地址',
					type: 1,
					area: ['580px', '400px'],
					content: $('.j-edit-box')
				});
	     	}
	     	if(type!=1){
				 $('.j-list-box').show();
		    	 $('.j-show-box').hide();
	     	}
	    	 $('input[name="addrUserPhone"]').val(json.data.userPhone);
	    	 if($("select[id^='area_0_']").length>0)return;
	    	 if(id>0){
			    	 var areaIdPath = json.data.areaIdPath.split("_");
			     	 $('#area_0').val(areaIdPath[0]);
			     	 var aopts = {id:'area_0',val:areaIdPath[0],childIds:areaIdPath,className:'j-areas'}
			 		 WST.ITSetAreas(aopts);
	    	 	}
	    	 WST.setValues(json.data);
	     }else{
	    	 WST.msg(json.msg,{icon:2});
	     }
	});
}
function getCartMoney(){
	var params = {};
	params.isUseScore = $('#isUseScore').prop('checked')?1:0;
	params.useScore = $('#useScore').val();
	params.areaId2 = $('#s_areaId').val();
	params.couponId = $('#couponId').val();
	params.rnd = Math.random();
	params.deliverType = $('#deliverType').val();
	var load = WST.load({msg:'正在计算运费，请稍后...'});
	$.post(WST.U('home/carts/getCartMoney'),params,function(data,textStatus){
		layer.close(load);  
		var json = WST.toJson(data);
		if(json.status==1){
			json = json.data;
			$('#maxScoreSpan').html(json.maxScore);
		    $('#maxScoreMoneySpan').html(json.maxScoreMoney);
		    $('#isUseScore').attr('dataval',json.maxScore);
		    $('#deliverMoney').html(json.freight+'元');
		    $('#useScore').val(json.useScore);
		    $('#orderScore').html(json.orderScore+'个');
		    $('#scoreMoney2').html('-'+json.scoreMoney+'元');
		 	$('#totalMoney').html(json.realTotalMoney);
		}
	});
}
function changeDeliverType(n,index,obj){
	changeSelected(n,index,obj);
	getCartMoney();
}
function submitOrder(){
	var params = WST.getParams('.j-ipt');
	params.isUseScore = $('#isUseScore').prop('checked')?1:0
	var load = WST.load({msg:'正在提交，请稍后...'});
	$.post(WST.U('home/orders/submit'),params,function(data,textStatus){
		layer.close(load);   
		var json = WST.toJson(data);
	    if(json.status==1){
	    	 WST.msg(json.msg,{icon:1},function(){
	    		 location.href=WST.U('home/orders/succeed','pkey='+json.pkey);
	    	 });
	    }else{
	    	WST.msg(json.msg,{icon:2});
	    }
	});
}



var invoicebox;
function changeInvoice(t,str,obj){
	var param = {};
	param.isInvoice = $('#isInvoice').val();
	param.invoiceId = $('#invoiceId').val();
	var loading = WST.load({msg:'正在请求数据，请稍后...'});
	$.post(WST.U('home/invoices/index'),param,function(data){
		layer.close(loading);
		// layer弹出层
		invoicebox =	layer.open({
			title:'发票信息',
			type: 1,
			area: ['628px', '420px'], //宽高
			content: data,
			success :function(){
				if(param.invoiceId>0){
				    $('.inv_codebox').show();
				    console.log($('#invoiceCode_'+param.invoiceId));
				    $('#invoice_num').val($('#invoiceCode_'+param.invoiceId).val());
				 }
			},
		});
	});
}
function layerclose(){
  layer.close(invoicebox);
}


function changeInvoiceItem(t,obj){
	$(obj).addClass('inv_li_curr').siblings().removeClass('inv_li_curr');
	$('#invoiceType').val($(obj).attr('type'));
	$('.inv_editing').remove();// 删除正在编辑中的发票信息
	$('.inv_add').show();
	$('#invoiceId').val(t);
	if(t==0){
		// 为个人时，隐藏识别号
		$('.inv_codebox').css({display:'none'});
		$('#invoice_num').val(' ');
	}else{
		$('#invoice_num').val($('#invoiceCode_'+t).val());
		$('.inv_codebox').css({display:'block'});
	}
	$("#invoice_obj").val(t);
}
// 是否需要开发票
function changeInvoiceItem1(t,obj){
	$(obj).addClass('inv_li_curr').siblings().removeClass('inv_li_curr');
	$('#isInvoice').val(t);
}
// 显示发票增加
function invAdd(){
	$("#invoice_obj").val(1);
	$('#invoice_num').val('');
	$('.inv_li').removeClass('inv_li_curr');// 移除当前选中样式
	$('.inv_ul').append('<li class="inv_li inv_li_curr inv_editing"><input type="text" id="invoiceHead" placeholder="新增单位发票抬头" value="" style="width:65%;height:21px;padding:1px;"><i></i><div style="top:8px;" class="inv_opabox"><a href="javascript:void(0)" onCLick="addInvoice()">保存</a></div></li>');
	$('.inv_ul').scrollTop($('.inv_ul')[0].scrollHeight);// 滚动到底部
	$('.inv_add').hide();// 隐藏新增按钮
	$('.inv_codebox').css({display:'block'});// 显示`纳税人识别号`
}
// 执行发票抬头新增
function addInvoice(){
	var head = $('#invoiceHead').val();
	if(head.length==0){
		WST.msg('发票抬头不能为空');
		return;
	}
	var loading = WST.load({msg:'正在提交数据，请稍后...'});
	$.post(WST.U('home/Invoices/add'),{invoiceHead:head},function(data){
		var json = WST.toJson(data);
		layer.close(loading);
		if(json.status==1){
			$('#invoiceId').val(json.data.id);
			WST.msg(json.msg,{icon:1});
			$('.inv_editing').remove();
			var code = [];
			code.push('<li class=\'inv_li inv_li_curr\' onClick="changeInvoiceItem(\''+json.data.id+'\',this)">');
     		code.push('<input type="text" value="'+head+'" readonly="readonly" class="invoice_input" id="invoiceHead_'+json.data.id+'" />');
			code.push('<input type="hidden" id="invoiceCode_'+json.data.id+'" value=""} /><i></i>');
			code.push('<div class="inv_opabox">');
			code.push('<a href=\'javascript:void(0)\' onClick="invEdit(\''+json.data.id+'\',this)" class="edit_btn">编辑</a>');
			code.push('<a href=\'javascript:void(0)\' onClick="editInvoice(\''+json.data.id+'\',this)" style="display:none;" class="save_btn">保存</a>');
			code.push('<a href=\'javascript:void(0)\' onClick="delInvoice(\''+json.data.id+'\',this)">删除</a></div></li>');
			$('.inv_li:first').after(code.join(''));
			// 显示新增按钮
			$('.inv_add').show();
		}else{
			WST.msg(json.msg,{icon:2});
		}
	});
}
// 显示发票修改
function invEdit(id,obj){
	var input = $(obj).parent().parent().find('.invoice_input');
	input.removeAttr('readonly').focus();
	input.mouseup(function(){return false});
	$(obj).parent().parent().mouseup(function(){
		input.attr('readonly','readonly');
		$(obj).show().siblings('.save_btn').hide();
	});
	$(obj).hide().siblings('.save_btn').show();
	var invoice_code = $('#invoiceCode_'+id).val();
	$('.inv_codebox').css({display:'block'})
	$('#invoice_num').val(invoice_code);// 显示`纳税人识别号`)
}
// 完成发票修改
function editInvoice(id,obj){
	var head = $('#invoiceHead_'+id).val();
	if(head.length==0){
		WST.msg('发票抬头不能为空');
		return;
	}
	var loading = WST.load({msg:'正在提交数据，请稍后...'});
	$.post(WST.U('home/Invoices/edit'),{invoiceHead:head,id:id},function(data){
		var json = WST.toJson(data);
		layer.close(loading);
		if(json.status==1){
			var input = $(obj).parent().parent().find('.invoice_input');
			input.attr('readonly','readonly')
			$(obj).hide().siblings('.edit_btn').show();
			WST.msg(json.msg,{icon:1});
		}else{
			WST.msg(json.msg,{icon:2});
		}
	});
}
// 保存纳税人识别号
function saveInvoice(){
	var isInv = $('#isInvoice').val();
	var num = $('#invoice_num').val();
	var id = $('#invoiceId').val();
	var invoiceHead = $('#invoiceHead').val();// 发票抬头
	var url = WST.U('home/Invoices/add');
	var params = {};
	if(id>0){
		url = WST.U('home/Invoices/edit');
		invoiceHead = $('#invoiceHead_'+id).val();// 发票抬头
		params.id = id;
	}
	console.log("param:",params);
	params.invoiceHead = invoiceHead;
	params.invoiceCode = num;
	if($('#invoice_obj').val()!=0){
		var loading = WST.load({msg:'正在提交数据，请稍后...'});
		$.post(url,params,function(data){
			var json = WST.toJson(data);
			layer.close(loading);
			if(json.status==1){
				// 判断用户是否需要发票
				setInvoiceText(invoiceHead);
				if(id==0)$('#invoiceId').val(json.data.id)
			}else{
				WST.msg(json.msg,{icon:2});
			}
		});
	}else{
		setInvoiceText('');
	}
}

// 设置页面显示值
function setInvoiceText(invoiceHead){
	var isInvoice  = $('#isInvoice').val();
	var invoiceObj = $('#invoice_obj').val();// 发票对象
	var invoiceType = $('#invoiceType').val();// 发票类型
	var text = '不开发票';
	var _taxText = invoiceType==1?'专用':'普通';
	if(isInvoice==1){
		text = (invoiceObj==0)?(_taxText+'发票（纸质）  个人   明细'):(_taxText+'发票（纸质）'+invoiceHead+' 明细');
	}
	$('#invoice_info').html(text);
	layerclose();
}



// 删除发票信息
function delInvoice(id,obj){
	WST.confirm({content:'您确定要删除该发票信息吗？',yes:function(index){
		$.post(WST.U('home/invoices/del'),{id:id},function(data,textStatus){
		     var json = WST.toJson(data);
		     if(json.status==1){
		    	 WST.msg(json.msg,{icon:1});
		    	 $(obj).parent().parent().remove();
		    	 $('#invoiceId').val(0);
		    	 // 选中 `个人`
		    	 $('.inv_li:first').click();
		     }else{
		    	 WST.msg(json.msg,{icon:2});
		     }
		});
	}});
}
function changeSelected(n,index,obj){
	$('#'+index).val(n);
	inEffect1(obj,2);
}
//查看详情
function seeOrder(){
	$("#orderInfo").slideToggle(300);
}

function getPayUrl(){
	var params = {};
		params.pkey = $("#pkey").val();
		params.payCode = $.trim($("#payCode").val());
	if(params.payCode==""){
		WST.msg('请先选择支付方式', {icon: 5});
		return;
	}
	jQuery.post(WST.U('home/'+params.payCode+'/get'+params.payCode+"URL"),params,function(data) {
		var json = WST.toJson(data);
		if(json.status==1){
			if(params.payCode=="alipays"){
				$("#alipayform").html(json.result);
			}else{
				location.href = json.url;
			}
		}else{
			WST.msg('您的订单已支付!', {icon: 5});
			setTimeout(function(){				
				window.location = WST.U('home/orders/waitReceive');
			},1500);
		}
	});
}

function payByWallet(){
    var params = WST.getParams('.j-ipt');
	var load = WST.load({msg:'正在核对支付密码，请稍后...'});
	$.post(WST.U('home/wallets/paybywallet'),params,function(data,textStatus){
		layer.close(load);   
		var json = WST.toJson(data);
	    if(json.status==1){
	    	WST.msg(json.msg, {icon: 1,time:1500},function(){
                window.location = WST.U('home/orders/waitsend');
	    	});
	    }else{
	    	WST.msg(json.msg,{icon:2,time:1500});
	    }
	});
}

function checkScoreBox(v){
    if(v){
    	var val = $('#isUseScore').attr('dataval');
    	$('#useScore').val(val);
        $('#scoreMoney').show();

    }else{
    	$('#scoreMoney').hide();
    }
    getCartMoney();
}


function setPaypwd(){
	layerbox =	layer.open({
		title:['设置支付密码','text-align:left'],
		type: 1,
		area: ['450px', '240px'],
		content: $('.j-paypwd-box'),
		btn: ['设置支付密码，并支付订单', '关闭'],
		yes: function(index, layero){
			var newPass = $.trim($("#payPwd").val());
			var reNewPass = $.trim($("#reNewPass").val());
			if(newPass==""){
				WST.msg("请输入支付密码！");
				return false;
			}
			if(reNewPass==""){
				WST.msg("请输入确认支付密码！");
				return false;
			}
			if(newPass!=reNewPass){
				WST.msg("密码不一致！");
				return false;
			}
			var load = WST.load({msg:'正在提交支付密码，请稍后...'});
			$.post(WST.U('home/users/payPassEdit'),{newPass:newPass,reNewPass:reNewPass},function(data,textStatus){
				layer.close(load);   
				var json = WST.toJson(data);
			    if(json.status==1){
			    	WST.msg(json.msg, {icon: 1,time:1500},function(){
			    		layer.close(layerbox);
		                payByWallet();
			    	});
			    }else{
			    	WST.msg(json.msg,{icon:2,time:1500});
			    }
			});
			
	    	return false;
	  	},
	  	btn2: function(index, layero){}
	});
}