/* 
* rmGrid  1.0.0 - jQuery  
* Copyright (c) 2013, 赵思海
* Date:2013-08-26
*/

/* update
* rmGrid  1.1.1 - jQuery  
* content:1.在插件内部处理了null值，将null值转化成空字符串 2.增加 getRowHtmlData 方法,用于获取修改的内容.3.增加 updateRowData方法,用于更新从数据库过来，在下次使用时保持最新
* Copyright (c) 2013, 赵思海
* Date:2013-10-08
*/




; (function ($) {

    var gridDefaults = {
        colNames: [],
        colModel: [],
        total: 0,
        page: 1,
        records: 0,
        rowNum: 10,
        isPage: false,
        multiLine: true,
        multiselect: false,
        headRowAlign: "center",
        width: "fixed",//fixed :根据每一列的固定宽度,  auto:平铺，由父元素的宽度决定, 数值：指定宽度
        sortorder: "desc",
        disabledSelect: false,
        lineHeight: 12,
        lang: "cn",
        showcolnum: 0,//后台保存的数据
        loadComplete: function () { },
        gridComplete: function () { },
        onSelectRow: function () { },
        data: {},//查询条件
        colspanBottom: null, //针对跟进记录扩展
        zebraCrossing:true,
        gridData: {},
        expendData: {} //返回其他的数据
    };

    $.fn.rmGrid = function () {

        var $gridId = this;
        var gridId = $gridId.attr("id");

        if (arguments.length == 1) {

            if (arguments[0] == "getDataIDs") {
                var rowIdArr = new Array();
                $("tbody tr", $gridId).each(function () {
                    var id = $(this).attr("rows").split('_')[1];
                    var ishaveval = false;
                    for (var i = 0; i < rowIdArr.length;i++ )
                    {
                        if (rowIdArr[i] == id) {
                            ishaveval = true;
                        }
                    }
                    
                    if (!ishaveval) {
                        rowIdArr.push(id);
                    }
                });
                return rowIdArr;

            }

            $gridId.addClass("rmgrid");

            //初始化


            var options = arguments[0]; 
            var settings = $.extend({}, gridDefaults,options);

            settings.multiLine = options.multiLine || false;


            $gridId[0].settings = $gridId[0].settings || {};
            if (($gridId[0].settings.colModel != settings.colModel) || ($gridId[0].settings.colModel != settings.colModel)) {
                
                if (settings.colNames.length != settings.colModel.length) {
                    alert("colNames and colModel length inconsistencies");
                    return false;
                }

                //表格设置总宽度
                var tableWidth = 0.00;
                settings.showcolnum = 0;
                for (var col = 0 ; col < settings.colModel.length; col++) {
                    if (!settings.colModel[col].hidden) {
                        settings.showcolnum++;
                        if (!settings.colModel[col].width) {
                            alert("Part of the column width is not set");
                            return false;
                        }
                        tableWidth += parseFloat(settings.colModel[col].width);
                    }
                }

                var theadhtml = "<thead>";
                theadhtml += (settings.multiselect ? '<th width="20" align="center" ><input type="checkbox" class="cbox" id="cb_' + gridId + '" role="checkbox"></th>' : '');

                var totalwith = 0;

                if (settings.width == "auto") {
                    $gridId.attr("width", "100%");
                    for (var col = 0 ; col < settings.colNames.length; col++) {
                        if (!settings.colModel[col].hidden) {
                            var width = parseInt(parseFloat(settings.colModel[col].width) / tableWidth * 100);
                            //IE7 bug
                            totalwith += width;
                            if ((col == settings.colNames.length - 1) && (totalwith < 98)) {
                                width += 98 - totalwith + width;
                            }
                            theadhtml += '<th class="align-' + settings.headRowAlign + '"  width="' + width + '%" ><span>' + settings.colNames[col] + '</span></th>';
                        } else {
                            theadhtml += '<th style="display:none;" class="align-' + settings.headRowAlign + '"  ><span>' + settings.colNames[col] + '</span></th>';
                        }
                    }
                } else if (settings.width == "fixed") {
                    
                    $gridId.attr("width", tableWidth);
                    for (var col = 0 ; col < settings.colNames.length; col++) {
                        if (!settings.colModel[col].hidden) {
                            var width = settings.colModel[col].width;
                            theadhtml += '<th width="' + width + '" class="align-' + settings.headRowAlign + '"  ><span>' + settings.colNames[col] + '</span></th>';
                        } else {
                            theadhtml += '<th style="display:none;" class="align-' + settings.headRowAlign + '"  ><span>' + settings.colNames[col] + '</span></th>';
                        }
                    }
                } else if (settings.width == "as")
                {
                    $gridId.attr("width", "100%");
                    for (var col = 0 ; col < settings.colNames.length; col++) {
                        if (!settings.colModel[col].hidden) {
                            var width = settings.colModel[col].width;
                            theadhtml += '<th width="' + width + '" class="align-' + settings.headRowAlign + '"  ><span>' + settings.colNames[col] + '</span></th>';
                        } else {
                            theadhtml += '<th style="display:none;" class="align-' + settings.headRowAlign + '"  ><span>' + settings.colNames[col] + '</span></th>';
                        }
                    }
                }
                else if (parseInt(settings.width)) {
                    $gridId.attr("width", settings.width);
                    for (var col = 0 ; col < settings.colNames.length; col++) {
                        if (!settings.colModel[col].hidden) {
                            var width = parseInt(parseFloat(settings.colModel[col].width) / tableWidth * 100);
                            //IE7 bug
                            totalwith += width;
                            if ((col == settings.colNames.length - 1) && (totalwith < 98)) {
                                width += 98 - totalwith + width;
                            }
                            theadhtml += '<th width="' + width + '%" class="align-' + settings.headRowAlign + '"  ><span>' + settings.colNames[col] + '</span></th>';
                        } else {
                            theadhtml += '<th style="display:none;" class="align-' + settings.headRowAlign + '"  ><span>' + settings.colNames[col] + '</span></th>';
                        }
                    }
                } else {
                    alert("Unknown width attribute");
                    return false;
                }

                if ($("thead", $gridId).length) {
                    $("thead", $gridId).replaceWith($(theadhtml + '</thead>'));
                } else {
                    $gridId.append($(theadhtml + '</thead>'));
                }
            }

            var tmppage = $('#totalPage' + gridId).text();
            if (!tmppage) {
                tmppage = 0;
            }

            $("#gridPager" + gridId).remove();

            if (settings.isPage)
            {
            
                $gridId.append(
                    '<tfoot  id="gridPager' + gridId + '" class="rmgridpage"><tr><td colspan="' + (settings.multiselect ? settings.showcolnum + 1 : settings.showcolnum) + '">' +
                    '<a id="firstPage' + gridId + '" class="btnGo" >' + (settings.lang == "cn" ? '首页' : 'Home') + '</a>' +
                    '<a id="prePage' + gridId + '"  class="btnGo" >' + (settings.lang == "cn" ? '上一页' : 'Prev') + '</a>' +
                    '<a id="nextPage' + gridId + '"  class="btnGo" >' + (settings.lang == "cn" ? '下一页' : 'Next') + '</a>' +
                    '<a id="lastPage' + gridId + '" class="btnGo" >' + (settings.lang == "cn" ? '尾页' : 'End') + '</a>' +
                    '<input id="gotoPageNo' + gridId + '" class="PageNo" type="text" />' +
                    ' / <span id="totalPage' + gridId + '">' + tmppage + '</span> ' +
                    '<a id="goBtn' + gridId + '"  class="btnGo">' + (settings.lang == "cn" ? '跳转' : 'Go') + '</a>' + '共有 <span style="color:red; width:60px; display:inline-block;" id="totalRecord' + gridId + '" ></span> 条记录' + '</td></tr></tfoot>'
                        
                    );
            }

            var data = {
                page: settings.page,
                rows: settings.rowNum,
                sidx: settings.sortname,
                sord: settings.sortorder,
                nd: (new Date()).getTime() //时间戳
            };

            $gridId[0].settings = settings;

            //
            var newObj = new Object();
            newObj = $.extend(newObj, settings);

            var isLoad = true;
            var lang = settings.lang;
            
            var time = setInterval(function () {
                
                if (isLoad) {
                    //show load
                    if (!$('#load_' + gridId).length) {
                        $("body").append('<div style="dispaly:none;line-height:22px;" class="rmgridload" id="load_' + gridId + '">' + (lang == "cn" ? '加载中' : 'Load') + '</div>');
                        var left = $gridId.offset().left;
                        var top = $gridId.offset().top;
                        var height = $gridId.height();
                        height = (height - $('#load_' + gridId).height()) / 2;
                        height = (height > 30) ? height : 30;
                        var width = $gridId.width();
                        var loadtop = (top + height);
                        $('#load_' + gridId).css("left", left + (width - $('#load_' + gridId).width()) / 2).css("top", loadtop).show();
                    }
                }
            }, 800);
            

            //filter
            if (settings.data) {
                var param = settings.data;
                if (typeof (param) == "object") {
                    for (var i in param) {
                        if (typeof (param[i]) == "string") {
                            param[i] = $.trim(param[i]);
                            if (param[i] == "undefined" || param[i] == "" || param[i] == null) {
                                delete param[i];
                            }
                        }
                    }
                }
            }
            
            data = $.extend(data, settings.data);

            if (!settings.url) {
                isLoad = false;
                $('#load_' + gridId).remove();
                return false;
            }

            $.ajax({
                type: "post",
                url: settings.url,
                dataType: "json",
                data: data,
                complete: function () {
                    isLoad = false;
                    $('#load_' + gridId).remove();
                },
                success: function (jsonData) {
                    
                    var settings = newObj;

                    var gridData = new Array();

                    if (jsonData.datarows) {
                        for (var i = 0; i < jsonData.datarows.length; i++) {
                            var obj = new Object();
                            obj.id = jsonData.datarows[i].id;
                            for (var ii = 0; ii < settings.colModel.length; ii++) {
                                obj[settings.colModel[ii].name] = jsonData.datarows[i].cell[ii];
                            }
                            gridData.push(obj);
                        }
                    }

                    settings = $.extend(settings, {
                        total: jsonData.total,
                        page: jsonData.page,
                        records: jsonData.records,
                        gridData: gridData,
                        expendData: jsonData.expendData
                    });

                    $gridId[0].settings = settings;

                    var total = jsonData.total;
                    var page = jsonData.page;
                    var records = jsonData.records;
                    var rows = jsonData.datarows;

                    var colspanNum = (settings.multiselect ? settings.showcolnum + 1 : settings.showcolnum);
        
                    //tbody
                    var tbodyhtml = "<tbody>";
                    if (rows) {
                        for (var tr = 0 ; tr < rows.length; tr++) {
                            var trhtml = '<tr rows="row_' + rows[tr].id + '" >';
                            trhtml += settings.multiselect ? '<td  align="center" ><input type="checkbox" name="checkboxname" class="cbox" id="jqg_' + gridId + '_' + rows[tr].id + '" role="checkbox" value="' + rows[tr].id + '"></td>' : "";
                            for (var td = 0; td < settings.colModel.length; td++) {
                                var align = settings.colModel[td].align || "center";

                                if (!settings.colModel[td].hidden) {
                                    trhtml += '<td title="' + (rows[tr].cell[td] ==null ?   "" : rows[tr].cell[td]) + '"   align="' + align + '" cols="col_' + settings.colModel[td].name + '" rows="row_' + rows[tr].id + '" >' + (rows[tr].cell[td] ==null ?   "" : rows[tr].cell[td]) + '</td>';
                                } else {
                                    trhtml += '<td title="' + (rows[tr].cell[td] ==null ?   "" : rows[tr].cell[td]) + '"  style="display:none;" align="' + align + '" cols="col_' + settings.colModel[td].name + '" rows="row_' + rows[tr].id + '" >' + (rows[tr].cell[td] ==null ?   "" : rows[tr].cell[td]) + '</td>';
                                }
                            }
                            trhtml += '</tr>';

                            if (settings.colspanBottom) {

                                var colspanHtml = '<tr rows="row_' + rows[tr].id + '_colspan" class="rmgridzebra">' +
                                    '<td colspan="' + colspanNum + '" style ="text-align:' + settings.colspanBottom.align + '; padding-left:' + settings.colspanBottom.paddingLeft + 'px;" title="" align="left" cols="' + settings.colspanBottom.name + '" rows="row_' + rows[tr].id + '" class="whitespace">' + rows[tr].colspan + '</td>' +
                                '</tr>'
                                trhtml += colspanHtml;
                            }
                            tbodyhtml += trhtml;
                        }
                    }
                    tbodyhtml += "</tbody>";

                    $("tbody", $gridId).remove();

                    //$gridId.append($(tbodyhtml));
                    if (rows && rows.length > 0) {
                        $("thead", $gridId).after($(tbodyhtml));
                    }

                    if (settings.zebraCrossing) {
                        $gridId.zebraCrossing();
                    }

                    

                    if (settings.multiLine) {
                       $("td",$gridId).addClass("whitespace"); 
                    }

                    if (!settings.disabledSelect) {
                        $("tbody tr", $gridId).rowClickEvent($gridId);
                    }

                    $("#cb_" + gridId).click(function () {
                        if ($(this).attr("checked")) {
                            $(this).attr("checked", true);
                            $("[name=checkboxname][type=checkbox][id*='_" + gridId + "_']").attr("checked", true);
                            $("tbody tr", $gridId).addClass("rmgridseleted");
                        } else {
                            $(this).attr("checked", false);
                            $("[name=checkboxname][type=checkbox][id*='_" + gridId + "_']").attr("checked", false);
                            $("tbody tr", $gridId).removeClass("rmgridseleted");
                        }
                    });

                    settings.loadComplete();

                    if (settings.isPage) {

                        var totalRecord = parseInt(records);
                        var rows = settings.rowNum;

                        var curPageNum = page;
                        var totalPage = totalRecord % rows == 0 ? totalRecord / rows : parseInt(totalRecord / rows) + 1;

                        if (totalPage <= 0)
                            totalPage = 1;

                        $('#totalPage' + gridId).text(totalPage);

                        //$("#gridPager" + gridId).remove();

                        //$gridId.append(
                        //    '<tfoot  id="gridPager' + gridId + '" class="rmgridpage"><tr><td colspan="'+ 300 +'">' +
                        //    '<input id="firstPage' + gridId + '" type="button"  value="首页" class="btnGo">' +
                        //    '<input id="prePage' + gridId + '" type="button"  value="上一页" class="btnGo">' +
                        //    '<input id="nextPage' + gridId + '" type="button"  value="下一页" class="btnGo">' +
                        //    '<input id="lastPage' + gridId + '" type="button"  value="尾页" class="btnGo">' +
                        //    '<input id="gotoPageNo' + gridId + '" class="PageNo" type="text">' +
                        //    ' / ' + totalPage + '  ' +
                        //    '<input id="goBtn' + gridId + '"   type="button"  value="跳转" class="btnGo"></td></tr></tfoot>'
                        //    );

                        $("#gotoPageNo" + gridId).val(page);

                        $("#firstPage" + gridId).click(function () {

                            if (curPageNum > 1) {
                                //$gridId.rmGrid('setGridParam', { page: 1 }).trigger();
                                $gridId.rmGrid('setGridParam', { page: 1 }).reloadGrid();
                            }
                        });

                        $("#lastPage" + gridId).click(function () {

                            if (totalPage > curPageNum)
                                $gridId.rmGrid('setGridParam', { page: totalPage }).reloadGrid();
                        });

                        $("#prePage" + gridId).click(function () {

                            if (curPageNum - 1 > 0)
                                $gridId.rmGrid('setGridParam', { page: curPageNum - 1 }).reloadGrid();
                        });

                        $("#nextPage" + gridId).click(function () {

                            if (curPageNum + 1 <= totalPage)
                                $gridId.rmGrid('setGridParam', { page: curPageNum + 1 }).reloadGrid();
                        });

                        $("#goBtn" + gridId).click(function () {

                            var pageNum = $("#gotoPageNo" + gridId).val();
                            if (isNaN(pageNum)) return;
                            if (pageNum > 0 && pageNum <= totalPage && page != pageNum)
                                $gridId.rmGrid('setGridParam', { page: pageNum }).reloadGrid();
                        });

                        $("#gotoPageNo" + gridId).keyup(function () {
                            $(this).val($(this).val().replace(/[^0-9]/g, ''));
                        });
                        
                        $("#totalRecord" + gridId).text(totalRecord);
                    }

                    settings.gridComplete();

                    //close load

                },
                error: function (e) {
                    $("tbody", $gridId).remove();
                    if (window.location.host.indexOf("localhost") > -1 && e.statusText == "timeout")
                    {
                        alert("Grid请求出错");
                    }
                }
            });



        } else {
            //调用方法
            if (arguments[0] == 'getRowData') {
                //var $td = $("tbody tr[rows*=" + arguments[1] + "]").find("td");
                //var model = new Object();
                //$td.each(function () {
                //    if ($(this).attr("rows")) {
                //        model[$(this).attr("cols").split("_")[1]] = $(this).html();
                //    }
                //});
                var gridData = $(this)[0].settings.gridData;
                var id = arguments[1];
                var model = new Object();
                $.each(gridData, function () {
                    if (this.id == id) {
                        model = this;
                        return false;
                    }
                });

                //在插件内部处理了null值，将null值转化成空字符串
                if (model) {
                    for (var index in model) {
                        if (model[index] == null || model[index] == undefined) {
                            model[index] = "";
                        }
                    }
                }
                return model;

            } else if (arguments[0] == "updateRowData") {
                return $gridId.updateRowData(arguments[1], arguments[2]);
            }
            
            else if (arguments[0] == "getRowHtmlData") {
                var $td = $("tbody tr[rows*=" + arguments[1] + "]").find("td");
                var model = new Object();
                $td.each(function () {
                    if ($(this).attr("rows")) {
                        model[$(this).attr("cols").split("_")[1]] = $(this).html();
                    }
                });
            }
            else if (arguments[0] == "getGridParam") {
                return $gridId.getGridParam(arguments[1]);
            } else if (arguments[0] == "setGridParam") {
                this[0].settings = $.extend(this[0].settings, arguments[1]);
                return this;
            } else if (arguments[0] == "addRowData") {
                $gridId.addRowData(arguments[1], arguments[2], arguments[3]);
            } else if (arguments[0] == "setRowData") {
                $gridId.setRowData(arguments[1], arguments[2]);
            } else if (arguments[0] == "delRowData") {
                $gridId.delRowData(arguments[1]);
            } else if (arguments[0] == "getDataIDs") {
                $gridId.getDataIDs();
            }
        }
    };

    $.extend($.fn, {
        //trigger: function (cmd) {
        //    if (cmd == "reloadGrid") {//上一次查询条件查询
        //        this.rmGrid(this[0].settings);
        //    }
        //    return this;
        //},
        reloadGrid: function () {
            this.rmGrid(this[0].settings);
        },
        addRowData: function (rowID, model, pos) {
            if ($("[rows='row_" + rowID + "']", this).length) {
                alert("rowID的行已经存在!");
                return false;
            }

            pos = pos || "last";
            var gridId = this.attr("id");
            var settings = this[0].settings;

            var trhtml = '<tr rows="row_' + rowID + '" >';
            trhtml += settings.multiselect ? '<td  align="center" ><input type="checkbox" name="checkboxname" class="cbox" id="jqg_' + gridId + '_' + rowID + '" role="checkbox" value="' + rowID + '"></td>' : "";
            for (var td = 0; td < settings.colModel.length; td++) {
                var align = settings.colModel[td].align || "center";
                var text = model[settings.colModel[td].name] || "";
                var title = "";
                if (!$(text)[0]) {
                    title = text;
                }
                if (!settings.colModel[td].hidden) {
                    trhtml += '<td title="' + title + '"  align="' + align + '" cols="col_' + settings.colModel[td].name + '" rows="row_' + rowID + '" >' + text + '</td>';
                } else {
                    trhtml += '<td title="' + title + '"  style="display:none;" align="' + align + '" cols="col_' + settings.colModel[td].name + '" rows="row_' + rowID + '" >' + text + '</td>';
                }
            }
            trhtml += '</tr>';

            if (!$("tbody", this).length) {
                $("thead", this).after('<tbody></tbody>');
            }

            var $tr = $(trhtml);
            if (pos == "first") {
                $("tbody", this).prepend($tr);
            } else {
                $("tbody", this).append($tr);
            }

            if (!this[0].settings.disabledSelect) {
                $tr.rowClickEvent(this);
            }

            this.zebraCrossing();

            this[0].settings.gridComplete();

        },
        setRowData: function (rowID, model) {
            for (var pop in model) {
                var value = model[pop];
                $("td[cols='col_" + pop + "'][rows='row_" + rowID + "']", this).html(value);
            }
        },
        updateRowData: function (rowID, model) {            
            var gridData = $(this)[0].settings.gridData;
            var id = rowID;
            $.each(gridData, function () {
                if (this.id == id) {
                    var oldModel = this;
                    for (var pop in model) {
                        oldModel[pop] = model[pop];
                    }
                    return false;
                }
            });
        },
        delRowData: function (rowId) {
            $("tbody tr[rows=row_" + rowId + "]", this).remove();
            this.zebraCrossing();
        },
        getDataIDs: function () {
            var arr = new Array();
            $("tbody tr", this).each(function () {
                arr.push($(this).attr("rows").split("_")[1]);
            });
            return arr;
        },
        rowClickEvent: function ($grid) {
            var settings = $grid[0].settings;
            var gridId = $grid.attr("id");
            this.click(function () {
                if ($(this).hasClass("rmgridseleted")) {
                    $(this).removeClass("rmgridseleted");
                    $("[name=checkboxname][id*='_" + gridId + "_'][value=" + $(this).attr("rows").split('_')[1] + "]").attr("checked", false);
                } else {
                    $(this).addClass("rmgridseleted");
                    $("[name=checkboxname][id*='_" + gridId + "_'][value=" + $(this).attr("rows").split('_')[1] + "]").attr("checked", true);
                    if (!settings.multiselect) {
                        $(this).siblings().removeClass("rmgridseleted");
                    }
                }
                settings.onSelectRow($(this).closest("tr").attr("rows").split('_')[1]);
            });

            
        },
        getGridParam: function (paramName) {
            if (paramName == 'selarrrow') {
                var selectarr = [];
                $("tr.rmgridseleted", this).each(function () {
                    selectarr.push($(this).attr("rows").split("_")[1]);
                });
                return selectarr;
            } else if (paramName == "selrow") {
                if ($("tr.rmgridseleted:first").attr("rows"))
                    return $("tr.rmgridseleted:first").attr("rows").split("_")[1] || false;
                else
                    return false;
            } else {
                return this[0].settings[paramName];
            }
        },
        zebraCrossing: function () {
            $("tbody tr", this).removeClass("rmgridzebra");
            $("tbody tr:odd", this).addClass("rmgridzebra");
        },
        getParamData: function () {
            var paramData = this[0].settings;

            return {
                data: paramData.data,
                page: paramData.page,
                rows: paramData.rowNum,
                sidx: paramData.sortname,
                sord: paramData.sortorder
            };
        }
    });

})(jQuery);
