(function() {

	function autoFit() {
		if($(window).width()<1000) {
			$("#table_list").jqGrid('setGridParam', {
				shrinkToFit: false
			})
		} else {
			$("#table_list").jqGrid('setGridParam', {
				shrinkToFit: true
			})
		}
	}
	function resetWidth($el, opt) {
		
		if(autoFit !== false) {
			autoFit()
		}
		var diffHeight =  opt.diffHeight || 5
		var diffWidth = opt.diffWidth || 40
		var containerId = opt.containerId
		var barEle = document.getElementById("searchbar")
        var searchbarHeight = (barEle && barEle.clientHeight) || 0
        var pagerEle = document.getElementById("pager_list")
        var pagerHeight = (pagerEle && pagerEle.clientHeight) || 0
        var tableHeaderHeight = 40
        
        var $c = containerId?$("#"+containerId):$(window)
        $(".ui-jqgrid-titlebar").width($el.width()-diffWidth)
        $el.setGridWidth($c.width()-diffWidth);
        if($el.width()>($c.width()-diffWidth)) {
        	$el.jqGrid("setGridHeight", $c.height() - searchbarHeight - tableHeaderHeight - pagerHeight - 20 - diffHeight)
        } else {
        	$el.jqGrid("setGridHeight", $c.height() -searchbarHeight - tableHeaderHeight - pagerHeight - diffHeight)
        }
    }
	
	function initContainer($el, opt) {
		resetWidth($el, opt)
		window.onresize = function() {
			resetWidth($el, opt)
		}
	}
	
	function getDefaultOpt() {
		return {
			datatype:"local",
            mtype: 'GET',
            ajaxGridOptions: {
            	beforeSend: function(request, grid) {
		        	var userAgent = window.localStorage.getItem(httpRequest.agentName);
		        	request.setRequestHeader(httpRequest.agentName, userAgent);
		        }
            },
            beforeProcessing: function(data,st, xhr) {
	        	if(data.status == 998) {
            		top.toastr.error(data.errorMsg || "登录失效请重新登录！")
            		setTimeout(function() {
            			top.location.href = "../login/login.html"
            		}, 500)
            		return false
            	}
	        	return true
		    },
            prmNames: {
            	page: "page",
            	rows: "size"
            },
            rowNum: 10,
            rownumbers: true,
            jsonReader: {
            	root: "detailModelList",
            	page: "currPage",
            	records: "totalCount",
            	total: "totalPage"
            },
            height:400,
            autowidth:true,
            shrinkToFit:true,
			rowList:[10,20,30],
			pager:"#pager_list",
			pagerpos: "left",
			viewrecords:true,
			hidegrid:false
		}
	}
	
	$.fn.jqGridExt = function(pin) {
		var opt = getDefaultOpt()
		if (typeof pin === 'string') {
			return this.jqGrid.apply(this,arguments) 
		}
		var p = $.extend(true,{}, opt, pin)
		var o = this.jqGrid(p)
		
		initContainer(this, p)
		
		return o
	}
})()
