(function($) {
    $.addFlex = function(t, p) {
        if (t.grid) return false; //如果Grid已经存在则返回
        // 引用默认属性
        p = $.extend({
            height: 200, //flexigrid插件的高度，单位为px
            width: 'auto', //宽度值，auto表示根据每列的宽度自动计算
            striped: true, //是否显示斑纹效果，默认是奇偶交互的形式
            novstripe: false,
            minwidth: 30, //列的最小宽度
            minheight: 80, //列的最小高度
            errormsg: '发生错误', //错误提升信息
            usepager: true, //是否分页
            dataType: 'json',
            nowrap: true, //是否不换行
            page: 1, //current page,默认当前页
            total: 1, //total pages,总页面数
            useRp: true, //use the results per page select box,是否可以动态设置每页显示的结果数
            rp: 20, // results per page,每页默认的结果数
            rpOptions: [5, 10, 20, 30, 40, 50, 100], //可选择设定的每页结果数
            title: false, //是否包含标题
            pagestat: '显示记录从{from}到{to}，总数 {total} 条', //显示当前页和总页面的样式
            procmsg: '正在处理数据，请稍候 ...', //正在处理的提示信息
            query: '', //搜索查询的条件
            nomsg: '没有符合条件的记录存在', //无结果的提示信息
            minColToggle: 1, //minimum allowed column to be hidden
            hideOnSubmit: true, //显示遮盖
            showTableToggleBtn: false, //显示隐藏Grid 
            autoload: true, //自动加载
            blockOpacity: 0.5, //透明度设置
            onToggleCol: false, //当在行之间转换时
            onChangeSort: false, //当改变排序时
            onSuccess: false, //成功后执行
            showcheckbox: false, //是否显示checkbox    
            singleselected: false, //是否单选
            rowhandler: false, //是否启用行的扩展事情功能
            rowbinddata: false,
            selectedonclick: false, //点击行是否选中
            gridClass: "bbit-grid",
            onrowchecked: false,
            rowcheckboxselect: true, //点击行时checkbox是否选中为false时行样式不改变
            showTree: false,
            extParam: false,
            extPageTheme: false,
            specialColumn: false,
            onLoaded: false,
            hideHeader: false,
            columndata: false,
            isClickColumn: false,
            rowHeight: 22    //行高度
        }, p);

        $(t)
		.show() //show if hidden
		.attr({ cellPadding: 0, cellSpacing: 0, border: 0 })  //remove padding and spacing
		.removeAttr('width') //remove width properties	
		;
        //create grid class
        var g = {
            hset: {},
            rePosDrag: function() {
                var cdleft = 0 - this.hDiv.scrollLeft;
                if (this.hDiv.scrollLeft > 0) cdleft -= Math.floor(p.cgwidth / 2);
                var cdpad = this.cdpad;
                //update by xuanye ,避免jQuery :visible 无效的bug
                var i = 0;
                $('thead tr:first th:visible', this.hDiv).each(function() {
                    if ($(this).css("display") == "none") {
                        return;
                    }
                    var n = i;
                    //var n = $('thead tr:first th:visible', g.hDiv).index(this);			 	  
                    var cdpos = parseInt($('div', this).width());
                    var ppos = cdpos;
                    if (cdleft == 0)
                        cdleft -= Math.floor(p.cgwidth / 2);

                    cdpos = cdpos + cdleft + cdpad;

                    cdleft = cdpos;
                    i++;
                }
				);

            },
            fixHeight: function(newH) {
                newH = false;
                if (!newH) newH = $(g.bDiv).height();
                var hdHeight = $(this.hDiv).height();
                $(g.block).css({ height: newH, marginBottom: (newH * -1) });
                var hrH = g.bDiv.offsetTop + newH;
            },
            reSize: function() {

                this.gDiv.style.width = p.width;
                this.bDiv.style.height = p.height;

            },
            scroll: function() {
                this.hDiv.scrollLeft = this.bDiv.scrollLeft;
                this.rePosDrag();
            },
            hideLoading: function() {
                $('.pReload', this.pDiv).removeClass('loading');
                if (p.hideOnSubmit) $(g.block).remove();
                if (p.usepager) {
                    $('.pPageStat', this.pDiv).html(p.errormsg);
                }
                this.loading = false;
            },
            /*控制指定小数四舍五入，保留位数为roundDigit     */
            DataToFixed: function(numberRound, roundDigit) {
                var tempNumber = numberRound;
                if (numberRound >= 0) {
                    tempNumber = parseInt((numberRound * Math.pow(10, roundDigit) + 0.5)) / Math.pow(10, roundDigit);
                }
                else {
                    numberRound1 = -numberRound;
                    tempNumber = parseInt((numberRound1 * Math.pow(10, roundDigit) + 0.5)) / Math.pow(10, roundDigit);
                    tempNumber = -tempNumber;
                }
                var tempString = tempNumber.toString();
                var tempLen = 0;
                if (roundDigit > 0) {
                    if (tempString.indexOf('.') == -1) {
                        tempString += ".";
                    }
                    else {
                        var tempValue = tempString.substring(parseInt(parseInt(tempString.indexOf('.')) + 1), tempString.length);
                        tempLen = tempValue.length;
                        tempValue = null;
                    }
                    if (tempLen < roundDigit) {
                        for (var i = 0; i < roundDigit - tempLen; i++) {
                            tempString += "0";
                        }
                    }
                }
                tempNumber = tempString;
                tempString = null;
                tempLen = null;
                CollectGarbage();
                return tempNumber;
            },
            addData: function(data) { //parse data
                /// $('thead tr:first th', g.hDiv).each(function() { alert($(this).parent().html())});
                //alert(12)
                $('.pReload', this.pDiv).removeClass('loading');
                this.loading = false;
                if (!data) {
                    if (p.usepager) {
                        $('.pPageStat', this.pDiv).html(p.errormsg);
                    }
                    return false;
                }
                var temp = p.total;
                if (data.result == "0") {
                    p.total = 0;
                }
                else {
                    if (typeof (data.AllCount) == "undefined") {
                        p.total = data.table[0].AllCount;
                    }
                    else {
                        p.total = parseInt(data.AllCount);
                    }
                }
                if (p.total < 0) {
                    p.total = temp;
                }
                if (p.total == 0) {
                    //alert($(t).html())
                    //$('tr, a, td, div', t).unbind();  事件清空时耗时太长
                    $(t).empty();
                    p.pages = 1;
                    p.page = 1;
                    this.buildpager();
                    if (p.usepager) {
                        $('.pPageStat', this.pDiv).html(p.nomsg);
                    }
                    if (p.hideOnSubmit) $(g.block).remove();
                    return false;
                }
                p.pages = Math.ceil(p.total / p.rp);
                p.page = data.pageIndex;
                this.buildpager();
                var ths = $('thead tr:first th', g.hDiv);
                var thsdivs = $('thead tr:first th div', g.hDiv);
                var tbhtml = [];
                tbhtml.push("<tbody>");
                var tfoot = [];
                tfoot.push("<tfoot>");
                var isAddFoot = false;
                var mierString = "";
                var mierObj = new Array();
                if (p.dataType == 'json') {
                    if (data.table != null) {
                        $.each(data.table, function(i, row) {
                            tbhtml.push("<tr id='", row["ID"], "'");
                            if (p.rowbinddata) {

                                var attList = [];
                                $(ths).each(function(j) {
                                    var fileName = $(this).attr('attrfiledname')
                                    if (typeof fileName != "undefined") {
                                        attList.push(fileName);
                                        attList.push("=");
                                        attList.push("\"");
                                        attList.push(row[fileName]);
                                        attList.push("\"");
                                        attList.push(" ")
                                    }

                                });
                                //tbhtml.push("chrow='", row, "' ");
                                tbhtml.push(attList.join(""));

                            }
                            tbhtml.push(">");
                            var trid = row["ID"];
                            var rowNum = i;
                            var _footIndex = 0;
                            $(ths).each(function(j) {
                                var tddata = "";
                                var tdclass = "";
                                tbhtml.push("<td align='", this.align, "'");
                                var idx = $(this).attr('attrfiledname');
                                if (p.sortname && p.sortname == $(this).attr('abbr')) {
                                    tdclass = 'sorted';
                                }
                                if (this.hide) {
                                    tbhtml.push(" style='display:none;'");
                                }
                                var width = thsdivs[j].style.width;
                                var div = [];
                                div.push("<div style='height:", p.rowHeight, ";text-align:", this.align, ";width:", width, ";");
                                if (p.nowrap == false) {
                                    div.push("white-space:normal");
                                }
                                div.push("'>");
                                if (typeof idx == "undefined") { //checkbox
                                    if (typeof row["IsLock"] == "undefined") {
                                        div.push("<input type='checkbox' id='chk_", row.id, "' class='itemchk' value='", row.id, "'/>");
                                    }
                                    else {
                                        div.push("<input type='checkbox' id='chk_", row["IsLock"], "' class='itemchk' value='", row["IsLock"], "'/>");
                                    }
                                    if (tdclass != "") {
                                        tdclass += " chboxtd";
                                    } else {
                                        tdclass += "chboxtd";
                                    }
                                }
                                else {
                                    var divInner = row[idx] || "&nbsp;";
                                    if (this.digit) {
                                        if (divInner == "&nbsp;") {
                                            divInner = 0;
                                        }
                                        divInner = g.DataToFixed(divInner, this.digit);
                                    }
                                    if (p.showfoot) {
                                        /*计算统计*/
                                        if (this.summary) {
                                            if (mierString.indexOf("{cell:" + j + "}") == -1) {
                                                if (mierString == "") {
                                                    mierString = "{cell:" + j + "}";
                                                }
                                                else {
                                                    mierString += "," + "{cell:" + j + "}";
                                                }
                                                mierObj.push({ cell: j, count: 1, sum: 0, avg: 0, summaryDigit: this.summaryDigit });
                                            }
                                            if (this.summary == 'count') {
                                                for (var nn = 0; nn < mierObj.length; nn++) {
                                                    if (mierObj[nn].cell == j) {
                                                        mierObj[nn].count = parseInt(mierObj[nn].count) + 1;
                                                        break;
                                                    }
                                                }
                                            }
                                            else if (this.summary == 'sum') {
                                                var DataValue = parseInt(divInner);
                                                if (DataValue == NaN) {
                                                    DataValue = 0;
                                                }
                                                for (var nn = 0; nn < mierObj.length; nn++) {
                                                    if (mierObj[nn].cell == j) {
                                                        mierObj[nn].sum = parseInt(mierObj[nn].sum) + DataValue;
                                                        break;
                                                    }
                                                }
                                            }
                                            else if (this.summary == 'avg') {
                                                var DataValue = parseInt(divInner);
                                                if (DataValue == NaN) {
                                                    DataValue = 0;
                                                }
                                                for (var nn = 0; nn < mierObj.length; nn++) {
                                                    if (mierObj[nn].cell == j) {
                                                        mierObj[nn].count = parseInt(mierObj[nn].count) + 1;
                                                        mierObj[nn].sum = parseInt(mierObj[nn].sum) + DataValue;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (this.process) {
                                        divInner = this.process(divInner, trid, row, rowNum);
                                    }
                                    if (this.control) {
                                        if (this.control == "text") {
                                            var divText = '<input type="text" class="inputList" style="width:97%" value="' + divInner + '"/>';
                                            div.push(divText);
                                        }
                                        else if (this.control == "check") {
                                            var divText = '<input type="checkbox" class="checkbox" value="' + divInner + '"';
                                            if (divInner == true || divInner == 1 || divInner == 'True') {
                                                divText += "checked=true";
                                            }
                                            divText += "/>";
                                            div.push(divText);
                                        }
                                        else if (this.control == "radio") {
                                            var divText = '<input type="radio" name="rd_' + j + '" class="radio" value="' + divInner + '"';
                                            if (divInner == true || divInner == 1 || divInner == 'True') {
                                                divText += "checked=true";
                                            }
                                            divText += "/>";
                                            div.push(divText);
                                        }
                                        else if (this.control == "select") {
                                            var divText = '<select style="width:97%">';
                                            if (this.dataSoucre) {
                                                var dataObj = eval(this.dataSoucre);
                                                for (var nn = 0; nn < dataObj.length; nn++) {
                                                    divText += "<option value='" + dataObj[nn].value + "'";
                                                    if (dataObj[nn].selected == true || dataObj[nn].value == divInner) {
                                                        divText += "selected='selected'";
                                                    }
                                                    divText += ">" + dataObj[nn].text + "</option>";
                                                }
                                                dataObj = null;
                                            }
                                            divText += "</select>";
                                            div.push(divText);
                                        }
                                        else {
                                            div.push(divInner);
                                        }
                                    }
                                    else {
                                        if (p.columndata) {
                                            var divText = '<span class="spanTable" id=span_' + j + '>' + divInner + '</span>';
                                            div.push(divText);
                                        }
                                        else {
                                            div.push(divInner);
                                        }
                                    }
                                }
                                div.push("</div>");
                                if (tdclass != "") {
                                    tbhtml.push(" class='", tdclass, "'");
                                }
                                tbhtml.push(">", div.join(""), "</td>");

                                if (isAddFoot == false) {
                                    if (p.showfoot) {
                                        var displayValue = '';
                                        if (this.hide) {
                                            displayValue = 'none';
                                        }
                                        if (_footIndex == 0) {
                                            tfoot.push("<td align='right' summary='" + this.summary + "' style='display:" + displayValue + "'><div style='height:", p.rowHeight, ";text-align:right;width:", width, ";white-space:normal'>统计：</div></td>");
                                        }
                                        else {
                                            tfoot.push("<td align='right' summary='" + this.summary + "' style='display:" + displayValue + "'><div style='height:", p.rowHeight, ";text-align:right;width:", width, ";white-space:normal'></div></td>");
                                        }
                                        displayValue = null;
                                    }
                                }
                                _footIndex++;
                            });
                            isAddFoot = true;
                            tbhtml.push("</tr>");
                        }
					    );
                    }

                }
                tbhtml.push("</tbody>");
                if (p.showfoot) {
                    tfoot.push("</tfoot>");
                    $(t).html(tbhtml.join("") + tfoot.join(""));
                    for (var jj = 0; jj < mierObj.length; jj++) {
                        if (t.rows(t.rows.length - 1).cells(mierObj[jj].cell).summary == 'count') {
                            t.rows(t.rows.length - 1).cells(mierObj[jj].cell).childNodes[0].innerText = "个数：" + (mierObj[jj].count - 1);
                        }
                        else if (t.rows(t.rows.length - 1).cells(mierObj[jj].cell).summary == 'sum') {
                            t.rows(t.rows.length - 1).cells(mierObj[jj].cell).childNodes[0].innerText = "总和：" + mierObj[jj].sum;
                        }
                        else if (t.rows(t.rows.length - 1).cells(mierObj[jj].cell).summary == 'avg') {
                            var avgValue = parseFloat(mierObj[jj].sum) / parseFloat(mierObj[jj].count);

                            avgValue = g.DataToFixed(avgValue, mierObj[jj].summaryDigit);

                            t.rows(t.rows.length - 1).cells(mierObj[jj].cell).childNodes[0].innerText = "平均值：" + avgValue;
                            avgValue = null;
                        }
                    }
                }
                else {
                    $(t).html(tbhtml.join(""));
                }
                mierString = null;
                mierObj = null;
                tbhtml = null;
                tfoot = null;
                //只能应用于tbody
                //列特别的样式
                if (p.specialColumn) {
                    //alert(p.specialColumn.position + "|" + p.specialColumn.bgColor);
                    $("tbody:eq(0)", t).find("tr").find("td:eq(" + p.specialColumn.position + ")").css({ "backgroundColor": p.specialColumn.bgColor, "color": p.specialColumn.color });
                }
                if (p.showTree) {
                    $("tbody:eq(0)", t).treetable(p.showTree);
                }
                //列修改
                if (p.columndata) {
                    $("span", $("div", $(t))).each(function(index, ele) {
                        if ($(ele).attr("id") == p.columndata) {
                            if (p.isClickColumn && $.isFunction(p.isClickColumn)) {
                                var rowData = $(ele).parent().parent().parent();
                                p.isClickColumn.call(ele, ele, rowData);
                            }
                        }
                    })
                }
                //this.rePosDrag();

                if (p.onSuccess) p.onSuccess();
                if (p.hideOnSubmit) {

                    $(g.block).remove(); //$(t).show();

                }
                //add strip		
                if (p.striped)
                    $('tbody tr:odd', g.bDiv).addClass('erow');
                this.addRowProp();
                if (p.hideHeader) {

                    this.hDiv.style.display = "none";
                }
                this.hDiv.scrollLeft = this.bDiv.scrollLeft;
                if ($.browser.opera) $(t).css('visibility', 'visible');
                if (p.onLoaded && $.isFunction(p.onLoaded)) {
                    p.onLoaded.call(this);
                }
                CollectGarbage();
            },
            hiddentColumnByIndex: function(colIndex) {
                //                /*隐藏指定列*/
                try {
                    var ths = $('thead tr:first th', g.hDiv);
                    $(ths).each(function(j) {
                        if (j == colIndex) {
                            this.style.display = "none";
                            this.hide = true;
                            for (var i = 0; i < t.rows.length; i++) {
                                t.rows(i).cells(j).style.display = 'none';
                            }
                            return false;
                        }
                    });
                }
                catch (e) {
                    alert("grid.hiddentColumnByIndex:" + e.message);
                }
                CollectGarbage();
            },
            showColumnByIndex: function(colIndex) {
                //                /*隐藏指定列*/
                try {
                    var ths = $('thead tr:first th', g.hDiv);
                    $(ths).each(function(j) {
                        if (j == colIndex) {
                            this.style.display = "";
                            this.hide = false;
                            for (var i = 0; i < t.rows.length; i++) {
                                t.rows(i).cells(j).style.display = '';
                            }
                            return false;
                        }
                    });
                }
                catch (e) {
                    alert("grid.showColumnByIndex:" + e.message);
                }
                CollectGarbage();
            },
            hiddentColumnByName: function(colName) {
                //                /*隐藏指定列*/
                try {
                    var ths = $('thead tr:first th', g.hDiv);
                    $(ths).each(function(j) {
                        if (this.name!=null && typeof(this.name)!="undefined" && this.name.toLocaleUpperCase() == colName.toLocaleUpperCase()) {
                            this.style.display = "none";
                            this.hide = true;
                            for (var i = 0; i < t.rows.length; i++) {
                                t.rows(i).cells(j).style.display = 'none';
                            }
                            return false;
                        }
                    });
                }
                catch (e) {
                    alert("grid.hiddentColumnByName:" + e.message);
                }
                CollectGarbage();
            },
            showColumnByName: function(colName) {
                //                /*隐藏指定列*/
                try {
                    var ths = $('thead tr:first th', g.hDiv);
                    $(ths).each(function(j) {
                        if (this.name!=null && typeof(this.name)!="undefined" && this.name.toLocaleUpperCase() == colName.toLocaleUpperCase()) {
                            this.style.display = "";
                            this.hide = false;
                            for (var i = 0; i < t.rows.length; i++) {
                                t.rows(i).cells(j).style.display = '';
                            }
                            return false;
                        }
                    });
                }
                catch (e) {
                    alert("grid.showColumnByName:" + e.message);
                }
                CollectGarbage();
            },
            changeSort: function(th) {
                /*排序方法*/
                if (this.loading) return true;
                if (p.sortname == $(th).attr('abbr')) {
                    if (p.sortorder == 'asc') p.sortorder = 'desc';
                    else p.sortorder = 'asc';
                }
                $(th).addClass('sorted').siblings().removeClass('sorted');
                $('.sdesc', this.hDiv).removeClass('sdesc');
                $('.sasc', this.hDiv).removeClass('sasc');
                $('div', th).addClass('s' + p.sortorder);
                p.sortname = $(th).attr('abbr');
                if (p.onChangeSort) {
                    p.onChangeSort(p.sortname, p.sortorder);
                }
                else {
                    this.populate();
                }
            },
            buildpager: function() {
                if (p.usepager) {
                    $('.pcontrol input', this.pDiv).val(p.page);
                    $('.pcontrol span', this.pDiv).html(p.pages);
                    var r1 = (p.page - 1) * p.rp + 1;
                    var r2 = r1 + p.rp - 1;
                    if (p.total < r2) r2 = p.total;
                    var stat = p.pagestat;

                    stat = stat.replace(/{from}/, r1);
                    stat = stat.replace(/{to}/, r2);
                    stat = stat.replace(/{total}/, p.total);
                    $('.pPageStat', this.pDiv).html(stat);

                    //控制按键样式
                    var btnNext = $(".pNext", this.pDiv); 																//下一页按钮
                    var btnPrev = $(".pPrev", this.pDiv); 																//上一页按钮
                    var btnFirst = $(".pFirst", this.pDiv); 														    //首页按钮
                    var btnLast = $(".pLast", this.pDiv);
                    var currentPageIndex = p.page;
                    var totalPage = p.pages;
                    if (currentPageIndex == 1 && totalPage == 1) {
                        btnNext.removeClass("pNextdisabled").addClass("pNextdisabled");
                        btnPrev.removeClass("pPrevdisabled").addClass("pPrevdisabled");
                        btnFirst.removeClass("pFirstdisabled").addClass("pFirstdisabled");
                        btnLast.removeClass("pLastdisabled").addClass("pLastdisabled");
                    }
                    else if (currentPageIndex == totalPage) {
                        btnNext.removeClass("pNextdisabled").addClass("pNextdisabled");
                        btnPrev.removeClass("pPrevdisabled");
                        btnFirst.removeClass("pFirstdisabled");
                        btnLast.removeClass("pLastdisabled").addClass("pLastdisabled");
                    } else if (currentPageIndex == 1) {

                        btnNext.removeClass("pNextdisabled");
                        btnPrev.removeClass("pPrevdisabled").addClass("pPrevdisabled");
                        btnFirst.removeClass("pFirstdisabled").addClass("pFirstdisabled");
                        btnLast.removeClass("pLastdisabled");

                    } else {
                        btnNext.removeClass("pNextdisabled");
                        btnPrev.removeClass("pPrevdisabled");
                        btnFirst.removeClass("pFirstdisabled");
                        btnLast.removeClass("pLastdisabled");
                    }
                    r1 = null;
                    r2 = null;
                    stat = null;
                    btnNext = null;
                    btnPrev = null;
                    btnFirst = null;
                    btnLast = null;
                    currentPageIndex = null;
                    totalPage = null;
                    CollectGarbage();
                }
            },
            populate: function() {
                if (this.loading) return true;
                this.loading = true;
                if (p.usepager) {
                    $('.pPageStat', this.pDiv).html(p.procmsg);
                }
                $('.pReload', this.pDiv).addClass('loading');
                $(g.block).css({ top: g.bDiv.offsetTop });
                if (p.hideOnSubmit) $(this.gDiv).prepend(g.block); //$(t).hide();
                if ($.browser.opera) $(t).css('visibility', 'hidden');
                if (!p.newp) p.newp = 1;
                if (p.page > p.pages) p.page = p.pages;
                var extp = "";
                var queryString = "&pageIndex=" + p.page + "&pageSize=" + p.rp + "&searchStr=" + p.query + "&sortname=" + p.sortname + "&sortorder=" + p.sortorder
                //执行自定义函数
                if (p.customFunction && $.isFunction(p.customFunction)) {
                    //$(this.gDiv).mask(p.procmsg);
                    var data = p.customFunction.call(this, p.rp, p.newp, p.query, p.extParam, p.sortname + " " + p.sortorder);
                    if (data != null) {
                        switch (data.result) {
                            case "0":
                                {
                                    g.addData(data);
                                    break;
                                }
                            case "1":
                                {
                                    g.addData(data);
                                    break;
                                }
                            default:
                                {
                                    alert("获取数据发生异常;");
                                    g.hideLoading();
                                    break;
                                }

                        }
                    }
                    else {
                        g.hideLoading();
                    }

                }
            },
            sleep: function(numberMillis) {
                var now = new Date();
                var exitTime = now.getTime() + numberMillis;
                while (true) {
                    now = new Date();
                    if (now.getTime() > exitTime)
                        return;
                }
            },
            setQueryString: function(query) {
                p.query = query;
                p.newp = 1;
            },
            changePage: function(ctype) { //change page
                if (this.loading) return true;
                switch (ctype) {
                    case 'first': p.newp = 1; break;
                    case 'prev': if (p.page > 1) p.newp = parseInt(p.page) - 1; break;
                    case 'next': if (p.page < p.pages) p.newp = parseInt(p.page) + 1; break;
                    case 'last': p.newp = p.pages; break;
                    case 'input':
                        var nv = parseInt($('.pcontrol input', this.pDiv).val());
                        if (isNaN(nv)) nv = 1;
                        if (nv < 1) nv = 1;
                        else if (nv > p.pages) nv = p.pages;
                        $('.pcontrol input', this.pDiv).val(nv);
                        p.newp = nv;
                        break;
                }

                if (p.newp == p.page) return false;

                if (p.onChangePage)
                    p.onChangePage(p.newp);
                else
                    this.populate();

            },
            cellProp: function(n, ptr, pth) {
                var tdDiv = document.createElement('div');
                if (pth != null) {
                    if (p.sortname == $(pth).attr('abbr') && p.sortname) {
                        this.className = 'sorted';
                    }
                    $(tdDiv).css({ textAlign: pth.align, width: $('div:first', pth)[0].style.width });
                    if (pth.hide) $(this).css('display', 'none');
                }
                if (p.nowrap == false) $(tdDiv).css('white-space', 'normal');
                if (this.innerHTML == '') this.innerHTML = '&nbsp;';
                tdDiv.innerHTML = this.innerHTML;

                var prnt = $(this).parent()[0];
                var pid = false;
                if (prnt.id) pid = prnt.id.substr(3);
                if (pth != null) {
                    if (pth.process)
                    { pth.process(tdDiv, pid); }
                }
                $("input.itemchk", tdDiv).each(function() {
                    $(this).click(function() {
                        if (this.checked) {
                            $(ptr).addClass("trSelected");
                        }
                        else {
                            $(ptr).removeClass("trSelected");
                        }
                        //                        if (p.onrowchecked && $.isFunction(p.onrowchecked)) {
                        //                           // p.onrowchecked.call(this,"fdfd");
                        //                        }
                    });
                });
                $(this).empty().append(tdDiv).removeAttr('width'); //wrap content
            },
            addCellProp: function() {
                var $gF = this.cellProp;

                $('tbody tr td', g.bDiv).each
					(
						function() {
						    var n = $('td', $(this).parent()).index(this);
						    var pth = $('th:eq(' + n + ')', g.hDiv).get(0);
						    var ptr = $(this).parent();
						    $gF.call(this, n, ptr, pth);
						}
					);
                $gF = null;
            },
            getCheckedRows: function() {
                var ids = [];
                for (var i = 0; i < t.rows.length; i++) {
                    var rowObj = t.rows(i);
                    if (rowObj.cells(0).childNodes.length > 0 && rowObj.cells(0).childNodes[0].childNodes.length > 0) {
                        if (rowObj.cells(0).childNodes[0].childNodes[0].checked == true) {
                            ids.push(rowObj);
                        }
                    }
                    rowObj = null;
                }
                CollectGarbage();
                //                $("input.itemchk:checked", g.bDiv).each(function() {
                //                    ids.push($(this).val());
                //                });
                return ids;
            },
            getSelectedRows: function() {
                var items = [];
                if (!p.rowbinddata) {
                    alert("请将属性rowbinddata设置为true");
                }
                $("tr.trSelected", g.bDiv).each(function() {
                    items.push($(this));
                });
                return items;
            },
            getRowByIndex: function(index) {
                return $('tr:eq(' + index + ')', g.bDiv).get(0);
            },
            getRowByID: function(ID) {
                var row = null;
                $('tr', g.bDiv).each(function() {
                    if (ID == $(this).attr("id")) {
                        row = this;
                    }
                })
                return row;
            },
            cancelSelectedRow: function(val) {

                $("tr.trSelected", g.bDiv).each(function() {
                    if ($(this).attr("ID") == val) {
                        $(this).removeClass("trSelected");
                        $(this).find("input.itemchk").first().attr("checked", false);
                        return;
                    }
                });
            },
            getCellDim: function(obj) // get cell prop for editable event
            {
                var ht = parseInt($(obj).height());
                var pht = parseInt($(obj).parent().height());
                var wt = parseInt(obj.style.width);
                var pwt = parseInt($(obj).parent().width());
                var top = obj.offsetParent.offsetTop;
                var left = obj.offsetParent.offsetLeft;
                var pdl = parseInt($(obj).css('paddingLeft'));
                var pdt = parseInt($(obj).css('paddingTop'));
                return { ht: ht, wt: wt, top: top, left: left, pdl: pdl, pdt: pdt, pht: pht, pwt: pwt };
            },
            rowProp: function() {
                if (p.rowhandler) {
                    p.rowhandler(this);

                }
                if ($.browser.msie && $.browser.version < 7.0) {
                    $(this).hover(function() { $(this).addClass('trOver'); }, function() { $(this).removeClass('trOver'); });
                }
            },
            checkhandler: function() {
                var $t = $(this);
                var $ck = $("input.itemchk", this);
                if (p.singleselected) {
                    $t.parent().find("tr.trSelected").each(function(e) {
                        if (this != $t[0]) {
                            $(this).removeClass("trSelected");
                        }
                        $("input.itemchk", this).each(function(e) { this.checked = false; });
                    });
                }
                var isLockButton = $(this).find("button").attr("xtype");
                if (isLockButton == "IsNoChecked") {

                }
                else {
                    if (p.rowcheckboxselect && p.showcheckbox) {
                        if ($t.hasClass("trSelected")) {
                            $ck.length > 0 && ($ck[0].checked = false);
                            $t.removeClass("trSelected");
                        }
                        else {
                            $ck.length > 0 && ($ck[0].checked = true);
                            $t.addClass("trSelected");
                        }
                    }
                    if (p.showcheckbox) {
                        if ($ck.length > 0 && $ck[0].checked) {
                            $t.addClass("trSelected");
                        } else {
                            $t.removeClass("trSelected");
                        }                                          
                    }
                }
            },
            clickhandler: function() {
                var $t = $(this);
                if (p.singleselected) {
                    $t.parent().find("tr.trSelected").each(function(e) {
                        if (this != $t[0]) {
                            $(this).removeClass("trSelected");
                        }
                    });
                }
                if ($t.hasClass("trSelected")) {
                    $t.removeClass("trSelected");
                }
                else {
                    $t.addClass("trSelected"); //改变选择时样式
                }
            },
            addRowProp: function() {
                var $gF = this.rowProp;
                var $cf = this.checkhandler;
                $('tbody tr', g.bDiv).each(
                    function() {
                        if (p.showcheckbox) {
                            $("input.itemchk", this).each(function() {
                                $(this).click(function(e) {
                                    var ptr = $(this).parent().parent().parent();
                                    $cf.call(ptr);
                                    if (p.onrowchecked) {
                                        p.onrowchecked.call(this, ptr);
                                    }
                                    e.stopPropagation();
                                });

                            });
                            if ($.isFunction(p.showcheckbox)) {
                                p.showcheckbox.call(this, this);
                            }

                        }
                        if (p.selectedonclick) //点击切换选中状态
                        {
                            var isLockCheckbox = $(this).find("input:checkbox").val();
                            if (isLockCheckbox == "true" || isLockCheckbox == "1") {

                            }
                            else {
                                $(this).click($cf);
                            }
                        }
                        $gF.call(this);
                    }
                );
                $gF = null;
            },
            checkAllOrNot: function(parent) {
                var ischeck = $(this).attr("checked");
                $('tbody tr', g.bDiv).each(function() {
                    if (ischeck) {
                        var isLockCheckbox = $(this).find("input:checkbox").val();
                        if (isLockCheckbox == "true" || isLockCheckbox == "1") {

                        }
                        else {
                            $(this).addClass("trSelected");
                        }
                    }
                    else {
                        $(this).removeClass("trSelected");
                    }
                });
                $("input.itemchk", g.bDiv).each(function() {
                    if ($(this).val() == "true" || $(this).val() == "1") {
                    }
                    else {
                        this.checked = ischeck;
                    }
                    //Raise Event
                    if (p.onrowchecked) {
                        p.onrowchecked.call(this);
                    }
                });
            },
            resizeColDownCode: function() {
                /*点击列准备改变列宽度时代码*/
                var actionCode = "";
                var arr = new Array();
                try {
                    arr.push("function(){");
                    arr.push("this.resized=false;");
                    arr.push("this.style.cursor='w-resize';");
                    arr.push("this.resizeState=true;");
                    arr.push("var _x=event.x;");
                    arr.push("var _cx=event.clientX;");
                    arr.push("this.DownX=_cx;");
                    arr.push("this.DownWidth=this.childNodes[0].style.width.replace('px','');");
                    arr.push("if(this.ShowText==undefined || this.ShowText==null){this.ShowText=this.childNodes[0].innerText;}");
                    arr.push("}");
                    actionCode = arr.join('');
                }
                catch (e) {
                    alert(e.message);
                }
                arr.length = 0;
                arr = null;
                CollectGarbage();
                return actionCode;
            },
            resizeColMoveCode: function(obj, objIndex) {
                /*改变列宽度时代码*/
                var actionCode = "";
                var arr = new Array();
                try {
                    arr.push("function(){try{");
                    arr.push("if(this.resizeState)");
                    arr.push("{");
                    arr.push("this.resized=true;");
                    arr.push("var _x=event.x;");
                    arr.push("var _cx=event.clientX;");
                    arr.push("var _NowX=parseInt(_cx)-parseInt(this.DownX);");
                    arr.push("this.style.cursor='w-resize';");
                    arr.push("var _NowWidth=parseInt(this.DownWidth) + parseInt(_NowX);");
                    arr.push("this.childNodes[0].style.width=_NowWidth+'px';");
                    arr.push("for(var i=0;i<t.rows.length;i++)");
                    arr.push("{");
                    arr.push("t.rows(i).cells(" + objIndex + ").childNodes[0].style.width=_NowWidth+'px';");
                    arr.push("}");
                    /*控制不选中任何文字*/
                    arr.push("if(document.selection){if(document.selection.empty)document.selection.empty();else{document.selection = null;}}else if(window.getSelection){window.getSelection().removeAllRanges();}");
                    arr.push("}");
                    arr.push("}catch(e){}}");
                    actionCode = arr.join('');
                }
                catch (e) {
                    alert(e.message);
                }
                arr.length = 0;
                arr = null;
                CollectGarbage();
                return actionCode;
            },
            deleteRow: function(rowIndex) {
                try {
                    t.deleteRow(rowIndex);
                }
                catch (e) {
                    alert("Grid.deleteRow:" + e.message);
                }
                CollectGarbage();
            },
            addRow: function(rowIndex) {
                /*增加行*/
                var newRowObj = null;
                var ths = $('thead tr:first th', g.hDiv);
                var thsdivs = $('thead tr:first th div', g.hDiv);
                try {
                    if (typeof (rowIndex) != "undefined") {
                        newRowObj = t.insertRow(rowIndex);
                    }
                    else {
                        newRowObj = t.insertRow(t.rows.length - 1);
                    }
                    /*
                    eval("newRowObj.onmouseover=function(){if(this.trSelected){this.className='trSelected';}else{this.className='trOver';}};");
                    eval("newRowObj.onmouseout=function(){if(this.trSelected){this.className='trSelected';}else{this.className='';}};");
                    var arrTrDownCode=new Array();
                    arrTrDownCode.push("function(){");
                    arrTrDownCode.push("for(var i=0;i<t.rows.length;i++)");
                    arrTrDownCode.push("{");
                    arrTrDownCode.push("if(t.rows(i).className=='trSelected')");
                    arrTrDownCode.push("{");
                    arrTrDownCode.push("t.rows(i).className='';");
                    arrTrDownCode.push("t.rows(i).trSelected=false;");
                    arrTrDownCode.push("}");
                    arrTrDownCode.push("}");
                    arrTrDownCode.push("if(this.trSelected){");
                    arrTrDownCode.push("this.className='';this.trSelected=false;");
                    arrTrDownCode.push("}");
                    arrTrDownCode.push("else{");
                    arrTrDownCode.push("this.className='trSelected';this.trSelected=true;");                    
                    arrTrDownCode.push("}");
                    arrTrDownCode.push("};");
                    
                    eval("newRowObj.onmousedown="+arrTrDownCode.join(''));
                    
                    arrTrDownCode.length=0;
                    arrTrDownCode=[];
                    arrTrDownCode=null;
                    */
                    newRowObj.id = "row_" + newRowObj.rowIndex + "_" + t.rows.length;
                    $(ths).each(function(j) {
                        var tddata = "";
                        var tdclass = "";
                        var newCellObj = newRowObj.insertCell(j);
                        var isHide=this.hide;
                        newCellObj.align = this.align;

                        var idx = $(this).attr('attrfiledname');
                        if (p.sortname && p.sortname == $(this).attr('abbr')) {
                            tdclass = 'sorted';
                        }
                        var width = thsdivs[j].style.width;
                        var div = [];
                        div.push("<div style='height:", p.rowHeight, ";text-align:", this.align, ";width:", width, ";");
                        if (p.nowrap == false) {
                            div.push("white-space:normal");
                        }
                        div.push("'>");
                        if (typeof idx == "undefined") {
                            div.push("<input type=\"checkbox\"  id=\"chk_", newRowObj.rowIndex, "_", j, "\""," class=\"itemchk\"/>");
                            if (tdclass != "") {
                                tdclass += " chboxtd";
                            } else {
                                tdclass += "chboxtd";
                            }
                        }
                        else {
                            var divInner = "";

                            if (this.control) {
                                if (this.dataSoucre) {
                                    divInner = this.dataSoucre;
                                }
                                if (this.control == "text") {
                                    var divText = '<input type="text" class="inputList" style="width:97%" value="' + divInner + '"/>';
                                    div.push(divText);
                                }
                                else if (this.control == "check") {
                                    var divText = '<input type="checkbox" class="checkbox" value="' + divInner + '"';
                                    if (divInner == true || divInner == 1 || divInner == 'True') {
                                        divText += "checked=true";
                                    }
                                    divText += "/>";
                                    div.push(divText);
                                }
                                else if (this.control == "radio") {
                                    var divText = '<input type="radio" name="rd_' + newCellObj.cellIndex + '" class="radio" value="' + divInner + '"';
                                    if (divInner == true || divInner == 1 || divInner == 'True') {
                                        divText += "checked=true";
                                    }
                                    divText += "/>";
                                    div.push(divText);
                                }
                                else if (this.control == "select") {
                                    var divText = '<select style="width:97%">';
                                    if (this.dataSoucre) {
                                        var dataObj = eval(this.dataSoucre);
                                        for (var nn = 0; nn < dataObj.length; nn++) {
                                            divText += "<option value='" + dataObj[nn].value + "'";
                                            if (dataObj[nn].selected == true || dataObj[nn].value == divInner) {
                                                divText += "selected='selected'";
                                            }
                                            divText += ">" + dataObj[nn].text + "</option>";
                                        }
                                        dataObj = null;
                                    }
                                    divText += "</select>";
                                    div.push(divText);
                                }
                                else {
                                    div.push(divInner);
                                }
                            }
                            else {
                                if (this.process) {
                                    divInner = this.process(divInner, newRowObj.id, newRowObj, newRowObj.rowIndex);
                                }
                                if (p.columndata == false) {
                                    div.push(divInner);
                                }
                                else {
                                    var divText = '<span class="spanTable" id=span_' + j + '>' + divInner + '</span>';
                                    div.push(divText);
                                }
                            }
                        }
                        div.push("</div>");

                        if (tdclass != "") {
                            newCellObj.className = tdclass;
                        }
                        newCellObj.innerHTML = div.join('');
                        if (isHide==true) {
                            newCellObj.style.display = 'none';
                        }
                        else
                        {
                            newCellObj.style.display = '';
                        }
                        isHide=null;
                        div.length = 0;
                        div = [];
                        tddata = null;
                        tdclass = null;
                        div = null;
                        newCellObj = null;
                        CollectGarbage();
                    });
                }
                catch (e) {
                    alert("Grid.addRow:" + e.message);
                }
                ths = null;
                thsdivs = null;
                tbhtml = null;
                CollectGarbage();
                return newRowObj;
            },
            setRowData: function(rowObj, data) {
                var ths = $('thead tr:first th', g.hDiv);
                var thsdivs = $('thead tr:first th div', g.hDiv);
                try {
                    var dataObj = eval(data);
                    $(ths).each(function(j) {
                        var dataValue = "";
                        var columnName = this.name;
                        eval("dataValue=dataObj[0]." + columnName);
                        if (dataValue != undefined && dataValue != null) {
                            if (!this.process) {
                                if (this.control == "text") {
                                    rowObj.cells(j).childNodes[0].childNodes[0].value = dataValue;
                                }
                                else if (this.control == "check") {
                                    if (dataValue == true || dataValue == 1 || dataValue == 'True') {
                                        rowObj.cells(j).childNodes[0].childNodes[0].checked = true;
                                    }
                                    else {
                                        rowObj.cells(j).childNodes[0].childNodes[0].checked = false;
                                    }
                                }
                                else if (this.control == "radio") {
                                    if (dataValue == true || dataValue == 1 || dataValue == 'True') {
                                        rowObj.cells(j).childNodes[0].childNodes[0].checked = true;
                                    }
                                    else {
                                        rowObj.cells(j).childNodes[0].childNodes[0].checked = false;
                                    }
                                }
                                else if (this.control == "select") {
                                    var controlObj = rowObj.cells(j).childNodes[0].childNodes[0];
                                    try {
                                        controlObj.value = dataValue;
                                    }
                                    catch (e) {

                                    }
                                }
                                else {
                                    rowObj.cells(j).childNodes[0].innerHTML = dataValue;
                                }
                            }
                            else if (this.processType) {
                                if (this.processType == "text") {
                                    $(rowObj.cells(j)).find("input:text").val(dataValue);
                                }
                                else if (this.processType == "check") {
                                    if (dataValue == true || dataValue == 1 || dataValue == 'True') {
                                        $(rowObj.cells(j)).find("input:checkbox").attr("checked", true);
                                    }
                                    else {
                                        $(rowObj.cells(j)).find("input:checkbox").attr("checked", false);
                                    }
                                }
                                else if (this.processType == "radio") {
                                    if (dataValue == true || dataValue == 1 || dataValue == 'True') {
                                        $(rowObj.cells(j)).find("input:radio").attr("checked", true);
                                    }
                                    else {
                                        $(rowObj.cells(j)).find("input:radio").attr("checked", false);
                                    }
                                }
                                else if (this.processType == "select") {
                                    $(rowObj.cells(j)).find("select").val(dataValue);
                                }
                            }
                        }
                        columnName = null;
                        dataValue = null;
                    });
                    dataObj = null;
                }
                catch (e) {
                    alert(e.message);
                }
                ths = null;
                thsdivs = null;
                CollectGarbage();
            },
            /*清空所有行*/
            clearRow: function() {
                try {
                    for (var i = t.rows.length - 1; i >= 0; i--) {
                        t.deleteRow(i);
                    }
                }
                catch (e) {
                    alert(e.message);
                }
                CollectGarbage();
            },
            /*获取当前行数*/
            rowCount: function() {
                return t.rows.length;
            },
            /*获取指定行数据对象，DataType:string 返回字符串否则是对象类型*/
            getRowData: function(rowObj, DataType) {
                var data = null;
                var dataString = "";
                var ths = $('thead tr:first th', g.hDiv);
                try {
                    for (var i = 0; i < t.rows.length; i++) {
                        if ((typeof (rowObj) != "undefined" && i == rowObj.rowIndex) || typeof (rowObj) == "undefined") {
                            if (typeof (rowObj) == "undefined" && i > 0) {
                                dataString += ",";
                            }
                            dataString += "{";
                            var ColumnValue = "";
                            $(ths).each(function(j) {
                                var columnName = this.name;
                                if (!this.process) {
                                    if (ColumnValue != "" && j > 0) {
                                        ColumnValue += ",";
                                    }
                                    if (this.control == "text") {
                                        ColumnValue += columnName + ":'" + escape(t.rows(i).cells(j).childNodes[0].childNodes[0].value) + "'";
                                    }
                                    else if (this.control == "check") {
                                        var dataValue = t.rows(i).cells(j).childNodes[0].childNodes[0].checked;
                                        if (dataValue == true || dataValue == 1 || dataValue == 'True') {
                                            ColumnValue += columnName + ":1";
                                        }
                                        else {
                                            ColumnValue += columnName + ":0";
                                        }
                                        dataValue = null;
                                    }
                                    else if (this.control == "radio") {
                                        var dataValue = t.rows(i).cells(j).childNodes[0].childNodes[0].checked;
                                        if (dataValue == true || dataValue == 1 || dataValue == 'True') {
                                            ColumnValue += columnName + ":1";
                                        }
                                        else {
                                            ColumnValue += columnName + ":0";
                                        }
                                        dataValue = null;
                                    }
                                    else if (this.control == "select") {
                                        var controlObj = t.rows(i).cells(j).childNodes[0].childNodes[0];
                                        try {
                                            ColumnValue += columnName + ":'" + escape(controlObj.value) + "'";
                                        }
                                        catch (e) {

                                        }
                                    }
                                    else {
                                        ColumnValue += columnName + ":'" + escape(t.rows(i).cells(j).childNodes[0].innerText) + "'";
                                    }
                                }
                                else if (this.processType) {
                                    if (ColumnValue != "" && j > 0) {
                                        ColumnValue += ",";
                                    }
                                    if (this.processType == "text") {
                                        if (typeof $(t.rows(i).cells(j)).find("input:text").val() != "undefined") {
                                            ColumnValue += columnName + ":'" + escape($(t.rows(i).cells(j)).find("input:text").val()) + "'";
                                        }
                                        else {
                                            ColumnValue += columnName + ":''";
                                        }
                                    }
                                    else if (this.processType == "check") {
                                        ColumnValue += columnName + ":" + ($(t.rows(i).cells(j)).find("input:checkbox").attr("checked") ? 1 : 0);
                                    }
                                    else if (this.processType == "radio") {
                                        ColumnValue += columnName + ":" + ($(t.rows(i).cells(j)).find("input:radio").attr("checked") ? 1 : 0);
                                    }
                                    else if (this.processType == "select") {
                                        try {
                                            if (typeof $(t.rows(i).cells(j)).find("select").find("option:selected").val() != "undefined") {
                                                ColumnValue += columnName + ":'" + escape($(t.rows(i).cells(j)).find("select").find("option:selected").val()) + "'";
                                            }
                                            else {
                                                ColumnValue += columnName + ":''";
                                            }
                                        }
                                        catch (e) {

                                        }
                                    }
                                }
                                columnName = null;
                            });
                            dataString += ColumnValue + "}";
                            ColumnValue = null;
                            if (typeof (rowObj) != "undefined" && i == rowObj.rowIndex) {
                                break;
                            }
                        }
                    }
                }
                catch (e) {
                    alert(e.message);
                }
                ths = null;
                /*如果传入的数据类型是字符串那么直接返回获取的各行的数据集合*/
                if (DataType == "string") {
                    data = dataString;
                }
                else {
                    data = eval("[" + dataString + "]");
                }
                dataString = null;
                CollectGarbage();
                return data;
            },
            pager: 0
        };
        //create model if any
        if (p.colModel) {
            /*构建grid表头及各列属性*/
            thead = document.createElement('thead');
            tr = document.createElement('tr');
            //p.showcheckbox ==true;
            if (p.showcheckbox) {
                var cth = jQuery('<th/>');
                var cthch = jQuery('<input type="checkbox"/>');
                cthch.addClass("noborder");
                if (p.singleselected) {
                    cthch.attr("disabled", true).css("visibility", "hidden");
                }
                cth.addClass("cth").attr({ 'axis': "col-1", width: "15", "isch": true }).append(cthch);
                $(tr).append(cth);
            }
            for (i = 0; i < p.colModel.length; i++) {
                var cm = p.colModel[i];
                var th = document.createElement('th');
                th.innerHTML = cm.display;
                if (cm.name && cm.sortable) {
                    /*如果当前列设置了可以排序，那么就设置排序动作*/
                    $(th).attr({ 'abbr': cm.name, "title": "点击按" + cm.display + "排序" }).css("cursor", "pointer");
                }
                //th.idx = i;
                $(th).attr('axis', 'col' + i);
                $(th).attr("attrfiledname", cm.name);
                if (cm.name) {
                    th.name = cm.name;
                }
                if (cm.align) {
                    th.align = cm.align;
                }
                if (cm.width) {
                    $(th).attr('width', cm.width);
                }
                if (cm.hide) {
                    th.hide = true;
                }
                if (cm.toggle != undefined) {
                    th.toggle = cm.toggle;
                }
                if (cm.process) {
                    th.process = cm.process;
                    if (cm.processType) {
                        th.processType = cm.processType;
                    }
                }
                if (cm.digit) {
                    /*指定当前列保留的小数位*/
                    th.digit = cm.digit;
                }
                if (cm.control) {
                    /*指定当前列使用的控件类型*/
                    th.control = cm.control;
                    if (cm.dataSoucre) {
                        th.dataSoucre = cm.dataSoucre;
                    }
                }
                if (cm.summary) {
                    /*当前列是否进行统计*/
                    th.summary = cm.summary;
                    if (cm.summaryDigit) {
                        /*当前列统计结果保留的小数位*/
                        th.summaryDigit = cm.summaryDigit;
                    }
                    else {
                        th.summaryDigit = 0;
                    }
                }
                //                if(cm.name && cm.sizeable)
                //                {
                /*如果当前列设置了可以改变宽度，那么就设置改变宽度的动作*/
                var actionCode = g.resizeColDownCode(th);
                eval("th.onmousedown=" + actionCode);
                actionCode = null;
                if (p.showcheckbox) {
                    actionCode = g.resizeColMoveCode(th, (i + 1));
                }
                else {
                    actionCode = g.resizeColMoveCode(th, i);
                }
                eval("th.onmousemove=" + actionCode);
                eval("th.onmouseup=function(){this.style.cursor='';this.resizeState=false;}");
                eval("th.onmouseout=function(){this.style.cursor='';this.resizeState=false;this.resized=false;}");
                actionCode = null;
                //                }
                $(tr).append(th);
            }
            $(thead).append(tr);
            $(t).prepend(thead);
            CollectGarbage();
        } // end if p.colmodel	

        //init divs
        g.gDiv = document.createElement('div'); //create global container
        g.mDiv = document.createElement('div'); //create title container
        g.hDiv = document.createElement('div'); //create header container
        g.bDiv = document.createElement('div'); //create body container
        g.vDiv = document.createElement('div'); //create grip
        g.rDiv = document.createElement('div'); //create horizontal resizer
        g.block = document.createElement('div'); //creat blocker
        if (p.usepager) g.pDiv = document.createElement('div'); //create pager container
        g.hTable = document.createElement('table');
        //set gDiv
        g.gDiv.className = p.gridClass;
        if (p.width != 'auto') g.gDiv.style.width = p.width + 'px';

        //add conditional classes
        if ($.browser.msie)
            $(g.gDiv).addClass('ie');

        if (p.novstripe)
            $(g.gDiv).addClass('novstripe');

        $(t).before(g.gDiv);
        $(g.gDiv)
		.append(t)
		;
        //set hDiv
        g.hDiv.className = 'hDiv';

        $(t).before(g.hDiv);

        //set hTable
        g.hTable.cellPadding = 0;
        g.hTable.cellSpacing = 0;
        $(g.hDiv).append('<div class="hDivBox"></div>');
        $('div', g.hDiv).append(g.hTable);
        var thead = $("thead:first", t).get(0);
        if (thead) $(g.hTable).append(thead);
        thead = null;
        if (!p.colmodel) var ci = 0;
        //setup thead			
        $('thead tr:first th', g.hDiv).each
			(
			 	function() {
			 	    $(this).css("textAlign", "center");
			 	    var thdiv = document.createElement('div');
			 	    if ($(this).attr('abbr')) {
			 	        $(this).click(
								function(e) {
								    if (!$(this).hasClass('thOver')) return false;
								    var obj = (e.target || e.srcElement);
								    if (obj.href || obj.type) return true;
								    if (obj.parentElement.resized == false) {
								        g.changeSort(this);
								    }
								}
							);

			 	        if ($(this).attr('abbr') == p.sortname) {
			 	            this.className = 'sorted';
			 	            thdiv.className = 's' + p.sortorder;
			 	        }
			 	    }

			 	    if (this.hide) $(this).hide();

			 	    if (!p.colmodel && !$(this).attr("isch")) {
			 	        $(this).attr('axis', 'col' + ci++);
			 	    }
			 	    $(thdiv).css({ textAlign: 'center', width: this.width + 'px' });
			 	    thdiv.innerHTML = this.innerHTML;
			 	    $(this).empty().append(thdiv).removeAttr('width');
			 	    if (!$(this).attr("isch")) {
			 	        $(this)
						.hover(
							function() {
							    if (!g.colresize && !$(this).hasClass('thMove') && !g.colCopy) $(this).addClass('thOver');

							    if ($(this).attr('abbr') != p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) $('div', this).addClass('s' + p.sortorder);
							    else if ($(this).attr('abbr') == p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) {
							        var no = '';
							        if (p.sortorder == 'asc') no = 'desc';
							        else no = 'asc';
							        $('div', this).removeClass('s' + p.sortorder).addClass('s' + no);
							    }
							},
							function() {
							    $(this).removeClass('thOver');
							    if ($(this).attr('abbr') != p.sortname) $('div', this).removeClass('s' + p.sortorder);
							    else if ($(this).attr('abbr') == p.sortname) {
							        var no = '';
							        if (p.sortorder == 'asc') no = 'desc';
							        else no = 'asc';

							        $('div', this).addClass('s' + p.sortorder).removeClass('s' + no);
							    }
							    if (g.colCopy) {
							        $(g.cdropleft).remove();
							        $(g.cdropright).remove();
							        g.dcolt = null;
							    }
							})

			 	    }
			 	}
			);

        //set bDiv
        g.bDiv.className = 'bDiv';
        $(t).before(g.bDiv);
        $(g.bDiv)
		.css({ height: (p.height == 'auto') ? 'auto' : p.height + "px" })
		.scroll(function(e) { g.scroll(); })
		.append(t);
        if (p.height == 'auto') {
            $('table', g.bDiv).addClass('autoht');
        }
        var cdcol = $('thead tr:first th:first', g.hDiv).get(0);
        if (cdcol != null) {
            g.cdpad = 0;
            g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderLeftWidth'))) ? 0 : parseInt($('div', cdcol).css('borderLeftWidth')));
            g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderRightWidth'))) ? 0 : parseInt($('div', cdcol).css('borderRightWidth')));
            g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingLeft'))) ? 0 : parseInt($('div', cdcol).css('paddingLeft')));
            g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingRight'))) ? 0 : parseInt($('div', cdcol).css('paddingRight')));
            g.cdpad += (isNaN(parseInt($(cdcol).css('borderLeftWidth'))) ? 0 : parseInt($(cdcol).css('borderLeftWidth')));
            g.cdpad += (isNaN(parseInt($(cdcol).css('borderRightWidth'))) ? 0 : parseInt($(cdcol).css('borderRightWidth')));
            g.cdpad += (isNaN(parseInt($(cdcol).css('paddingLeft'))) ? 0 : parseInt($(cdcol).css('paddingLeft')));
            g.cdpad += (isNaN(parseInt($(cdcol).css('paddingRight'))) ? 0 : parseInt($(cdcol).css('paddingRight')));
            var cdheight = $(g.bDiv).height();
            var hdheight = $(g.hDiv).height();
            $('thead tr:first th', g.hDiv).each
			(
			 	function() {

			 	    if ($.browser.msie && $.browser.version < 7.0) {
			 	        g.fixHeight($(g.gDiv).height());
			 	    }
			 	}
			);
        }

        // add pager
        if (p.usepager) {
            g.pDiv.className = 'pDiv';
            if (p.extPageTheme) {
                $(g.pDiv).addClass(p.extPageTheme);
            }
            g.pDiv.innerHTML = '<div class="pDiv2"></div>';
            $(g.bDiv).after(g.pDiv);
            var html = '<div class="pGroup"><div class="pFirst pButton" title="转到第一页"><span></span></div><div class="pPrev pButton" title="转到上一页"><span></span></div> </div><div class="btnseparator"></div> <div class="pGroup"><span class="pcontrol">当前页 <input type="text" size="1" value="1" /> &nbsp;总页数 <span> 1 </span></span></div><div class="btnseparator"></div><div class="pGroup"> <div class="pNext pButton" title="转到下一页"><span></span></div><div class="pLast pButton" title="转到最后一页"><span></span></div></div><div class="btnseparator"></div><div class="pGroup"> <div class="pReload pButton" title="刷新"><span></span></div> </div> <div class="btnseparator"></div><div class="pGroup"><span class="pPageStat"></span></div>';
            $('div', g.pDiv).html(html);

            $('.pReload', g.pDiv).click(function() { g.populate(); });
            $('.pFirst', g.pDiv).click(function() { g.changePage('first'); });
            $('.pPrev', g.pDiv).click(function() { g.changePage('prev'); });
            $('.pNext', g.pDiv).click(function() { g.changePage('next'); });
            $('.pLast', g.pDiv).click(function() { g.changePage('last'); });
            $('.pcontrol input', g.pDiv).keydown(function(e) { if (e.keyCode == 13) g.changePage('input'); });
            if ($.browser.msie && $.browser.version < 7) $('.pButton', g.pDiv).hover(function() { $(this).addClass('pBtnOver'); }, function() { $(this).removeClass('pBtnOver'); });
            if (p.useRp) {
                var opt = "";
                for (var nx = 0; nx < p.rpOptions.length; nx++) {
                    if (p.rp == p.rpOptions[nx]) sel = 'selected="selected"'; else sel = '';
                    opt += "<option value='" + p.rpOptions[nx] + "' " + sel + " >" + p.rpOptions[nx] + "&nbsp;&nbsp;</option>";
                };
                $('.pDiv2', g.pDiv).prepend("<div class='pGroup'>每页 <select name='rp'>" + opt + "</select>条</div> <div class='btnseparator'></div>");
                $('select', g.pDiv).change(
					function() {
					    if (p.onRpChange)
					        p.onRpChange(+this.value);
					    else {
					        p.newp = 1;
					        p.rp = +this.value;
					        g.populate();
					    }
					}
				);
            }
        }
        $(g.pDiv).append("<div style='clear:both'></div>");
        // add title
        if (p.title) {
            g.mDiv.className = 'mDiv';
            g.mDiv.innerHTML = '<div class="ftitle">' + p.title + '</div>';
            $(g.gDiv).prepend(g.mDiv);
            if (p.showTableToggleBtn) {
                $(g.mDiv).append('<div class="ptogtitle" title="Minimize/Maximize Table"><span></span></div>');
                $('div.ptogtitle', g.mDiv).click
					(
					 	function() {
					 	    $(g.gDiv).toggleClass('hideBody');
					 	    $(this).toggleClass('vsble');
					 	}
					);
            }
            //g.rePosDrag();
        }

        //setup cdrops
        g.cdropleft = document.createElement('span');
        g.cdropleft.className = 'cdropleft';
        g.cdropright = document.createElement('span');
        g.cdropright.className = 'cdropright';

        //add block
        g.block.className = 'gBlock';
        var blockloading = $("<div/>");
        /*2011-09-08 注释 因为会让网格出现假死状态*/
        //        blockloading.addClass("loading");
        $(g.block).append(blockloading);
        /*--------------------------------------*/
        var gh = $(g.bDiv).height();
        var gtop = g.bDiv.offsetTop;
        $(g.block).css(
		{
		    width: g.bDiv.style.width,
		    height: gh,
		    position: 'relative',
		    marginBottom: (gh * -1),
		    zIndex: 1,
		    top: gtop,
		    left: '0px'
		}
		);
        $(g.block).fadeTo(0, p.blockOpacity);

        // add column control
        if ($('th', g.hDiv).length) {

            var cn = 0;

            $('th div', g.hDiv).each
			(
			 	function() {
			 	    var kcol = $("th[axis='col" + cn + "']", g.hDiv)[0];
			 	    if (kcol == null) return;
			 	    var chkall = $("input[type='checkbox']", this);
			 	    if (chkall.length > 0) {
			 	        chkall[0].onclick = g.checkAllOrNot;
			 	        return;
			 	    }
			 	    if (kcol.toggle == false || this.innerHTML == "") {
			 	        cn++;
			 	        return;
			 	    }
			 	    var chk = 'checked="checked"';
			 	    if (kcol.style.display == 'none') chk = '';
			 	    cn++;
			 	}
			);
        }
        //browser adjustments
        if ($.browser.msie && $.browser.version < 7.0) {
            $('.hDiv,.bDiv,.mDiv,.pDiv,.vGrip', g.gDiv)
			.css({ width: '100%' });
            $(g.gDiv).addClass('ie6');
            if (p.width != 'auto') $(g.gDiv).addClass('ie6fullwidthbug');
        }
        g.rePosDrag();
        g.fixHeight();

        //make grid functions accessible
        t.p = p;
        t.grid = g;
        // load data
        if (p.autoload) {
            g.populate();
        }
        return t;

    };
    var docloaded = false;
    $(document).ready(function() { docloaded = true });
    $.fn.ikegrid = function(p) {
        return this.each(function() {
            if (!docloaded) {
                $(this).hide();
                var t = this;
                $(document).ready
					(
						function() {
						    $.addFlex(t, p);
						}
					);
            } else {
                $.addFlex(this, p);
            }
        });

    }; //end flexigrid
    $.fn.flexReload = function(p) { // function to reload grid
        return this.each(function() {
            if (this.grid) {
                $.extend(this.p, p);
                this.grid.populate();
            }
        });
    }; //end flexReload
    //重新指定宽度和高度
    $.fn.flexResize = function(w, h) {
        var p = { width: w, height: h };
        return this.each(function() {
            if (this.grid) {
                $.extend(this.p, p);
                this.grid.reSize();
            }
        });
    };
    $.fn.DoSearch = function(query) {
        return this.each(function() {
            if (this.grid) { this.grid.setQueryString(query); this.grid.populate(); }
        });
    }
    $.fn.ChangePage = function(type) {
        return this.each(function() {
            if (this.grid) {
                this.grid.changePage(type);
            }
        })
    };
    $.fn.flexOptions = function(p) { //function to update general options
        return this.each(function() {
            if (this.grid) $.extend(this.p, p);
        });

    }; //end flexOptions
    $.fn.GetOptions = function() {
        if (this[0].grid) {
            return this[0].p;
        }
        return null;
    };
    // 获取选中的行，返回选中行的主键
    $.fn.getCheckedRows = function() {
        if (this[0].grid) {
            return this[0].grid.getCheckedRows();
        }
        return [];
    };
    // 获取选中的行，返回选中行的所有数据
    $.fn.getSelectedRows = function() {
        if (this[0].grid) {
            return this[0].grid.getSelectedRows();
        }
        return [];
    };
    // 获取选中的行，返回选中行的所有数据
    $.fn.getRowByIndex = function(index) {
        if (this[0].grid) {
            return this[0].grid.getRowByIndex(index);
        }
        return [];
    };
    // 根据ID返回行的所有数据
    $.fn.getRowByID = function(ID) {
        if (this[0].grid) {
            return this[0].grid.getRowByID(ID);
        }
        return [];
    }
    //取消选中的行
    $.fn.cancelSelectedRow = function(value) {
        if (this[0].grid) {
            return this[0].grid.cancelSelectedRow(value);
        }
        return [];
    };
    /*删除指定行*/
    $.fn.deleteRow = function(rowIndex) {
        if (this[0].grid) {
            this[0].grid.deleteRow(rowIndex);
        }
    };
    /*在指定位置增加行*/
    $.fn.addRow = function(rowIndex) {
        if (this[0].grid) {
            return this[0].grid.addRow(rowIndex);
        }
        return [];
    };
    /*设置指定行数据*/
    $.fn.setRowData = function(rowObj, data) {
        if (this[0].grid) {
            this[0].grid.setRowData(rowObj, data);
        }
    };
    /*获取值数据*/
    $.fn.getRowData = function(rowObj, DataType) {
        if (this[0].grid) {
            return this[0].grid.getRowData(rowObj, DataType);
        }
        return [];
    };
    /*清除所有行*/
    $.fn.clearRow = function() {
        if (this[0].grid) {
            return this[0].grid.clearRow();
        }
    };
    /*获取当前页行数*/
    $.fn.rowCount = function() {
        if (this[0].grid) {
            return this[0].grid.rowCount();
        }
    };
    /*根据列下标隐藏指定列*/
    $.fn.hiddentColumnByIndex = function(colIndex) {
        if (this[0].grid) {
            this[0].grid.hiddentColumnByIndex(colIndex);
        }
    };
    /*根据列下标显示指定列*/
    $.fn.showColumnByIndex = function(colIndex) {
        if (this[0].grid) {
            this[0].grid.showColumnByIndex(colIndex);
        }
    };
    /*根据列名隐藏指定列*/
    $.fn.hiddentColumnByName = function(colName) {
        if (this[0].grid) {
            this[0].grid.hiddentColumnByName(colName);
        }
    };
    /*根据列名显示指定列*/
    $.fn.showColumnByName = function(colName) {
        if (this[0].grid) {
            this[0].grid.showColumnByName(colName);
        }
    };
    $.fn.flexToggleCol = function(cid, visible) { // function to reload grid

        return this.each(function() {
            if (this.grid) this.grid.toggleCol(cid, visible);
        });

    }; //end flexToggleCol

    $.fn.flexAddData = function(data) { // function to add data to grid

        return this.each(function() {
            if (this.grid) this.grid.addData(data);
        });

    };
    $.fn.noSelect = function(p) { //no select plugin by me :-)
        if (p == null)
            prevent = true;
        else
            prevent = p;

        if (prevent) {
            return this.each(function() {
                if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function() { return false; });
                else if ($.browser.mozilla) {
                    $(this).css('MozUserSelect', 'none');
                    $('body').trigger('focus');
                }
                else if ($.browser.opera) $(this).bind('mousedown', function() { return false; });
                else $(this).attr('unselectable', 'on');
            });

        } else {
            return this.each(function() {
                if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
                else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
                else if ($.browser.opera) $(this).unbind('mousedown');
                else $(this).removeAttr('unselectable', 'on');
            });

        };

    }; //end noSelect

})(jQuery);