var status_spec = 0;//刚进入页面不要列出规格,点击"添加规格"后再获取列表
var status_cat = 0;
var spec = "";
var spec_desc = "";
var spec_length = 1;//货品数
var specChanged=false;
var specDescL = '';
var old_pid_info="";
var temp_catname="";
var temp_catpath="";
var temp_cid=0;
var isSearchGiftsLoaded = false;//标示是否加载了ProductAdd.SearchGifts.js文件，如果为false，则在点击选择礼品时加载这个文件，第一次加载时把这个变量设置为true;

$(document).ready(function(){
    //纪录最开始的商品购买赠送积分点数
    defaultScore=$('#txtScore').val();

	$(document).click(function(){
		$('[@id^=specselect-]').hide();
	});
	$('#container').scroll(function(){
		$('[@id^=specselect-]').hide();
	});
    //loading
    $('#loadingContainer').ajaxStart(function(){$(this).show();$('#loadingbackground').show().css({"opacity": "0.5"});}).ajaxStop(function(){$(this).hide();});
	//修改子商品的时候移除规格添加
	/*if(pid!=gid){
		$(".menuitem").eq(4).remove();
		$(".frame").eq(3).remove();
	};*/
	//if(pid != '0')
//	{
//		$('#add_spec').attr('disabled',true);
		//$('#remove_spec').attr('disabled',true);
//	}

	InitFB(cid);
	if(pid != '0' && cid != '0'){
		$("#cid").attr("value",cid);
        $.ajax({
            url:'ProductAdd_Step2.aspx?type=ajax&Action=GetCatName&cid='+cid+'&ProductID='+pid + '&NoCopyRight=1',
            cache:false,
            success:function(data){
                if(!checkLoginStatus(data)){return false;}//是否要重新登陆
                if(data != ''){
                    $("#catname").text(data.split('|')[0]);
                    $("#catpath").attr("value",data.split('|')[1]);
                }
            },//end seccess
            error:function(){alert('error 1');}
        });//end ajax
        //绑定属性和参数
        Init(pid);
        //if(pid==gid){
			//修改主商品的时候才绑定规格
			BindSpecList();
        //};
        //绑定相关商品删除事件
        BindDeleteEvent(1);
        //绑定附件商品删除事件
        BindDeleteEvent(2);
        //绑定赠送商品删除事件
        BindDeleteEvent(3);
        //绑定赠送礼品删除事件
        BindDeleteEvent(4);
    }
	setInterval(function(){
		if(getQueryStringRegExp('from') != 'list'){
			$('div.save').css('top',$(window).height()-$('div.save').height()); //设置底部分页区域的位置
			$('#container').css('height',$(window).height()-$('div.save').height()-$(".sub_container_title").height()-$(".tabmenu").height()-20); //设置内容区域的高度
		}else{//从列表页面链接过来修改
			var windowHeight = $('#frmHeight',window.parent.document).val();
			$('div.save').css('top',windowHeight-$('div.save').height()); //设置底部分页区域的位置
			$('#container').css('height',windowHeight-$('div.save').height()-$(".sub_container_title").height()-$(".tabmenu").height()-20); //设置内容区域的高度
		}
    },1000);
    
    //设置商品赠送的默认积分.当商品已设有赠送积分时不要再设此值。
    $('#txtMemberPrice').keyup(function(){
        if(defaultScore==0)
        $('#txtScore').val(Math.floor($('#txtMemberPrice').val()*defaultScoreRate));
    });

	//添加规格
    $('#add_spec').click(function(){
        if($('[@id^=ptable_thead-]').length==0 || $('[@id^=ptable_thead-]').children().length <11){
            $('#ShowSpec').popup({width:'60%',height:'80%',popupHead:'SpecHead',btnClose:'popupClose'});
            if(status_spec == 0){BindSpecs('Specs.aspx',"type=ajax&action=GetSpecName");status_spec = 1;};
            $("select").hide();
        }
        else{
            alert("商品最多只能选择二种规格");
        }
    });
    

    $('#remove_spec').click(function(){
		specChanged=true;
        $('[@name=cbsvalue]').attr('checked',false);
		$('#btnSubmit').click();
		$(this).attr('disabled',true);
    });
	
    //确定增加规格
    $('#btnSubmit').click(function(){
           specChanged=true;
           CreateSpecList();
	});
    
    //更改分类
    $("#btnChangeCat").click(function(){
		if(confirm("重新选择分类将重新关联品牌和扩展属性，确认吗？")){
            $('#ShowCategory').popup({width:'60%',height:'80%',popupHead:'SelectCategoryHead',btnClose:'popupClose'});
            if(status_cat == 0){GetCategorys(0,1,$('#catpath').val());status_cat=1;};
		};
    }); 
    
    //更改品牌
    $("#ddlBrand").change(function(){
		if($(this).val() != "0"){		
			$.ajax({
				url:'ProductAdd_Step2.aspx?type=ajax&Action=GetAfterService&bid='+ $(this).val() + '&NoCopyRight=1',
				cache:false,
				success:function(data){
					if(!checkLoginStatus(data)){return false;}//是否要重新登陆
						$("#ftbAfterService").val(data);
						ftbAfterService_editor.focus();
						ftbAfterService_editor.document.open();
						ftbAfterService_editor.document.write("");
						ftbAfterService_editor.document.close();
						var sel = ftbAfterService_editor.document.selection.createRange();
						sel.pasteHTML(data);
				},//end seccess
				error:function(){alert('error 2');}
			});//end ajax
        };
    });
    //20110225 modify by liwenhai
    //绑定多图
    //	if(relatedimgs != '')
    //防止对relatedimgs_m为空时，对其的操作.因为relatedimgs必需是要存在的图片，要不下面的src路径返回的将会是不存在的图。
    if(relatedimgs != ''&&relatedimgs.length>3)
	{
		var relatedimg = relatedimgs.split('|');
		var relatedimg_s = relatedimg[0].split(',');
		var relatedimg_m = relatedimg[1].split(',');
		var relatedimg_b = relatedimg[2].split(',');
		$('#uploadImg').append('');
		for(var i = 0; i < relatedimg_m.length; i++)
		{
			var img_item = $('<div style="float:left;"><img id="img_' + (i+1) + '" src="/Upload/ProductImg/' + folder + '/' + relatedimg_m[i] + '" width="75" height="75" extname="' + (i+1) + '" forname="' + (i+1) + '" /></div>');
			var delete_item = $('<div><input type="checkbox" name="pic_' 
				+ (i+1) + '" value="' + (i+1) + '" extname="' 
				+ (i+1) + '" style="display:none;" /><input type="hidden" name="pics_' 
				+ (i+1) + '" value="' + relatedimg_s[i] + '" /><input type="hidden" name="picm_' 
				+ (i+1) + '" value="' + relatedimg_m[i] + '" /><input type="hidden" name="picb_' 
				+ (i+1) + '" value="' + relatedimg_b[i] + '" /></div>');
			img_item.append(delete_item).appendTo($('#uploadImg'));
            $('<img src="../images/x-red.gif" title=' + relatedimg_m[i] + '>').addClass("delete_img hand").bind("click",function(){
			    var canDelete = true;
			    var thisMImg = $(this).attr("title");
			    $('input[@name^=pics-m-]','#spec_list_tbody').each(function(){
			        var tempPic = $(this).val();
			        if(tempPic.indexOf(thisMImg) > -1){
						canDelete = false;
					}
			    });
			    if(canDelete){
					$(this).parent().parent().remove();
			    }
			    else{
					alert("无法删除，商品规格里面关联了此图片");
					return false;
				}
			}).appendTo(delete_item);
		}
	}

	  //绑定日历控件
    $('.datepicker').datepicker();
    //取消按钮   
    $('#btnCancel').click(function(){
        if(getQueryStringRegExp('from') == 'list'){
            $('#frmModify',window.parent.document).hide().siblings(':not("#loadingContainer")').show();
            return false;
        }else{
            window.location.href = 'Product.aspx?ProductType=Normal';
            return false;
        }
    });	
    settab();//顶部tab
    CheckAlert();
    SetThumbnail();
    $('#cbxNeedAlert').click(function(){CheckAlert()});
    $('#cbxFromBigPic').click(function(){SetThumbnail();});
    $('#customselectCount').val($('select[@name^=ddlFildValues_]').length);//扩展属性Select的个数
    
    if(getQueryStringRegExp('ProductID') == ''){$('#cbxAutoCreate').attr('checked','checked')};//添加商品默认将checkbox选中
    $('#cbxAutoCreate').attr('checked') ? $('#txtProductNo').hide() : $('#txtProductNo').show();
    $('#cbxAutoCreate').click(function(){
        if($(this).attr('checked')){
            $('#txtProductNo').hide();
			if($('[@id^=pproductno-]').length > 0){$('[@id^=pproductno-]').hide();}
			if($('[@id^=auto-]').length > 0){$('[@id^=auto-]').show();}
        }else{
            $('#txtProductNo').show();
			if($('[@id^=auto-]').length > 0){$('[@id^=auto-]').hide();}
			if($('[@id^=pproductno-]').length > 0){$('[@id^=pproductno-]').show();}
        }
    });
    
    //当扩展属性为select控件时,若选择的Value为0,就将文本框显示出来
    $('select[@name^=ddlFildValues_]').each(function(){
        SelectFieldValue($(this));
        $(this).change(function(){
            SelectFieldValue($(this));
        });
    });
    $('input[@id^=txtFieldValue_]').keyup(function(){$(this).val($(this).val().replace(/\|/g,''))});
   
    
    $('#btnAddFile').click(function(){
//        var str = '<br><INPUT type="file" NAME="File"><img src="../Images/reduce.gif" name="reduce" class="reduce" />';
		var str = '<br><INPUT type="file" NAME="File" class="file" class="file" /> <input type="button" name="remove" value="移除" style="height:18px !important;height:17px;border:1px solid #888;vertical-align:middle;"/>';
        $('#FileCollection').append(str);
		$('#NormalUploadCount').val(Number($('#NormalUploadCount').val())+1);
		$('#FileCollection').children('input[@name=remove]').click(function()
		{
			$(this).prev().remove();
			$(this).prev().remove();
			$(this).remove();
			$('#NormalUploadCount').val(Number($('#NormalUploadCount').val())-1);
		});
    });
    //删除相关图片
    $('#dgRelatedImgs .deleteRltImg').each(function(index){
        var obj = $(this);
        obj.click(function(){
            var productID = getQueryStringRegExp('ProductID');
            var img = $(this).attr('img');//要删除的图片名
            $.ajax({
                url:'ProductAdd_Step2.aspx?&type=ajax&Action=DeleteRelatedImgByAjax&ProductID=' + productID + '&ItemIndex=' + index + '&img=' + img + '&NoCopyRight=1',
                cache:false,
                success:function(data){
                    if(!checkLoginStatus(data)){return false;}//是否要重新登陆
                    if(data == 1){
                        obj.parent().parent().remove();//如果返回值为1,就将行删除
                    }    
                },
                error:function(){alert('error 3');}
            });
            return false;
        });
    });
     
	//保存前先检测填写是否正确
    $('#btnSave').click(function(){
        if(!check()){
            return false;
        }else{
            //获取属性参数
			GetPropPara();			
            GetSpecInfo();
	        //获取要添加或要删除的相关商品的ID
	        CountPIDs();
        };

//		return false;
    });
    
    $('#btnAddPresent').click(function(){
        if(!isSearchGiftsLoaded && $('[@name=rdPresentType][@checked]').val() == '2'){
            $.getScript('../inc/ProductAdd.SearchGifts.js');//加载搜索礼品的js
        }
    });
	
});

function SelectFieldValue(obj){
    var index = obj.attr('name').split('_')[1];
    if(obj.val() == '0'){$('#span_fieldvalue_'+index).show();}else{$('#span_fieldvalue_'+index).hide();}
};

//是否显示库存警告数量
function CheckAlert(){if($('#cbxNeedAlert').attr('checked')){$("#mininum").show();}else{$("#mininum").hide();}};
//是否显示缩图宽度
function SetThumbnail(){if($('#cbxFromBigPic').attr('checked')){$("#ThumbnailPic").hide();}else{$("#ThumbnailPic").show();}};

//tab
function settab(){
    var items = $('li.menuitem').length;
    $('li.menuitem').each(function(index){
        $(this).click(function(){
            $(this).addClass('tabon').removeClass('tabout').siblings('.menuitem').removeClass('tabon').addClass('tabout');
            if(index != 0){
                $('div.tab').hide();
                $('div.tab').eq(index - 1).show();
            }else{
                $('div.tab').show();
				if($('[@id^=pproductno-]').length > 0)
				{
					$(".frame").eq(3).hide();
				}
            }
        });
    });
};

    //更改商品价格时按比例设置赠送积分


//检测填写的信息是否合法
function check(){
    //20110305 add by liwenhai
    //当增加货品而又没有选择规格时，是不能保存的，否则会出现商品的规格为请选择。
    if($('[@id^=tdselect-]:contains("--请选择--")').size()>0){
        alert('请选择商品的规格');
        return false;
    }
    var floatReg = new RegExp(/[^\d\.]/g);
    var intReg = new RegExp(/[^\d]/g);//整数
	var posIntReg = /^[1-9]\d*$/;//非负整数
	var flag = true;
    if($('#txtName').val().Trim() == ''){alert('商品名称必须填写'); flag = true; return false;}
    if(pid == '0'){
        $('[@id^=pproductno-]').each(function(i){
			if(flag){
				var id = $(this).attr('id').split('-')[1];
				if($(this).val().Trim() == '' && !$('#cbxAutoCreate').attr('checked')){
					alert('[' + $('#lei-' + id).text() + '] 商品编号必须填写'); flag = false; return false;
				}
				
				if($('#pmarketprice-' + id).val().Trim() == ''){
					alert('[' + $('#lei-' + id).text() + '] 市场价必须填写'); flag = false; return false;
				}
				else if(floatReg.test($('#pmarketprice-' + id).val().Trim())){
					alert('[' + $('#lei-' + id).text() + '] 市场价填写不正确'); flag = false; return false;
				}
				
				if($('#pmemberprice-' + id).val().Trim() == ''){
					alert('[' + $('#lei-' + id).text() + '] 会员价必须填写'); flag = false; return false;
				}
				else if(floatReg.test($('#pmemberprice-' + id).val().Trim())){
					alert('[' + $('#lei-' + id).text() + '] 会员价填写不正确'); flag = false; return false;
				}
				
				if($('[@name^=pstorage-' + id + '-]').length > 0){
					$('[@name^=pstorage-' + id + '-]').each(function(){
						var obj = $(this);
						if(obj.val().Trim() == ''){
							alert('[' + $('#lei-' + id).text() + '] 库存必须填写'); flag = false; return false;
						}
						else if(intReg.test(obj.val().Trim())){
							alert('[' + $('#lei-' + id).text() + '] 库存填写不正确'); flag = false; return false;
						}
					});
				} 
			}			
		});
		if(!flag){
			return false;
		}
    }else{
        if(!$('#cbxAutoCreate').attr('checked')){
			if($('#txtProductNo').val().Trim() == ''){alert('商品编号必须填写');return false;}
			var flag = true;
			$('[@name^=pstorage-]').each(function(i,n){
			    var obj = $(n);
				if(obj.val().Trim() == ''){
					alert('库存必须填写'); flag = false; $('#menu_spec').click(); return false;
				}
				else if(intReg.test(obj.val().Trim())){
					alert('库存填写不正确!'); flag = false; $('#menu_spec').click(); return false;
				}
			});
		}
    };
    if(!flag){
        return false;
    }
		
    if($('#txtUnit').val().Trim() == ''){alert('商品单位必须填写');return false;}
    if($('#txtWeight').val().Trim() == ''){alert('单位重量必须填写');return false;}else if(floatReg.test($('#txtWeight').val().Trim())){alert('单位重量填写不正确');return false;}
    if($('#txtScore').val().Trim() == ''){alert('积分必须填写');return false;}else if(intReg.test($('#txtScore').val().Trim())){alert('积分填写不正确');return false;}
    if($('#txtUseScore').val().Trim() == ''){alert('购买最多可使用积分必须填写');return false;}else if(intReg.test($('#txtUseScore').val().Trim())){alert('购买最多可使用积分填写不正确');return false;}
    if($('#txtMarketPrice').val().Trim() == ''){alert('市场价格必须填写');return false;}else if(floatReg.test($('#txtMarketPrice').val().Trim())){alert('市场价格填写不正确');return false;}
    if($('#txtMemberPrice').val().Trim() == ''){alert('会员价格必须填写');return false;}else if(floatReg.test($('#txtMemberPrice').val().Trim())){alert('会员价格填写不正确');return false;}
    if($('#txtMin').val().Trim() == ''){alert('最低购买量必须填写');return false;}else if(!posIntReg.test($('#txtMin').val().Trim())){alert('最低购买量填写不正确');return false;}
    //if($('#startTime').val().Trim() == ''){alert('上架时间必须填写');return false;};
    //if($('#endTime').val().Trim() == ''){alert('下架时间必须填写');return false;};
    //if($('#lbxCategories').val() == null){alert('请至少选择一个分类');return false;}
    
    //图片格式
    var imgpass = true;
    $('input[@type=file]').each(function(){
        if($(this).val().Trim() != ''){
            var extendName = $(this).val().substring($(this).val().lastIndexOf('.'));
            if(extendName.toLowerCase() != '.gif' && extendName.toLowerCase() != '.jpg'){
                imgpass = false;
            }
        }
    });
    if(!imgpass){alert('产品图片只支持.gif或者.jpg格式');return false;}
    
    if($('#cbxFromBigPic').attr('checked')){if(! posIntReg.test($('#txtPicWidth').val())){alert('缩略图宽度不正确');return false;}}
    if($('#txtStorage').val().Trim() == ''){alert('最新入库数量填写不正确');return false;}else if(intReg.test($('#txtStorage').val().Trim())){alert('最新入库数量填写不正确');return false;}
    if($('#txtMininum').val().Trim() == ''){alert('库存警告数量填写不正确');return false;}else if(intReg.test($('#txtMininum').val().Trim())){alert('库存警告数量填写不正确');return false;}
    
    var isNoExists = false;//判断商品编号是否存在
    if(getQueryStringRegExp("ProductID") == ""){//添加商品
        if(!$('#cbxAutoCreate').attr('checked')){
            $.ajax({
                url:'ProductAdd_Step2.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:'ProductAdd_Step2.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('此商品编号已存在！');return false;}else{return true;};
};

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

function ManageCustomFields(pid){
    temp=window.open('../ProductCustomField.aspx?productid='+pid,'customfield','width=680,height=600,scrollbars=yes,top=0,left=0');
    temp.focus();
};

function BindSpecs(weburl,urldata){
    $.ajax({
        type:"get",
        dataType:"json",
        url:weburl+'?NoCopyRight=1',
        data:urldata,
        cache:false,
        success:function(msg){
            var data = msg.Specs;
             $.each(data,function(i,m){
				$("<li>"+m.SpecName +"</li>").attr("SpecID",m.SpecID).attr("IsMain",m.IsMain).addClass("hand").appendTo($("#spec_name")).click(function(){
					$(this).addClass("selected");
					$(".svalue").hide();
					$(".spec_value_item"+m.SpecID).show();
					
				});
				var spec_value = eval('('+m.SpecValue+')');
				$.each(spec_value,function(j,n){
					$("<li class='svalue'><input type='checkbox' specid='" + m.SpecID + "' name='cbsvalue' value='"+n.value+"'/>"+n.value+"</li>").addClass("spec_value_item"+m.SpecID).addClass("hide").appendTo($("#spec_value"));
				});

             });
        },//end success
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!');parent.window.location="../../adminlogin.aspx";}}
    });//end ajax
};//end funciton

function CreateSpecList(){
	$(".menuitem").eq(4).show();
	if($(".frame").eq(2).is(":visible")){
		$(".frame").eq(3).show();
	}
	$("#trstorage").show();
	var spec_info="{'Specs':[";	
	spec = "{'Specs':[";	
	var flag1=false;
	$('#isModifyMainSpec').val(0);
	$("#spec_name").children().each(function(){
		var temp="";
		var temp0="";
		var contain = "'Contain':[";
		temp += "{'SpecID':'"+$(this).attr("SpecID")+"','SpecName':'"+$(this).text()+"','IsMain':'"+$(this).attr('IsMain')+"','SpecValue':[";
		temp0 += "{'SpecID':'"+$(this).attr("SpecID")+"','SpecName':'"+$(this).text()+"','SpecValue':[";
		var flag2 = false;
		var flag3 = false;
		//alert($(this).attr("SpecID"));
		$(".spec_value_item"+$(this).attr("SpecID")).children("[@checked]").each(function(i){
			temp += "{'value':'"+$(this).val()+"'},";
			contain += "'"+$(this).val()+"',";
			flag1 = true;
			flag2 = true;
			flag3 = true;
		});
		$(".spec_value_item"+$(this).attr("SpecID")).children().each(function(i){
			temp0 += "{'value':'"+$(this).val()+"'},";
		});
		if(flag2){
			temp = temp.substring(0,temp.length-1);
			temp0 = temp0.substring(0,temp0.length-1);
			contain = contain.substring(0,contain.length-1);
		};
		temp += "]},";
		//temp0 += "]},";
		temp0 += "]," + contain + "]},";
		if(flag2){
			spec_info += temp;
			spec += temp0;
		};
	});
	if(flag1){
		spec_info = spec_info.substring(0,spec_info.length-1);
		spec = spec.substring(0,spec.length-1);
	};
	spec_info += "]}";
	spec += "]}";
	$("#spec_list_thead").empty();
	$("#spec_list").empty();
	$('#specUploadCount').val(0);
	var specArray = new Array();
	var selected_spec_info = eval('('+spec_info+')');
	//document.write(spec_info);
	var haveMain = false;
	$('#remove_spec').attr('disabled',true);
	$.each(selected_spec_info.Specs,function(i,m){
		//alert(i);
		$('#remove_spec').attr('disabled',false);
		if(i == 0 && m.IsMain == '1')
		{
			haveMain = true;
			$(".menuitem").eq(4).hide();
			$(".frame").eq(3).hide();
			$("#trstorage").hide();
			$.each(m.SpecValue,function(j,n){
				$('<tr><td width="100px"><input type="hidden" value="' + n.value + '" name="specname-' + (j+1) + '" /><span id="lei-' + (j+1) + '">' + m.SpecName + '：'
				  + n.value + '</td><td width="200px">商品编号：<input id="pproductno-' + (j+1)
				  + '" name="pproductno-' + (j+1) + '" value="'
				  + ($('#cbxAutoCreate').attr('checked') == true ? '' : ($.trim($('#txtProductNo').val()) != '' ? ($.trim($('#txtProductNo').val()) + '-' + (j+1)) : ''))//($('#cbxAutoCreate').attr('checked',true) ? '' : ($('#txtProductNo').val() + '-' + (j+1)))
				  + '"  size="15" /><span id="auto-' + (j+1) + '" style="color:blue;">自动生成</span></td><td width="200px">市场价：<input id="pmarketprice-' + (j+1)
				  + '" name="pmarketprice-' + (j+1) + '" value="' + $('#txtMarketPrice').val() + '" size="15" /></td><td width="200px">会员价：<input id="pmemberprice-' + (j+1)				  
				  + '" name="pmemberprice-' + (j+1) + '" value="' + $('#txtMemberPrice').val() + '" size="15" /></td><td name="pstorage" width="200px">库存：<input id="pstorage-' + (j+1) + '-1" name="pstorage-' + (j+1) + '-1" value="' + $('#txtStorage').val() + '" size="15" /></td><td width="100px"><span id="spanShow-' + (j+1) + '" style="cursor:pointer; color:blue;"><u>图片管理</u></span>'
				  
				  //图片管理div部分开始
				  + '<div id="div-' + (j+1) + '" style="position:absolute; top:100px; right:400px;width:320px; display:none;"><div style="border:solid 1px #666666; text-align:right;">'
				  + '<div id="divc-' + (j+1) + '" style="background-color:#666666;width:320px; height:20px; line-height:20px;"><div style="width:200px;float:left;">' + m.SpecName + '：'
				  + n.value + '</div><div id="spanClose-' + (j+1) + '" style="cursor:pointer;float:right;">关闭</div></div>'
				  + '<table cellpadding="10" cellspacing="0" style="border-spacing: 0px; border-color: #C0C0C0;" border="1" bgcolor="#EEEEEE" width="320px">'
				  + '<tr><td width="60px">商品大图：</td><td style="text-align:left"><input type="file" size="15" name="File" class="file" /></td></tr>'
				  + '<tr><td>商品小图：</td><td style="text-align:left"><input type="file" size="15" name="File" class="file" /></td></tr>'
				  + '<tr><td>商品多图：</td><td style="text-align:left"><p id="FileCollection-' + (j+1) + '"><input type="file" size="15" name="File" class="file" /></td></tr>'				  
				  + '<tr><td colspan="2" style="text-align:center"><input type="hidden" name="specUploadCount-' + (j+1) + '" value="3" /><input type="button" id="btnAddFile-' + (j+1) + '" value="增加多图" class="inputbtn"><input type="button" name="btnImgSure" value="确 定" class="inputbtn"></td></tr>'
				  + '</table></div></div>'
				  //图片管理div部分结束	
				  			  
				  + '</td><td>&nbsp;</td></tr><tr id="spec-' + (j+1)
				  + '"><td colspan="6"><table class="tableBorder" cellspacing="0" cellpadding="0" width="50%" align="left" border="1" id="ptable-' + (j+1)
				  + '"><thead><tr id="ptable_thead-' + (j+1) + '"></tr></thead><tbody id="ptable_tbody-' + (j+1) + '"><tr></tr><tbody></table></td></tr>').appendTo($("#spec_list"));
			
				$('#btnAddFile-' + (j+1)).click(function(){
					var str = '<br><input type="file" size="15" name="File" class="file" /> <input type="button" name="remove" value="移除" class="file" style="height:18px !important;height:17px;border:1px solid #888;vertical-align:middle;"/>';
					$('#FileCollection-' + (j+1)).append(str);
					
					$('#FileCollection-' + (j+1)).children('input[@name=remove]').click(function()
					{
						$(this).prev().remove();
						$(this).prev().remove();
						$(this).remove();
						$('[@name=specUploadCount-' + (j+1) + ']').val(Number($('[@name=specUploadCount-' + (j+1) + ']').val()) - 1);
					});
					
					$('[@name=specUploadCount-' + (j+1) + ']').val(Number($('[@name=specUploadCount-' + (j+1) + ']').val()) + 1); //--每组有几个需要上传的
				});
				$('#spanShow-' + (j+1)).click(function(){
					$('[@id^=div-]').hide();
					$('#div-' + $(this).attr('id').split('-')[1]).show();
				});

				$('#spanClose-' + (j+1)).click(function(){
					$('#div-' + $(this).attr('id').split('-')[1]).hide();
				});
				
				if($('#cbxAutoCreate').attr('checked'))
				{
					$('#pproductno-' + (j+1)).hide();
				}
				else
				{
					$('#auto-' + (j+1)).hide();
				}
				//--拖动开始
				$('#div-' + (j+1)).easydrag();
        		$('#div-' + (j+1)).setHandler('divc-' + (j+1));
				//--拖动结束
				$('[@name=btnImgSure]').click(function(){$('[@id^=div-]').hide();});
				$('#specUploadCount').val(Number($('#specUploadCount').val()) + 1);//--看有几组需要上传的
				
			});
		}
		else if(i == 0 && m.IsMain == '0')
		{
			$('<tr id="spec-1"><td><table class="tableBorder" cellspacing="0" cellpadding="0" width="90%" align="left" border="1" id="ptable-1"><thead><tr id="ptable_thead-1"></tr></thead><tbody id="ptable_tbody-1"><tr></tr><tbody></table></td></tr>').appendTo($("#spec_list"));
			$("<td width='100px'>"+m.SpecName+"</td>").addClass("hd").appendTo($('[id^=ptable_thead-]'));
			$('#specUploadCount').val(0);//--规格图片数量
		}
		else
		{
			$('td[@name=pstorage]').remove();
			$("<td width='100px'>"+m.SpecName+"</td>").addClass("hd").appendTo($('[id^=ptable_thead-]'));
		}
		
		if(i==selected_spec_info.Specs.length-1 && (i!=0 || i==0 && !haveMain)){
			$("<td width='150px'>商品编号</td><td width='100px'>市场价</td><td width='100px'>会员价</td><td width='100px'>积分</td><td width='100px'>重量</td><td width='100px'>库存</td><td>图片管理</td><td width='80px'>操作</td><td>&nbsp;</td>").addClass("hd").appendTo($('[id^=ptable_thead-]'));
		}
		else if(i==selected_spec_info.Specs.length-1 && i==0 && haveMain)
		{
			$('[id^=spec-]').hide();
		}

		var svalue="";
		$.each(m.SpecValue,function(p,q){									
			if(i == 0 && haveMain)
			{
				haveMain = true;
			}
			else
			{
				if(p == m.SpecValue.length-1)
				{
					svalue += q.value;
				}
				else
				{
					svalue += q.value + ",";
				}
			}
		});
		if(svalue != "")
		{
			specArray.push(svalue);
		}
	});//end each
	//获取规格的组合个数
	if($('[id^=ptable_tbody-]').length > 0)
	{
		$('[id^=ptable_tbody-]').children().remove();
	}
	
	if(specArray.length > 0){
	    var zuheResult=null;
	    zuheResult = CC(specArray,specArray.length,0);
		spec_length = zuheResult.length;
	    for(var i=0;i<zuheResult.length;i++){
		    //自动生成编码
		    //var obj="<td><input type='text' name='pno' value='"+CreateNo(i)+"' /></td>";
		    var obj="<tr>";
		    for(var j=0;j<zuheResult[i].length;j++){
			    obj += "<td>"+zuheResult[i][j]+"</td>";
		    };
			obj += "<td width='150px'><input id='pproductno-" + (i+1)
				  + "' name='pproductno-" + (i+1) + "' value='"
				  + ($("#cbxAutoCreate").attr("checked") == true ? "" : ($.trim($("#txtProductNo").val()) != "" ? ($.trim($("#txtProductNo").val()) + "-" + (i+1)) : ""))//($("#cbxAutoCreate").attr("checked",true) ? "" : ($("#txtProductNo").val() + "-" + (j+1)))
				  + "'  size='17' /></td><td width='100px'><input type='text' id='pmarketprice-" + (i+1) + "' name='pmarketprice-" + (i+1)
				  + "' value='" + $.trim($("#txtMarketPrice").val()) + "' size='10' style='text-align:center;' /></td><td width='100px'><input type='text' id='pmemberprice-" + (i+1) + "' name='pmemberprice-" + (i+1)
				  + "' value='" + $.trim($("#txtMemberPrice").val()) + "' size='10' style='text-align:center;' /></td><td width='100px'><input type='text' id='pscore-" + (i+1) + "' name='pscore-" + (i+1)
				  + "' value='" + $.trim($("#txtStorage").val()) + "' size='10' style='text-align:center;' /></td><td width='100px'><input type='text' id='pweight-" + (i+1) + "' name='pweight-" + (i+1)
				  + "' value='" + $.trim($("#txtWeight").val()) + "' size='10' style='text-align:center;' /></td><td><input type='text' id='pstorage-" + (i+1) + "' name='pstorage-" + (i+1)
				  + "' value='" + $('#txtStorage').val() + "' size='10' style='text-align:center;' /></td><td width='80px'><span id='spanShow-" + (i+1) + "' style='cursor:pointer; color:blue;'><u><input type='hidden' name='sno' value='" + (i+1) + "' /><input type='hidden' name='pics-b-" + (i+1) + "' value='' /><input type='hidden' name='pics-m-" + (i+1) + "' value='' /><input type='hidden' name='pics-s-" + (i+1) + "' value='' />图片管理</u></span></td><td id='delete-" + (i+1)
				  + "'>"  
				  
				  //图片管理div部分开始
				  + "<div id='div-" + (i+1) + "' style='position:absolute; top:100px; right:400px;width:320px; display:none;'><div style='border:solid 1px #666666; text-align:right;'>"
				  + "<div id='divc-" + (i+1) + "' style='background-color:#666666;width:320px; height:20px; line-height:20px;'><div style='width:200px;float:left;'>"
				  + "</div><div id='spanClose-" + (i+1) + "' style='cursor:pointer;float:right;'>关闭&nbsp;&nbsp;</div></div>"
				  + "<div id='divd-" + (i+1) + "' style='width:100%;height:200px;background-color:white;overflow-y:scroll;'></div><div style='text-align:center; width:100%;background-color:white; height:30px; line-height:30px;'><input type='button' name='btnImgSure-" + (i+1) 
				  + "' value='确 定' class='inputbtn'></div></div></div>"
				  //图片管理div部分结束				  
				  
				  + "</td><td>&nbsp;</td></tr>";
			$(obj).addClass("hd").appendTo($('[id^=ptable_tbody-]'));
		    $("<span>删除</span>").addClass("hand").click(function(){
				if($(this).parent().parent().parent().children().length < 2)
				{
					alert('无法再删除！');
				}
				else
				{
			    	$(this).parent().parent().remove();
				}
		    }).appendTo($('[id^=delete-' + (i+1) + ']'));
		    
			$('#spanShow-' + (i+1)).click(function(){
			    $('[@id^=div-]').hide();
			    var numid = $(this).attr('id').split('-')[1];
			    $('#div-' + numid).show();
			    $('#divd-' + numid).empty();
			    $('#uploadImg').children().clone().appendTo($('#divd-' + numid));
	            $('#divd-' + numid).find('[@class^=delete_img]').remove();
			    $('#divd-' + numid).find('[@name^=pic_]').show();					
			    $('#divd-' + numid).find('[@name^=pic_]').show().each(function(){
				    if($('[@name=pics-m-' + numid + ']').val().indexOf($('[@name=picm_' + $(this).val() + ']').val()) > -1)
				    {
					    $(this).attr('checked',true);
				    }
			    });
			});
			$('#spanClose-' + (i+1)).click(function(){
				$('#div-' + $(this).attr('id').split('-')[1]).hide();
			});
			//--拖动开始
			$('#div-' + (i+1)).easydrag();
			$('#div-' + (i+1)).setHandler('divc-' + (i+1));
			//--拖动结束
			$('[@name=btnImgSure-' + (i+1) + ']').click(function(){
				//alert('btnImgSure clicked');
				var id = $(this).attr('name').split('-')[1];
				var pics_b = '';
				var pics_m = '';
				var pics_s = '';
				$('#divd-' + id).contents().find('input[checked]').each(function(){
					pics_b += (pics_b != '' ? ',' : '') + ($('[@name=picb_' + $(this).val() + ']').val().replace(/%20/g,' '));
					pics_m += (pics_m != '' ? ',' : '') + ($('[@name=picm_' + $(this).val() + ']').val().replace(/%20/g,' '));
					pics_s += (pics_s != '' ? ',' : '') + ($('[@name=pics_' + $(this).val() + ']').val().replace(/%20/g,' '));
				});
				$('[@name=pics-b-' + id + ']').val(pics_b);
				$('[@name=pics-m-' + id + ']').val(pics_m);
				$('[@name=pics-s-' + id + ']').val(pics_s);
				$('[@id^=div-' + id + ']').hide();
			});
			//--给相应的控件赋好name
	    };
	}
	else{
	};
};

function CC(arr,num,item){
	var r=[];
	(function f(t,a,len,it){
		if(it < len){
			for(var i=0;i<a[it].split(',').length;i++){
				f(t.concat(a[it].split(',')[i]),a,len,it+1);
			};
		}else{
			r.push(t);
		};
	})
	([],arr,num,item);
	return r;
}

function CreateNo(item){
	item++;
	var pno = null;
	if($("#txtProductNo").val()!=""){
		pno=$("#txtProductNo").val()+"-"+Array(2).join("0").concat(item).slice(-2);
	}else{
		pno="";
	};
	return pno;
};
function GetSpecInfo(){
	$("#hidden_info").empty();
	$("<input type='hidden' name='spec_num'/>").val($('input[@name^=pproductno-]').length).appendTo($("#hidden_info"));
	$("<input type='hidden' name='spec_length'/>").val(spec_length).appendTo($("#hidden_info"));
	
	var allpics = '';
	var allpicm = '';
	var allpicb = '';
	$('#uploadImg').find('[@name^=pics_]').each(function(){
		allpics += (allpics != '' ? ',' : '') + $(this).val().replace(/%20/g,' ');//替换文件名中的空格
	});
	$('#uploadImg').find('[@name^=picm_]').each(function(){
		allpicm += (allpicm != '' ? ',' : '') + $(this).val().replace(/%20/g,' ');
	});
	$('#uploadImg').find('[@name^=picb_]').each(function(){
		allpicb += (allpicb != '' ? ',' : '') + $(this).val().replace(/%20/g,' ');
	});
	$('<input type="hidden" name="allpic" />').val(allpics + '|' + allpicm + '|' + allpicb).appendTo($("#hidden_info"));
	
	var spec_str="";
	//$('[@id=ptable_tbody-1]')
	//20110123 modify by liwenhai 当新加商品没有增加规则时要略过
	if($('[@id^=spec-]').length>0){
	    if($('[@id=ptable_tbody-1]').length > 0)//添加商品的时候选择规格后构造的货品数量，大于0则为添加商品，否则为修改商品
	    {
		    $("<input type='hidden' name='spec'/>").val(spec).appendTo($("#hidden_info"));
		    $('[@id=ptable_tbody-1]').each(function(i){
			    var spec_desc = "{'MainDesc':'" + ($('[@name^=specname-]').length == 0 ? '' : $('[@name=specname-'+(i+1)+']').val()) + "','Goods':[";
			    var $tempTBody = $(this);
			    var tempstrL = '';
			    var no = $tempTBody.attr('id').split('-')[1];
			    $tempTBody.children().each(function(j){
				    var $tempTr = $(this);
				    var tempstr = '';
				    tempstrL = '';
				    var specval='';
				    for(var kk=0;kk<$(this).children().length-9;kk++){ 
                        specval += $tempTr.find('td:eq('+kk+')').text()+" ";
                    }
                    specval=$.trim(specval);
//				    var specval = $tempTr.find('td:eq(0)').text() + ' ' + $tempTr.find('td:eq(1)').text();
    //				alert($tempTr.find('td:eq(0)').html());
    //				alert($tempTr.find('td:eq(2)').html());
				    spec_str += specval;
				    tempstr += specval;
				    var ptable_thead = $('#ptable_thead-' + no);
                    for(var p=0;p<$(this).children().length-9;p++){ 
                        tempstrL += ptable_thead.find('td:eq('+p+')').text()+" ";
                    }
                    tempstrL=$.trim(tempstrL);
    //				if($(this).children().length>10){
    //				    tempstrL += ptable_thead.find('td:eq(0)').text() + ' ' + ptable_thead.find('td:eq(1)').text(); 
    //                    alert("spec"+tempstrL+"|");
    //				}
    //				else{
    //				    tempstrL += ptable_thead.find('td:eq(0)').text(); 
    //                       alert("spec"+tempstrL+"||");
    //                }
				    spec_desc += "{'GID':'{GID-" + (j+1) + "}','Desc':'" + tempstr + "'}";
				    if(j!=$tempTBody.children().length-1){spec_desc += ",";};
			    });
			    if(tempstrL == '')
			    {
				    spec_desc += "{'GID':'{GID-1}','Desc':''}";
			    }
			    spec_desc += "],'DescL':'" + tempstrL + "'}";
			    $("<input type='hidden' name='spec_desc-" + (i+1) + "'/>").val(spec_desc).appendTo($("#hidden_info"));
		    });
	    }
	    else//修改商品
	    {
		    var specAll_info = eval('('+specAll+')');
		    spec = specAll;
		    $.each(specAll_info.Specs,function(i,n){
		        var old_contain = "'Contain':[";
		        var new_contain = "'Contain':[";
		        $.each(n.Contain,function(j,m){
		            old_contain += "'" + m + "'";
		            if(j != n.Contain.length-1){
		                old_contain += ",";	            
		            }
		        });
		        old_contain += "]";
		        var arrSpec = new Array();
		        $('[@id^=tdselect-'+n.SpecName+'-]').each(function(){	
		            arrSpec.push($(this).text());
		        });
		        arrSpec = unique(arrSpec);
		        $.each(arrSpec,function(p,q){
		            new_contain += "'" + q + "'";
		            if(p != arrSpec.length-1){
		                new_contain += ",";
		            }
		        });
		        new_contain += "]";
		        spec = spec.replace(old_contain,new_contain);
		    });
		    $("<input type='hidden' name='spec'/>").val(spec).appendTo($("#hidden_info"));
		    var spec_desc = "{'MainDesc':'" + ($('[@name^=specname-]').length == 0 ? '' : $('[@name=specname-'+(i+1)+']').val()) + "','Goods':[";
		    var tempstrL = '';
		    $('[@id^=spec-]').each(function(j){
			    if(j > 0)
			    {
				    var $tempTr = $(this);
				    var tempstr = '';
				    tempstrL = '';
				    var specval = $tempTr.find('td:eq(0)').text() + ' ' + $tempTr.find('td:eq(1)').text();
				    //20110211 modify by liwenhai,当只有一个规则时要去掉后面的空格，要不在绑定规格组合表格时会把一个规则通过split(' ')折分成二个规则导致绑定出错
                    specval=$.trim(specval);
				    spec_str += specval;
				    tempstr += specval;
				    spec_desc += "{'GID':'{GID-" + j + "}','Desc':'" + tempstr + "'}";
				    if(j!=$('[@id^=spec-]').length-1){spec_desc += ",";};
			    }
		    });
		    if(tempstrL == '')
		    {
			    //spec_desc += "{'GID':'{GID-1}','Desc':''}";
		    }
		    spec_desc += "],'DescL':'" + specDescL + "'}";
    //		alert(spec);
    //		alert(spec_desc);
		    $("<input type='hidden' name='spec_desc-1'/>").val(spec_desc).appendTo($("#hidden_info"));//给specdesc赋值，以便后台获取
	    }
	}
};

function BindSpecList(){
	$('#add_spec').hide();
	$('#remove_spec').hide();
	//增加货品开始
	$('#addnew_spec').click(function(){
		spec_length ++;//货品数加1
		//alert(spec_length);
		var n = Number($('[@id^=spec-]').eq($('[@id^=spec-]').length-1).attr('id').split('-')[1]);
        var rowhtml = '';
		$('#spec-' + n).find('[@id^=tdselect-]').each(function(){
		    rowhtml += '<td width="100px" id="' + 'tdselect-' + $(this).attr('id').split('-')[1] + '-' + (n+1) + '" class="hd hand"><span style="color: blue;">--请选择--</span></td>';
		})
		rowhtml += '<td width="150px" class="hd"><input type="text" style="text-align: center;" size="17" value="" name="pproductno-' + (n+1) + '"></td>';
		rowhtml += '<td width="100px" class="hd"><input type="text" style="text-align: center;" size="10" value="0.00" name="pmarketprice-' + (n+1) + '" id="pmarketprice-' + (n+1) + '"></td>';
		rowhtml += '<td width="100px" class="hd"><input type="text" style="text-align: center;" size="10" value="0.00" name="pmemberprice-' + (n+1) + '" id="pmemberprice-' + (n+1) + '"></td>';
		rowhtml += '<td width="100px" class="hd"><input type="text" style="text-align: center;" size="10" value="0" name="pscore-' + (n+1) + '" id="pscore-' + (n+1) + '"></td>';
		rowhtml += '<td width="100px" class="hd"><input type="text" style="text-align: center;" size="10" value="0.00" name="pweight-' + (n+1) + '" id="pweight-' + (n+1) + '"></td>';
		rowhtml += '<td width="100px" class="hd"><input type="hidden" value="540" name="gid-' + (n+1) + '"><input type="text" style="text-align: center;" size="10" value="0" name="pstorage-' + (n+1) + '"></td>';
		rowhtml += '<td class="hd"><span style="cursor: pointer; color: blue;" id="spanShow-' + (n+1) + '"><u><input type="hidden" name = "sno" value="' + (n+1) + '"/><input type="hidden" value="nopic.gif" name="pics-b-' + (n+1) + '"><input type="hidden" value="nopic.gif" name="pics-m-' + (n+1) + '"><input type="hidden" value="nopic.gif" name="pics-s-' + (n+1) + '">图片管理</u></span></td>';
		rowhtml += '<td width="100px" id="tdelete_' + Math.random() + '" class="hd"><div style="position: absolute; top: 100px; right: 400px; width: 320px; display: none;" id="div-' + (n+1) + '"><div style="border: 1px solid rgb(102, 102, 102); text-align: right;"><div style="background-color: rgb(102, 102, 102); width: 320px; height: 20px; line-height: 20px; cursor: move;" id="divc-' + (n+1) + '"><div style="width: 200px; float: left;"></div><div style="cursor: pointer; float: right;" id="spanClose-' + (n+1) + '">关闭&nbsp;&nbsp;</div></div><div style="width: 100%; height: 200px; background-color: white;" id="divd-' + (n+1) + '"></div><div style="text-align: center; width: 100%; background-color: white; height: 30px; line-height: 30px;"><input type="button" class="inputbtn" value="确 定" name="btnImgSure-' + (n+1) + '"></div></div></div><span id="delete_' + Math.random() + '" class="hand">删除</span></td>';
		rowhtml += '<td class="hd">&nbsp;</td>';
		
		var newrow = $('<tr id="spec-' + (n+1) + '">' + rowhtml + '</tr>');
		newrow.find('[@id^=delete_]').attr('id','delete_'+Math.random());
		//删除货品开始
		newrow.find('[@id^=delete_]').click(function(){
		    //20101106黎宇修改，解决IE新赠规格不能删除，但如果连续新增1个以上规格，IE里删除事件丢失
		    if(spec_length < 2)
		    {
			    alert('无法再删除！');
		    }
		    else
		    {
			    var rname = '';
			    $('#spec-' + (n+1)).find('[@id^=tdselect-]').each(function(){
				    rname += (rname != '' ? ',' : '') + $(this).text();
			    });
			    $('[@id=' + rname + ']').val('false');
			    $('#spec-' + (n+1)).remove();
		    }
    		
		    /***
		    if($(this).parent().parent().parent().children().length < 2)
		    {
			    alert('无法再删除！');
		    }
		    else
		    {
			    //--光删除还不行，还得将相关的内容置为false
			    var rname = '';
			    $(this).parent().parent().find('[@id^=tdselect-]').each(function(){
				    rname += (rname != '' ? ',' : '') + $(this).text();
			    });
			    $('[@id=' + rname + ']').val('false');
			    $(this).parent().parent().remove();
		    }
		    ***/
		});//删除货品结束
		//newrow.find('[@id^=tdselect-]').html('<span style="color:blue">--请选择--</span>');
		newrow.appendTo($('#spec_list_tbody'));
		
		//绑定添加货品的时候选择规格的click事件
		$('[@id^=tdselect-][@id$=-' + (n+1) + ']').addClass("hand").find('span').click(function(e){
			var objTD = $(this).parent();
			var option = objTD.attr('id').split('-')[1];
			$('[@id^=specselect-]').hide();
			var offset = objTD.offset();
			$('#specselect-' + option).show().css('top',offset.top).css('left',offset.left + 102).css("width","100px").find('[@id^=specCell-]').each(function(k){
				var specid = '';
				var cell = $(this).attr('id').split('-')[1];
				var rname = '';
				$('[@id^=specselect-]').each(function(){
					var o = $(this).attr('id').split('-')[1];
					rname += (rname != '' ? ',' : '') + $('#tdselect-' + o + '-' + (n+1)).text();
					if(option == o)
					{
						specid += (specid != '' ? ',' : '') + cell;
					}
					else
					{
						specid += (specid != '' ? ',' : '') + $('#tdselect-' + o + '-' + (n+1)).text();
					}
				});
				if($('[@id=' + specid + ']').val() == 'true' && cell != $('#tdselect-' + option + '-' + (n+1)).text())
				{
					$(this).removeClass('sepc_click').addClass('sepc_no_click').unbind();
				}
				else
				{
					$(this).removeClass('sepc_no_click').addClass('sepc_click').unbind().click(function(){
						//$('#tdselect-' + option + '-' + (n+1)).text($(this).text());
						$('#tdselect-' + option + '-' + (n+1)).find('span').text($(this).text());//11-29 wangyao
						$('[@id^=specselect-]').hide();
						$('[@id=' + rname + ']').val('false');
						$('[@id=' + specid + ']').val('true');
					});
				}
			});
			e.stopPropagation();
		});		
		
		$('#spanShow-' + (n+1)).click(function(){
			$('[@id^=div-]').hide();
			var numid = (n+1);
			$('#div-' + numid).show();
			$('#divd-' + numid).empty();
			$('#uploadImg').children().clone().appendTo($('#divd-' + numid));
	        $('#divd-' + numid).find('[@class^=delete_img]').remove();
			$('#divd-' + numid).find('[@name^=pic_]').show();					
			$('#divd-' + numid).find('[@name^=pic_]').show().each(function(){
				if($('[@name=pics-m-' + numid + ']').val().indexOf($('[@name=picm_' + $(this).val() + ']').val()) > -1)
				{
					$(this).attr('checked',true);
				}
			});
		});
		
		$('[@name=btnImgSure-' + (n+1) + ']').click(function(){
			var id = n+1;
			var pics_b = '';
			var pics_m = '';
			var pics_s = '';
			$('#divd-' + id).contents().find('input[checked]').each(function(){
				pics_b += (pics_b != '' ? ',' : '') + ($('[@name=picb_' + $(this).val()+ ']').val().replace(/%20/g,' '));
				pics_m += (pics_m != '' ? ',' : '') + ($('[@name=picm_' + $(this).val() + ']').val().replace(/%20/g,' '));
				pics_s += (pics_s != '' ? ',' : '') + ($('[@name=pics_' + $(this).val() + ']').val().replace(/%20/g,' '));
			});
			$('[@name=pics-b-' + id + ']').val(pics_b);
			$('[@name=pics-m-' + id + ']').val(pics_m);
			$('[@name=pics-s-' + id + ']').val(pics_s);
			$('[@id^=div-' + id + ']').hide();
		});
		
		$('#spanClose-' + (n+1)).click(function(){
			$('#div-' + (n+1)).hide();
		});
		
		//--拖动开始
		$('#div-' + (n+1)).easydrag();
		$('#div-' + (n+1)).setHandler('divc-' + (n+1));
	});
	//--点击新增货品结束	
	
	var specAllArray = new Array();
//	alert(specAll);
    //20110305 add by liwenhai
    //如果specAll不是以"{'Specs':[")开头的话就直接给它个默认值{'Specs':[],'Contain':[]}，因为SpecAll是有规律的，没有规格是{'Specs':[],'Contain':[]}，有规格的话是以{'Specs':[开头。
    if(specAll.indexOf("{'Specs':[")!=0){
        specAll="{'Specs':[],'Contain':[]}";
    }
	var specAll_info = eval('('+specAll+')');
	if(specAll_info.Specs.length > 0){$('#addnew_spec').show();}
	$.each(specAll_info.Specs,function(i,m){
		var svalue="";
		$('<input type="hidden" name="specOptions-' + (i+1) + '" value="" >').appendTo($('#specAll'));
		$.each(m.SpecValue,function(p,q){
			$('input[@name=specOptions-' + (i+1) + ']').val($('input[@name=specOptions-' + (i+1) + ']').val() + ($('input[@name=specOptions-' + (i+1) + ']').val() != '' ? ',' : '') + q.value);
			if(p == m.SpecValue.length-1)
			{
				svalue += q.value;
			}
			else
			{
				svalue += q.value + ",";
			}
		});
		if(svalue != "")
		{
			specAllArray.push(svalue);
		}
	});
	
	var zuheResult=null;
	zuheResult = CC(specAllArray,specAllArray.length,0);
	for(var i=0;i<zuheResult.length;i++){
		var hidden = '';
		for(var j = 0; j < zuheResult[i].length; j++)
		{
			hidden += (hidden != '' ? ',' : '') + zuheResult[i][j];
		}
		
		$('<input type="hidden" id="' + hidden + '" value="false" name="spechidden" />').appendTo($('#specAll'));
	}	
	//绑定规格组合表格
	$.ajax({
		type:"get",
		dataType:"json",
		url:'ProductAdd_Step2.aspx?NoCopyRight=1',
		data:'type=ajax&action=GetSpecDesc&cid='+cid+'&ProductID='+pid,
		cache:false,
		success:function(msg){
			var data = msg.Goods;
			spec_length = msg.Goods.length;
			$('<tr id="spec-0"></tr>').addClass("hd").appendTo($("#spec_list"));
			
			if(msg.DescL != '')
			{
				specDescL = msg.DescL;
				var descL = msg.DescL.split(' ');
				for(var v = 0; v < descL.length; v++)
				{
					var one = '';
					var specOne = $('[@name=specOptions-' + (v+1) + ']').val().split(',');
					for(var p = 0; p < specOne.length; p++)
					{
						one += '<span class="one" id="specCell-' + specOne[p] + '" onmouseover="this.style.backgroundColor=\'#EEEEEE\'" onmouseout="this.style.backgroundColor=\'#FFFFFF\'">' + specOne[p] + '</span>&nbsp;';
					}
					$('<td width="100px">' + descL[v] + '<div id="specselect-' + descL[v] + '" style="position:absolute;display:none; background-color:white; padding:5px;border:solid #3366CC 1px;">' + one + '</div>' + '</td>').appendTo($("#spec-0"));
				}
			}
			$("<td width='150px'>货品编号</td><td width='100px'>市场价</td><td width='100px'>会员价</td><td width='100px'>积分</td><td width='100px'>重量</td><td width='100px'>库存</td><td width='80px'>图片管理</td><td width='100px'>操作</td><td>&nbsp;</td>").appendTo($("#spec-0"));
			
			$.each(data,function(i,m){
				//记录修改前的商品ID
				$('<tr id="spec-' + (i+1) + '"></tr>').appendTo($("#spec_list"));
				var obj = '';
				if(msg.DescL != '')
				{
				//20110224 modify by liwenhai 
//				var desc=$.trim(m.Desc);
				//去掉Desc尾部中可能会出现的空格
					var desc = $.trim(m.Desc).split(' ');
//					var desc = m.Desc.split(' ');
					var show = '';
					for(var j = 0; j < desc.length; j++)
					{
						obj += '<td width="100px" id="tdselect-' + descL[j] + '-' + (i+1) + '">' + desc[j] + '</td>';
						show += (show != '' ? ',' : '') + desc[j];
					}
					$('[@id=' + show + ']').val('true');
				}
				
				obj += "<td width='150px'><input type='text' name='pproductno-" + (i+1) + "' value='" + m.GoodsNo + "' size='17' style='text-align:center;' /></td>";
				obj += "<td width='100px'><input type='text' id='pmarketprice-" + (i+1) + "' name='pmarketprice-" + (i+1) + "' value='" + m.MarketPrice + "' size='10' style='text-align:center;' /></td>";
				obj += "<td width='100px'><input type='text' id='pmemberprice-" + (i+1) + "' name='pmemberprice-" + (i+1) + "' value='" + m.MemberPrice + "' size='10' style='text-align:center;' /></td>";
				obj += "<td width='100px'><input type='text' id='pscore-" + (i+1) + "' name='pscore-" + (i+1) + "' value='" + m.Score + "' size='10' style='text-align:center;' /></td>";
				obj += "<td width='100px'><input type='text' id='pweight-" + (i+1) + "' name='pweight-" + (i+1) + "' value='" + m.Weight + "' size='10' style='text-align:center;' /></td>";
				
				obj += "<td width='100px'><input type='hidden' name='gid-" + (i+1) + "' value='" + m.GID + "' /><input type='text' name='pstorage-" 
					+ (i+1) + "' value='" + m.Storage + "' size='10' style='text-align:center;' /></td><td>     <span id='spanShow-" 
					+ (i+1) + "' style='cursor:pointer; color:blue;'><u><input type='hidden' name = 'sno' value='" + (i+1) + "'/><input type='hidden' name='pics-b-" 
					+ (i+1) + "' value='" + m.BPicture + "' /><input type='hidden' name='pics-m-" 
					+ (i+1) + "' value='" + m.MPicture + "' /><input type='hidden' name='pics-s-" 
					+ (i+1) + "' value='" + m.SPicture + "' />图片管理</u></span></td><td width='100px' id='tdelete_" + m.GID + "'>"
					
					//图片管理div部分开始
					+ "<div id='div-" + (i+1) + "' style='position:absolute; top:100px; right:400px;width:320px; display:none;'><div style='border:solid 1px #666666; text-align:right;'>"
					+ "<div id='divc-" + (i+1) + "' style='background-color:#666666;width:320px; height:20px; line-height:20px;'><div style='width:200px;float:left;'>"
					+ "</div><div id='spanClose-" + (i+1) + "' style='cursor:pointer;float:right;'>关闭&nbsp;&nbsp;</div></div>"
					+ "<div id='divd-" + (i+1) + "' style='width:100%;height:200px;background-color:white;'></div><div style='text-align:center; width:100%;background-color:white; height:30px; line-height:30px;'><input type='button' name='btnImgSure-" + (i+1) 
					+ "' value='确 定' class='inputbtn'></div></div></div>"
					//图片管理div部分结束	
					+ "</td><td>&nbsp;</td>";
				
				$(obj).addClass("hd").appendTo($("#spec-" + (i+1)));
				$('[@id^=tdselect-][@id$=-' + (i+1) + ']').addClass("hand").click(function(e){
					var option = $(this).attr('id').split('-')[1];
					$('[@id^=specselect-]').hide();
					var offset = $(this).offset();
					$('#specselect-' + option).show().css('top',offset.top).css('left',offset.left + 102).css("width","100px").find('[@id^=specCell-]').each(function(k){
						var specid = '';
						var cell = $(this).attr('id').split('-')[1];
						var rname = '';
						$('[@id^=specselect-]').each(function(n){
							var o = $(this).attr('id').split('-')[1];
							rname += (rname != '' ? ',' : '') + $('#tdselect-' + o + '-' + (i+1)).text();
							if(option == o)
							{
								specid += (specid != '' ? ',' : '') + cell;
							}
							else
							{
								specid += (specid != '' ? ',' : '') + $('#tdselect-' + o + '-' + (i+1)).text();
							}

						});

						if($('[@id=' + specid + ']').val() == 'true' && cell != $('#tdselect-' + option + '-' + (i+1)).text())
						{
							$(this).removeClass('sepc_click').addClass('sepc_no_click').unbind();
						}
						else
						{	$(this).removeClass('sepc_no_click').addClass('sepc_click').unbind().click(function(){
						        if($('#tdselect-' + option + '-' + (i+1)).text()==($(this).text())){
						           	$('#specCell-一等品').unbind();
        						
						        }
								$('#tdselect-' + option + '-' + (i+1)).text($(this).text());
								$('[@id^=specselect-]').hide();
								$('[@id=' + rname + ']').val('false');
								$('[@id=' + specid + ']').val('true');
							});
						}
					});
					//因为在document中新加了click事件，要防止这个click事件传送到上层的Document中去，要阻止这个事件冒泡
                    e.stopPropagation();
				});
				
				$('#spanShow-' + (i+1)).click(function(){				    
					$('[@id^=div-]').hide();
					var numid = $(this).attr('id').split('-')[1];
					$('#div-' + numid).show();
					$('#divd-' + numid).empty();
					$('#uploadImg').children().clone().appendTo($('#divd-' + numid));
			        $('#divd-' + numid).find('[@class^=delete_img]').remove();
					$('#divd-' + numid).find('[@name^=pic_]').show();					
					$('#divd-' + numid).find('[@name^=pic_]').show().each(function(){
						if($('[@name=pics-m-' + numid + ']').val().indexOf($('[@name=picm_' + $(this).val() + ']').val()) > -1)
						{
							$(this).attr('checked',true);
						}
					});					
				});
				$('#spanClose-' + (i+1)).click(function(){
					$('#div-' + $(this).attr('id').split('-')[1]).hide();
				});
				//--弹出的图片管理层拖动开始
				$('#div-' + (i+1)).easydrag();
				$('#div-' + (i+1)).setHandler('divc-' + (i+1));
				
				$('[@name=btnImgSure-' + (i+1) + ']').click(function(){
					var id = $(this).attr('name').split('-')[1];
					var pics_b = '';
					var pics_m = '';
					var pics_s = '';
					$('#divd-' + id).contents().find('input[checked]').each(function(){
						pics_b += (pics_b != '' ? ',' : '') + ($('[@name=picb_' + $(this).val() + ']').val().replace(/%20/g,' '));
						pics_m += (pics_m != '' ? ',' : '') + ($('[@name=picm_' + $(this).val() + ']').val().replace(/%20/g,' '));
						pics_s += (pics_s != '' ? ',' : '') + ($('[@name=pics_' + $(this).val() + ']').val().replace(/%20/g,' '));
					});
					$('[@name=pics-b-' + id + ']').val(pics_b);
					$('[@name=pics-m-' + id + ']').val(pics_m);
					$('[@name=pics-s-' + id + ']').val(pics_s);
					$('[@id^=div-' + id + ']').hide();
				});
				//删除货品开始
				$("<input type='hidden' name='spec_desc_unit' value=\"{'GID':'" + m.GID + "','Desc':'" + m.Desc + "'}\" /><span id='delete_" + m.GID + "'>删除</span>").addClass("hand").click(function(){//绑定删除货品
					if($(this).parent().parent().parent().children().length < 3)
					{
						alert('无法再删除！');
					}
					else
					{
						if(confirm('删除后将无法恢复,确实要删除吗?'))
						{
							$(this).parent().parent().remove();							
							//--异步更新SpecDesc
							var specDesc = "{'MainDesc':'" + msg.MainDesc + "','Goods':[";
							$('[@name=spec_desc_unit]').each(function(p){
								specDesc += (p != 0 ? ',' : '') + $(this).val();
							});
							
							specDesc += "],'DescL':'" + msg.DescL + "'}";
//							alert(specDesc);
//							return false;
							//--异步删除
							$.ajax({
								url:'ProductAdd_Step2.aspx?type=ajax&Action=DeleteGoods&gid=' + m.GID + '&NoCopyRight=1',
								cache:false,
								async:false,
								success:function(msg){
									$.ajax({
										url:'ProductAdd_Step2.aspx?type=ajax&Action=UpdateSpecDesc&pid=' + pid + '&SpecDesc=' + escape(specDesc) + '&NoCopyRight=1',
										cache:false,
										async:false,
										success:function(mg){
											if(mg != '0')
											{
												spec_length--;//货品数减1
												alert('删除成功！');
											}
										},
										error:function(){alert('error');}
									});
								},
								error:function(){alert('error');}
							});
						}
					}					
				}).appendTo($("#tdelete_" + m.GID));//删除货品结束
				
			});
		},
		error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!');parent.window.location="../../adminlogin.aspx";}}
	});
};
function GetNSP(pid){
	 var nsp=null;
	 $.ajax({
        url:'ProductAdd_Step2.aspx?type=ajax&Action=GetNSP&pid='+pid + '&NoCopyRight=1',
        cache:false,
        async:false,
        success:function(data){
            if(!checkLoginStatus(data)){return false;};//是否要重新登陆
            if(data != ''){
               nsp=data;
            };
        },
        error:function(){alert('error 4');}
    });
    return nsp;
};
function GetCategorys(cid,depth,path){
	 $.ajax({
		type:"get",
        dataType:"json",
        url:"ProductAdd_Step1.aspx?NoCopyRight=1&action=GetCategorys&cid="+cid,
        cache:false,
        success:function(msg){
			var parentObj = $("<li><ul><ul></li>").appendTo($("#cul"));
            var data = msg.Categorys;
			$.each(data,function(i,n){
				var item=$("<li>"+n.Name+"</li>").addClass("citem").appendTo(parentObj).click(function(){
					temp_cid=n.CategoryID;
					if(depth==1){
						temp_catname=n.Name;
						temp_catpath=n.CategoryID;
					}else{
						var arr_catname = temp_catname.split('>>');
						var arr_catpath = temp_catpath.split(',');
						temp_catname="";
						temp_catpath="";
						$.each(arr_catpath,function(p,q){
							if(p<(depth-1)){
								if(p!=0){
									temp_catname += ">>";
									temp_catpath += ",";
								};
								temp_catname += arr_catname[p];
								temp_catpath += arr_catpath[p];
							};						
						});	
						temp_catname += ">>"+n.Name;
						temp_catpath += ","+n.CategoryID;
					};
					parentObj.nextAll().remove();//绑定下级分类前清空之前的数据
					$("#next").unbind("click");//取消下一步按钮的click事件
					if(n.Child=="0"){						
						//最底层分类的时候激活下一步按钮并绑定事件			
						$("#next").removeClass("disable");
						$("#next").addClass("enable");
						$("#next").click(function(){
							if($("#cid").val() != temp_cid){
								InitFB(temp_cid);
								$("#cid").attr("value",temp_cid);
							};
							$("#catname").text(temp_catname);
							$("#catpath").attr("value",temp_catpath);
							disablePopup($("#ShowCategory"),$("#backgroundPopup"));
						});
					}else{						
						$("#next").removeClass("enable");
						$("#next").addClass("disable");
						GetCategorys(n.CategoryID,depth+1,path);
					};
					$(this).siblings().removeClass("selected");
					$(this).addClass("selected");
				});//end click
				if(n.Child!="0"){
					item.addClass("more");
				};
				if(n.CategoryID==path.split(',')[depth-1]){
					item.siblings().removeClass("selected");
					item.addClass("selected");
					if(depth!=1){
						temp_catname += ">>";
						temp_catpath +=",";
					};
					temp_catname += n.Name;
					temp_catpath += n.CategoryID;
					if(depth==(path.split(',').length)){
						//最底层分类的时候激活下一步按钮并绑定事件
						$("#next").removeClass("disable");
						$("#next").addClass("enable");
						$("#next").click(function(){
							if($("#cid").val() != temp_cid){
								InitFB(temp_cid);
								$("#cid").attr("value",temp_cid);
							};
							$("#catname").attr("value",temp_catname);
							$("#catpath").attr("value",temp_catpath);
						});
					}else{					
						GetCategorys(n.CategoryID,depth+1,path);
					};
				};
            });//end each
        },//end success
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!');parent.window.location="../../adminlogin.aspx";}}
    });//end ajax
};
//修改分类后重新绑定扩展属性和品牌及商品默认的可赠送积分比例
function InitFB(arg){
    //获取扩展属性
    if(arg==0){return false;};
    $("#prop tr").remove();
    $("#para").html("");
    $.ajax({
        url:'ProductAdd_Step2.aspx?type=ajax&Action=GetFieldValues&cid='+arg + '&NoCopyRight=1',
        cache:false,
        success:function(data){
            if(!checkLoginStatus(data)){return false;}//是否要重新登陆
            if(data != ''){
				if(data.split('^@^')[0] != ''){
				    var prop=eval('('+data.split('^@^')[0]+')');
				    $.each(prop.props,function(i,n){
					    var tempRow=$("<tr></tr>").appendTo($("#prop"));
					    var tempCell1=$("<th class='tl'>"+n.name+"：</td>").appendTo(tempRow);
					    var tempCell2=$("<td class='tr'></td>").appendTo(tempRow);
					    var tempSelect=$("<select name='prop'><option value='0'>请选择"+n.name+"</option></select>").appendTo(tempCell2);
					    $.each(n.options,function(j,m){
						    var tempOption=$("<option value='"+(j+1)+"'>"+m.value+"</option>").appendTo(tempSelect);
					    });
				    });
				}
				
				if(data.split('^@^')[1] != ''){
				    var para=eval('('+data.split('^@^')[1]+')');
				        $.each(para.paras,function(i,n){
					    var tempItem=$("<div class='para_group'><input type='hidden' name='group' value='"+n.group+"'/><label>"+n.group+"</label></div>").appendTo($("#para"));					
					    $.each(n.options,function(j,m){
						    var tempRow=$("<dl></dl>").appendTo(tempItem);
						    var tempCell1=$("<dt>"+m.name+"：</dt>").appendTo(tempRow);
						    var tempCell2=$("<dd><input type='hidden' name='paraname' value='"+m.name+"'/><input type='text' name='paravalue' /></dd>").appendTo(tempRow);
					    });
					    var tempRow=$("<dl class='clear'></dl>").appendTo(tempItem);	
				    });
				}
				
			};
        },//end seccess
        error:function(){alert('error:GetFieldValues');}
    });//end ajax
    
    //获取品牌
    $.ajax({
        url:'ProductAdd_Step2.aspx?type=ajax&Action=GetBrandByCatID&cid='+arg +(pid==0 ? "" : "&ProductID="+pid)+'&NoCopyRight=1',
        cache:false,
        success:function(data){
            $('#ddlBrand').html(data);
        },
        error:function(){alert('error:GetBrandByCatID');}
    });
    
    //设置商品的赠送积分比例
    $.ajax({
        url:'ProductAdd_Step2.aspx?type=ajax&Action=GetScoreRateByCatID&cid='+arg+'&NoCopyRight=1',
        cache:false,
        success:function(data){
            $('#txtScoreRate').val(data);
            $('#txtScoreRate').attr("disabled","true");
            defaultScoreRate=data;
        },
        error:function(){alert('error:GetScoreRateByCatID');}
    });
    return false;
};
function GetPropPara(){
	//参数
	var gcount=$("input[@name=group]").length;
	var paras='"paras":[';
	if(gcount!=0){
		var flag=false;
		$("input[@name=group]").each(function(i){
			var tempGroup='{"id":"'+(i+1)+'","group":"'+$(this).val()+'","options":[';
			var paraname=$(this).siblings("dl").find("input[@name=paraname]");
			var tempGroupValue="";
			paraname.each(function(j){
				var tempValue=$(this).next().val().Trim();
				if(tempValue!=""){
//					tempGroupValue+='{"index":"'+(j+1)+'","name":"'+$(this).val()+'","value":"'+tempValue+'"}';
                    while(tempValue.indexOf('"') != -1){
                        tempValue = tempValue.replace('"','“');
                    };
					tempGroupValue+='{"index":"'+(j+1)+'","name":"'+$(this).val()+'","value":"'+tempValue+'"}';
					tempGroupValue+=',';
				};
			});
			if(tempGroupValue!=""){
				tempGroupValue=tempGroupValue.substring(0,tempGroupValue.length-1);
				paras+=tempGroup;
				paras+=tempGroupValue;
				paras+=']}'
				paras+=',';
				flag=true;
			};			
		});
		if(flag){
			paras=paras.substring(0,paras.length-1);
		};		
	};
	paras+=']';
	$("<input type='hidden' value='"+paras+"' name='paras' />").appendTo($("#para"));
}

//修改商品的时候绑定商品属性和参数
function Init(arg){
    $.ajax({
        type:"get",
        dataType:"json",
        url:"ProductAdd_Step2.aspx?NoCopyRight=1",
        data:"type=ajax&Action=GetPropPara&pid="+arg,
        cache:false,
        success:function(msg){
			var props=msg.props;
			var paras=msg.paras;
			$.each(props,function(i,n){
				if(n.value!=0){
					$("select[@name=prop]").eq(i).val(n.value);
				};
			});
			$.each(paras,function(i,n){
				$.each(n.options,function(j,m){
					$("input[@name=group]").eq(n.id-1).siblings("dl").find("input[@name=paravalue]").eq(m.index-1).val(m.value);
				});
			});
        },//end seccess
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!');}else{alert('error_GetPropPara')};}
    });//end ajax
    return false;
};

//相关商品和附件商品删除事件;type为1相关商品,为2附件商品,为3赠送商品,为4赠送礼品
function BindDeleteEvent(type){
    var productIDs = '';
    var objhidename = null;
    var objPID_curr = null;
    var objPID_old = null;
    if(type=='1'){
        objhidename = 'rltpid';
        objPID_curr = $('#RltPID_curr');
        objPID_old = $('#RltPID_old');
    }else if(type=='2'){
        objhidename = 'fitpid';
        objPID_curr = $('#FitPID_curr');
        objPID_old = $('#FitPID_old');
    }else if(type=='3'){
        objhidename = 'prepid';
        objPID_curr = $('#PrePID_curr');
        objPID_old = $('#PrePID_old');
    }else if(type=='4'){
        objhidename = 'pregid';
        objPID_curr = $('#PreGID_curr');
        objPID_old = $('#PreGID_old');        
    };

    $('input[@name=' + objhidename + ']').each(function(i,n){
        var row = $(this).parent().parent();
        row.find('.delete').css('cursor','pointer').click(function(){
            row.remove();
            var ids = '';
            $('input[@name=' + objhidename + ']').each(function(){
                ids += $(this).val() + ',';
            });
            if(ids != ''){ids = ids.substring(0,ids.length-1);};
            objPID_curr.val(ids);
        }).find('img').mouseover(function(){
            $(this).attr('src','../images/x-red.gif');
        }).mouseout(function(){
            $(this).attr('src','../images/x-gray.gif');
        });
        productIDs += $(this).val() + ',';
        
        if(type == '3'){
            row.find('[@name=preNum_pdt]').blur(function(){
                CheckNum($(this));
            });
        }else if(type == '4'){
            row.find('[@name=preNum_gift]').blur(function(){
                CheckNum($(this));
            });
        }
    });
    if(productIDs != ""){
		productIDs = productIDs.substring(0,productIDs.length-1);
		objPID_old.val(productIDs);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)
		objPID_curr.val(productIDs);
	};
};

//统计要添加和要删除的相关商品的ID,并将这些ID记录在隐藏控件上
function CountPIDs(){
    //相关商品
    var rltPIDs = GetPIDs($('#RltPID_old').val(),$('#RltPID_curr').val());
    var arry_rltIDs = rltPIDs.split('|');
    $('#RltPID_new').val(arry_rltIDs[0]);       //要添加到数据库中的ID
    $('#RltPID_deleted').val(arry_rltIDs[1]);   //要从数据库中删除的相关商品ID
    
    //配件商品
    var fitPIDs = GetPIDs($('#FitPID_old').val(),$('#FitPID_curr').val());
    var arry_fitIDs = fitPIDs.split('|');
    $('#FitPID_new').val(arry_fitIDs[0]);
    $('#FitPID_deleted').val(arry_fitIDs[1]);
    
    //赠送商品
    var prePIDs = GetPIDs($('#PrePID_old').val(),$('#PrePID_curr').val());
    var arry_preIDs = prePIDs.split('|');
    $('#PrePID_new').val(arry_preIDs[0]);
    $('#PrePID_deleted').val(arry_preIDs[1]);
    
    //赠送礼品
    var preGIDs = GetPIDs($('#PreGID_old').val(),$('#PreGID_curr').val());
    var arry_preGIDs = preGIDs.split('|');
    $('#PreGID_new').val(arry_preGIDs[0]);
    $('#PreGID_deleted').val(arry_preGIDs[1]);
}

function GetPIDs(oldIDs,currIDs){
    var arryPID_old = oldIDs.split(',');
    var arryPID_curr = currIDs.split(',');
    //循环后arryPID_old里剩下的ID为需要从数据库里删除的PID,arryPID_curr里剩下的ID为需要添加到数据库中的PID
    if(oldIDs != ''){
        for(var i=0;i<arryPID_old.length;i++){
            for(var j=0;j<arryPID_curr.length;j++){
                if(arryPID_old[i]==arryPID_curr[j]){
                    arryPID_old.splice(i,1);arryPID_curr.splice(j,1);
                    i--;j--;
                    break;
                };
            };
        };
    };
    
    return arryPID_curr.toString() + "|" + arryPID_old.toString();
}

//检查是否为数字
function CheckNum(obj){
	var reg = new RegExp(/\D/g);
	if(reg.test($.trim(obj.val())) || obj.val().Trim() == ''){
	    alert('礼品数量填写有误');
	    obj.focus();
	};
}

function unique( array ) {
   var ret = [], done = {};

   try {

    for ( var i = 0, length = array.length; i < length; i++ ) {
     var id = array[ i ] ;

     if ( !done[ id ] ) {
      done[ id ] = true;
      ret.push( array[ i ] );
     }
    }

   } catch( e ) {
    ret = array;
   }

   return ret;
}

