var PageSize = 15;//每页计数
var CurrentPage = 1; //当前页
var keyword = '';
var catID = '0';
var brandID = '0';
var searchType = '0';
var status = 0;//刚进入页面不要列出商品,点击"添加商品"后再获取列表
var showadv = 0;//高级搜索显示状态

var memberExist = false;
var isSubmit = false;//点击提交按钮时将此变量设置为true;此时不执行$(window).unload()里的代码

var jsonPdtInfo = '';//添加商品时查询出的商品信息json数据
var Spec = '';
var SepcDesc = '';
var productID = '0';

$(document).ready(function(){
    $('#loadingContainer').ajaxStart(function(){$(this).show();}).ajaxStop(function(){$(this).hide();});
	var isIE6 = ($.browser.msie && $.browser.version=='6.0');
	setInterval(function(){
        $('#sub_container').css('height',$(window.parent.frames.right).height()-$('div.sub_container_title').height()); //设置内容区域的高度
        if(isIE6){
            $('#datacontainer').css('height','300px');
        }else{
            $('#content').css('height',$('#popupContact').height()-$('#popupHead').height());
            $('#datacontainer').css('height',$('#content').height()-$('#sub_container_listhead').height()-$('#pageDataList1_Pager').height()-$('#divsave').height()-80);
        };
    },1000);
    
    //页面关闭时删除购物车记录
//    $(window).unload(function(){
//        if(!isSubmit){
//            $.ajax({url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=ClearCart&CartID='+escape($('#cartID').val())});
//        };
//    });	
    
    $('[@name=member]').click(function(){
        if($(this).val() == '0'){
            $('#txtMemberName').val('anonymous');
            memberExist = true;
        }else{
            $('#txtMemberName').val('');
            memberExist = false;
        }
    });
    
    /*获取用户信息开始*/
    $('#txtMemberName').change(function(){
        var membername = $.trim($(this).val());
        if(membername == ''){
            alert('请输入会员号');
            $(this).focus();
        };
        $('#ship_0').prevAll().remove();//地址簿
        $('#advMoney').text('0');
        $('#frmAdvance').hide();
        $('#cbAdvPay').attr('checked',false);
        $.ajax({
            url:'OrderAdd.aspx?ajax=GetMemberInfo&MemberName='+escape(membername),
            dataType:'json',
            cache:false,
            async:false,
            success:function(msg){
                if(msg.Exist == 'true'){
                    memberExist = true;
                    var MemberInfo = msg.MemberInfo;
                    $('#memberInfo').text('用户信息：　会员帐号：' + MemberInfo.MemberName + '　会员级别：' + MemberInfo.GroupName + '　折扣：' + MemberInfo.Discount +'%'+ '　预付款：' + Number(MemberInfo.AdvancePayment).toFixed(2) + '　积分：' + MemberInfo.Score);
                    $('#GroupID').val(MemberInfo.GroupId);
                    //当读取到用户信息后要在此处理一些价格信息,显示预付款等.
                    if(Number(MemberInfo.AdvancePayment) > 0){
                        $('#advMoney').text(Number(MemberInfo.AdvancePayment).toFixed(2));
                        $('#frmAdvance').show();
                    };
                }else{
                    memberExist = false;
                    $('#memberInfo').text('用户帐号 ' + membername + ' 不存在');
                };
            },
            error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('error')};}
        });
    });//end txtMemberName change
    /*获取用户信息结束*/
    
    /*获取商品信息开始*/
    $('#btnGetProInfo').click(function(){
        var productno = $.trim($('#ProductNo').val());
        if(productno == ''){
            alert('请输入商品编号');
            $('#ProductNo').focus();
            return false;
        };
        $.ajax({
            url:'OrderAdd.aspx?ajax=GetProInfo&ProductNo='+escape(productno),
            dataType:'json',
            cache:false,
            async:false,
            success:function(msg){
                $('#pinfo tr:gt(0)').remove();
                var objtb = $('#pinfo');
                if(msg.Exist == 'true'){
                    var p = msg.Product;
                    objtb.append('<tr><th class="tl">商品名称：</th><td class="tr">' + p.Name + '</td></tr>');
                    objtb.append('<tr><th class="tl">价格：</th><td class="tr">' + p.MemberPrice + '</td></tr>');
                    $.each(p.CustomField,function(i,n){
                        objtb.append('<tr><th class="tl">' + n.FieldName + '：</th><td class="tr">' + n.FieldValue + '</td></tr>');
                    });
                    $.each(p.CustomChoice,function(i,n){
                        var row = '<tr>';
                        row += '<th class="tl">' + n.FieldName + '：</th>';
                        row += '<td class="tr">';
                        row += '<select name="custom">';
                        var customvalue = n.FieldValue.split(',');
                        for(var j=0;j<customvalue.length;j++){
                            row += '<option value="' + n.FieldName + '：' + customvalue[j] + '">' + customvalue[j] + '</option>';
                        }
                        row += '</select>';
                        row += '</td>';
                        row += '</tr>';
                        objtb.append(row);
                    });
                    objtb.append('<tr><th class="tl"></th><td class="tr"><input type="button" id="btnAdd" value="添加此商品" /></td></tr>');
                    objtb.find('#btnAdd').click(function(){
                        var customvalue = '';
                        var customtext = '';
                        $('[@name=custom]').each(function(){
                            customvalue += $(this).val() + '^';
                            customtext += $(this).val() + '<br/>';
                        });
                        var pass = true;
                        $('[@name=PCustom_' + p.ProductID + ']').each(function(){
                            if($(this).val() == customvalue){alert('已经选择过此商品');pass=false;return false;}
                        });
                        if(!pass){return false;}
                        
                        var row = '<tr>';
                        row += '<td class="tr">' + p.ProductNo + '</td>';
                        row += '<td class="tr">' + p.Name + '</td>';
                        row += '<td class="tr">' + customtext + '</td>';
                        row += '<td class="tr" style="text-align:center">' + p.MemberPrice + '</td>';
                        row += '<td class="tr" style="text-align:center"><input type="text" style="text-align:center" size="5" name="quantity_' + p.ProductID + '" value="' + p.Min + '" /><input type="hidden" name="PID" value="' + p.ProductID + '" /><input type="hidden" name="PCustom_' + p.ProductID + '" value="' + customvalue + '" /></td>';
                        row += '<td class="tr" style="text-align:center"><span class="subprice">' + (Number(p.MemberPrice) * Number(p.Min)) + '</span></td>';
                        row += '<td class="tr" style="text-align:center"><span style="cursor:pointer" class="delete">删除</span></td>';
                        row += '</tr>';
                        row = $(row);
                        row.find('[@name=quantity_' + p.ProductID + ']').blur(function(){
                            if(isNum($(this),'数量不正确')){
                                var num = $.trim($(this).val());
                                row.find('.subprice').text(Number(p.MemberPrice * num).toFixed(2));
                            }else{
                                return false;
                            }
                        });
                        row.find('.delete').click(function(){
                            row.remove();
                            if($('[@name=PID]').length==0){$('#cart').hide()}
                        });
                        $('#cart').append(row).show();
                    });
                }else{
                    alert('输入的商品编号不存在');
                };
            },
            error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('error')};}
        });
    });//end txtMemberName change
    /*获取商品信息结束*/
    
    //给地区下拉框绑定事件
    $('#ddlTopAreas').change(function(){$('#ddlSubAreas option:gt(0)').remove();$('#ddlThirdAreas option:gt(0)').remove();if($(this).val()!='0'){BindAreas(this,'ddlSubAreas')};});
    $('#ddlSubAreas').change(function(){$('#ddlThirdAreas option:gt(0)').remove();if($('option[selected]',this).val() != '0')(BindAreas(this,'ddlThirdAreas'));});
	
    $('#btnSubmit').click(function(){
        if(!memberExist){alert('输入的会员不存在');return false;};
        var pass = true;
		$('[@name^=quantity_]').each(function(){
		    if(!isNum($(this),'购买数量不正确')){
		        pass = false;
		        return false;
		    }
		});
		if(!pass){return false;}
        if(!CheckReceivAddr()){return false};
        if(!CheckPayment()){alert('请选择支付方式');return false;};
        if(!CheckShipping()){return false;};
        $('[@name^=quantity_]').each(function(i){
            $(this).attr('name','quantity_' + i);
        });
        $('[@name^=PCustom_]').each(function(i){
            $(this).attr('name','PCustom_' + i)
        });
		isSubmit = true;		
    });
    
});

function CheckShipping(){
    if($('[@name=rblShipping][@checked]').length == 0){alert('请选择配送方式');return false};
    return true;
};


//判断是否选择了支付类型
function CheckPayment(){
    if($('[@name=rblPayment][@checked]').length==0){return false;};
    return true;
};

function CheckFullAddr(){
    if($('#ddlThirdAreas')[0] && $('#ddlThirdAreas').val() == 0){
        return false;
    }else if($('#ddlSubAreas')[0] && $('#ddlSubAreas').val() == 0){
        return false;
    }else if($('#ddlTopAreas').val() == 0){
        return false;
    }else{
        return true;
    };
};

function CheckReceivAddr(){
    if($.trim($('#txtRName').val())==''){alert('请填写收货人姓名!');return false;};
    if(!CheckFullAddr()){alert('请选择完整的地区');return false;};
    if($.trim($('#txtRAddress').val())==''){alert('请填写收货人详细地址!');return false;};
    if($.trim($('#txtRPostalcode').val())==''){alert('请填写收货人邮政编码!');return false;};
    return true;
};


//绑定地区的方法
function BindAreas(obj1,obj2){
	var svalue = obj1.value; 
	var weburl = "../ajax.aspx?NoCopyright=1&parent_id="+svalue + "&r=" + Math.random(); 
	$.get(weburl,function(data){
		document.getElementById(obj2).length = 0; 
		document.getElementById(obj2).options.add(new Option(strSelectArea,"0")); 
		if(data!=""){ 
			var allArray = data.split("<")[0].toString().split(","); 
			for(var i=1;i<allArray.length;i++){ 
				var thisArray = allArray[i].split("|"); 
				document.getElementById(obj2).options.add(new Option(thisArray[1].toString(),thisArray[0].toString())); 
			} 
		} 
	});
	
	//根据选择的地区绑定相应的配送价格
	var areaID = $('#ddlSubAreas').val() == '0' ? $('#ddlTopAreas').val() : $('#ddlSubAreas').val();
	var url_getShippings = "../ajax.aspx?NoCopyright=1&type=GetShippings&areaID=" + areaID + "&ran=" + Math.random();
	$.get(url_getShippings,function(data){
		$('#shippingsList').html(data);
	})

} //End BindAreas()

function isNum(obj,msg){
	var reg = new RegExp(/\D/g);
	if(reg.test(obj.val()) || $.trim(obj.val()) == ''){
	    alert(msg);
	    obj.focus();
	    return false;
	};
	return true;
}

function checkLoginStatus(data){
    var result = true;
    if(data.indexOf('<!DOCTYPE') != -1){
        result = false;
        alert('身份已过期,请重新登陆!');
    };
    return result;
};

