$(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);
    
    //初始化txtProductNo输入框
    if(getQueryStringRegExp('ProductID') == ''){$('#cbxAutoCreate').attr('checked','checked')};//添加捆绑商品默认将checkbox选中
	$('#cbxAutoCreate').attr('checked') ? $('#txtProductNo').hide() : $('#txtProductNo').show();
    $('#cbxAutoCreate').click(function(){
        if($(this).attr('checked')){
            $('#txtProductNo').hide();
            $('#txtProductNo').val('');
        }else{
            $('#txtProductNo').show();

        }
    });
    
    
 

	//--修改绑定商品时，需要将绑定的信息显示出来
	
	
	if(getQueryStringRegExp('ProductID').replace('#','') != '')
    {
        if(packageInfo != '')
        {
            eval("var packageInfojson="+packageInfo);
            var data = packageInfojson.Product;
            $.each(data,function(i,n)
            {
                var productno = n.ProductNo;
                var row = $('<tr><td class="delete ccenter"><img src="../images/x-gray.gif" alt="删除" /><input type="hidden" name="pid" value=' 
                + n.ProductID + '><input type="hidden" name="uprice" value="' 
                + n.MemberPrice + '"><input type="hidden" name="pname" value="' 
                + n.ProductName + '"><input type="hidden" name="pno" value="' 
                + n.ProductNo + '"><input type="hidden" name="image" value="' 
                + n.ThumbnailImg + '"></td><td style="overflow-x:hidden;"class="ccenter"><div style="overflow:hidden;width:250px;white-space:nowrap;" class="ccenter">' 
                + n.ProductName + '</div></td><td class="ccenter">' 
                + n.ProductNo + '</td><td class="ccenter">' 
                + n.MemberPrice + '</td><td class="ccenter"><input id="input_' 
                + n.ProductID + '" type="text" size="5" maxlength="10" style="text-align:center;" value="' 
                + n.BindSum + '" /></td></tr>');
                row.find('.delete').css('cursor','pointer').click(function(){
                    $(this).parent().remove();
                    $('#count').text(Number($('#count').text())-1);
                    //--商品ID
                    var ids = '';
                    $('input[@name=pid]').each(function(){
                        ids += $(this).val() + ',';
                    });
                    if(ids != ''){ids = ids.substring(0,ids.length-1);};
                    $('#PIDs').val(ids);
                    //--商品价格
                    var ups = '';
                    $('input[@name=uprice]').each(function(){
                        ups += $(this).val() + ',';
                    });
                    if(ups != ''){ups = ups.substring(0,ups.length-1);};
                    $('#uprices').val(ups);
                    //--商品名称
                    var pnames = '';
                    $('input[@name=pname]').each(function(){
                        pnames += $(this).val() + ',';
                    });
                    if(pnames != ''){pnames = pnames.substring(0,pnames.length-1);};
                    $('#pnames').val(pnames);
                    
                    //--商品编号
                    var pnos = '';
                    $('input[@name=pno]').each(function(){
                        pnos += $(this).val() + ',';
                    });
                    if(pnos != ''){pnos = pnos.substring(0,pnos.length-1);};
                    $('#pnos').val(pnos);
                    
                    //--商品图片
                    var images = '';
                    $('input[@name=image]').each(function(){
                        images += $(this).val() + ',';
                    });
                    if(images != ''){images = images.substring(0,images.length-1);};
                    $('#images').val(images);
                }).find('img').mouseover(function(){
                    $(this).attr('src','../images/x-red.gif');
                }).mouseout(function(){
                    $(this).attr('src','../images/x-gray.gif');
                });
                $('#listresult').append(row);
                $('#PIDs').val($('#PIDs').val() + ($('#PIDs').val() != '' ? ',' : '') + n.ProductID);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)
                $('#uprices').val($('#uprices').val() + ($('#uprices').val() != '' ? ',' : '') + n.MemberPrice);
                $('#pnames').val($('#pnames').val() + ($('#pnames').val() != '' ? ',' : '') + n.ProductName);
                $('#pnos').val($('#pnos').val() + ($('#pnos').val() != '' ? ',' : '') + n.ProductNo);
                $('#pidsums').val($('#pidsums').val() + ($('#pidsums').val() != '' ? ',' : '') + n.BindSum);
                $('#images').val($('#images').val() + ($('#images').val() != '' ? ',' : '') + n.ThumbnailImg);
            });
            $('#count').text(packageInfojson.RelationProductID.split(',').length);
            
        }
	}
	
	//弹出层
	$("#btnAdd").click(function(){
	     $('#popupContact').popup({width:'80%',height:'80%',popupHead:'popupHead',btnClose:'popupContactClose'});
	    if(status == 0){BindProducts('BindingAdd.aspx',search_urldata);status = 1;};
	});//如果是第一次弹出层,要获取商品列表,否则只需要显示层即可 
	
	if($.browser.mozilla){setInterval(setList,100);}
//	$('.sub_container_content').height(400);
    $('input[@name=chkAll]').click(function(){$('input[@name=chkItem]').attr('checked',$(this).attr('checked'));});//全选
	
	$('#showadvsearch').toggle(function(){
	    $('#advsearch').show();
	    $('#showadvsearch').text('简易搜索');
	    showadv = 1;
	},function(){
	    $('#advsearch').hide();
	    $('#sel_category').val('0')
        $('#sel_brand').val('0');
        $('#showadvsearch').text('高级搜索');
        showadv = 0;
	});
	
	$('#deleteall').click(function(){$('#listresult tr:gt(0)').remove();$('#PIDs').val('');$('#count').text('0');});//删除所有已选择的商品
    
    $('#sel_category option').eq(0).attr('selected','selected');
    $('#sel_category').change(function(){
        var categoryIDs = $(this).val();
        if(categoryIDs == null){return false;};
        $.ajax({
            url:'BindingAdd.aspx?type=ajax&Action=GetBrandByCatID&product_category_id='+categoryIDs + '&NoCopyRight=1',
            cache:false,
            success:function(data){
                if(!checkLoginStatus(data)){return false;}
                $('#sel_brand').html(data);
                $('#sel_brand option').eq(0).attr('selected','selected');
            },
            error:function(){alert('error');}
        });
    });
    
    //搜索
    $('#btnSearch').click(function(){
        CurrentPage = 1;
        keyword = $('#txtKeyword').val();
        catID = $('#sel_category').val();
        brandID = $('#sel_brand').val();
        if(catID == null){catID = '0'};
        if(brandID == null){brandID = '0';}
        searchType = $('#sel_searchType').val();
        search_urldata = 'type=ajax&Action=SearchProductsAjax&keyword=' + escape(keyword) + '&CatID=' + catID + '&BrandIDs=' + brandID + '&SearchType=' + searchType + '&PageSize=15&Page='+CurrentPage;
        BindProducts('BindingAdd.aspx',search_urldata);
        if(showadv == 1){
            $('#showadvsearch').click();
        }
    });
    
    $('#btnSubmit').click(function(){
        var productIDs = '';
        var uprices = '';
        var pnames = '';
        var pnos = '';
        var images = '';
        var selectedPIDs = '';
        if($('#PIDs').val() != ''){
            selectedPIDs = ','+$('#PIDs').val()+',';
        };
        $('input[@name=chkItem][@checked]').each(function(){
            var currobj = $(this);
            if(selectedPIDs.indexOf(',' + currobj.val() + ',') == -1){
                var productname = currobj.parent().siblings('#Name').text();
                var productno = currobj.parent().siblings('#ProductNo').text();
                var uprice = currobj.parent().siblings('#MemberPrice').text();
                var image = currobj.parent().siblings('#ThumbnailImg').val();
                var row = $('<tr><td class="delete ccenter"><img src="../images/x-gray.gif" alt="删除" /><input type="hidden" name="pid" value=' + currobj.val() + '><input type="hidden" name="uprice" value="' + uprice + '"><input type="hidden" name="pname" value="' + productname + '"><input type="hidden" name="pno" value="' + productno + '"><input type="hidden" name="image" value="' + image + '"></td><td style="overflow-x:hidden;"><div style="overflow:hidden;width:250px;white-space:nowrap;">' + productname + '</div></td><td class="ccenter">' + productno + '</td><td class="ccenter">'+uprice+'</td><td class="ccenter"><input id="input_' + currobj.val() + '" type="text" size="5" maxlength="10" style="text-align:center;" value="1" /></td></tr>');
                row.find('.delete').css('cursor','pointer').click(function(){
                    $(this).parent().remove();
                    $('#count').text(Number($('#count').text())-1);
                    //--商品ID
                    var ids = '';
                    $('input[@name=pid]').each(function(){
                        ids += $(this).val() + ',';
                    });
                    if(ids != ''){ids = ids.substring(0,ids.length-1);};
                    $('#PIDs').val(ids);
                    
                    //--商品价格
                    var ups = '';
                    $('input[@name=uprice]').each(function(){
                        ups += $(this).val() + ',';
                    });
                    if(ups != ''){ups = ups.substring(0,ups.length-1);};
                    $('#uprices').val(ups);
                    
                    //--商品名称
                    var pnames = '';
                    $('input[@name=pname]').each(function(){
                        pnames += $(this).val() + ',';
                    });
                    if(pnames != ''){pnames = pnames.substring(0,pnames.length-1);};
                    $('#pnames').val(pnames);
                    //--商品编号
                    var pnos = '';
                    $('input[@name=pno]').each(function(){
                        pnos += $(this).val() + ',';
                    });
                    if(pnos != ''){pnos = pnos.substring(0,pnos.length-1);};
                    $('#pnos').val(pnos);
                    //--商品图片
                    var images = '';
                    $('input[@name=image]').each(function(){
                        images += $(this).val() + ',';
                    });
                    if(images != ''){images = images.substring(0,images.length-1);};
                    $('#images').val(images);
                }).find('img').mouseover(function(){
                    $(this).attr('src','../images/x-red.gif');
                }).mouseout(function(){
                    $(this).attr('src','../images/x-gray.gif');
                });
                $('#listresult').append(row);
                productIDs += currobj.val() + ',';
                uprices += uprice + ',';
                pnames += productname.replace(',',' ') + ',';
                pnos += productno + ',';
                images += image + ',';
            };
        });//end each
        if(productIDs != ""){
            productIDs = productIDs.substring(0,productIDs.length-1);
            uprices = uprices.substring(0,uprices.length-1);
            pnames = pnames.substring(0,pnames.length-1);
            pnos = pnos.substring(0,pnos.length-1);
            images = images.substring(0,images.length-1);
            $('#PIDs').val($('#PIDs').val() + ($('#PIDs').val() != '' ? ',' : '') + productIDs);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)
            $('#uprices').val($('#uprices').val() + ($('#uprices').val() != '' ? ',' : '') + uprices);
            $('#pnames').val($('#pnames').val() + ($('#pnames').val() != '' ? ',' : '') + pnames);
            $('#pnos').val($('#pnos').val() + ($('#pnos').val() != '' ? ',' : '') + pnos);
            $('#images').val($('#images').val() + ($('#images').val() != '' ? ',' : '') + images);
        };
        var oldprice = Number(0);
        $('[@name=uprice]').each(function(){
            oldprice += Number($(this).val());
        });
        $('#lblMarketPrice').text(oldprice);
        
        $('#popupContactClose').click();
        $('#count').text($('input[@name=pid]').length);
        
    });
    
    //--清空
    $('#btnClear').click(function(){
        $('#count').text('0');
        $('tr:gt(0)','#listresult').remove();
        $('#PIDs').val('');
        $('#pidsums').val('');
        $('#uprices').val('');
        $('#pnames').val('');
        $('#pnos').val('');
        $('#images').val('');
    });
    
    var isNoExists = false;//判断商品编号是否存在
    $('#txtProductNo').blur(function(){
//      var isNoExists = false;//判断商品编号是否存在
        if(getQueryStringRegExp('ProductID') == ''){
            $.ajax({
                url:'BindingAdd.aspx?type=ajax&Action=IsExistProductNo&ProductNo='+escape($('#txtProductNo').val()) + '&NoCopyRight=1',
                async:false,
                cache:false,
                success:function(data){
                    if(!checkLoginStatus(data)){return false;}//是否要重新登陆
                    if(data==0){isNoExists = false;}else{isNoExists = true;}
                },
                error:function(){alert('IsExistProductNo_error1')}
          });
        }else{//修改商品
            $.ajax({
                url:'BindingAdd.aspx?type=ajax&Action=IsExistProductNo&ProductNo='+escape($('#txtProductNo').val())+'&ProductID='+getQueryStringRegExp("ProductID") + '&NoCopyRight=1',
                async:false,
                cache:false,
                success:function(data){
                    if(!checkLoginStatus(data)){return false;}//是否要重新登陆
                    if(data==0){isNoExists = false;}else{isNoExists = true;}
                },
                error:function(){alert('IsExistProductNo_error2')}
            });
        }
        if(isNoExists){
            alert('此商品编码已存在！');
        }
    });
   
    //--完成
    $('#btnSave').click(function(){
        if(isNoExists){
            alert('此商品编码已存在！');
            return false;
        }
        if($.trim($('#txtProductName').val()) == '')
        {
            alert('捆绑商品名称必须填写');
            return false;
        }
        if($.trim($('#txtProductNo').val()) == ''&& !$('#cbxAutoCreate').attr('checked'))
        {
            alert('商品编码必须填写');
            return false;
        }
        if($.trim($('#txtStorage').val()) == '')
        {
            alert('库存必须填写');
            return false;
        }
        if($.trim($('#txtWeight').val()) == '')
        {
            $('#txtWeight').val('0')
        }
        if($.trim($('#txtMemberPrice').val()) == '')
        {
            alert('捆绑销售价必须填写');
            return false;
        }
        var intReg = new RegExp(/[^\d]/g);//整数
        if($.trim($('#txtUseScore').val()) == ''){alert('最多可使用积分必须填写');return false;}else if(intReg.test($.trim($('#txtUseScore').val()))){alert('最多可使用积分填写不正确');return false;}
        if($.trim($('#count').text()) < 2)
        {
            alert('捆绑商品必须为两件或两件以上');
            return false;
        }
        //--将每种商品的数量放到隐藏控件里面pidsums
        var pID = $.trim($('#PIDs').val()).split(',');
        $('#pidsums').val('');
        for(var i=0; i<pID.length; i++)
        {
            $('#pidsums').val($('#pidsums').val() + ($('#pidsums').val() != '' ? ',' : '') + $('#input_'+pID[i]).val());
        }

//        alert($('#PIDs').val());
//        alert($('#pidsums').val());
//        alert($('#uprices').val());
//        alert($('#pnos').val());
//        alert($('#images').val());
//        return false;
     });
     
     //--测试
    $('#test').click(function(){
        alert($('#PIDs').val());
        alert($('#pidsums').val());
        alert($('#uprices').val());
        alert($('#pnames').val());
        alert($('#pnos').val());
    });
    
});

function getQueryStringRegExp(name)
{
    var reg = new RegExp("(^|\\?|&)" + name.toLowerCase() + "=([^&]*)(\\s|&|$)", "i");
    if (reg.test(location.href.toLowerCase()))
    return unescape(RegExp.$2.replace(/\+/g, " "));
    return "";
}

