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

//列表查询条件
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();});
	
	var isIE6 = ($.browser.msie && $.browser.version=='6.0'); 
    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);
        if(isIE6){
            $('#datacontainer').css('height','390px');
        }else{
            $('#content').css('height',$('#popupContact').height()-$('#popupHead').height());
            $('#datacontainer').css('height',$('#content').height()-$('#sub_container_listhead').height()-$('#pageDataList1_Pager').height()-$('#divsave').height()-60);
        };
    },1000);
    
    $('#ddlCategory').change(function(){GetDefRank();popStatus = 0});
        
       
    $('#btnNext').click(function(){
        $('#popupContact').popup({width:'80%',height:'80%',popupHead:'popupHead',btnClose:'popupContactClose'});
        //如果是第一次弹出层,或者改变了分类,要重新获取商品列表,否则只需要显示层即可
        if(popStatus == 0){
            CurrentPage = 1;
            keyword = $('#txtKeyword').val();
            catID = $('#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();
        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();
        }
    });
    
    
    $('#chk_search').click(function(){    
        $('[@name=chkItem]').attr('checked',$('#chk_search').attr('checked'));
    });
    
    //显示隐藏高级搜索
    $('#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();
                //绑定行
                BindRows(pid,productname,categoryID,marketPrice,memberPrice,productno,2);
                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(){
        $.ajax({
            url:'TopSaleSet.aspx?NoCopyRight=1&type=ajax&Action=save&CatID=' + $('#ddlCategory').val() + '&PIDs=' + $('#PIDs').val(),
            type:'get',
            cache:false,
            success:function(data){
                if(!checkLoginStatus(data)){return false;}
                if(data > 0){
                    alert('已保存');
                };
            },
            error:function(){alert('error');}
        });
    });//end btnSave click
    
});// end ready


//读取当前选择类别下商品的默认销售排行
function GetDefRank(){
    $('#PIDs').val('');
    $('#selected_template').siblings().remove();
    $('#custom_data tr').remove();
    $.ajax({
        url:'TopSaleSet.aspx?NoCopyRight=1&type=ajax&Action=GetList&CatID=' + $('#ddlCategory').val(),
        type:"get",
        cache:false,
        dataType:"json",
        success:function(msg){
            var data = msg.Product;
            $.each(data,function(i,n){
                BindRows(n.ProductID,n.ProductName,n.CategoryID,n.MarketPrice,n.MemberPrice,n.ProductNo,n.SaleNum,1);
            });
            
            if(msg.ExistPdt){
                var productIDs = '';
                $.each(msg.ExistPdt,function(j,m){
                    BindRows(m.ProductID,m.ProductName,m.CategoryID,m.MarketPrice,m.MemberPrice,m.ProductNo,m.SaleNum,2);
                    productIDs += m.ProductID + ',';
                });
                
                if(productIDs != ""){
                    productIDs = productIDs.substring(0,productIDs.length-1);
                    $('#PIDs').val(productIDs);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)
                };
            };
        },
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert(textStatus)};}
    });
};

function BindRows(pid,productname,categoryID,marketPrice,memberPrice,productno,salenum,container){
    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="hidden" name="CategoryID" value="' + categoryID + '" />');//checkbox
    row.find('.Name').html(productname);
    row.find('.SaleNum').html(salenum);
    row.find('.MarketPrice').html(marketPrice);
    row.find('.MemberPrice').html(memberPrice);
    row.find('.ProductNo').html(productno);
    row.find('.Delete').html('<img src="../images/x-gray.gif" alt="移除" />');

//    row.find('.Delete').css('cursor','pointer')
//    .find('img').click(function(){
//        row.remove();
     row.find('.Delete').css('cursor','pointer')
    .find('img').click(function(){
		if(confirm("你确定要删除这项吗?")){
			row.remove();
		}
		else{
			return false;
		}
        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');
    });
    if(container == 1){
        $('#selected_datas').append(row);
    }else{
        row.find('.Delete').removeClass('hide');
        row.find('.checkbox').html('<input type="hidden" name="chkSelectedItem" value="' + pid + '">');
        $('#custom_data').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.attr("id","ready_" + n.ProductID);//改变绑定好数据的行的id
				row.appendTo("#datas");//添加到模板的容器中
            });
            
        },//end success
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert(textStatus)};}
    });//end ajax
}//end funciton

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