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

//列表查询条件
var search_urldata = 'type=ajax&Action=SearchProductsAjax&keyword=' + keyword + '&CatID=' + catID + '&BrandIDs=' + brandID + '&SearchType=' + searchType + '&PageSize='+PageSize+'&Page='+CurrentPage;

function setList(){
	var pageWidth=$('#popupContact').width()-20;
	$(".sub_container_content").css("width",pageWidth);
	$(".sub_container_listhead").css("width",pageWidth);
	$(".llist").css("width",pageWidth);
	var c1_width = pageWidth*0.05+"px";
	var c2_width = pageWidth*0.25+"px";
	var c3_width = pageWidth*0.25+"px";
	var c4_width = pageWidth*0.15+"px";
	var c5_width = pageWidth*0.15+"px";
	var c6_width = pageWidth*0.15+"px";
	$('.c1').css("width",c1_width);
	$('.c2').css("width",c2_width);
	$('.c3').css("width",c3_width);
	$('.c4').css("width",c4_width);
	$('.c5').css("width",c5_width);	
	$('.c6').css("width",c6_width);	
}

$(document).ready(function(){    
    //弹出搜索相关商品的层
    $('#btnAddRelate').click(function(){
        PopupSearchPdts(1);
    });
    //弹出搜索附件商品的层
    $('#btnAddFitting').click(function(){
        PopupSearchPdts(2);
    });
    //弹出搜索赠送商品的层
    $('#btnAddPresent').click(function(){
        //如果从商品里选择赠品,则弹出筛选商品的层
        if($('[@name=rdPresentType][@checked]').val()=='1'){
            PopupSearchPdts(3);
        }
    });
	
	if($.browser.mozilla){setInterval(setList,1000);};
	setInterval(function(){
		$('#search_result_content').css('height','370px');
    },1000);
	
	//$('.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();$('#RelatePdtIds').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:'../SearchProduct.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 = $('#txtSearchKeyword').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='+PageSize+'&Page='+CurrentPage;
        BindProducts('../SearchProduct.aspx',search_urldata);
        if(showadv == 1){
            $('#showadvsearch').click();
        }
    });
    
    $('#btnAddPdt').click(function(){
        var productIDs = '';
        var selectedPIDs = '';
        var objSelectedPIDs = null;//记录当前页面中已选择的商品的控件
        var objResultContainer = null;//显示选择结果的控件
        var objHideName = null;
        
        var addType = $(this).data('type');
        if(addType == '1'){
            //如果为2则是添加商品配件
            objSelectedPIDs = $('#RltPID_curr');
            objResultContainer = $('#listresult');
            objHideName = 'rltpid';
        }else if(addType == '2'){
            //如果为2则是添加商品配件
            objSelectedPIDs = $('#FitPID_curr');
            objResultContainer = $('#fitcontent');
            objHideName = 'fitpid';
        }else if(addType == '3'){
            //如果为3则是添加赠送商品
            objSelectedPIDs = $('#PrePID_curr');
            objResultContainer = $('#presentcontent');
            objHideName = 'prepid';
        };
        if(objSelectedPIDs.val() != ''){
            selectedPIDs = ','+objSelectedPIDs.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 catname = currobj.parent().siblings('#Category').text();
                var row = null;
                if(addType == '3'){
                    //添加赠送商品
                    row = $('<tr><td class="delete"><img src="../images/x-gray.gif" alt="删除" /><input type="hidden" name="' + objHideName + '" value=' + currobj.val() + '></td><td>'+productname+'</td><td>' + productno + '</td><td>' + currobj.siblings('[@name=search_storage]').val() + '</td><td><input type="text" name="preNum_pdt" value="1" /></td></tr>');
                }else{
                    //添加附件或相关商品
                    row = $('<tr><td class="delete"><img src="../images/x-gray.gif" alt="删除" /><input type="hidden" name="' + objHideName + '" value=' + currobj.val() + '></td><td>'+productno+'</td><td>' + productname + '</td></tr>');
                }
                
                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);};
                    //$('#RelatePdtIds').val(ids);
                    objSelectedPIDs.val(ids);
                }).find('img').mouseover(function(){
                    $(this).attr('src','../images/x-red.gif');
                }).mouseout(function(){
                    $(this).attr('src','../images/x-gray.gif');
                });
                objResultContainer.append(row);
                productIDs += currobj.val() + ',';
                
                if(addType == '3'){
                    row.find('[@name=preNum_pdt]').blur(function(){
                        CheckNum($(this));
                    });
                }
            };
        });//end each
        if(productIDs != ""){
            productIDs = productIDs.substring(0,productIDs.length-1);
//            $('#RelatePdtIds').val($('#RelatePdtIds').val() + ($('#RelatePdtIds').val() != '' ? ',' : '') + productIDs);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)
            objSelectedPIDs.val(objSelectedPIDs.val() + (objSelectedPIDs.val() != '' ? ',' : '') + productIDs);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)
        };        
    });//end click
    
});// end ready

//弹出筛选商品的层
function PopupSearchPdts(type){
    $('#btnAddPdt').data('type',type);//type为1表示要添加相关商品,为2表示要添加配件商品,为3表示要添加赠送商品
    $('#ShowRelate').popup({width:'80%',height:'500',popupHead:'RelateHead',btnClose:'popupClose'});
    if(status == 0){BindProducts('../SearchProduct.aspx',search_urldata);status = 1;};//如果是第一次弹出层,要获取商品列表,否则只需要显示层即可
};

//绑定数据
function BindProducts(weburl,urldata){
    $('#template').hide();//将第一行模板隐藏
    $.ajax({
        type:"get",
        dataType:"json",
        url:weburl+'?NoCopyRight=1',
        data:urldata,
        cache:false,
        success:function(msg){
            $('input[@name=chkAll]').attr('checked','');
            $('tr:gt(0)','#datas').remove();
            var data = msg.Product;
            $.each(data,function(i,n){
                var row = $('#template').clone();
                row.show().mouseover(function(){$(this).addClass('on')}).mouseout(function(){$(this).removeClass('on')}); //将复制的行显示出来并添加样式
                row.find('#checkbox').html('<input type="checkbox" name="chkItem" value="' + n.ProductID + '" /><input type="hidden" name="search_storage" value="' + n.Storage + '" />');//checkbox
                row.find('#Name').html('<a href="../../products/product-'+n.ProductID+'.html" target="_blank">'+n.ProductName+'</a>'); //商品名称
                row.find('#ProductNo').text(n.ProductNo);   //编码
                var categoryname = (n.CategoryID != 0 ? $('#sel_category option[@value=' + n.CategoryID + ']').text().replace('├','') : "");
                var brandname = (n.BrandID != 0 ? $('#sel_brand option[@value=' + n.BrandID + ']').text() : "");
                row.find('#Category').text(categoryname);//商品类别
                row.find('#Brand').text(brandname);//商品品牌
                row.find('#MemberPrice').text(Number(n.MemberPrice).toFixed(2))//两位小数
				row.attr("id","ready_" + n.ProductID);//改变绑定好数据的行的id
				row.appendTo("#datas");//添加到模板的容器中
            });
           
            //分页
            $('.sub_container_page').show();
            var pagerStyle = "flickr";//jPagerBar样式
            ShowPageBar("pageDataList1_Pager",//[containerId]
               "Products.aspx",//[url]
               {style:pagerStyle,mark:"pageDataList1Mark",
               totalCount:msg.totalCount,showPageNumber:3,pageCount:PageSize,currentPageIndex:CurrentPage,noRecordTip:" 没有记录",preWord:"上一页",nextWord:"下一页",
               onclick:"CurrentPage={pageindex};BindProducts('../SearchProduct.aspx','type=ajax&Action=SearchProductsAjax&keyword=" + escape(keyword) + "&CatID=" + catID + "&BrandIDs=" + brandID + "&SearchType=" + searchType + "&PageSize=" + PageSize + "&Page={pageindex}');return false;"}//[attr]
            );
            
        },//end success
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('error12')};}
    });//end ajax
}//end funciton

//相关商品和附件商品删除事件;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 checkLoginStatus(data){
    var result = true;
    if(data.indexOf('<!DOCTYPE') != -1){
        result = false;
        alert('身份已过期,请重新登陆!');
    }
    return result;
}
