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

$(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);
        $('#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);
    
    //全选
    $('#chkAll').click(function(){$('input[@name=chkItem]').attr('checked',$(this).attr('checked'));});
        
    $('#btnAddRelate').click(function(){
        $('#popupContact').popup({width:'80%',height:'80%',popupHead:'popupHead',btnClose:'popupContactClose'});
        //如果是第一次弹出层,或者改变了分类,要重新获取商品列表,否则只需要显示层即可
        if(popStatus == 0){
            CurrentPage = 1;
            BindProducts();popStatus = 1;
        };
    });
    
    BindDeleteEvent(1);
    
    //显示隐藏高级搜索
    $('#showadvsearch').toggle(function(){$('#advsearch').show();$('#showadvsearch').text('隐藏品牌');showadv = 1;},function(){$('#advsearch').hide();$('#showadvsearch').text('显示品牌');showadv = 0;});
	
	$('#sel_category').click(function(){
	    BindBrand();
	});
	
	$('#btnSearch').click(function(){
	    CurrentPage = 1;
	    BindProducts();
	});
	
	$('#btnSubmit').click(function(){
        var productIDs = '';
        var selectedPIDs = '';
        if($('#RltPID_curr').val() != ''){selectedPIDs = ','+$('#RltPID_curr').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 productno = objTRs.find('#ProductNo').text();
                var catname = objTRs.find('#Category').text();
                //绑定行
                var row = '<tr>';
                row += '<td class="delete"><img src="images/x-gray.gif" alt="删除" /><input type="hidden" name="rltpid" value='+ pid +'/></td>';
                row += '<td>' + productno + '</td>';
                row += '<td>' + productname + '</td>';
                row += '</tr>';
                row = $(row);
                row.find('.delete').css('cursor','pointer')
                    .find('img').click(function(){
                        row.remove();
                        var ids = '';
                        $('input[@name=rltpid]').each(function(){
                            ids += $(this).val() + ',';
                        });
                        if(ids != ''){ids = ids.substring(0,ids.length-1);};
                        $('#RltPID_curr').val(ids);
                    }).mouseover(function(){
                        $(this).attr('src','images/x-red.gif');
                    }).mouseout(function(){
                        $(this).attr('src','images/x-gray.gif');
                    });
                productIDs += pid + ',';
                
                row.appendTo($('#listresult'));
            };
        });//end each
        if(productIDs != ""){
            productIDs = productIDs.substring(0,productIDs.length-1);
            $('#RltPID_curr').val($('#RltPID_curr').val() + ($('#RltPID_curr').val() != '' ? ',' : '') + productIDs);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)            
        };
        $('#popupContactClose').click();//关闭层
    });//end click
    
    $('#btnSave').click(function(){
        if(NewsID != ''){
            //统计要从数据库中删除和要添加到数据库中的ID
            var oldPIDs = $('#RltPID_old').val();  //数据库中已存在的ID
            var currPIDs = $('#RltPID_curr').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
            
            $('#RltPID_new').val(newPIDs);
            $('#RltPID_deleted').val(deletedPIDs);
        };//end if
        
    });//end btnSave click
    
    
});// end ready

function BindBrand(){
    var catIDs = ($('#sel_category').val()==null ? '0' : $('#sel_category').val());
    $.ajax({
        url:'SearchProduct.aspx?type=ajax&Action=GetBrandByCatID&product_category_id='+catIDs + '&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(){
    var catIDs = ($('#sel_category').val()==null ? '0' : $('#sel_category').val());
    var brandIDs = ($('#sel_brand').val()==null ? '0' : $('#sel_brand').val());
    $('#template').hide();//将第一行模板隐藏
    $.ajax({
        type:"get",
        dataType:"json",
        url:'SearchProduct.aspx?NoCopyRight=1&type=ajax&Action=SearchProductsAjax&keyword=' + escape($('#txtKeyword').val()) + '&CatID=' + catIDs + '&BrandIDs=' + brandIDs + '&SearchType=' + $('#sel_searchType').val() + '&PageSize=' + PageSize + '&Page=' + CurrentPage,
        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('#Category').text($('#sel_category option[@value='+ n.CategoryID +']').text().replace('├',''));
				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();return false;"}//[attr]
            );
            
        },//end success
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert(textStatus)};}
    });//end ajax
}//end funciton

//相关商品删除事件;type为1相关商品
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');
    };

    $('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(productIDs != ""){
		productIDs = productIDs.substring(0,productIDs.length-1);
		objPID_old.val(productIDs);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)
		objPID_curr.val(productIDs);
	};
};

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