<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Management.aspx.cs" Inherits="GigaTech.CMS.Web.Apps.Post.Management" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
    <script language=javascript>
    var rootIdent = "<%=rootIdent %>";
    var totalLevel = "<%=totalLevel %>";
    var InDoorType = "<%=InDoorType%>";
    var grid;
    
    function getGridSelectedIdent() {
        var list = "";
        Ext.Array.each(grid.getSelectionModel().getSelection(), function(v) {
            if (list != "") list = list + ",";
            list = list + v.get("Ident");
        });
        return list;
    }

        
    Ext.onReady(function () {
        Ext.QuickTips.init();

        var gridStore = Ext.create('Ext.data.Store', {
            pageSize: 20,
            remoteSort: true,
            autoLoad: true,
            fields: ['Ident', 'Subject', 'Who', 'PostDateTime', 'MsgType'],
            proxy: {
                type: 'ajax',
                url: 'Handler.ashx?action=GetGridData',
                reader: {
                    type: 'json',
                    root: 'items',
                    totalProperty: 'totalCount'
                },
                simpleSortMode: true,
                extraParams: {
                    isSearch: '0',
                    name: '',
                    id: '',
                    group: '',
                    status: ''
                }
            },
            sorters: [{
                property: "PostDateTime",
                direction: "DESC"
            }]
        });

        grid = Ext.create('Ext.grid.Panel', {
            tbar: ['<font color=darkblue><b>【<%=GetGlobalResourceObject("CMSResource", "MsgPost")%>】</b></font>',
                '->',
                {
                    text: '<%=GetGlobalResourceObject("CMSResource", "PostTextMsg")%>',
                    cls: 'x-btn-default-small',
                    border: 1,
                    style: {
                        borderColor: 'gray',
                        borderStyle: 'solid'
                    },
                    icon: '/Common/DMZ/Images/16x16/comment.png',
                    handler: function() {
                        ShowWin("",false,1);
                    }
                },
                {
                    text: '<%=GetGlobalResourceObject("CMSResource", "PostImgMsg")%>',
                    cls: 'x-btn-default-small',
                    border: 1,
                    style: {
                        borderColor: 'gray',
                        borderStyle: 'solid'
                    },
                    icon: '/Common/DMZ/Images/16x16/picture_add.png',
                    hidden:InDoorType!="0",
                    handler: function () {
                        ShowWin("", false,2);
                    }
                }

            ],
            region: 'center',
            store: gridStore,
            columns: [
                { text: '<%=GetGlobalResourceObject("CMSResource", "Subject")%>', dataIndex: 'Subject', flex: 2 },
                { text: '<%=GetGlobalResourceObject("CMSResource", "ReleaseTarget")%>', dataIndex: 'Who', flex: 1 },
                {
                    text: '<%=GetGlobalResourceObject("CMSResource", "PropType")%>', dataIndex: 'MsgType', width: 50,
                    renderer: function (value) {
                        return value == "1" ? "<%=GetGlobalResourceObject("CMSResource", "Text")%>" : "<%=GetGlobalResourceObject("CMSResource", "Picture")%>";
                    }
                },
                { text: '<%=GetGlobalResourceObject("CMSResource", "PostDateTime")%>', dataIndex: 'PostDateTime', width: 150 },
                {
                    xtype: 'actioncolumn',
                    hideable: false,
                    width: 30,
                    sortable: false,
                    menuDisabled: true,
                    align: 'center',
                    items: [{
                        icon: '/Common/DMZ/Images/16x16/view.png',
                        tooltip: '<%=GetGlobalResourceObject("CMSResource", "View")%>',
                        scope: this,
                        handler: function(view, rowIndex, colIndex, item, e, record, row) {
                            ShowWin(record.get("Ident"), true, record.get("MsgType"));
                        }
                    }]
                },
                {
                    xtype: 'actioncolumn',
                    hideable: false,
                    width: 30,
                    sortable: false,
                    menuDisabled: true,
                    align: 'center',
                    items: [{
                        icon: '/Common/DMZ/Images/16x16/edit.png',
                        tooltip: '<%=GetGlobalResourceObject("CMSResource", "Eidt")%>',
                        scope: this,
                        handler: function(view, rowIndex, colIndex, item, e, record, row) {
                            ShowWin(record.get("Ident"), false, record.get("MsgType"));
                        },
                        isDisabled: function (view, rowIndex, colIndex, item, record) {
                            return record.get("MsgType")=="2";
                        }
                    }]
                },
                {
                    xtype: 'actioncolumn',
                    hideable: false,
                    width: 30,
                    sortable: false,
                    menuDisabled: true,
                    align: 'center',
                    hidden:true,
                    items: [{
                        icon: '/Common/DMZ/Images/16x16/delete.png',
                        tooltip: '<%=GetGlobalResourceObject("CMSResource", "Delete")%>',
                        scope: this,
                        handler: function (view, rowIndex, colIndex, item, e, record, row) {
                            if(confirm("<%=GetGlobalResourceObject("CMSResource", "SureDeleteData")%>")) {
                                Ext.Ajax.request({
                                    url: 'Handler.ashx',
                                    params: {
                                        action: 'DelData',
                                        ident: record.get("Ident")
                                    },
                                    success: function (response) {
                                        grid.store.load();
                                    }
                                });
                            }

                        }
                    }]
                }
            ],
            dockedItems: [{
                xtype: 'pagingtoolbar',
                store: gridStore,
                dock: 'bottom',
                displayInfo: true
            }]
        });

        Ext.create('Ext.container.Viewport', {
            layout: {
                type: 'border'
            },
            items: [grid]
        });

        var task = {
            run: function () {
                Ext.Ajax.request({
                    url: '/Common/Empty.ashx'
                });
            },
            interval: 300000
        };

        var runner = new Ext.util.TaskRunner();
        runner.start(task);
    });

    function ShowWin(ident,viewOnly,MsgType) {
        var title =viewOnly? '<%=GetGlobalResourceObject("CMSResource", "Msg")%>': '<%=GetGlobalResourceObject("CMSResource", "EditMsg")%>';

        var contentForm = Ext.create('Ext.form.Panel', {
            border: false,
            bodyPadding: 5,
            layout: {
                type: 'vbox',
                align: 'stretch'  // Child items are stretched to full width
            },
            url: 'Handler.ashx?action=SaveData',
            defaults: {
                anchor: '100%',
                labelWidth: 74
            },
            defaultType: 'textfield',
            items: [{
                xtype: 'hiddenfield',
                name: 'msgType',
                value: MsgType
            },{
                xtype: 'hiddenfield',
                name: 'ident',
                value: ident
            }, {
                xtype: 'hiddenfield',
                name: 'who',
                id: 'who'
            }, {
                xtype: 'container',
                layout: 'hbox',
                margin: '0 0 5 0',
                hidden: viewOnly,
                items: [
                    {
                        xtype: 'button',
                        text: '<%=GetGlobalResourceObject("CMSResource", "ReleaseTarget")%>...',
                        margin: '3 5 3 0',
                        tooltip: '<%=GetGlobalResourceObject("CMSResource", "SelectPublish")%>',
                        border: 1,
                        style: {
                            borderColor: 'gray',
                            borderStyle: 'solid'
                        },
                        handler: function () {
                            OpenSelectWin("receiverPanel");
                        }
                    }
                                ,
                    {
                        xtype: 'panel',
                        id: 'receiverPanel',
                        height: 55,
                        autoScroll: true,
                        items: [],
                        flex: 1
                    }

                ]
            }, {
                fieldLabel: '<%=GetGlobalResourceObject("CMSResource", "Subject")%>',
                xtype: 'textfield',
                name: 'subject',
                allowBlank: false
            },
                                                                      {
                                                                          xtype: "component",
                                                                          border: false,
                                                                          flex: 1,
                                                                          hidden: MsgType == 1 || !viewOnly,
                                                                          autoEl: {
                                                                              tag: "iframe",
                                                                              src: "/Common/DMZ/Device/ShowMsgContent4Device.ashx?msgID=" + ident
                                                                          }
                                                                      },
            {
                xtype: 'filefield',
                name: 'imgMsg',
                fieldLabel: '<%=GetGlobalResourceObject("CMSResource", "ImgMsg")%>',
                msgTarget: 'side',
                allowBlank: MsgType == 1,
                anchor: '100%',
                hidden: MsgType == 1 || viewOnly,
                buttonText: '<%=GetGlobalResourceObject("CMSResource", "SelectPls")%>'
            }, {
                xtype: 'htmleditor',
                id: 'content',
                margin: '5 0 0 0',
                fieldLabel: 'Message text',
                hideLabel: true,
                name: 'content',
                grow: true,
                enableFont: false,
                enableFontSize: false,
                enableLists: false,
                flex: 1,
                hidden: MsgType == 2,
                listeners: {
                    'render': function () {
                        var obj = Ext.getCmp('content');
                        if (InDoorType == "1") {
                            //ITE
                            obj.getToolbar().setHeight(1);
                        }
                    }
                }
            }],
            buttons: [
                {
                    text: '<%=GetGlobalResourceObject("CMSResource", "SendMsg")%>',
                    formBind: true,
                    hidden:viewOnly,
                    handler: function () {
                        var form = this.up('form').getForm();
                       
                        if (MsgType != 2) {
                            //Check HTMLEdit Content
                            var content = Ext.getCmp("content").getValue();
                            if (content == "") {
                                alert("<%=GetGlobalResourceObject("CMSResource", "MsgContentEmpty")%>");
                                return;
                            }
                        }

                        if (form.isValid()) {

                            var receiver = "";
                            Ext.getCmp('receiverPanel').items.each(function (item) {
                                if (receiver != "") receiver = receiver + ",";
                                receiver = receiver + item.text + "|" + (item.text.indexOf("#") == -1 ? "M" : "D") + "|" + item.tooltip;
                            });

                            if (receiver == "") {
                                alert("<%=GetGlobalResourceObject("CMSResource", "PleaseSelectPublish")%>");
                                return;
                            }
                            else {
                                Ext.getCmp('who').setValue(receiver);
                                
                                form.submit({
                                    success: function (f, action) {
                                        grid.store.load();
                                        w.close();
                                    },
                                    failure: function (f, action) {
                                        var msg = "<%=GetGlobalResourceObject("CMSResource", "SaveFail")%>";
                                        if (action.result.msg != "") msg = action.result.msg;
                                        alert(msg);
                                    }
                                });
                            }


                        }
                    }
                },
                {
                    text: viewOnly ? '<%=GetGlobalResourceObject("CMSResource", "Close")%>' : '<%=GetGlobalResourceObject("CMSResource", "Cancel")%>',
                    handler: function () {
                        this.up("window").close();
                    }
                }
            ]
        });

        if (ident != "") {
            contentForm.getForm().load({
                url: 'Handler.ashx?action=GetData&ident=' + ident,
                success: function (form, action) {

                    var cc = action.result.data.who.split(",");

                    if (cc != "") {
                        for (key in cc) {
                            opencc = true;

                            var targetPanel = "receiverPanel";
                            var selectedID = cc[key].split("|")[0];
                            var selectedName = cc[key].split("|")[2];
                            var id = targetPanel + "_" + selectedID;

                            if (!Ext.getCmp(id)) Ext.getCmp(targetPanel).add(BuildReceiver(id, selectedID, selectedName.replace(/\s+/g, "")));

                        }
                    }

                }
            });
        }

        var w = Ext.create('Ext.window.Window', {
            title: title,
            layout: 'fit',
            modal: true,
            constrain: true,
            shadow: true,
            shadowOffset: 50,
            width: '90%',
            height:'90%',
            items: contentForm
        }).show();

        Ext.getCmp('content').focus("", 200);

        //Ext.Function.defer(function () {
        //    var obj=Ext.getCmp('content');
        //    obj.relayCmd('fontsize', '8');
        //}, 1000);
    }

    function OpenSelectWin(targetPanel) {

        var HouseWin = Ext.create('Ext.window.Window', {
            id: 'HouseWin',
            title: "<%=GetGlobalResourceObject("CMSResource", "SelectFloor")%>",
            layout: 'fit',
            width: 650,
            height: 500,
            modal: true,
            constrain: true,
            shadow: true,
            shadowOffset: 50,
            items: [
                Ext.create('Ext.tree.Panel', {
                    id: 'HouseTree',
                    flex: 1,
                    border: false,
                    store: Ext.create('Ext.data.TreeStore', {
                        autoLoad: true,
                        fields: [
                            'children', 'realId', 'expanded', 'icon', 'mac', 'note', 'leaf', { name: 'text', sortType: 'asNatural' }, 'status', 'assigned', 'text_f', 'ver', 'level'
                        ],
                        proxy: {
                            type: 'ajax',
                            url: '/Common/SystemAdmin/Building/Handler.ashx?action=GetStructureTree'
                        },
                        root: {
                            text: '<%=GetGlobalResourceObject("CMSResource", "AllArea1")%>',
                            id: rootIdent,
                            realId: '-1',
                            checked: false
                        },
                        sorters: [{ property: 'text', direction: 'ASC' }],
                        folderSort: true
                    }),
                    multiSelect: false,
                    singleExpand: false,

                    viewConfig: {
                        stripeRows: true,
                        markDirty: false
                    },
                    sortableColumns: false,
                    sorters: [{
                        property: 'text',
                        direction: 'ASC'
                    }],

                    columns: [{
                        xtype: 'treecolumn',
                        text: '',
                        flex: 1,
                        sortable: false,
                        dataIndex: 'text',
                        menuDisabled: true
                    }, {
                        text: '<%=GetGlobalResourceObject("CMSResource", "Description")%>',
                        flex: 1,
                        dataIndex: 'note',
                        hidden: false,
                        sortable: false,
                        menuDisabled: true
                    }],
                    listeners: {
                        //'afteritemexpand': function () {
                        //    this.getStore().sort("text", "ASC");
                        //},
                        'itemappend': function (n, node, index, eOpts) {
                            //var note = getParentName(node) + " " + node.get("text");
                            var note = getParentName(node) + " " + processInt(node.get("text").split(" ")[0]) + " " + node.get("text").split(" ")[1];
                            if (totalLevel == node.getDepth()) {
                                node.set("icon", "/Common/DMZ/Images/16x16/home.png");
                            } else {
                                note = "<font color=gray>" + note + "</font>";
                            }
                            node.set("note", note);

                        }
                    },
                    buttons: [
                        {
                            text: '<%=GetGlobalResourceObject("CMSResource", "OK")%>',
                            id: 'SaveButton',
                            //                            disabled: true,
                            border: 1,
                            style: {
                                borderColor: 'gray',
                                borderStyle: 'solid'
                            },
                            handler: function () {
                                var tree = Ext.getCmp("HouseTree");


                                tree.getRootNode().cascadeBy(function (n) {
                                    if (n.get("checked")) {
                                        var selectedName = getParentName(n) + " " + n.get("text");
                                        var selectedID = getParentID(n) + n.get("realId") + (n.getDepth() == totalLevel ? "" : "#");
                                        //                                            return false;

                                        if (selectedID == "-1#") {
                                            //全區
                                            selectedID = "#";
                                        }

                                        var id = targetPanel + "_" + selectedID;

                                        if (selectedID.indexOf('#') != -1) selectedName = "【" + selectedName + "】";

                                        if (!Ext.getCmp(id)) Ext.getCmp(targetPanel).add(BuildReceiver(id, selectedID, selectedName.replace(/\s+/g, "")));
                                    }

                                });

                                this.up("window").close();
                            }
                        }, {
                            text: '<%=GetGlobalResourceObject("CMSResource", "Cancel")%>',
                            border: 1,
                            style: {
                                borderColor: 'gray',
                                borderStyle: 'solid'
                            },
                            handler: function () {
                                this.up("window").close();
                            }
                        }
                    ]
                })
            ]
        }).show();

    }

    function getParentName(node) {
        var parentNode = node.parentNode;
        var names = "";
        if (parentNode) {
            if (parentNode.get("text").split(" ").length == 2)
                names = getParentName(parentNode) + " " + (processInt(parentNode.get("text").split(" ")[0]) + " " + parentNode.get("text").split(" ")[1]);
            else
                names = getParentName(parentNode) + " " + (processInt(parentNode.get("text").split(" ")[0]));
        }
        return names;

    }

    function processInt(str) {
        if (isNaN(parseInt(str))) {
            return str;
        }
        else {
            return parseInt(str);
        }
    }

    function getParentID(node) {
        var parentNode = node.parentNode;
        var names = "";
        if (parentNode) {
            if (parentNode.get("text").split(" ").length == 2)
                names = getParentID(parentNode) + parentNode.get("realId");
            else
                names = "";
        }
        return names;

    }

    function BuildReceiver(id, text, tooltip) {

        return Ext.create('Ext.button.Split', {
            id: id,
            text: text,
            tooltip: tooltip,
            margin: 2,
            border: 1,
            style: {
                borderColor: '#ccd5e4',
                borderStyle: 'solid',
                background: '#eff2f7'
            },
            listeners: {
                'arrowclick': function () {
                    this.up('panel').remove(this);
                    //                    Ext.getCmp('rPanel').remove(this);
                }
            }
        });

    }
</script>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
