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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
    <style type="text/css">
        .x-btn-default-small .x-btn-split-right {
background-image: url(/Apps/eMessage/Images/s-arrow_.gif);
padding-right: 14px;
}
</style>
<script language=javascript>
    var rootIdent = "<%=rootIdent %>";
    var totalLevel = "<%=totalLevel %>";
    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', 'MsgText', 'Who', 'BeginDateTime', 'EndDateTime'],
            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: "BeginDateTime",
                direction: "DESC"
            }]
        });

        grid = Ext.create('Ext.grid.Panel', {
            tbar: ['<font color=darkblue><b>【<%=GetGlobalResourceObject("CMSResource", "MarqueeManage")%>】</b></font>',
                {
                    text: '<%=GetGlobalResourceObject("CMSResource", "UpdateMsg2Device")%>',
                    cls: 'x-btn-default-small',
                    border: 1,
                    style: {
                        borderColor: 'gray',
                        borderStyle: 'solid'
                    },
                    icon: '/Common/DMZ/Images/16x16/rss_black.png',
                    handler: function () {
                        Ext.Ajax.request({
                            url: 'Handler.ashx',
                            params: {
                                action: 'SendAll2Device'
                            },
                            success: function (response) {
                                alert("<%=GetGlobalResourceObject("CMSResource", "UpdateSuccess")%>");
                            }
                        });
                    }
                },
                '->',
                {
                    text: '<%=GetGlobalResourceObject("CMSResource", "NewMsg")%>',
                    cls: 'x-btn-default-small',
                    border: 1,
                    style: {
                        borderColor: 'gray',
                        borderStyle: 'solid'
                    },
                    icon: '/Common/DMZ/Images/16x16/comment.png',
                    handler: function() {
                        ShowWin("");
                    }
                }

            ],
            region: 'center',
            store: gridStore,
            columns: [
                { text: '<%=GetGlobalResourceObject("CMSResource", "MsgText")%>', dataIndex: 'MsgText', flex: 2 },
                { text: '<%=GetGlobalResourceObject("CMSResource", "ReleaseTarget")%>', dataIndex: 'Who', flex: 1 },
                { text: '<%=GetGlobalResourceObject("CMSResource", "EndDate")%>', dataIndex: 'BeginDateTime', width: 80 },
                { text: '<%=GetGlobalResourceObject("CMSResource", "BeginDate")%>', dataIndex: 'EndDateTime', width: 80 },
                {
                    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"));
                        }
                    }]
                },
                {
                    xtype: 'actioncolumn',
                    hideable: false,
                    width: 30,
                    sortable: false,
                    menuDisabled: true,
                    align: 'center',
                    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]
        });
    });

    function ShowWin(ident) {
        var title = ident == '' ? '<%=GetGlobalResourceObject("CMSResource", "NewMsg")%>' : '<%=GetGlobalResourceObject("CMSResource", "ModifyMsg")%>';

        var contentForm = Ext.create('Ext.form.Panel', {
            border: false,
            bodyPadding: 5,
            layout: 'anchor',
            url: 'Handler.ashx?action=SaveData',
            defaults: {
                anchor: '100%',
                labelWidth: 74
            },
            defaultType: 'textfield',
            items: [{
                xtype: 'hiddenfield',
                name: 'ident',
                value: ident
            }, {
                xtype: 'container',
                layout: 'hbox',
                margin: '0 0 5 0',
                items: [
                    {
                        xtype: 'datefield',
                        fieldLabel: '<%=GetGlobalResourceObject("CMSResource", "EffectDate")%>',
                        name: 'displaytime_begin',
                        labelWidth: 74,
                        allowBlank: false
                    },
                    {
                        xtype: 'label',
                        text: '<%=GetGlobalResourceObject("CMSResource", "To")%>',
                        margin: 3
                    },
                    {
                        xtype: 'datefield',
                        name: 'displaytime_end',
                        allowBlank: false

                    }
                ]
            }, {
                xtype: 'hiddenfield',
                name: 'who',
                id: 'who'
            }, {
                xtype: 'container',
                layout: 'hbox',
                margin: '0 0 5 0',
                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", "MsgText")%>',
                xtype: 'textfield',
                name: 'msgtext',
                allowBlank: false
            }],
            buttons: [
                {
                    text: '<%=GetGlobalResourceObject("CMSResource", "Save")%>',
                    formBind: true,
                    handler: function () {
                        var login_begin = this.up("form").getForm().findField("displaytime_begin").getValue();
                        var login_end = this.up("form").getForm().findField("displaytime_end").getValue();
                        login_begin = login_begin == null ? "" : login_begin;
                        login_end = login_end == null ? "" : login_end;

                        if (login_begin != "" && login_end != "") {
                            if (login_begin > login_end) {
                                alert("<%=GetGlobalResourceObject("CMSResource", "EffectDateError")%>");
                                return;
                            }
                        }


                        var form = this.up('form').getForm();
                        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: '<%=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 val = action.result.data.groups;
//                    if (val.split) {
//                        val = val.split(',');
//                    }
//                    var group = form.findField('groups');
//                    group.reset();
//                    for (var i = 0; i < val.length; i++) {
//                        group.items.each(function(c) {
//                            if (c.inputValue == val[i]) {
//                                c.setValue(true);
//                            }
//                        });
//                    }
                }
            });
        }

        var w = Ext.create('Ext.window.Window', {
            title: title,
            layout: 'fit',
            modal: true,
            constrain: true,
            shadow: true,
            shadowOffset: 50,
            width: 600,
            items: contentForm
        }).show();
        Ext.getCmp('accountName').focus(false, 200);
    }

    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>
