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','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);
    
    //$('#ddlCategory').change(function(){GetDefRank();popStatus = 0});
    var subcat,currObg;
    $('#ddlCategory').change(function(){//一级分类选择
        popStatus = 0;
        currObg=$(this);
        $('#ddlSubCat').remove();
        $('#ddlThirdCat').remove();
        if(currObg.val()!=0){
            subcat=GetSubCat(currObg.val());//获取二级分类
            var subcatoptions = $('<select id="ddlSubCat" name="ddlSubCat"></select>').append(subcat);
            if(subcatoptions.find('option').length > 1){
				$('#ddlCategory').after(subcatoptions);
                $('#ddlSubCat').change(function(){//二级分类选择
					popStatus = 0;
					currObg=$(this);
					$('#ddlThirdCat').remove();
					if(currObg.val()!=0){
						subcat=GetSubCat(currObg.val());//获取三级分类
						var thirdcatoptions=$('<select id="ddlThirdCat" name="ddlThirdCat"></select>').append(subcat);
						if(thirdcatoptions.find('option').length > 1){
							$('#ddlSubCat').after(thirdcatoptions);
							$('#ddlThirdCat').change(function(){//三级分类选择
								popStatus = 0;
								currObg=$(this);
								GetDefRank();
							});
						}
					};
					GetDefRank();
                });//end subcat
            }
        };
        GetDefRank();
    });//end topcat
        
    $('#chk_search').click(function(){
        $('[@name=chkItem]').attr('checked',$(this).attr('checked'));
    });   
    $('#btnNext').click(function(){
        $('#popupContact').popup({width:'80%',height:'80%',popupHead:'popupHead',btnClose:'popupContactClose'});
        //如果是第一次弹出层,或者改变了分类,要重新获取商品列表,否则只需要显示层即可
        if(popStatus == 0){
            CurrentPage = 1;
            keyword = $('#txtKeyword').val();
            catID = GetCurrCatID();
            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 = GetCurrCatID();
        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(i){
            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,"",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(){
		var sort = "";
		$('.sort').each(function(){
			sort += $(this).val()+",";
		});
		if(sort != ""){
			sort = sort.substring(0,sort.length-1)
		}
		//alert(sort);
		//return false;
        $.ajax({
            url:'TopSaleSet.aspx?NoCopyRight=1&type=ajax&Action=save&CatID=' + GetCurrCatID() + '&PIDs=' + $('#PIDs').val()+'&sorts='+sort,
            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 GetSubCat(topCatID){
    var options = null
    $.ajax({
        url:'ProductStatus.aspx?NoCopyRight=1&type=ajax&Action=GetSubCategory&CatID=' + topCatID,
        type:'get',
        async:false,
        success:function(data){
			if(!checkLoginStatus(data)){
				options="";
			}else{
				options=data;
            };
        },
        error:function(){alert('error');return false;}
    });
    return options;
};
function GetCurrCatID(){
    var currCatID = '0';
	if($('#ddlThirdCat').length != 0 && $('#ddlThirdCat').val() != '0'){
        currCatID = $('#ddlThirdCat').val();
    }else if($('#ddlSubCat').length != 0 && $('#ddlSubCat').val() != '0'){
        currCatID = $('#ddlSubCat').val();
    }else{
        currCatID = $('#ddlCategory').val();
    };
    return currCatID;
};

//读取当前选择类别下商品的默认销售排行
function GetDefRank(){
    $('#PIDs').val('');
    $('#selected_template').siblings().remove();
    $('#custom_template').siblings().remove();
    catID = GetCurrCatID();
    $.ajax({
        url:'TopSaleSet.aspx?NoCopyRight=1&type=ajax&Action=GetList&CatID=' + catID,
        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,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,m.Sort,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,sort,container)
{
    var row = "";
    if(container == 1){
		row = $('#selected_template').clone();
	}else{
		row = $('#custom_template').clone();
	}
	if(container == 1){
		 row.show().attr('id','selected_template_'+pid).mouseover(function(){$(this).addClass('on')}).mouseout(function(){$(this).removeClass('on')});
	}else{
		 row.show().attr('id','custom_template_'+pid).mouseover(function(){$(this).addClass('on')}).mouseout(function(){$(this).removeClass('on')});
	}   
    row.find('.checkbox').html('<input type="hidden" name="CategoryID" value="' + categoryID + '" />');//checkbox
    if(container == 2){
		var tsort = sort=='' ? $('.sort').length+1 : sort;
		row.find('.Sort').html('<input type="text" class="sort" name="sort" style="width:40px;" value="'+tsort+'" />');
	}
    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();
        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 BindCustomRows(pid,productname,categoryID,marketPrice,memberPrice,productno,salenum,container){
    var row = $('#custom_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();
        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=chk_search]').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;
};