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())});
        };
    });
    
    /*获取用户信息开始*/
    $('#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?NoCopyRight=1&type=ajax&Action=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();
                    };
                    //地址簿
                    
                    $.ajax({
                        url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=GetAddress&MemberName=' + escape(membername),
                        cache:false,
                        async:false,
                        success:function(data){
                            if(!checkLoginStatus(data)){return false;}
                            $('#ship_0').before(data);
                            BindAddress();
                            
                        },
                        error:function(){alert('get address error');}
                    });
                }else{
                    memberExist = false;
                    $('#memberInfo').text('用户帐号 ' + membername + ' 不存在');
                };
            },
            error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('error')};}
        });
        $('[@name=shipAddr]').eq(0).attr('checked','checked').click();//默认选择收货地址中的第一项
    });//end txtMemberName change
    /*获取用户信息结束*/
    
    var tipwords = '输入商品编号或商品ID';
    $('#txtQueryKey').focus(function(){
        if($(this).val() == tipwords){
            $(this).val('').removeClass('disabled');
        };
    }).blur(function(){
        if($.trim($(this).val()) == ''){
            $(this).val(tipwords).addClass('disabled');
        }
    }).val(tipwords).addClass('disabled');
    
    //点击查询商品信息
    $('#btnQuery').click(function(){
        if($.trim($('#txtQueryKey').val()) == tipwords){
            alert('请在文本框里输入商品编号或ID');
            return false;
        }else{
            QueryPdtInfo();
        };
    });
    
    $('#btnAddPdt').click(function(){
        var gid = $('#tmp_GID').val();
        if(gid == '0'){
            alert('请先选择要添加的商品');return;
        }else{
            var isExist = false;
            $('[name=GID]').each(function(){
                if($(this).val() == gid){
                    isExist = true;
                    return;
                }
            });
            if(isExist){
                alert('此商品已在订单中');return;
            }else{
                var row = '<tr>';
                row += '<td>' + jsonPdtInfo.ProductNo + '</td>';
                row += '<td>' + jsonPdtInfo.ProductName + '</td>';
                row += '<td>' + unescape($('#spectext').val()) + '</td>';
                row += '<td>' + jsonPdtInfo.MemberPrice + '</td>';
                row += '<td><input type="text" name="txtQuantity" size="9" value="1" /></td>';
                row += '<td><span class="delete" style="color:red; cursor:pointer">删除</span><input type="hidden" name="OrderPID" value="' + jsonPdtInfo.ProductID + '" /><input type="hidden" name="GID" value="' + gid + '" /></td>';
                row += '</tr>';
                
                row = $(row);
                row.find('[@name=txtQuantity]').blur(function(){
                    if(!isNum($(this),'商品数量填写有误')){
                        return false;
                    }else{
                        if($(this).val()<1){
                            alert('商品数量填写有误');
                            $(this).focus();
                        };
                    };
                }).change(function(){
                    var objtxtNum = $(this);
                    if(isNaN(objtxtNum.val())){
                        return false;
                    }
                    $.ajax({
                        url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=UpdateNum&CartID=' + escape($('#cartID').val()) + '&GroupID=' + $('#GroupID').val() + '&ProductID=' + jsonPdtInfo.ProductID + '&GID=' + gid + '&Quantity=' + objtxtNum.val(),
                        dataType:'json',
                        cache:false,
                        success:function(data){
                            $('#total').text(Number(data.NewTotal).toFixed(2));
                            $('#favourable').html(data.favourable);
                            setPriceInfo();
                        },
                        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('error')};}
                    });
                });
                row.find('span.delete').click(function(){
                    row.remove();
                    var pids = '';
                    $('input[@name=OrderPID]').each(function(){
                        pids += $(this).val() + ',';
                    });
                    if(pids != ''){pids = pids.substring(0,pids.length-1)};
                    $('#PIDs').val(pids);
                    
                    //从购物车里删除
                    $.ajax({
                        url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=DeleteCartItem&CartID=' + escape($('#cartID').val()) + '&GroupID=' + $('#GroupID').val() + '&ProductID=' + jsonPdtInfo.ProductID + '&GID=' + gid,
                        dataType:'json',
                        cache:false,
                        async:false,
                        success:function(data){
                            $('#total').text(Number(data.NewTotal).toFixed(2));
                            $('#favourable').html(data.favourable);
                            setPriceInfo();
                        },
                        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('error')};}
                    });
                });//end click;
                row.appendTo('#tbPdts');
                
                //添加到购物车
                $.ajax({
                    url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=AddToCart',
                    data:'OrderPID=' + jsonPdtInfo.ProductID + '&GID=' + gid + '&Spec=' + $('#spectext').val() + '&CartID=' + escape($('#cartID').val()) + '&GroupID=' + $('#GroupID').val(),
                    dataType:'json',
                    type:'post',
                    async:false,
                    cache:false,
                    success:function(data){
                        $('#total').text(Number(data.NewTotal).toFixed(2));
                        $('#favourable').html(data.favourable);
                        setPriceInfo();
                    },
                    error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('error')};}
                });
            };//end else
        };//end else
    });//end click
    
    $('[@name=shipAddr]').eq(0).attr('checked','checked').click();//默认选择收货地址中的第一项
    $('#ddlTopAreas').change(function(){topAreaChange();});

    /*收货地址结束*/
    
    /*支付方式开始*/
    //选择从自提点取货
    $('input[@name=rbPayType][@value=6]').click(function(){
        if(!CheckReceivAddr()){return false};
        GetZtds($('#ddlTopAreas').val());
        $('#ztdContainer').show();
        $('.shipContainer').hide();
        
        setZtdVisible();
    });
    $('input[@name=rbPayType][@value!=6]').click(function(){
        if(!CheckReceivAddr()){return false};
        ClearZtds();
        $('#ztdContainer').hide();
        
        var areaID = GetAreaID();
        if(areaID == 0){return false;};
        if($(this).val()==5){
            GetShippings(areaID,true);//该地区仅支付货到付款的配送方式
        }else{
            GetShippings(areaID,false);//该地区所有配送方式
        }
    });
    /*支付方式结束*/
    
    /*配送时间开始*/
    $('#ddlDate').change(function(){
        if($(this).val() == '3'){
            $('#specal_day').show();
        }else{
            $('#specal_day').hide();
        };
    });
    $("#txt_Date").datepicker().click(function(){$(this).blur()});
    /*配送时间结束*/
    
    /*发票开始*/
    //发票
    $('#chkInvoice').click(function(){
        if($(this).attr('checked')){
            $('#invoice').show();
            $('#rbtnInvoiceTypeGeneral').click();
        }else{
            $('#invoice').hide();
            $('#taxPrice').text('0');
        };

        setPriceInfo();
        $(this).blur();
    });
    //普通发票税金
    $('#rbtnInvoiceTypeGeneral').click(function(){
        $('#taxPrice').text(Number($('#total').text()*taxRateGeneral).toFixed(2));
        setPriceInfo();
    });
    //增值税发票税金
    $('#rbtnInvoiceTypeVAT').click(function(){
        $('#taxPrice').text(Number($('#total').text()*taxRateVAT).toFixed(2));
        setPriceInfo();
    });
	
	$('#rbtnInvoiceHeadCompany').click(function(){
		$('#txtCompanyName').show();
	});
	$('#rbtnInvoiceHeadPerson').click(function(){
		$('#txtCompanyName').hide();
	});
	$('#rbtnInvoiceContentOther').click(function(){
		$('#txtInvoiceContent').show();
	});
	$('#rbtnInvoiceContentDetails').click(function(){
		$('#txtInvoiceContent').hide();
	});
    /*发票结束*/
    
    /*预付款开始*/
    $('#advMoney').text(memberAdvance);
    //预付款
	if(Number(memberAdvance) > 0){
	    $('#frmAdvance').show();
	};
	$('#cbAdvPay').click(function(){
	    setPriceInfo();
	});
    /*预付款结束*/
    
    $('#btnSubmit').click(function(){
        if(!memberExist){alert('输入的会员不存在');return false;};
        if($('input[@name=OrderPID]').length == 0){alert('请选择商品');return false;};
        if(!CheckReceivAddr()){alert('!pass');return false};
        if(!CheckPayment()){alert('请选择支付类型');return false;};
        if(!CheckShipping()){return false;};
        isSubmit = true;
    });
    
});

//点击地址簿事件
function BindAddress(){
    $('[@name=shipAddr]').click(function(){
        var addrID = $(this).val();
        if(addrID != 0){
            $('#saveaddr').hide();$('#isSaveAddr').attr('checked','');
            $.ajax({
                url:ShopFolder+'Order.aspx?NoCopyRight=1&type=ajax&Action=GetAddrDetail&AddrID='+addrID,
                type:'get',
                dataType:'json',
                cache:false,
                success:function(msg){
                    if(msg.Addr.length > 0){
                        var n = msg.Addr[0];
                        $('#txtRName').val(n.ReceiverName);
                        $('#txtRPhone').val(n.ReceiverPhone);
                        $('#txtRPostalcode').val(n.ReceiverZip);
                        $('#ddlTopAreas').val(n.AddressID.split(',')[0]).unbind().change(function(){
                            topAreaChange();
                        }).change();
                        if($('#ddlSubAreas').length > 0){
                            $('#ddlSubAreas').val(n.AddressID.split(',')[1]).change();
                            $('#ddlThirdAreas').val(n.AddressID.split(',')[2]).change();
                        };
                        
                        var area = n.ReceiverAddress.replace($('#ddlTopAreas option[@selected]').text(),'').replace($('#ddlSubAreas option[@selected]').text(),'').replace($('#ddlThirdAreas option[@selected]').text(),'');
                        while(area.indexOf(',') == 0){
                            area = area.replace(',','');
                        };
                        $('#txtRAddress').val(area);
                        
                        $('#txtRName').change(function(){CheckSave();});
                        $('#txtRPhone').change(function(){CheckSave();});
                        $('#txtRAddress').change(function(){CheckSave();});
                        $('#txtRPostalcode').change(function(){CheckSave();});
                        $('#ddlTopAreas').change(function(){CheckSave();});
                        $('#ddlSubAreas').change(function(){CheckSave();});
                        $('#ddlThirdAreas').change(function(){CheckSave();});
                    }else{
                        $('#txtRName').val('');
                        $('#txtRPhone').val('');
                        $('#txtRAddress').val('');
                        $('#txtRPostalcode').val('');
                        $('#ddlTopAreas').val('0').change();
                    };
                },
                error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!');}else{alert(textStatus)};}
            });
        }else{
            CheckSave();
            $('#txtRName').val('');
            $('#txtRPhone').val('');
            $('#txtRAddress').val('');
            $('#txtRPostalcode').val('');
            $('#ddlTopAreas').val('0').change();
            setPriceInfo();
        };
    });//end click
}

function CheckSave(){$('#saveaddr').show();$('#isSaveAddr').attr('checked','checked');};//显示是否保存地址的选项

function topAreaChange(){
    $('#ddlSubAreas').remove();
    $('#ddlThirdAreas').remove();
    var topoption = $('#ddlTopAreas option[@selected]');
    if(topoption.attr('child') == 'true'){
        var subareas = GetSubArea(topoption.val());//获取二级地区
        var subareaoptions = $('<select id="ddlSubAreas" name="ddlSubAreas"></select>').append(subareas);
        if(subareaoptions.find('option').length > 1){
            $('#ddlTopAreas').after(subareaoptions);
            $('#ddlSubAreas').change(function(){
                $('#ddlThirdAreas').remove();
                var suboption = $('option[@selected]',this);
                if(suboption.attr('child') == 'true'){
                    var thirdareas = GetSubArea(suboption.val());//获取三级地区
                    var thirdareaoptions = $('<select id="ddlThirdAreas" name="ddlThirdAreas"></select>').append(thirdareas);
                    if(thirdareaoptions.find('option').length > 1){
                        $(this).after(thirdareaoptions);
                        $('#ddlThirdAreas').change(function(){
                            //三级地区自提点
                            if($('option[@selected]',this).attr('ztd') > 0){$('tr.paytype_6').show();};
                            $('input[@name=rbPayType][@value=6]').removeAttr('checked');
                            $('#ztdContainer').hide();
                            //三级地区货到付款
                            if($('option[@selected]',this).attr('hdfk') > 0){$('tr.paytype_5').show();}else{$('tr.paytype_5').hide();};
                            $('input[@name=rbPayType][@value=5]').removeAttr('checked');
                            $('[@name=Shipping]').eq(0).data('isHdfk','2');
                            GetShippings($('#ddlThirdAreas').val(),false);
                            setPriceInfo();
                        });
                    };//end if
                }else{
                    //没有三级地区,获取二级地区的配送方式
                    $('[@name=Shipping]').eq(0).data('isHdfk','2')
                    GetShippings($('#ddlSubAreas').val(),false);
                    setPriceInfo();
                };
                showZtd(suboption.attr('ztd'));
                //二级地区货到付款
                if(suboption.attr('hdfk') > 0){$('tr.paytype_5').show();}else{$('tr.paytype_5').hide();};
                $('input[@name=rbPayType][@value=5]').removeAttr('checked');
            });//end change
        };//end if
    }else{
        //没有二级地区,获取一级地区的配送方式
        $('[@name=Shipping]').eq(0).data('isHdfk','2');
        GetShippings($('#ddlTopAreas').val(),false);
        setPriceInfo();
    };
    
    //是否显示自提点选项
    showZtd(topoption.attr('ztd'));
    //是否显示货到付款选项
    if(topoption.attr('hdfk') > 0){$('tr.paytype_5').show();}else{$('tr.paytype_5').hide();$('input[@name=rbPayType][@value=5]').removeAttr('checked');}    
};

//获取子地区
function GetSubArea(areaID){
    var options = null
    var login = true;
    $.ajax({
        url:ShopFolder+'Order.aspx?NoCopyRight=1&type=ajax&Action=GetSubArea&AreaID='+areaID,
        type:'get',
        async:false,
        success:function(data){
            if(!checkLoginStatus(data)){login=false;return false;};
            options = data;
        },
        error:function(){alert('error');}
    });
    if(!login){return false};
    return options;
};

//显示隐藏自提点容器
function showZtd(ztdNum){
    if(ztdNum > 0){$('tr.paytype_6').show();}else{$('tr.paytype_6').hide();$('#ztdContainer').hide();}
    $('input[@name=rbPayType][@value=6]').removeAttr('checked');
};

//根据地区获取配送方式
function GetShippings(areaID,isHdfk){
    $('.shipContainer').show();
    if($('[@name=Shipping]')[0]){
        if($('[@name=Shipping]').eq(0).data('isHdfk') == (isHdfk ? "1" : "0")){
            return false;//不用读取
        };
    }else{
        $('[@name=Shipping]').eq(0).data('isHdfk','0');
    };
    var areaIDForPrice = 0;
    if($('#ddlSubAreas')[0] && $('#ddlSubAreas').val() != 0){
        areaIDForPrice = $('#ddlSubAreas').val();
    }else{
        areaIDForPrice = $('#ddlTopAreas').val();
    };

    $.ajax({
        url:ShopFolder+'Order.aspx?NoCopyRight=1&type=ajax&Action=GetShipps&ShipType=' + (isHdfk ? '1' : '0') + '&AreaID=' + areaID + '&AreaIDForPrice=' + areaIDForPrice,
        type:'get',
        dataType:'json',
        cache:false,
        success:function(msg){
            $('#tmp_ship').nextAll().remove();
            var data = msg.Shippings;
            $.each(data,function(i,n){
                var row = $('#tmp_ship').clone().show();
                row.find('.shipname').html('<input type="radio" id="ship_' + i + '" name="Shipping" value="' + n.ShippingID + '" price="' + n.Price + '" /><label for="ship_' + i + '">' + n.Name + '</label>');
                row.find('.shipprice').html(n.Price);
                row.find('.shipdetail').html(n.Description);
                row.find('[@name=Shipping]').click(function(){
                    if(!CheckPayment()){alert('请先选择支付类型');return false;};
                    setPriceInfo();
                });
                row.attr('id','row_ship_'+i).appendTo($('#shipContainer tbody'));
            });
            $('[@name=Shipping]').eq(0).data('isHdfk',(isHdfk ? '1' : '0'));//记录当前读取的是所有配送方式还是仅支持货到付款的配送方式
            
        },
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert(textStatus)};}
    });
};

function setPriceInfo(){
    var shipPrice = 0;
    if($('[@name=Shipping][@checked]').attr('price')){
        shipPrice = $('[@name=Shipping][@checked]').attr('price');
    };
    $('#shipPrice').text(shipPrice);
    $('#freeTip').hide();
    if(shipFreeType==0){//不开通免运费
        $('#shipPrice').text(shipPrice);
    }else if(shipFreeType==1){//全国统一最低金额
        if($('#total').text() >= leastMoney){
            $('#shipPrice').text('0');
            $('#freeTip').show();
        };
    }else{//按地区设置最低金额
        var arealeast = 0;
        if($('#ddlSubAreas')[0] && $('#ddlSubAreas').val() != 0){
            arealeast = $('#ddlSubAreas option[@selected]').attr('freeleast') ? $('#ddlSubAreas option[@selected]').attr('freeleast') : 0;
        }else{
            arealeast = $('#ddlTopAreas option[@selected]').attr('freeleast') ? $('#ddlTopAreas option[@selected]').attr('freeleast') : 0;
        };
        if(Number($('#total').text()) >= Number(arealeast)){
            $('#shipPrice').text('0');
            $('#freeTip').show();
        };
    };
    
    setAdvancePrice();
    
    $('#ptotalPrice').text($('#originaltotal').text());
    $('#couponPrice').text(Number($('#originaltotal').text() - $('#total').text()).toFixed(2));
    var lefttotal = Number($('#ptotalPrice').text()) + Number($('#shipPrice').text()) + Number($('#taxPrice').text()) - Number($('#advPrice').text()) - Number($('#couponPrice').text());
    $('#lefttotal').text(Number(lefttotal).toFixed(2));
};

function setAdvancePrice(){
    if($('#cbAdvPay').attr('checked')){
        var tmpTotal = Number($('#total').text()) + Number($('#taxPrice').text()) + Number($('#shipPrice').text());
        var advMoney = Number($('#advMoney').text());
        if(advMoney >= tmpTotal){
            $('#advPrice').text(Number(tmpTotal).toFixed(2));
        }else{
            $('#advPrice').text(Number(data).toFixed(2));
        }
    }else{
        $('#advPrice').text('0');
    };
};

//判断是否选择了完整的地区
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 CheckPayment(){
    if($('[@name=rbPayType][@checked]').length==0){return false;};
    return true;
};
//检查配送信息
function CheckShipping(){
    if($('input[@name=rbPayType][@checked]').val() == 6){
        if($('[@name=rbZtd][@checked]').length == 0){alert('请选择自提点!');return false};//如果选择了到自提点提货,判断是否选择了自提点
    }else{
        if($('[@name=Shipping][@checked]').length == 0){alert('请选择配送方式');return false};//如果没有选择从自提点取货,判断是否选择了送货方式
    };
    return true;
};


//清除自提点
function ClearZtds(){$('#tmp_ztd').nextAll().remove();};


//获取选择的最后一级地区ID
function GetAreaID(){
    var areaID = 0;
    if($('#ddlThirdAreas')[0] && $('#ddlThirdAreas').val() != 0){
        areaID = $('#ddlThirdAreas').val();
    }else if($('#ddlSubAreas')[0] && $('#ddlSubAreas').val() != 0){
        areaID = $('#ddlSubAreas').val();
    }else{
        areaID = $('#ddlTopAreas').val();
    }
    return areaID;
};

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;
};


function QueryPdtInfo(){
    var flag = false;
    $.ajax({
        url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=QueryProduct&QueryType=' + $('[@name=rdQueryType][@checked]').val() + '&QueryKey='+escape($('#txtQueryKey').val()),
        dataType:'json',
        cache:false,
        async:false,
        success:function(msg){
            var exist = msg.Exist;
            if(msg.Exist == 'true'){
                //商品在订单中已经存在
                alert('此商品在订单中已经存在');
            }else{
                var data = msg.Product;
                if(data.length > 0){
                    var n = data[0];
                    jsonPdtInfo = data[0];//全局变量
                    productID = n.ProductID
                    $('#queryResult').html('<th class="tl">查询结果：</td><td class="tr">商品名称：<a href="../products/product-' + n.ProductID + '.html" target="_blank">' + n.ProductName + '</a>　编号：' + n.ProductNo + '　会员价格：' + n.MemberPrice + '　是否打折：' + (n.IsDiscount.toLowerCase() == 'true' ? '是' : '否') + '　状态：' + (n.Status == -1 ? '已删除' : (n.Status == 1 ? '发布':'未发布')) + '</td>');
                    flag = true;
                    
                    //给全局变量赋值
                    Spec = n.Spec;
                    SpecDesc = n.SpecDesc;
                    ShowSpecs();
                }else{
                    alert('没找到商品');
                    $('#queryResult').html('<th class="tl">查询结果：</th><td class="tr">没找到商品</td>');
                    $('#Specs').hide();
                    $('#SpecItems').html('<tr><td></td></tr>');
                    $('#spectext').val('');
                    Spec = '';
                    SpecDesc = '';
                    $('#tmp_GID').val('0');
                    flag = false;
                };
            };
        },
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('error')};}
    });
    return flag;
};

var mainSpecCount = 0;//记录主规格的数量
var subSpecCount = 0;//记录次规格数量
var mainSpecName = '';//当前商品的主规格名称
var mainSpecValue = '';//当前商品的主规格值
function ShowSpecs(){
    if($.trim(Spec) != ''){
        //有规格的情况，看是否有子规格
        var subSpecCount = 0;
        Spec = eval('(' + Spec + ')');
        $('#SpecItems').children().remove();
        $.each(Spec.Specs,function(i,n){
            if(n.IsMain == '1'){
                mainSpecCount += 1;
                mainSpecName = n.SpecName;
                $.each(n.Contain,function(j,m){
                    if(m.PID == productID){
                        mainSpecValue = m.Pro;
                    };
                });//end each
            }else{
                subSpecCount += 1;
                var tr = $('<tr></tr>');
                tr.append('<td>' + n.SpecName + '：</td>');
                var td = $('<td></td>');
                //循环次规格的每一项值
                $.each(n.Contain,function(j,m){
                    var radio = $('<input type="radio" id="spec_' + i + '_'+ j +'" name="spec_' + i + '" specname=' + n.SpecName + ' value="' + m + '" ' + (j == 0 ? 'checked=checked' : '') + ' /><label for="spec_' + i + '_'+ j +'">' + m + '</label>　　');
                    radio.click(function(){
                        SelectSpecs();
                    }).appendTo(td);
                });
                tr.append(td);
                $('#SpecItems').append(tr);
            };//end if
        });//end each
        if(subSpecCount > 0){$('#Specs').show()}else{$('#Specs').hide()};
    }else{
        //没有规格的情况，只需记录下GoodsID
        if($.trim(SpecDesc) != ''){
            var goods = eval('(' + SpecDesc + ')').Goods;
            //$('#GID').val(goods[0].GID);
            //20100312 by hakkas
            $('#tmp_GID').val(goods[0].GID);
            $('#btnAddPdt').removeAttr('disabled');
        };
    }//end else
    $('input[type=radio][name^=spec_][@checked]').eq(0).click();
};

function SelectSpecs(){
    var selected_values = '';//记录选择的尺寸,用来匹配对应的GoodsID
    var text_spec_result = '';//存入数据库的文本内容
    if(mainSpecCount > 0){
        text_spec_result += mainSpecName + '：' + mainSpecValue + '<br/>';
    };
    $('input[type=radio][name^=spec_][@checked]').each(function(){
        selected_values += $(this).val() + ' ';
        text_spec_result += $(this).attr('specname') + '：' + $(this).val() + '<br/>';
    });
    if(selected_values != ''){
        selected_values = selected_values.substring(0,selected_values.length-1);
        text_spec_result = text_spec_result.substring(0,text_spec_result.length-5);
    };
    
    if($.trim(SpecDesc) != ''){
        var goods = eval('(' + SpecDesc + ')').Goods;
        $.each(goods,function(i,n){
            if(selected_values == n.Desc){
                $('#tmp_GID').val(n.GID);
            };
        });
    };
    $('#spectext').val(escape(text_spec_result));
    
    if($('#tmp_GID').val() != '0'){
        $('#btnAddPdt').removeAttr('disabled');
    }else{
        $('#btnAddPdt').attr('disabled','disabled');
    };
};