/*
*2013/6/2
*   表格控件汇总
*   包括：jqGrdi
*/

var ebGrid = {};

/**
*   异步获取jqGrid 表头
*/
ebGrid.ajaxJqGrid = function(options){
    var defaults = {
        timeout: 60000
    };
    var options = $.extend(true, defaults, options);
    $.ajax({
        type: "POST",
        url: options.columns_url,
        data: options.data,
        cache: false,
        dataType: "json",
        timeout: options.timeout,
        beforeSend: function(XMLHttpRequest){
    		$('h3.warn',options.$target).remove();
    		//options.$target.append('<h3 class="ajax-loading warn" ></h3>');
    	},
        error: function (XMLHttpRequest, textStatus, errorThrown) {
    		console.log(textStatus);
            $('h3.warn',options.$target).remove();
            var $h = $('<h3 class="warn ajax-failed"></h3><h3 class="ajax-warn"><a href="javascript: ;">点击这里，刷新数据</a></h3>');
            $('a', $h).click(function() { // 表头数据请求错误，提供刷新功能
            	$.ebAjax(options);
            });
            options.$target.html($h);
        },
        success: function(msg){
        	$('h3.warn',options.$target).remove();
            if( msg.success ){
                options = $.extend(true, msg, options);
                ebGrid[options.grid_type](options);
            } else {
            	$('h3.warn',options.$target).remove();
                options.$target.append('<h3 class="warn">系统错误，请联系管理员...</h3>');
            }
            
        }
    });
}

/**
*   异步获取普通jqGrid数据
*/
ebGrid.jqGrid = function(options){
    var defaults = {
            rowNum: 10,
            rownumbers: true,
            rowList: [10,20,30],
            sortname: options.colModel[0].name
    };
    options = $.extend(true,defaults,options);
    options.$target.html('<table id="eb_grid_'+options.id+'"></table><div id="eb_pager_'+options.id+'"></div>');
    
    $('#eb_grid_'+options.id).jqGrid({
        url: options.grid_url,
        datatype: 'json',
        mtype: 'POST',
        jsonReader : {
            root: "rows",
            page: "currpage",
            total: "totalpages",
            records: "totalrecords",
            repeatitems: false,
            id: "0"
        },
        multiselect: options.multiselect,
		multiboxonly: options.multiboxonly,
        postData: options.data,
        colNames: options.colNames,
        colModel: options.colModel,
        rowNum: options.rowNum,
        rownumbers: options.rownumbers,
//        rowList: options.rowList,
        caption : options.caption,
        pager: '#eb_pager_'+options.id,
        shrinkToFit: options.shrinkToFit,
        autowidth:true,
        sortname: options.sortname,
        sortorder: "desc",
        viewrecords: true,
        width: options.width,
        height: options.height,
        recordtext: options.recordtext || "共{2}条记录,显示{0}到{1}",
        emptyrecords: "没有要显示的记录",
        loadtext: "",
        pgtext : "{0}/{1}页",
        beforeRequest:function(){
        	
        	loading('数据读取中...',$('#eb_grid_'+options.id));
        	$('#eb_grid_'+options.id).jqGrid('clearGridData');	// 请求下次数据前，清空前一次数据
            $('h3.warn',$('#eb_grid_'+options.id).parent()).remove();
            $('h3.norecords',$('#eb_grid_'+options.id).parent()).remove();
        },
        loadError:function(xhr,status,error){
        	
        	console.log("error status:"+status+";error message:"+error);
        	 $('h3.warn',options.$target).remove();
        	 var $h = $('<h3 class="warn ajax-failed"></h3><h3 class="ajax-warn"><a href="javascript: ;">点击这里，刷新数据</a></h3>');
            $('a',$h).click(function(){// 表头数据请求错误，提供刷新功能
                ebGrid.jqGrid(options);
            });
            $('#eb_grid_'+options.id).parent().html($h);
            loadClose($('#eb_grid_'+options.id));
        },
        loadComplete:function(){
        	loadClose($('#eb_grid_'+options.id));
			},
        ondblClickRow:function(id){
        	if(options.ondblClickRow)
        		options.ondblClickRow(id);
        },
        gridComplete:function(){
        	
        	$('h3.warn',options.$target).remove();
        	$('h3.norecords',options.$target).remove();
            var records  = $('#eb_grid_'+options.id).getGridParam('records');
            if( !records || records<= 0 ){
            	$('#eb_grid_'+options.id).parent().find('.norecords').remove();
                $('#eb_grid_'+options.id).parent().append('<h3 class="norecords">没有符合条件的记录</h3>');
            } else {
                // 以下是添加百分比的背景色
                if( options.ratios){ 
                    var _ids  = $('#eb_grid_'+options.id).jqGrid('getDataIDs');
                    $(_ids).each(function(i, n) {
                        var _html = {};
                        for( var index in options.ratios){
                            var currCol = options.ratios[index];
                            _html[currCol] = $('#eb_grid_'+options.id).jqGrid('getCell', n, currCol).replace('%','');
                            var color = 'red' ;
                            if( _html[currCol] < 0 ){
                                color = '#97C61A';
                            }
                            _html[currCol] = ('<div style="position: relative;">' +
                                    '<div style="position: relative;width: '+Math.abs(_html[currCol])+'%;height: 20px;margin-top: 1px;background: none repeat 0 0 '+color+';">&nbsp;</div>' +
                                    '<div style="position: absolute;top: 0px;right: 20%;width: 80%;height: 20px;line-height: 20px;">'+ _html[currCol] +'</div>' + 
                                '</div>');
                        }
                        
                        $('#eb_grid_'+options.id).jqGrid('setRowData', n, _html);//{ func: _html }
                    });
                }
                if( options.percentFormate){ 
                    var _ids  = $('#eb_grid_'+options.id).jqGrid('getDataIDs');
                    
                    $(_ids).each(function(i, n) {
                        var rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['RATE'];
                        var pvrate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['PVRATE'];
                        var uvrate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['UVRATE'];
                        var odr_rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['ODR_RATE'];
         				var quit_rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['QUIT_RATE'];
         				var bkid_read_rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['BKID_READ_RATE'];
         				var bkid_odr_rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['BKID_ODR_RATE'];
         				var read_rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['READ_RATE'];
         				if(rate){rate = Math.round(rate * 10000) / 100 + "%";}else{rate = "0%"}
         				if(odr_rate){odr_rate = Math.round(odr_rate * 10000) / 100 + "%";}else{odr_rate = "0%"}
         				if(quit_rate){quit_rate = Math.round(quit_rate * 10000) / 100 + "%";}else{quit_rate = "0%"}
                        if(pvrate){pvrate = Math.round(pvrate * 10000) / 100 + "%";}else{pvrate = "0%"}
                        if(uvrate){uvrate = Math.round(uvrate * 10000) / 100 + "%";}else{pvrate = "0%"}
                        if(bkid_read_rate){bkid_read_rate = Math.round(bkid_read_rate * 10000) / 100 + "%";}else{bkid_read_rate = "0%"}
                        if(bkid_odr_rate){bkid_odr_rate = Math.round(bkid_odr_rate * 10000) / 100 + "%";}else{bkid_odr_rate = "0%"}
                        if(read_rate){read_rate = Math.round(read_rate * 10000) / 100 + "%";}else{read_rate = "0%"}
                        
                        $('#eb_grid_'+options.id).jqGrid('setRowData', n, {RATE:rate,ODR_RATE:odr_rate,QUIT_RATE:quit_rate,PVRATE:pvrate,UVRATE:uvrate,BKID_READ_RATE:bkid_read_rate,BKID_ODR_RATE:bkid_odr_rate,READ_RATE:read_rate});//{ func: _html }
                    });
                }
                $('#eb_grid_'+options.id).jqGrid('setFrozenColumns');
                if( options.gridCallback ){
                    options.gridCallback();
                }
            }
        }
    });

    // 表头提示信息    
    for( var index in options.colModel ){
        var column = options.colModel[index];
        if( column.describe ){
            $('#jqgh_eb_grid_'+options.id+'_'+ column.name ).append('<a class="help-img tooltips" title="'+column.describe+'"></a>');
            $('.tooltips',$('#jqgh_eb_grid_'+options.id+'_'+ column.name )).toolTip();
        }                
    }
    $('#eb_grid_'+options.id).setGridWidth(options.$target.parent().width());
//  $('#eb_grid_'+options.id).setGridHeight((window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight))-565);
    $(window).resize(function(){
        $('#eb_grid_'+options.id).setGridWidth(options.$target.parent().width());
//      $('#eb_grid_'+options.id).setGridHeight((window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight))-265);
    });
};

/**
*   异步获取jqGrid数据 包括checkbox勾选功能
*/
ebGrid.checkGrid = function(options){
    var defaults = {
            rowNum: 10,
            rownumbers: true,
//            rowList: [10,20,30],
            sortname: options.colModel[0].name
    };
    options = $.extend(true,defaults,options);
    options.$target.html('<table id="eb_grid_'+options.id+'"></table><div id="eb_pager_'+options.id+'"></div>');
    
    $('#eb_grid_'+options.id).jqGrid({
        url: options.grid_url,
        datatype: 'json',
        mtype: 'POST',
        jsonReader : {
            root: "rows",
            page: "currpage",
            total: "totalpages",
            records: "totalrecords",
            repeatitems: false,
            id: "id"
        },
        postData: options.postData,
        colNames: options.colNames,
        colModel: options.colModel,
        rowNum: options.rowNum,
        rownumbers: options.rownumbers,
        rowList: options.rowList,
        caption : options.caption,
        pager: '#eb_pager_'+options.id,
        shrinkToFit: options.shrinkToFit,
        sortname: options.sortname,
        sortorder: "desc",
        viewrecords: true,
        width: options.width,
        height: options.height,
        autowidth:options.autowidth,
        recordtext: "共{2}条记录,显示{0}到{1}",
        emptyrecords: "没有要显示的记录",
        loadtext: "数据读取中...",
        pgtext : "{0}/{1}页",
        multiselect:true,
		onSelectRow: function (rowId, status, e) {
			if( options.onSelectRow ){
                    options.onSelectRow(rowId);
            }
	    },
		onSelectAll: function (rowId, status, e) {
			if( options.onSelectAll ){
                    options.onSelectAll(rowId, status);
            }
	    },
        beforeRequest:function(){
        	$('#eb_grid_'+options.id).jqGrid('clearGridData');	// 请求下次数据前，清空前一次数据
            $('h3.warn',$('#eb_grid_'+options.id).parent()).remove();
            $('h3.norecords',$('#eb_grid_'+options.id).parent()).remove();
        },
        loadError:function(xhr,status,error){
        	console.log("status:"+status+",error:"+error);
        	 $('h3.warn',options.$target).remove();
        	 var $h = $('<h3 class="warn ajax-failed"></h3><h3 class="ajax-warn"><a href="javascript: ;">点击这里，刷新数据</a></h3>');
            $('a',$h).click(function(){// 表头数据请求错误，提供刷新功能
                ebGrid.jqGrid(options);
            });
            $('#eb_grid_'+options.id).parent().html($h);
        },
        loadComplete:function(){
			if( options.loadComplete ){
				options.loadComplete();
			}
		},
        gridComplete:function(){
        	$('h3.warn',options.$target).remove();
            var records  = $('#eb_grid_'+options.id).getGridParam('records');
            if( !records || records<= 0 ){
                $('#eb_grid_'+options.id).parent().append('<h3 class="warn">没有符合条件的记录</h3>');
            } else {
                // 以下是添加百分比的背景色
                if( options.ratios){ 
                    var _ids  = $('#eb_grid_'+options.id).jqGrid('getDataIDs');
                    
                    $(_ids).each(function(i, n) {
                        var _html = {};
                        for( var index in options.ratios){
                            var currCol = options.ratios[index];
                            _html[currCol] = $('#eb_grid_'+options.id).jqGrid('getCell', n, currCol).replace('%','');
                            var color = 'red' ;
                            if( _html[currCol] < 0 ){
                                color = '#97C61A';
                            }
                            _html[currCol] = ('<div style="position: relative;">' +
                                    '<div style="position: relative;width: '+Math.abs(_html[currCol])+'%;height: 20px;margin-top: 1px;background: none repeat 0 0 '+color+';">&nbsp;</div>' +
                                    '<div style="position: absolute;top: 0px;right: 20%;width: 80%;height: 20px;line-height: 20px;">'+ _html[currCol] +'</div>' + 
                                '</div>');
                        }
                        
                        $('#eb_grid_'+options.id).jqGrid('setRowData', n, _html);//{ func: _html }
                    });
                }
            }
            if( options.gridCallback ){
            	options.gridCallback();
            }

            
        }
    });
};
/**
*   异步获取普通jqGrid数据,增加行选中事件处理
*/
ebGrid.jqGrid_OnSelect = function(options){
    var defaults = {
            rowNum: 10,
            rownumbers: true,
            rowList: [10,20,30],
            sortname: options.colModel[0].name
    };
    options = $.extend(true,defaults,options);
    options.$target.html('<table id="eb_grid_'+options.id+'"></table><div id="eb_pager_'+options.id+'"></div>');
    
    $('#eb_grid_'+options.id).jqGrid({
        url: options.grid_url,
        datatype: 'json',
        mtype: 'POST',
        jsonReader : {
            root: "rows",
            page: "currpage",
            total: "totalpages",
            records: "totalrecords",
            repeatitems: false,
            id: "0"
        },
        multiselect: options.multiselect,
		multiboxonly: options.multiboxonly,
        postData: options.data,
        colNames: options.colNames,
        colModel: options.colModel,
        rowNum: options.rowNum,
        rownumbers: options.rownumbers,
        rowList: options.rowList,
        caption : options.caption,
        pager: '#eb_pager_'+options.id,
        shrinkToFit: options.shrinkToFit,
        sortname: options.sortname,
        sortorder: "desc",
        viewrecords: true,
        width: options.width,
        height: options.height,
        recordtext: options.recordtext || "共{2}条记录,显示{0}到{1}",
        emptyrecords: "没有要显示的记录",
        loadtext: "数据读取中...",
        pgtext : "{0}/{1}页",
        onSelectRow: options.onSelectRow,
        beforeRequest:function(){
        	$('#eb_grid_'+options.id).jqGrid('clearGridData');	// 请求下次数据前，清空前一次数据
            $('h3.warn',$('#eb_grid_'+options.id).parent()).remove();
            $('h3.norecords',$('#eb_grid_'+options.id).parent()).remove();
        },
        loadError:function(){
        	 $('h3.warn',options.$target).remove();
        	 var $h = $('<h3 class="warn ajax-failed"></h3><h3 class="ajax-warn"><a href="javascript: ;">点击这里，刷新数据</a></h3>');
            $('a',$h).click(function(){// 表头数据请求错误，提供刷新功能
                ebGrid.jqGrid(options);
            });
            $('#eb_grid_'+options.id).parent().html($h);
        },
        loadComplete:function(){},
        gridComplete:function(){
        	$('h3.warn',options.$target).remove();
        	$('h3.norecords',options.$target).remove();
            var records  = $('#eb_grid_'+options.id).getGridParam('records');
            if( !records || records<= 0 ){
            	$('#eb_grid_'+options.id).parent().find('.norecords').remove();
                $('#eb_grid_'+options.id).parent().append('<h3 class="norecords">没有符合条件的记录</h3>');
            } else {
            	 $('#eb_grid_'+options.id).jqGrid('setSelection', "1");
                // 以下是添加百分比的背景色
                if( options.ratios){ 
                    var _ids  = $('#eb_grid_'+options.id).jqGrid('getDataIDs');
                    
                    $(_ids).each(function(i, n) {
                        var _html = {};
                        for( var index in options.ratios){
                            var currCol = options.ratios[index];
                            _html[currCol] = $('#eb_grid_'+options.id).jqGrid('getCell', n, currCol).replace('%','');
                            var color = 'red' ;
                            if( _html[currCol] < 0 ){
                                color = '#97C61A';
                            }
                            _html[currCol] = ('<div style="position: relative;">' +
                                    '<div style="position: relative;width: '+Math.abs(_html[currCol])+'%;height: 20px;margin-top: 1px;background: none repeat 0 0 '+color+';">&nbsp;</div>' +
                                    '<div style="position: absolute;top: 0px;right: 20%;width: 80%;height: 20px;line-height: 20px;">'+ _html[currCol] +'</div>' + 
                                '</div>');
                        }
                        
                        $('#eb_grid_'+options.id).jqGrid('setRowData', n, _html);//{ func: _html }
                    });
                }
                if( options.percentFormate){ 
                    var _ids  = $('#eb_grid_'+options.id).jqGrid('getDataIDs');
                    
                    $(_ids).each(function(i, n) {
                        var pvrate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['PVRATE'];
                        var uvrate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['UVRATE'];
                        var odr_rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['ODR_RATE'];
         				var quit_rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['QUIT_RATE'];
         				var bkid_read_rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['BKID_READ_RATE'];
         				var bkid_odr_rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['BKID_ODR_RATE'];
         				var read_rate = $('#eb_grid_'+options.id).jqGrid('getRowData',n)['READ_RATE'];
         				
         				if(odr_rate){odr_rate = Math.round(odr_rate * 10000) / 100 + "%";}else{odr_rate = "0%"}
         				if(quit_rate){quit_rate = Math.round(quit_rate * 10000) / 100 + "%";}else{quit_rate = "0%"}
                        if(pvrate){pvrate = Math.round(pvrate * 10000) / 100 + "%";}else{pvrate = "0%"}
                        if(uvrate){uvrate = Math.round(uvrate * 10000) / 100 + "%";}else{pvrate = "0%"}
                        if(bkid_read_rate){bkid_read_rate = Math.round(bkid_read_rate * 10000) / 100 + "%";}else{bkid_read_rate = "0%"}
                        if(bkid_odr_rate){bkid_odr_rate = Math.round(bkid_odr_rate * 10000) / 100 + "%";}else{bkid_odr_rate = "0%"}
                        if(read_rate){read_rate = Math.round(read_rate * 10000) / 100 + "%";}else{read_rate = "0%"}
                        
                        $('#eb_grid_'+options.id).jqGrid('setRowData', n, {ODR_RATE:odr_rate,QUIT_RATE:quit_rate,PVRATE:pvrate,UVRATE:uvrate,BKID_READ_RATE:bkid_read_rate,BKID_ODR_RATE:bkid_odr_rate,READ_RATE:read_rate});//{ func: _html }
                    });
                }
                $('#eb_grid_'+options.id).jqGrid('setFrozenColumns');
                if( options.gridCallback ){
                    options.gridCallback();
                }
            }

            
        }
    });

    // 表头提示信息    
    for( var index in options.colModel ){
        var column = options.colModel[index];
        if( column.describe ){
            $('#jqgh_eb_grid_'+options.id+'_'+ column.name ).append('<a class="help-img tooltips" title="'+column.describe+'"></a>');
            $('.tooltips',$('#jqgh_eb_grid_'+options.id+'_'+ column.name )).toolTip();
        }                
    }
    $('#eb_grid_'+options.id).setGridWidth(options.$target.parent().width()-2);
//  $('#eb_grid_'+options.id).setGridHeight((window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight))-565);
    $(window).resize(function(){
        $('#eb_grid_'+options.id).setGridWidth(options.$target.parent().width()-2);
//      $('#eb_grid_'+options.id).setGridHeight((window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight))-265);
    });
};

/**
 * 包含子表格的表格
 * 
 * 参数：
 * {
 		id: id,
		height: 800,
        $target: $('#id'),
        grid_type: "subGrid",
        columns_url: ,
        grid_url: ,
		callback: func,	// 回调函数
 * }
 */
ebGrid.subGrid = function(options){
	var defaults = {
        rowNum: 10,
        rownumbers: true,
        rowList: [10, 20, 30],
        sortname: options.colModel[1].name
    };
	options = $.extend(true, defaults, options);
	options.$target.html('<table id="eb_grid_' + options.id + '" class="sub-grid-table"></table><div id="eb_pager_' + options.id + '"></div>');
	
	$("#eb_grid_" + options.id).jqGrid({
		url: options.grid_url,
		datatype: 'json',
		mtype: 'POST',
		jsonReader : {
			root: "rows",
			page: "currpage",
			total: "totalpages",
			records: "totalrecords",
			repeatitems: false,
			id: "0"
		},
		postData: options.data,
		colNames: options.colNames,
		colModel: options.colModel,
		rowNum: options.rowNum,
		rownumbers: options.rownumbers,
        rowList: options.rowList,
        pager: "eb_pager_" + options.id, 
        shrinkToFit: false,
        sortname: options.sortname, 
        sortorder: options.sortorder,
        viewrecords: true,
        width: options.width,
        height: options.height,
        recordtext: "共{2}条记录,显示{0}到{1}",
        emptyrecords: "没有要显示的记录",
        loadtext: "数据读取中...",
        pgtext : "{0}/{1}页",
        hidegrid: false,
		caption: "<span id='caption_" + options.id + "' class='sub-grid'>图书数据报表<a class='star custome-column' href='javascript:void(0)'>自定义指标</a></spam>",
		subGrid: true,
		subGridRowExpanded: function(subgrid_id, row_id) {
			options.callback && options.callback(subgrid_id, row_id, options);
		},
		subGridRowColapsed: function(subgrid_id, row_id) { 
			$("#"+subgrid_id + "_t").remove();
			$("#eb_grid_" + options.id).jqGrid('resetSelection');			
		},
		ondblClickRow:function(rowid){
		    $(this).jqGrid("toggleSubGridRow", rowid);
		},
		beforeRequest:function(){
            $('h3.warn',$('#eb_grid_'+options.id).parent()).remove();
            $('h3.norecords',$('#eb_grid_'+options.id).parent()).remove();
        },
        loadError:function(){
        	$('h3.warn',options.$target).remove();
            var $h = $('<h3 class="warn">数据读取失败</h3><h3 class="warn"><a href="#">点击这里，刷新数据</a></h3>');
            $('a',$h).click(function(){// 表头数据请求错误，提供刷新功能
                ebGrid.subGrid(options);
            });
            $('#eb_grid_'+options.id).parent().html($h);
        },
        loadComplete:function(){},
		gridComplete:function() {
			var records = $("#eb_grid_" + options.id).getGridParam('records');
            if( !records || records<= 0 ) {
            	$("#eb_grid_" + options.id).parent().append('<h3 class="norecords">没有符合条件的记录</h3>');
            } else {
                // 以下是添加百分比的背景色
                if( options.ratios){ 
                    var _ids = $("#eb_grid_" + options.id).jqGrid('getDataIDs');
                    
                    $(_ids).each(function(i, n) {
                        var _html = {};
                        for( var index in options.ratios){
                            var currCol = options.ratios[index];
                            _html[currCol] = $("#eb_grid_" + options.id).jqGrid('getCell', n, currCol);
                            var tmp = _html[currCol].split("_");
                            if (tmp.length == 2) {	//一列包含两个字段，需要拆分处理
                            	_html[currCol] = tmp[1];
                            }
                            var color = 'red' ;
                            if( _html[currCol] < 0 ){
                                color = 'blue';
                                _html[currCol] = -_html[currCol];
                            }
                            _html[currCol] = ('<div style="position: relative; float:left; width: 60px; margin-left:10px;">' +
                                    '<div style="position: relative;width: '+_html[currCol]+'%;height: 20px;margin-top: 1px;background: none repeat 0 0 '+color+';">&nbsp;</div>' +
                                    '<div style="position: absolute;top: 0px;right: 20%;width: 80%;height: 20px;line-height: 20px;">'+ _html[currCol] +'%</div>' + 
                                '</div>');
                            
                            if (tmp.length == 2) {
                            	_html[currCol] = ('<div style="align: center;"><div style="float:left; width: 70px;">' + tmp[0] + '</div>' + _html[currCol] + '</div>');
                            }
                        }
                        
                        $("#eb_grid_" + options.id).jqGrid('setRowData', n, _html);
                    });
                }
            }
		}
	});
	$("#eb_grid_" + options.id).jqGrid('navGrid', "eb_pager_" + options.id, {search:false, add:false, del:false});	
	$("#eb_grid_" + options.id).jqGrid('hideCol', 'subgrid');
	
	$('#eb_grid_' + options.id).setGridWidth(options.$target.parent().width()-2);
    $(window).resize(function(){
    	$('#eb_grid_'+options.id).setGridWidth(options.$target.parent().width()-2);
    });
	
	// 自定义字段
	$('#caption_' + options.id + " .custome-column").click(function() {
		var id = 'dlg_customeColumn_' + options.id;
		var dlgHtml = dialogTmp({
			id: id,
			hiddenColumn: $("#caption_" + options.id).data('hiddenColumn_' + options.id),	// 拿缓存的数据
			colNames: options.colNames,
			colModel: options.colModel
		});
		
		$('#eb_grid_' + options.id).append(dlgHtml);
		
		$("#" + id).dialog({
			title: '自定义字段',
			height: 300,
		    width: 200,
			closed: false,
	    	autoOpen: true,
	    	modal: true,
	    	resizable: false,
	    	buttons: {
	        	"确定": function() {
	        		var allColumn = [];
	        		for (var i=0; i<options.colModel.length; i++) {
	        			allColumn.push(options.colModel[i].name);
	        		}
	        		
	        		$("#eb_grid_" + options.id).jqGrid('showCol', allColumn); // 首先显示所有列
	        		
	        		// 重新读取选中的列
	        		var hiddenColumn = [];
	        		$("#" + id + ' input[name="checkbox"]:checked').each(function(){  
	        			hiddenColumn.push($(this).val());
	        		});
	        		$("#caption_" + options.id).data('hiddenColumn_' + options.id, hiddenColumn); // 缓存数据
	        		
	        		$("#eb_grid_" + options.id).jqGrid('hideCol', hiddenColumn);	// 然后隐藏选中的列
	        		$("#eb_grid_" + options.id).trigger("resize");

	        		$(this).dialog("close");
	        		$(this).remove();
	        	},
				"取消": function() {
					$(this).dialog("close");
					$(this).remove();
				}
	    	}
	    });
	});
};

/**
 * 下钻子表格
 * 参数
 * {
 * 		id: id,
 * 		$target: $("#xxxx"),
 * 		grid_url: /bi/xx/xxxx.action,
 * 		data:{},						// 往后台传的参数
 * 		width: 800,
 * 		height: 300,
 * 		width_diff: 2,					// 设置宽度时的差值
 * 		group_head: true/false,			// 是否合并表头
 * }
 */
ebGrid.drillDownGrid = function(options){
	var defaults = {
		nodeid: '',
		expand_column: options.colModel[1].name,
		width_diff: 2
	};
	options = $.extend(true, defaults, options);
	var isGridInit = true;
	options.$target.html("<table id='eb_grid_" + options.id + "' class='scroll'></table><div id='eb_pager_" + options.id + "' class='scroll'></div>");
	$("#eb_grid_" + options.id).jqGrid({
		url: options.grid_url,
		datatype: 'json',
		mtype: 'POST',
		postData: options.data,
		treeGrid: true,
		treeGridModel: 'adjacency',
		ExpandColumn: options.expand_column,
		ExpandColClick: true,
		colNames: options.colNames,
		colModel: options.colModel,
		rowNum: 10,
		rownumbers: false,
		pager: 'eb_pager_' + options.id,
		shrinkToFit: false,
		viewrecords: true,
		width: options.width,
		height: options.height,
		recordtext: "共{2}条记录,显示{0}到{1}",
		emptyrecords: "没有要显示的记录",
		loadtext: "数据读取中...",
		pgtext : "{0}/{1}页",
		beforeRequest:function(){
			options.nodeid = $('#eb_grid_'+options.id).getPostDataItem('nodeid');
			$('h3.warn',$('#eb_grid_'+options.id).parent()).remove();
			$('h3.norecords',$('#eb_grid_'+options.id).parent()).remove();
		},
		loadError:function(){
			$('h3.warn',options.$target).remove();
			var $h = $('<h3 class="warn">数据读取失败</h3><h3 class="warn"><a href="#">点击这里，刷新数据</a></h3>');
            $('a',$h).click(function(){// 表头数据请求错误，提供刷新功能
                ebGrid.drillDownGrid(options);
            });
            $('#eb_grid_'+options.id).parent().html($h);
		},
		loadComplete:function(){},
		gridComplete:function(){
			if( isGridInit ){
				isGridInit = false;
				var records  = $('#eb_grid_'+options.id).getGridParam('records');
	            if( !records || records<= 0 ){
	                $('#eb_grid_'+options.id).parent().html('<h3 class="norecords">没有符合条件的记录</h3>');
	            }
			}
			if( options.gridComplete ){
            	options.gridComplete();
            }
		}
	});
	
	$("#eb_grid_" + options.id).jqGrid('navGrid', "#eb_pager_" + options.id, {edit:false, add:false, del:false, search:false,refresh: false});
	$('#eb_grid_' + options.id).setGridWidth(options.$target.parent().width()-options.width_diff);
    $(window).resize(function(){
    	$('#eb_grid_' + options.id).setGridWidth(options.$target.parent().width()-options.width_diff);
    });

    // 合并表头
    if (options.group_head) {
    	$("#eb_grid_" + options.id).jqGrid('setGroupHeaders', { 
    		useColSpanStyle: true, 
    		groupHeaders: options.group_head_column
    	});
    }
};
