var $layoutcolumnselector = function (grid) {
    this.title = GetTextByKey("P_GRID_XXXXXX", 'Layout');
    this.dialogId = 'dialog_layouts';
    $("#" + this.dialogId).remove();
    this.grid = grid;
    this.dialog = null;
    this.onOK = null;
    this.onDialogClosed = null;
};

(function () {
    var __proto = $layoutcolumnselector.prototype;

    var tbdata;

    function initColumnsGrid(parent) {
        var divheader = $("<div style='font-size:14px;background-color:#fafafa;'></div>").appendTo(parent);
        var tbheader = $("<table style='width:100%;'></table>").appendTo(divheader);
        var trheader = $("<tr></tr>").appendTo(tbheader);
        trheader.append();
        var td = $("<td style='width:30px'></td>");
        trheader.append(td);
        $("<input type='checkbox' />").appendTo(td).on('click', function (e) {
            tbdata.find("input[type='checkbox']:enabled").prop("checked", $(e.target).prop("checked"));
        });
        trheader.append($("<td style='width:220px'></td>").text(GetTextByKey("P_GRID_COLUMN", "Column")));
        trheader.append($("<td style='width:220px'></td>").text(GetTextByKey("P_GRID_CAPTION", "Caption")));
        trheader.append($("<td></td>").text(GetTextByKey("P_XXXXXX", "Width")));

        var divdata = $("<div style=' height: 400px; overflow: auto;line-height:30px;'></div>").appendTo(parent);
        tbdata = $("<table style='width:100%;'></table>").appendTo(divdata);
    }

    function createDialog() {
        var dialog = $('<div class="dialog" style="display: none; width: 605px; height: 610px;min-width: 560px;line-height:30px;">').attr('id', this.dialogId);

        var title = $('<div class="dialog-title"></div>').appendTo(dialog);
        title.append($('<span class="title"></span>').text(this.title));
        title.append('<em class="dialog-close"></em>');

        var _this = this;
        var layoutOptionDiv = $('<div style="margin-left:10px;margin-right:10px;"></div>').appendTo(dialog);
        var rdoCurrentLayout = $("<input type='radio' id='rdoCurrentLayout' checked='checked' name='layoutoption' style='margin-left:20px;' />").on('click', function () {
            txtSearch && txtSearch.val("");
            showdata.call(_this, false);
        }).appendTo(layoutOptionDiv);
        $("<label for='rdoCurrentLayout'></label>").text(GetTextByKey("P_XXXXXX", "Show Current Layout")).appendTo(layoutOptionDiv);
        var rdoDefaultLayout = $("<input type='radio' id='rdoDefaultLayout' name='layoutoption' style='margin-left:60px;' />").on('click', function () {
            txtSearch && txtSearch.val("");
            showdata.call(_this, true);
        }).appendTo(layoutOptionDiv);
        $("<label for='rdoDefaultLayout'></label>").text(GetTextByKey("P_XXXXXX", "Show Default Layout")).appendTo(layoutOptionDiv);
        var chkDisplayedOnly = $("<input type='checkbox' id='chkDisplayedOnly' name='layoutoption' style='margin-left:60px;' />").on('click', function () {
            searchColumns(txtSearch.val().trim());
        }).appendTo(layoutOptionDiv);
        $("<label for='chkDisplayedOnly'></label>").text(GetTextByKey("P_XXXXXX", "Displayed Only")).appendTo(layoutOptionDiv);

        $('<div style="margin-left:20px;"></div>').text(GetTextByKey("P_XXXXXX", "To move columns, drag and drop on column name.")).appendTo(dialog);

        var searchDiv = $('<div style="margin-left:10px;margin-right:10px;"></div>').appendTo(dialog);
        var txtSearch = $("<input type='text' style='margin-left: 7px;width:95%;' />").appendTo(searchDiv);
        txtSearch.attr("placeholder", GetTextByKey("P_XXXXXX", "Search Columns"));
        txtSearch.on('input propertychange', function () {
            searchColumns($(this).val().trim());
        });
        txtSearch.on('keydown', function () {
            searchColumns($(this).val().trim());
        });

        var columnListDiv = $('<div style="width: 580px; height: 440px; margin: 5px 10px 4px 10px;overflow:auto;"></div>').appendTo(dialog);

        var dialogFunction = $('<div class="dialog-func"></div>').appendTo(dialog);
        $('<input type="button" value="' + GetTextByKey("P_GRID_CANCEL", "Cancel") + '" class="dialog-close" />').appendTo(dialogFunction);
        $('<input type="button" value="' + GetTextByKey("P_GRID_OK", "OK") + '" />').on('click', onOKClick.bind(this)).appendTo(dialogFunction);
        $('<div class="clear"></div>').appendTo(dialogFunction);

        $('<div class="maskbg" style="display: none"><div class="loading_icon icon c-spin"></div></div>').appendTo(dialog);

        // init
        initColumnsGrid.call(this, columnListDiv);
        $(document.body).append(dialog);

        dialog.dialog(this.onDialogClosed);
        return dialog;
    }

    function searchColumns(filter) {
        var trs = tbdata.find("tr");
        for (var i = 0; i < trs.length; i++) {
            var tr = $(trs[i]);
            var rowInfo = tr.data("rowInfo");
            if (rowInfo) {
                var col = rowInfo.ColumnData;
                var colinfo = {
                    'Column': col.OriginalCaption,
                    'Caption': rowInfo.txtCaption.val().trim()
                }

                if ((!$("#chkDisplayedOnly").prop("checked") || rowInfo.chkSelected.prop("checked"))
                    && (colinfo.Column.toLowerCase().indexOf(filter.toLowerCase()) >= 0 || colinfo.Caption.toLowerCase().indexOf(filter.toLowerCase()) >= 0))
                    tr.show();
                else
                    tr.hide();
            }
        }
    }

    __proto.showLayoutSelector = function (topRatio, force) {
        var dialog;
        if (force) {
            $('#' + this.dialogId).remove();
            dialog = createDialog.call(this);
        } else {
            dialog = $('#' + this.dialogId);
            if (!dialog.length) {
                dialog = createDialog.call(this);
            }
        }
        this.dialog = dialog;
        dialog.attr('init', '1').showDialog().css({
            'top': (document.documentElement.clientHeight - $('#dialog_machines').height()) / (topRatio || 3),
            'left': (document.documentElement.clientWidth - $('#dialog_machines').width()) / 2
        });
        showdata.call(this, false);
    };

    function showdata(showall) {
        if (!this.grid.allcolumns || this.grid.allcolumns.length <= 0)
            return;

        var tmpColumns = [];
        if (showall) {
            for (var j = 0; j < this.grid.allcolumns.length; j++) {
                var dc = this.grid.allcolumns[j];

                dc = $.extend(true, {}, dc);
                dc.OriginalCaption = dc.caption;
                dc.UserCaption = "";
                dc.Width = dc.width;
                dc.Selected = dc.visible !== false;
                tmpColumns.push(dc);

            }
        }
        else if (this.grid.columns && this.grid.columns.length > 0) {
            for (var i = 0; i < this.grid.columns.length; i++) {
                var cc = $.extend(true, {}, this.grid.columns[i]);

                //if (!cc.alwaysshow) {
                cc.Width = cc.width;
                cc.Selected = cc.visible !== false;
                tmpColumns.push(cc);
                //}
            }

            for (var j = 0; j < this.grid.allcolumns.length; j++) {
                var dc = this.grid.allcolumns[j];
                //if (dc.alwaysshow) continue;

                var selected = false;
                for (var i = 0; i < tmpColumns.length; i++) {
                    var tc = tmpColumns[i];
                    if (tc.name == dc.name) {
                        selected = true;
                        break;
                    }
                }
                if (!selected) {
                    dc = $.extend(true, {}, dc);
                    dc.OriginalCaption = dc.caption;
                    dc.UserCaption = "";
                    dc.Width = dc.width;
                    dc.Selected = false;
                    tmpColumns.push(dc);
                }
            }
        }

        tbdata.empty();
        for (var i = 0; i < tmpColumns.length; i++) {
            var c = tmpColumns[i];
            var rowInfo = {};
            rowInfo.ColumnData = c;
            var tr = $("<tr></tr>").appendTo(tbdata).data("rowInfo", rowInfo);

            var td = $("<td style='width:30px'></td>").appendTo(tr);
            rowInfo.chkSelected = $("<input type='checkbox' />").appendTo(td);
            rowInfo.chkSelected.prop("checked", c.Selected);
            if (c.alwaysshow)
                rowInfo.chkSelected.prop("checked", true).prop("disabled", true);

            td = $("<td style='width:220px'></td>").appendTo(tr);
            rowInfo.txtOriginalCaption = $("<span></span>").appendTo(td);
            rowInfo.txtOriginalCaption.text(c.alwaysshow ? c.text : c.OriginalCaption);
            if (c.name === "Selected")
                rowInfo.txtOriginalCaption.text('\uf0c8');
            if (c.alwaysshow)
                rowInfo.txtOriginalCaption.addClass('icon-col').css('cursor', 'default');

            td = $("<td style='width:220px'></td>").appendTo(tr);
            rowInfo.txtCaption = $("<input type='text' style='width:210px' maxlength='200' />").appendTo(td);
            rowInfo.txtCaption.val(c.UserCaption);
            if (c.alwaysshow)
                rowInfo.txtCaption.prop("disabled", true);

            td = $("<td></td>").appendTo(tr);
            rowInfo.txtWidth = $("<input type='text' style='width:70px' maxlength='6' />").appendTo(td);
            rowInfo.txtWidth.val(c.Width || c.width);
            if (c.alwaysshow)
                rowInfo.txtWidth.prop("disabled", true);

            if (c.name !== "Selected")
                bindDrag(tr);
        }
    }

    var draggingrow = null;
    function bindDrag(tr) {//拖动调整顺序
        tr.attr('draggable', true);
        tr.bind('dragstart', function (e) {
            draggingrow = $(this);
        });
        tr.find('input').attr('draggable', true).bind('dragstart', function (e) {
            e.originalEvent.preventDefault()
        });
        tr.bind('dragend', function (e) {
            draggingrow = null;
        });
        tr.bind('dragover', function (e) {
            e.originalEvent.preventDefault()
        });
        tr.bind('drop', function (e) {
            var t = $(this);
            if (t.is(draggingrow))
                return;
            var t = $(this);
            var after = e.originalEvent.clientY > t.offset().top + t.height() / 2;
            if (after) {
                t.after(draggingrow);
            }
            else {
                t.before(draggingrow);
            }
        });
    }

    function onOKClick() {
        var colinfos = [];
        var trs = tbdata.find("tr");
        for (var i = 0; i < trs.length; i++) {
            var tr = $(trs[i]);
            var rowInfo = tr.data("rowInfo");
            var col = rowInfo.ColumnData;
            if (rowInfo) {
                var sort = 0;
                if (col.sortDesc != undefined)
                    sort = col.sortDesc ? 2 : 1;
                var colinfo = {
                    'Visible': rowInfo.chkSelected.prop("checked"),
                    'ColumnKey': col.name,
                    'Caption': $.trim(rowInfo.txtCaption.val()),
                    'Width': $.trim(rowInfo.txtWidth.val()),
                    'Sort': sort
                }
                if (isNaN(colinfo.Width) || eval(colinfo.Width) <= 0)
                    colinfo.Width = col.width;
                colinfos.push(colinfo);
            }
        }

        if (colinfos.length == 0) {
            showAlert(GetTextByKey("P_GRID_PLEASESELECTATLEASTONECOLUMN", "Please select at least one column."), GetTextByKey("P_GRID_XXXXXX", 'Layout'));
            return;
        }

        this.onOK && this.onOK(colinfos);
    }
})();

var $layoutsavedialog = function (grid, layoutid, type) {
    this.title = GetTextByKey("P_GRID_XXXXXX", 'Save Layout');
    this.type = type;
    this.dialogId = 'dialog_savelayout';
    $("#" + this.dialogId).remove();
    this.grid = grid;
    this.layoutid = layoutid;
    this.dialog = null;
    this.onOK = null;
    this.onDialogClosed = null;
};

(function () {
    var __proto = $layoutsavedialog.prototype;

    var txtLayoutName;
    var chkMyDefault;
    var chkPublic;
    var chkCompanyDefault;

    var _this = null;
    __proto.showSaveLayoutDialog = function (topRatio, force) {
        _this = this;
        var dialog;
        if (force) {
            $('#' + this.dialogId).remove();
            dialog = createSaveLayoutDialog.call(this);
        } else {
            dialog = $('#' + this.dialogId);
            if (!dialog.length) {
                dialog = createSaveLayoutDialog.call(this);
            }
        }
        this.dialog = dialog;
        dialog.attr('init', '1').showDialog().css({
            'top': (document.documentElement.clientHeight - $('#dialog_machines').height()) / (topRatio || 3),
            'left': (document.documentElement.clientWidth - $('#dialog_machines').width()) / 2
        });

        getAllGridLayoutsForSave(this.layoutid);
    };

    function createSaveLayoutDialog() {
        var dialog = $('<div class="dialog" style="display: none; width: 440px; height: 220px;min-width:440px;line-height:30px;">').attr('id', this.dialogId);

        var title = $('<div class="dialog-title"></div>').appendTo(dialog);
        title.append($('<span class="title"></span>').text(this.title));
        title.append('<em class="dialog-close"></em>');

        var layoutNameDiv = $('<div style="margin-left:10px;margin-right:10px;margin-top:10px;"></div>').appendTo(dialog);
        layoutNameDiv.append($('<span style="margin-left:10px;"></span>').text(GetTextByKey("P_XXXXXX", "Layout Name:")));
        txtLayoutName = $("<input type='text' style='width:320px;margin-left:5px;' maxlength='200' />").appendTo(layoutNameDiv);
        if (currentLayout && this.type == 1) {//type == 1 在列表上直接保存
            if (!currentLayout.IsPublic || IsAdmin)
                txtLayoutName.val(currentLayout.LayoutName || "");
        }

        var layoutAttrDiv = $('<div style="margin-left:10px;margin-right:10px;"></div>').appendTo(dialog);
        chkMyDefault = $("<input type='checkbox' id='chkMyDefault' style='margin-left: 83px;' />").appendTo(layoutAttrDiv);
        $("<label for='chkMyDefault'></label>").text(GetTextByKey("P_XXXXXX", "Save as my Default")).appendTo(layoutAttrDiv);

        if (IsAdmin) {
            layoutAttrDiv = $('<div style="margin-left:10px;margin-right:10px;"></div>').appendTo(dialog);
            chkPublic = $("<input type='checkbox' id='chkPublic' style='margin-left: 83px;' />").appendTo(layoutAttrDiv);
            $("<label for='chkPublic'></label>").text(GetTextByKey("P_XXXXXX", "Make Public")).appendTo(layoutAttrDiv);

            layoutAttrDiv = $('<div style="margin-left:10px;margin-right:10px;"></div>').appendTo(dialog);
            chkCompanyDefault = $("<input type='checkbox' id='chkCompanyDefault' style='margin-left: 83px;' />").appendTo(layoutAttrDiv);
            $("<label for='chkCompanyDefault'></label>").text(GetTextByKey("P_XXXXXX", "Save as Company Default")).appendTo(layoutAttrDiv);

            chkMyDefault.on('click', function (e) {
                if (chkMyDefault.prop("checked")) {
                    chkPublic.prop("checked", false);
                    chkCompanyDefault.prop("checked", false);
                }
            });

            chkPublic.on('click', function (e) {
                if (chkPublic.prop("checked"))
                    chkMyDefault.prop("checked", false);
                else
                    chkCompanyDefault.prop("checked", false);
            });

            chkCompanyDefault.on('click', function (e) {
                if (chkCompanyDefault.prop("checked")) {
                    chkMyDefault.prop("checked", false);
                    chkPublic.prop("checked", true);
                }
            });

            if (currentLayout && this.type == 1) {//type == 1 在列表上直接保存
                if (!currentLayout.IsPublic)
                    chkMyDefault.prop('checked', currentLayout.IsDefault);
                if (IsAdmin) {
                    chkPublic.prop('checked', currentLayout.IsPublic);
                    if (currentLayout.IsPublic)
                        chkCompanyDefault.prop('checked', currentLayout.IsDefault);
                }
            }
        }
        else {
            dialog.css('height', 140);
        }

        var dialogFunction = $('<div class="dialog-func"></div>').appendTo(dialog);
        $('<input type="button" value="' + GetTextByKey("P_GRID_CANCEL", "Cancel") + '" class="dialog-close" />').appendTo(dialogFunction);
        $('<input type="button" value="' + GetTextByKey("P_GRID_XXXXXX", "Save Layout") + '" />').on('click', onSaveLayoutClick.bind(this)).appendTo(dialogFunction);
        $('<div class="clear"></div>').appendTo(dialogFunction);

        $('<div class="maskbg" style="display: none"></div>').appendTo(dialog);

        $(document.body).append(dialog);

        dialog.dialog(this.onDialogClosed);
        return dialog;
    }

    function onSaveLayoutClick() {
        var layoutinfo = {
            LayoutName: txtLayoutName.val().trim(),
            IsPublic: chkPublic == null ? false : chkPublic.prop("checked"),
        };
        if (!layoutinfo.LayoutName || layoutinfo.LayoutName.trim() == '') {
            showAlert(GetTextByKey("P_GRID_XXXXXX", "Layout name is required."), GetTextByKey("P_GRID_XXXXXX", 'Layout'));
            return;
        }
        if (layoutinfo.IsPublic)
            layoutinfo.IsDefault = chkCompanyDefault == null ? false : chkCompanyDefault.prop("checked");
        else
            layoutinfo.IsDefault = chkMyDefault.prop("checked");

        var overwrite = false;//private and name not changed, overwrite without prompt
        if (currentLayout && !currentLayout.IsPublic && layoutinfo.IsPublic && currentLayout.LayoutName == layoutinfo.LayoutName)
            overwrite = true;

        this.onOK && this.onOK(layoutinfo, overwrite);
    }

    function getAllGridLayoutsForSave(layoutid) {
        _network.commonpagequery(15, layoutid, function (data) {//getGridLayouts
            if (typeof data !== 'string') {
                loadLayoutTip(data);
            }
        });
    }

    function loadLayoutTip(data) {
        $("#div_layout_tooltip").remove();

        if (data.length == 0) return;
        var text = "";
        var priLayouts = [];
        var pubLayouts = [];
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            if (!item) continue;

            var ls = item.IsPublic ? pubLayouts : priLayouts;
            if (item.IsDefault)
                ls.splice(0, 0, item);
            else
                ls.push(item);
        }

        if (priLayouts.length > 0) {
            text += GetTextByKey("P_XXXXXX", "My Saved Layouts");
            for (var i = 0; i < priLayouts.length; i++) {
                var item = priLayouts[i];
                text += "<br/>&nbsp;&nbsp;&nbsp;&nbsp;" + item.LayoutName + (item.IsDefault ? " *" : "");
            }
        }

        if (IsAdmin) {
            if (pubLayouts.length > 0) {
                if (text != "")
                    text += "<br/>";
                text += GetTextByKey("P_XXXXXX", "Company Layouts");
                for (var i = 0; i < pubLayouts.length; i++) {
                    var item = pubLayouts[i];
                    text += "<br/>&nbsp;&nbsp;&nbsp;&nbsp;" + item.LayoutName + (item.IsDefault ? " *" : "");
                }
            }
        }

        var div = $("<div id='div_layout_tooltip' class='div_tooltip' style='display:none; '></div>").html(text);
        var left = _this.dialog.offset().left + _this.dialog.width() + 2;
        var top = _this.dialog.offset().top;
        div.css({ 'display': '', 'left': left, 'top': top, 'max-height': 320, 'max-width': 240, 'overflow': 'hidden' });
        $(window.document.body).append(div);
    }
})();



var $managelayoutdialog = function (layoutid) {
    this.title = GetTextByKey("P_GRID_XXXXXX", 'Manage Layout');
    this.dialogId = 'dialog_managelayout';
    $("#" + this.dialogId).remove();
    this.layoutid = layoutid;
    this.dialog = null;
    this.onDialogClosed = null;
};

(function () {
    var __proto = $managelayoutdialog.prototype;

    var myLayoutsDiv = null;
    var companyLayoutsDiv = null;

    var _this = null;
    __proto.showManageLayoutDialog = function (topRatio, force) {
        var dialog;
        _this = this;
        if (force) {
            $('#' + this.dialogId).remove();
            dialog = createManageLayoutDialog.call(this);
        } else {
            dialog = $('#' + this.dialogId);
            if (!dialog.length) {
                dialog = createManageLayoutDialog.call(this);
            }
        }
        this.dialog = dialog;
        dialog.attr('init', '1').showDialog().css({
            'top': (document.documentElement.clientHeight - $('#dialog_machines').height()) / (topRatio || 3),
            'left': (document.documentElement.clientWidth - $('#dialog_machines').width()) / 2
        });

        getAllGridLayoutsForManage(this.layoutid);
    };

    function createManageLayoutDialog() {
        var dialog = $('<div class="dialog" style="display: none; width: 540px; height: 440px;min-width:440px;line-height:30px;">').attr('id', this.dialogId);

        var title = $('<div class="dialog-title"></div>').appendTo(dialog);
        title.append($('<span class="title"></span>').text(this.title));
        title.append('<em class="dialog-close"></em>');

        var content = $('<div style="height: 360px;overflow:auto;">').appendTo(dialog);

        var labelDiv = $('<div style="margin-left:10px;margin-right:10px;margin-top:10px;"></div>').appendTo(content);
        labelDiv.append($('<span style="margin-left:10px;"></span>').text(GetTextByKey("P_XXXXXX", "My Saved Layouts")));
        myLayoutsDiv = $('<div style="margin-left:10px;margin-right:10px;margin-top:10px;"></div>').appendTo(content);

        if (IsAdmin) {
            labelDiv = $('<div style="margin-left:10px;margin-right:10px;margin-top:10px;"></div>').appendTo(content);
            labelDiv.append($('<span style="margin-left:10px;"></span>').text(GetTextByKey("P_XXXXXX", "Company Layouts")));
            companyLayoutsDiv = $('<div style="margin-left:10px;margin-right:10px;margin-top:10px;"></div>').appendTo(content);
        }

        var dialogFunction = $('<div class="dialog-func"></div>').appendTo(dialog);
        $('<input type="button" value="' + GetTextByKey("P_GRID_OK", "OK") + '" class="dialog-close" />').appendTo(dialogFunction);
        $('<div class="clear"></div>').appendTo(dialogFunction);

        $('<div class="maskbg" style="display: none"></div>').appendTo(dialog);

        $(document.body).append(dialog);

        dialog.dialog(this.onDialogClosed);
        return dialog;
    }

    function getAllGridLayoutsForManage(layoutid) {
        _network.commonpagequery(15, layoutid, function (data) {//getGridLayouts
            if (typeof data !== 'string') {
                var priLayouts = [];
                var pubLayouts = [];
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    if (!item) continue;

                    var ls = item.IsPublic ? pubLayouts : priLayouts;
                    if (item.IsDefault)
                        ls.splice(0, 0, item);
                    else
                        ls.push(item);
                }

                if (priLayouts.length > 0) {
                    for (var i = 0; i < priLayouts.length; i++) {
                        var item = priLayouts[i];
                        var div = $('<div style="padding-left:50px;clear:both;"></div>');
                        div.append($('<span style="width:400px;overflow:hidden;"></span>').text(item.LayoutName + (item.IsDefault ? " *" : "")));
                        var icon = $('<span class="sbutton icondelete" style="float:right;padding: 0px 5px 0px 10px;"></span>').appendTo(div);
                        icon.on('click', item, function (e) {
                            deleteLayout(e.data.ID, $(e.target).parent());
                        });
                        myLayoutsDiv.append(div);
                    }
                }

                if (IsAdmin) {
                    if (pubLayouts.length > 0) {
                        for (var i = 0; i < pubLayouts.length; i++) {
                            var item = pubLayouts[i];
                            var div = $('<div style="padding-left:50px;clear:both;"></div>');
                            div.append($('<span style="width:400px;overflow:hidden;"></span>').text(item.LayoutName + (item.IsDefault ? " *" : "")));
                            var icon = $('<span class="sbutton icondelete" style="float:right;padding: 0px 5px 0px 10px;"></span>').appendTo(div);
                            icon.on('click', item, function (e) {
                                deleteLayout(e.data.ID, $(e.target).parent());
                            });
                            companyLayoutsDiv.append(div);
                        }
                    }
                }
            }
        });
    }

    function deleteLayout(id, div) {
        var msg = GetTextByKey("P_GRID_XXXXXX", 'Are you sure you want to delete this layout?');
        var title = GetTextByKey("P_GRID_XXXXXX", 'Layout');
        showLayoutConfirm(_this.dialog, msg, title, function (e) {
            div.remove();
            _network.commonpagequery(9, id, function (data) { }, function (e) { });
        }, function (e) {
        }, function (e) {
        });
    }
})();








/***************************Public Method********************************************/
function CreateLayoutMenus(sender, layoutid, grid) {
    hidePanels();//hide other menu
    $("#layout_panel_holder").remove();// remove layout_panel_holder

    var panel_holder = $('<div id="layout_panel_holder" class="panel_holder"></div>').appendTo(document.body);
    var funmenu = $('<div class="menupanel panel" style="box-shadow: rgba(0, 0, 0, 0.24) 0px 4px 8px 0px;"></div>');
    panel_holder.append(funmenu);
    var ulmenus = $('<ul class="lefttitlemenu_ul" style="line-height:32px;max-height:480px;max-width:400px; overflow: hidden auto;"></ul>');
    funmenu.append(ulmenus);

    var li = $('<li style="line-height:32px;"></li>').text(GetTextByKey("P_GRID_XXXXXX", 'Update Layout'));
    ulmenus.append(li);
    li.on('click', function () {
        ShowSelectLayoutColumnsDialog(layoutid, grid);
    });
    li = $('<li style="line-height:32px;"></li>').text(GetTextByKey("P_GRID_XXXXXX", 'Save Layout'));
    ulmenus.append(li);
    li.on('click', function () {
        ShowSaveLayoutDialog(null, null, layoutid, grid, 1);
    });
    li = $('<li style="line-height:32px;"></li>').text(GetTextByKey("P_GRID_XXXXXX", 'Manage Layout'));
    ulmenus.append(li);
    li.on('click', function () {
        ShowManageLayoutDialog(layoutid);
    });

    var left = $(sender).offset().left;
    var top = $(sender).offset().top + $(sender).height();
    var minwidth = 150;
    if (minwidth < $(sender).width())
        minwidth = $(sender).width()
    panel_holder.css({
        'opacity': 0,
        'left': left,
        'right': 'auto',
        'top': top + 4,
        'min-width': minwidth,

    }).show().animate({ 'opacity': 1 }, 100);

    getAllGridLayouts(layoutid, grid, ulmenus);
}

function getAllGridLayouts(layoutid, grid, ulmenus) {
    _network.commonpagequery(15, layoutid, function (data) {//getGridLayouts
        if (typeof data !== 'string') {
            var priLayouts = [];
            var pubLayouts = [];
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                if (!item) continue;

                var ls = item.IsPublic ? pubLayouts : priLayouts;
                if (item.IsDefault)
                    ls.splice(0, 0, item);
                else
                    ls.push(item);
            }

            if (priLayouts.length > 0) {
                var li = $('<li style="line-height:unset;height:1px;padding: 0; margin: 0.35em 0; border-bottom: 1px solid #d0d0d0;"></li>');
                ulmenus.append(li);
                for (var i = 0; i < priLayouts.length; i++) {
                    var item = priLayouts[i];
                    var li = $('<li></li>');
                    if (item.LayoutName.length > 35) {
                        li.text(item.LayoutName.substring(0, 35) + '...' + (item.IsDefault ? " *" : ""));
                        li.attr("title", item.LayoutName);
                    }
                    else
                        li.text(item.LayoutName + (item.IsDefault ? " *" : ""));
                    li.on('click', item, function (e) {
                        currentLayout = e.data;
                        showGridLayout(grid, JSON.parse(e.data.Layout), OnRefresh);
                    });
                    ulmenus.append(li);
                }
            }

            if (pubLayouts.length > 0) {
                var li = $('<li style="line-height:unset;height:1px;padding: 0; margin: 0.35em 0; border-bottom: 1px solid #d0d0d0;"></li>');
                ulmenus.append(li);
                for (var i = 0; i < pubLayouts.length; i++) {
                    var item = pubLayouts[i];
                    var li = $('<li></li>');
                    if (item.LayoutName.length > 35) {
                        li.text(item.LayoutName.substring(0, 35) + '...' + (item.IsDefault ? " *" : ""));
                        li.attr("title", item.LayoutName);
                    }
                    else
                        li.text(item.LayoutName + (item.IsDefault ? " *" : ""));
                    li.on('click', item, function (e) {
                        currentLayout = e.data;
                        showGridLayout(grid, JSON.parse(e.data.Layout), OnRefresh);
                    });
                    ulmenus.append(li);
                }
            }
        }
    });
}

function ShowSelectLayoutColumnsDialog(layoutid, grid) {
    showmaskbg(true);

    var dialogColumns = new $layoutcolumnselector(grid);
    dialogColumns.onDialogClosed = function () {
        showmaskbg(false);
    };
    dialogColumns.onOK = function (colinfos) {
        dialogColumns.dialog.find('.maskbg').css('display', '');
        ShowSaveLayoutDialog(dialogColumns, colinfos, layoutid, grid, 0, function () {
            currentLayout = currentLayout || {};
            currentLayout.Layout = JSON.stringify(colinfos);
            showGridLayout(grid, colinfos, OnRefresh);
            dialogColumns && dialogColumns.dialog.hideDialog();
            showmaskbg(false);
        });
    };
    dialogColumns.showLayoutSelector(3, true);
}

function ShowSaveLayoutDialog(sender, colinfos, layoutid, grid, type, next) {
    showmaskbg(true);

    var dialogSaveLayout = new $layoutsavedialog(grid, layoutid, type);
    dialogSaveLayout.onDialogClosed = function () {
        if (sender)
            sender.dialog.find('.maskbg').css('display', 'none');
        else
            showmaskbg(false);
        $("#div_layout_tooltip").remove();
    };
    dialogSaveLayout.onOK = function (layoutinfo, overwrite) {
        saveGridLayout(dialogSaveLayout.dialog, layoutid, grid, layoutinfo, colinfos, next, overwrite);
    };
    dialogSaveLayout.showSaveLayoutDialog(3, true);
}

function ShowManageLayoutDialog(layoutid) {
    showmaskbg(true);

    var dialogManageLayout = new $managelayoutdialog(layoutid);
    dialogManageLayout.onDialogClosed = function () {
        showmaskbg(false);
    };
    dialogManageLayout.showManageLayoutDialog(3, true);
}

var currentLayout = null;
function getGridLayout(layoutid, grid, next) {
    _network.commonpagequery(7, layoutid, function (data) {//GetGridLayout
        currentLayout = data;
        showGridLayout(grid, data == null ? null : JSON.parse(data.Layout), next);
    });
}

function showGridLayout(grid, columninfos, next) {
    var allColumns = $.extend(true, [], grid.allcolumns);
    for (var i = 0; i < allColumns.length; i++) {
        allColumns[i].OriginalCaption = allColumns[i].caption;
        if (allColumns[i].alwaysshow && columninfos && columninfos.length > 0) {//new alwaysshow column
            var exists = false;
            for (var j = 0; j < columninfos.length; j++) {
                if (allColumns[i].name == columninfos[j].ColumnKey) {
                    exists = true;
                    break;
                }
            }
            if (!exists)
                columninfos.push({ ColumnKey: allColumns[i].name, Caption: allColumns[i].caption, Width: allColumns[i].width });
        }
    }

    grid.sortIndex = -1;
    var tmpColumns = allColumns;
    if (columninfos && columninfos.length > 0) {
        tmpColumns = [];
        for (var i = 0; i < columninfos.length; i++) {
            var tmpcol = readColumnWidthSort(allColumns, columninfos[i]);
            if (tmpcol) {
                if (tmpcol.Sort != undefined && tmpcol.Sort != 0) {
                    if (grid.$refs && grid.$refs.grid) {//datagrid:vue
                        grid.$refs.grid.sortKey = tmpcol.name;
                        grid.$refs.grid.sortDirection = tmpcol.Sort;
                    }
                    else {
                        grid.sortIndex = i;
                        grid.sortDirection = tmpcol.Sort;
                    }
                }
                if (tmpcol.name == "Selected")
                    tmpColumns.splice(0, 0, tmpcol);
                else
                    tmpColumns.push(tmpcol);
            }
        }
    }

    //grid.setColumns(tmpColumns);
    grid.columns = tmpColumns;
    if (grid.sortIndex >= grid.columns.length)
        grid.sortIndex = -1;
    if (typeof grid.init == "function")
        grid.init();

    if (next) {
        next(tmpColumns);
    }
}

function readColumnWidthSort(columns, colinfo) {
    for (var i = 0; i < columns.length; i++) {
        if (columns[i].name == colinfo.ColumnKey) {
            if (colinfo.Caption && colinfo.Caption.trim() != "") {
                columns[i].caption = colinfo.Caption;
                columns[i].UserCaption = colinfo.Caption;
            }
            columns[i].width = parseInt(colinfo.Width);
            columns[i].Sort = colinfo.Sort;
            if (columns[i].visible !== false || !columns[i].alwaysshow)
                columns[i].visible = colinfo.Visible == undefined ? true : colinfo.Visible;
            return columns[i];
        }
    }
    return undefined;
}

function saveGridLayout(dialog, layoutid, grid, layoutinfo, colinfos, next, overwrite) {
    if (!colinfos) {
        colinfos = getLayoutOnGrid(grid);
    }

    layoutinfo.LayoutId = layoutid;
    layoutinfo.Layout = JSON.stringify(colinfos)
    _network.commonpagequery(8, htmlencode(JSON.stringify([JSON.stringify(layoutinfo), overwrite ? 1 : 0])), function (e) {
        if (e == -1) {
            showAlert(GetTextByKey("P_GRID_XXXXXX", "Layout {0} is in use by the Organization and cannot be used. Please select another name.").replace('{0}', layoutinfo.LayoutName)
                , GetTextByKey("P_GRID_XXXXXX", 'Layout'));
        }
        else if (e == -2) {
            showLayoutConfirm(dialog, GetTextByKey('P_GRID_XXXXXX', 'Layout {0} already exists, Do you want to overwrite it?').replace('{0}', layoutinfo.LayoutName)
                , GetTextByKey('P_GRID_XXXXXX', 'Layout'), function () {
                    saveGridLayout(dialog, layoutid, grid, layoutinfo, colinfos, next, true);
                });
        }
        else {//Successfully
            dialog && dialog.hideDialog();
            $("#div_layout_tooltip").remove();
            if (next) {
                next();
                return;
            }
            showmaskbg(false);
        }
    });
}

function getLayoutOnGrid(grid) {
    colinfos = [];
    for (var i = 0; i < grid.columns.length; i++) {
        var sort = 0;
        var sortKey = "";
        var sortDirection = 0;
        if (grid.$refs && grid.$refs.grid) { //datagrid:vue
            sortKey = grid.$refs.grid.sortKey;
            sortDirection = grid.$refs.grid.sortDirection;
        }
        else {
            sortKey = grid.sortKey;
            sortDirection = grid.sortDirection;
        }
        if (sortKey && (sortKey == grid.columns[i].name || sortKey == grid.columns[i].key))
            sort = sortDirection;
        if (isNaN(sort))
            sort = 0;
        var columnwidth = {
            'Visible': grid.columns[i].visible !== false,
            'ColumnKey': grid.columns[i].name,
            'Caption': grid.columns[i].UserCaption,
            'Width': grid.columns[i].width,
            'Sort': sort
        }
        colinfos.push(columnwidth);
    }
    return colinfos;
}

function showLayoutConfirm(dialog, msg, title, fok, fcancel) {
    dialog.find('.maskbg').css('display', '');
    _dialog.showConfirm(msg, title, function (e) {
        dialog.find('.maskbg').css('display', 'none');
        if (typeof fok === 'function') {
            fok(e);
        }
    }, function () {
        dialog.find('.maskbg').css('display', 'none');
    });
}