var PageSize = 30;//每页计数
var CurrentPage = 1; //当前页
//搜索条件
var keyword = '';
var catID = '0';
var brandID = '0';
var searchType = '0';
var popStatus = 0;
var showadv = 0;//高级搜索显示状态

function setList(){
	var pageWidth=document.documentElement.clientWidth-9;
	$(".sub_container_content").css("width",pageWidth);
	$(".sub_container_listhead").css("width",pageWidth);
	$(".llist").css("width",pageWidth);
	var c1_width = pageWidth*0.03+"px";
	var c2_width = pageWidth*0.2+"px";
	var c3_width = pageWidth*0.15+"px";
	var c4_width = pageWidth*0.15+"px";
	var c5_width = pageWidth*0.15+"px";
	var c6_width = pageWidth*0.1+"px";
	var c7_width = pageWidth*0.1+"px";
	var c8_width =  pageWidth*0.12+"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);
	$('.c7').css("width",c7_width);
	$('.c8').css("width",c8_width);
}

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

$(document).ready(function(){
    //loading
    $('#loadingContainer').ajaxStart(function(){$(this).show();$('#loadingbackground').show().css({"opacity": "0.5"});}).ajaxStop(function(){$(this).hide();});
	
	    setInterval(function(){
        $('#selected_container').css('height',$(window).height()-$('.sub_container_title').height()-$('.sub_container_operation').height()-$('#selected_container_listhead').height()-$('#selected_pageDataList1_Pager').height()-10);
        $('#selected_pageDataList1_Pager').css('top',$(window).height()-$('#selected_pageDataList1_Pager').height()-2);
//        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()-60);
//        };
    },1000);
    
    //获取已存在的商品
    GetSelectedPdt();
    
    $('#ddlTags').change(function(){GetSelectedPdt();});
    $('#ddlCategory').change(function(){
        popStatus = 0;
        //获取二级分类
        if($(this).val()!=0){
            $.ajax({
                url:'ProductStatus.aspx?NoCopyRight=1&type=ajax&Action=GetSubCategory&CatID=' + $('#ddlCategory').val(),
                async:false,
                success:function(data){
                    if(!checkLoginStatus(data)){return false;}
                    $('#ddlSubCat').html(data).show();
                },
                error:function(){alert('error');}
            });
        }else{
            $('#ddlSubCat').hide().html('<option value="0">所有子分类</option>');
        };
        GetSelectedPdt();
    });
    $('#ddlSubCat').change(function(){GetSelectedPdt();popStatus = 0;});
    $('#ddlIsHome').change(function(){GetSelectedPdt();});
    
    //全选
    $('#chk_search').click(function(){$('input[@name=chkItem]').attr('checked',$(this).attr('checked'));});
    $('#chk_selected').click(function(){$('input[@name=chkSelectedItem]').attr('checked',$(this).attr('checked'));});
    
    //批量删除商品
    $('#btnDelete').click(function(){
        var selectedItem = $('input[@name=chkSelectedItem][@checked]');
        if(selectedItem.length != 0){
            if(confirm("确定要移除选中的商品吗?")){
                $('input[@name=chkSelectedItem][@checked]').each(function(){
                    $(this).parent().siblings('.Delete').find('img').click();
                });
            };
        }else{
            alert('请先选择要移除的商品');
        };
    });
    
    $('#btnNext').click(function(){
        $('#popupContact').popup({width:'80%',height:'80%',popupHead:'popupHead',btnClose:'popupContactClose'});
        //如果是第一次弹出层,或者改变了分类,要重新获取商品列表,否则只需要显示层即可
        if(popStatus == 0){
            CurrentPage = 1;
            keyword = $('#txtKeyword').val();
//            catID = $('#ddlCategory').val();
            catID = $('#ddlSubCat').val() != 0 ? $('#ddlSubCat').val() : $('#ddlCategory').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(search_urldata);popStatus = 1;
        };
        
        catID = $('#ddlCategory').val();
        if($('#sel_brand').data('CatID')){
            if($('#sel_brand').data('CatID') != catID){
                BindBrand();
                $('#sel_brand').data('CatID',catID);
            };
        }else{
            BindBrand();
            $('#sel_brand').data('CatID',catID);
        };
    });
    
    //搜索
    $('#btnSearch').click(function(){
        CurrentPage = 1;
        keyword = $('#txtKeyword').val();
//        catID = $('#ddlCategory').val();
        catID = $('#ddlSubCat').val() != 0 ? $('#ddlSubCat').val() : $('#ddlCategory').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(search_urldata);
        if(showadv == 1){
            $('#showadvsearch').click();
        }
    });
    
    //显示隐藏高级搜索
    $('#showadvsearch').toggle(function(){$('#advsearch').show();$('#showadvsearch').text('隐藏品牌');showadv = 1;},function(){$('#advsearch').hide();$('#showadvsearch').text('显示品牌');showadv = 0;});
	
	$('#btnSubmit').click(function(){
        var productIDs = '';
        var selectedPIDs = '';
        if($('#PIDs').val() != ''){selectedPIDs = ','+$('#PIDs').val()+',';};
        $('input[@name=chkItem][@checked]').each(function(){
            var currobj = $(this);
            var objTRs = $(this).parent().parent();
            
            if(selectedPIDs.indexOf(',' + currobj.val() + ',') == -1){
                var pid = currobj.val();
                var productname = objTRs.find('.Name').text();
                var marketPrice = objTRs.find('.MarketPrice').text();
                var memberPrice = objTRs.find('.MemberPrice').text();
                var productno = objTRs.find('.ProductNo').text();
                var storage = objTRs.find('.Storage').text();
                var categoryID = objTRs.find('.CategoryID').text();
                var sort = objTRs.find('.Sort').text()
                //绑定行
                BindRows(pid,productname,categoryID,marketPrice,memberPrice,productno,storage,sort,0);
                productIDs += pid + ',';
            };
        });//end each
        if(productIDs != ""){
            productIDs = productIDs.substring(0,productIDs.length-1);
            $('#PIDs').val($('#PIDs').val() + ($('#PIDs').val() != '' ? ',' : '') + productIDs);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)            
        };
        $('#popupContactClose').click();//关闭层
    });//end click
    
    $('#btnSave').click(function(){
        $(this).blur();
        var oldPIDs = $('#OldPIDs').val();  //数据库中已存在的ID
        var currPIDs = $('#PIDs').val();    //当前页面中存在的ID
        var newPIDs = '';   //要添加到数据库中的新ID
        var deletedPIDs = '';   //要从数据库中删除的ID
        var arryOldPID = oldPIDs.split(',');
        var arryCurrPID = currPIDs.split(',');
        //循环后arryOldPID里剩下的ID为需要从数据库里删除的PID,arryCurrPID里剩下的ID为需要添加到数据库中的PID
        if(oldPIDs != ''){
            for(var i=0;i<arryOldPID.length;i++){
                for(var j=0;j<arryCurrPID.length;j++){
                    if(arryOldPID[i]==arryCurrPID[j]){
                        arryOldPID.splice(i,1);arryCurrPID.splice(j,1);
                        i--;j--;
                        break;
                    };
                };
            };
        };
        newPIDs = arryCurrPID.toString();//新增的PID
        deletedPIDs = arryOldPID.toString();//要删除的PID
        var catIDs = '';
        var sorts = '';
        if(newPIDs != ''){
            $.each(arryCurrPID,function(index,n){
                var chkObj = $('input[@name=chkSelectedItem][@value=' + n + ']');
                catIDs += chkObj.next().val() + ',';//catID
                sorts += chkObj.parent().siblings('.Sort').find('[@name=sort]').val() + ',';
            });
            catIDs = catIDs.substring(0,catIDs.length-1);
            sorts = sorts.substring(0,sorts.length-1);
        };
        
        $.ajax({
            url:'ProductStatus.aspx?NoCopyRight=1&type=ajax&Action=Save',
            type:'post',
            data:'&ddlTags=' + $('#ddlTags').val() + '&ddlIsHome=' + $('#ddlIsHome').val() + '&NewPIDs=' + newPIDs + '&CatIDs='+catIDs + '&Sorts=' + sorts + '&DeletedPIDs=' + deletedPIDs,
            cache:false,
            success:function(data){
                if(!checkLoginStatus(data)){return false;}
                if(data=='ok'){
                    $('#OldPIDs').val($('#PIDs').val());
                    alert('已保存');
                };                
            },
            error:function(){alert('error');}
        });//end ajax
    });//end btnSave click
    
    $('#btnUpdateSort').click(function(){
        var sortInfos = '';
        var hasnew = false;
        $('input[@name=chkSelectedItem][@checked]').each(function(){
            var txtSort = $(this).parent().siblings('.Sort').find('[@name=sort]');
            if(txtSort.data('PdtTagID')){
                sortInfos += txtSort.data('PdtTagID') + ',' + txtSort.val() + '|';
            }else{
                hasnew = true;
                return false;
            };
        });
        
        if(hasnew){
            alert('您已选择了新商品,请先保存再修改排序');
        }else{
            if(sortInfos != ''){sortInfos = sortInfos.substring(0,sortInfos.length-1)}else{alert('请先选择要修改商品');return false;};
            $.ajax({
                type:'post',
                url:'ProductStatus.aspx?NoCopyRight=1&type=ajax&Action=UpdateSort',
                data:'SortInfo='+sortInfos,
                cache:false,
                success:function(data){
                    if(!checkLoginStatus(data)){return false;};
                    if(data > 0){
                        GetSelectedPdt();
                    };
                },
                error:function(){alert('error');}
            });
        };
        
    });
    
});// end ready

function setEnable(pid){
    alert($('input[@name=chkItem][@value=' + pid + ']').length);
    $('input[@name=chkItem][@value=' + pid + ']').attr('disabled','disabled');
};

//读取当前选择的状态下已经存在的商品
function GetSelectedPdt(){
    $('#PIDs').val('');
    $('#selected_template').siblings().remove();
    catID = $('#ddlSubCat').val() != 0 ? $('#ddlSubCat').val() : $('#ddlCategory').val();
    $.ajax({
        url:'ProductStatus.aspx?NoCopyRight=1&type=ajax&Action=GetList&TagID='+$('#ddlTags').val() + '&CatID=' + catID + '&IsHomeShow=' + $('#ddlIsHome').val()+'&Page=' + CurrentPage + '&PageSize=' + PageSize,
        type:"get",
        dataType:"json",
        cache:false,
        success:function(msg){
            var productIDs = '';
            var data = msg.Product;
            $.each(data,function(i,n){
                BindRows(n.ProductID,n.ProductName,n.CategoryID,n.MarketPrice,n.MemberPrice,n.ProductNo,n.Storage,n.Sort,n.PdtTagID);
                productIDs += n.ProductID + ',';
            });
            //分页
            $('.sub_container_page').show();
            var pagerStyle = "flickr";//jPagerBar样式
            ShowPageBar("selected_pageDataList1_Pager",//[containerId]
               "ProductsStatus.aspx",//[url]
               {style:pagerStyle,mark:"pageDataList1Mark",
               totalCount:msg.totalCount,showPageNumber:3,pageCount:PageSize,currentPageIndex:CurrentPage,noRecordTip:" 没有记录",preWord:"上一页",nextWord:"下一页",
               onclick:"CurrentPage={pageindex};GetSelectedPdt();return false;"}//[attr]
            );
            if(productIDs != ""){
                productIDs = productIDs.substring(0,productIDs.length-1);
                $('#PIDs').val($('#PIDs').val() + ($('#PIDs').val() != '' ? ',' : '') + productIDs);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)
            };
            $('#OldPIDs').val($('#PIDs').val());
        },
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert(textStatus)};}
    });
};

function BindRows(pid,productname,categoryID,marketPrice,memberPrice,productno,storage,sort,pdtTagID){
    var row = $('#selected_template').clone();
    row.show().attr('id','selected_template_'+pid).mouseover(function(){$(this).addClass('on')}).mouseout(function(){$(this).removeClass('on')});
    row.find('.checkbox').html('<input type="checkbox" name="chkSelectedItem" value="' + pid + '" /><input type="hidden" name="CategoryID" value="' + categoryID + '" />');//checkbox
    row.find('.Name').html(productname);
    row.find('.MarketPrice').html(marketPrice);
    row.find('.MemberPrice').html(memberPrice);
    row.find('.ProductNo').html(productno);
    row.find('.Storage').html(storage);
    row.find('.Sort').find('[@name=sort]')
        .val(sort)
        .data('PdtTagID',pdtTagID)
        .change(function(){CheckOn($(this));})
        .blur(function(){CheckSort($(this));});
    row.find('.Delete').html('<img src="../images/x-gray.gif" alt="移除" />');

    row.find('.Delete').css('cursor','pointer')
    .find('img').click(function(){
        row.remove();
        var ids = '';
        $('input[@name=chkSelectedItem]').each(function(){
            ids += $(this).val() + ',';
        });
        if(ids != ''){ids = ids.substring(0,ids.length-1);};
        $('#PIDs').val(ids);
    }).mouseover(function(){
        $(this).attr('src','../images/x-red.gif');
    }).mouseout(function(){
        $(this).attr('src','../images/x-gray.gif');
    });
    $('#selected_datas').append(row);
};

function BindBrand(){
    $.ajax({
        url:'../SearchProduct.aspx?type=ajax&Action=GetBrandByCatID&product_category_id='+catID + '&NoCopyRight=1',
        async: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');}
    });
};

//绑定数据
function BindProducts(urldata){
    $('#template').hide();//将第一行模板隐藏
    $.ajax({
        type:"get",
        dataType:"json",
        url:'../SearchProduct.aspx?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 + '" />');//checkbox
                row.find('.Name').html('<a href="../../Show.aspx?PID=' + n.ProductID + '" target="_blank">'+n.ProductName+'</a>'); //商品名称
                row.find('.ProductNo').text(n.ProductNo);   //编码
                var brandname = (n.BrandID != 0 ? $('#sel_brand option[@value=' + n.BrandID + ']').text() : "");
                row.find('.Brand').text(brandname);//商品品牌
                row.find('.MemberPrice').text(Number(n.MemberPrice).toFixed(2));//两位小数
                row.find('.MarketPrice').text(Number(n.MarketPrice).toFixed(2));//两位小数
                row.find('.Storage').text(n.Storage);
                row.find('.CategoryID').text(n.CategoryID);
                row.find('.Sort').text(n.Sort);
				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('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(textStatus)};}
    });//end ajax
}//end funciton


//当填写会员价格,市场价格,排序时,自动将前面的checkbox选中
function CheckOn(obj){
    obj.parent().siblings('td.checkbox').find('input[@name=chkSelectedItem]').attr('checked',true);
}

function CheckSort(obj){
	var reg = new RegExp(/\D/g);
	if(reg.test(obj.val()) || obj.val().Trim() == ''){
	    alert('排序填写错误');
	    obj.focus();
	};
};

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