﻿///<reference path="../../Lib/Extjs_Intellisense.js" />

Ext.namespace('LUL');
        
var newsPanelTPL = new Ext.XTemplate(
    '<tpl for="PanelData">',
        // titel
        '<div id="newsPanel{parent.id}Title" class="title">{name}</div>',
        '<div class="addIcon"></div>',
        // länkar
        '<tpl for="News">',
            '<div class="newsPanelNews ">',
                '<div class="newsTitle">{title}</div>',
                '<div class="newsPublished">Publicerad {[values["date"].format("Y-m-d")]} av {who}</div>',
                '<div class="newsBody">{text}</div>',
            '</div>',
        '</tpl>',
    '</tpl>'
);

// redigeringspanel för länkar
LUL.NewsEditor = Ext.extend(LUL.EditorPanel, {

    initComponent: function() {
        LUL.NewsEditor.superclass.initComponent.call(this);

        if (this.height < 200) this.height = 200;

        var action = new Ext.ux.grid.RowActions({
            header: 'Actions',
            actions: [
                { iconCls: 'icon-edit-record', qtip: 'Redigera länk' },
                { iconCls: 'icon-minus', qtip: 'Ta bort länk' }
            ]
        });

        action.on('action', function(grid, record, action, row, col) {
            // redigera eller ta bort?
            if (action == 'icon-edit-record') {
                this.editNews(record);
            } else {
                if (record.data.removed)
                    record.data.removed = false;
                else
                    record.data.removed = true;
                grid.getView().refresh();
            }
        }, this);

        function renderDate(value, meta, record, row) {
            return value.format('Y-m-d');
        }

        var grid = new Ext.grid.GridPanel({
            hideHeaders: true,
            store: new Ext.data.JsonStore({
                root: 'News',
                data: this.data.PanelData,
                fields: ['id', 'title', { name: 'date', type: 'date' }, 'who', 'text', 'created'],
                sortInfo: { field: 'created', direction: 'DESC' }
            }),
            viewConfig: {
                getRowClass: function(record, rowIndex, rowParams, store) {
                    if (record.data.removed) return 'removed';
                    if (record.data.added) return 'added';
                    if (record.data.edited) return 'edited';
                }
            },
            autoExpandColumn: 'title',
            columns: [
                { id: 'title', header: 'Titel', dataIndex: 'title' },
                { header: 'Datum', dataIndex: 'date', renderer: renderDate, width: 65 },
                { header: 'Sign', dataIndex: 'who', width: 65 },
                action
            ],
            plugins: [
                action
            ],
            tbar: [
                { text: 'Lägg till', iconCls: 'icon-plus', handler: function() { this.addNews(grid.getStore()); }, scope: this }
            ]
        });
        grid.on('rowdblclick', function(grid, row) {
            this.editNews(grid.getStore().getAt(row));
        }, this);

        this.add(grid);
        this.grid = grid;

        this.setTitle(this.data.PanelData.name);

        if (document.selection && document.selection.createRange().htmlText == '') document.selection.clear();

        // hoppa direkt till "lägg till nyhet"?
        if (this.extra == 'add') this.addNews(grid.getStore());
    },

    showNewsWindow: function(title, init, ok) {
        var statusBar = new Ext.StatusBar({
            text: '',
            items: [
                { text: 'OK', iconCls: 'icon-ok', handler: function() { ok.call(this, form.form); win.close(); }, scope: this },
                { text: 'Avbryt', iconCls: 'icon-cancel', handler: function() { win.close(); } }
            ]
        });

        var form = new Ext.form.FormPanel({
            labelAlign: 'top',
            items: [
                new LUL.TextField({ fieldLabel: 'Titel', name: 'title', anchor: '100%', tooltip: 'Nyhetens titel/rubrik', statusBar: statusBar }),
                new Ext.form.DateField({ fieldLabel: 'Publicerad', name: 'date', anchor: '100%' }),
                new LUL.TextField({ fieldLabel: 'Sign', name: 'who', anchor: '100%', tooltip: 'Upphovsmannens namn', statusBar: statusBar }),
            //new Ext.form.TextArea({ fieldLabel: 'Text', name: 'text', anchor: '100%', height: 100 })
                new LUL.HtmlEditor({ id: 'newsEditor', fieldLabel: 'Text', name: 'text', anchor: '100%', height: 200,
                    enableAlignments: false, enableFont: false, enableParagraphFormat: false
                })
            ]
        });
        var win = new Ext.Window({
            title: title,
            width: 350,
            height: 450,
            layout: 'fit',
            hideBorders: true,
            bodyStyle: 'padding: 10px; background: white',
            modal: true,
            items: [
                form
            ],
            bbar: statusBar
            /*buttons: [
            { text: 'OK', handler: function() { ok.call(this, form.form); win.close(); }, scope: this },
            { text: 'Avbryt', handler: function() { win.close(); } }
            ]*/
        });
        win.on('render', function() {
            
        }, this);
        win.show();

        if (init) init.call(this, form.form);
    },

    addNews: function(store) {
    this.showNewsWindow(
            'Lägg till nyhet',
        // init
            function(form) {
                form.setValues({ date: new Date() });
            },
        // ok
            function(form) {
                var NewsRecord = Ext.data.Record.create(store.fields.items);
                var news = new NewsRecord({ id: 0, title: '', date: '', text: '', who: '' });
                news.data.added = true;
                form.updateRecord(news);
                news.data.created = new Date();
                store.add(news);
                //store.sort('created', 'DESC');
                // Sabbar id-hanteringen, måste göra mer robust sån om det ska gå att sortera direkt
                // Sorterar vid sparande istället
            }
        );
    },

    editNews: function(record) {
    this.showNewsWindow(
            'Redigera nyhet',
        // init
            function(form) {
                var id = record.data.id;
                form.loadRecord(record);
            },
        // ok
            function(form) {
                form.updateRecord(record);
                if (record.dirty) record.data.edited = true;
                this.grid.getView().refresh();
            }
        );
    },

    onSave: function() {
        var allData = [];
        var modified = [];
        var modifiedData = [];
        this.grid.getStore().each(function(r) {
            if (r.dirty || r.data.removed) {
                modified.push(r);
                modifiedData.push(r.data);
            }
            allData.push(r.data);
        });

        var p = this;

        function success(response) {
            var res = Ext.util.JSON.decode(response.responseText);
            if (res.success) {
                p.getEl().unmask();
                LUL.NewsEditor.superclass.onSave.call(p);

                for (var i = 0; i < modified.length; i++) {
                    // ta bort
                    if (modified[i].data.removed == true) {
                        p.grid.getStore().remove(modified[i]);
                    }
                }

                for (var i = 0; i < modified.length; i++) {
                    // fixa id för nya
                    if (modified[i].data.id == 0 && !modified[i].data.removed) {
                        var index = p.grid.store.indexOf(modified[i]);
                        //allData[index].id = id;
                        modified[i].data.id = res.ids[index].id;
                        modified[i].data.added = null;
                    }
                    // redigerad
                    if (modified[i].data.edited == true) {
                        modified[i].data.edited = null;
                    }
                }

                p.grid.getStore().sort('created', 'DESC');

                // uppdatera paneldata
                p.data.PanelData.News = [];
                p.grid.getStore().each(function(r) {
                    p.data.PanelData.News.push(r.data);
                });
                p.removedRecords = null;

                // visa visst antal?
                if (p.data.instanceData != null && p.data.instanceData.max > 0) {
                    // klipp tillfälligt ut rätt antal poster
                    var tempNews = p.data.PanelData.News;
                    p.data.PanelData.News = tempNews.slice(0, p.data.instanceData.max);
                    newsPanelTPL.overwrite(p.editElement, p.data);
                    p.data.PanelData.News = tempNews;
                } else {
                    newsPanelTPL.overwrite(p.editElement, p.data);
                }
                newsPanelHandler.initPanel(p.editElement);
            }
        }

        function failure() {
            p.getEl().unmask();
            alert('Kunde inte spara!');
        }

        this.getEl().mask('Sparar');

        var mod = Ext.util.JSON.encode(modifiedData);

        Ext.Ajax.request({
            url: dataManager.editNewsURL,
            success: success,
            failure: failure,
            params: { id: this.data.PanelData.id, modified: mod }
        });
    },

    onClose: function() {
        LUL.NewsEditor.superclass.onClose.call(this);
        Ext.get('newsPanel' + this.data.id + 'Title').dom.innerHTML = this.data.PanelData.name;
        newsPanelHandler.initPanel(this.editElement);
    },

    onPanelSettings: function() {
        var me = this;
        var fieldNames = [
            ['Namn', 'PanelData.name', true, 'Panelens namn & titel'],
        // data i instanceData är unikt för sidpanelen, inte för panelen som övrig data här är
            ['Antal nyheter', 'instanceData.max', true, 'Max antal visade nyheter (instans)'],
            new LUL.Checkbox({ hideLabel: true, boxLabel: 'Tillåt flera kopior', name: 'PanelData.allowMultiple', tooltip: 'Tillåt användning på flera sidor' }),
            ['CSS stilmall', 'PanelData.style', true],
            ['CSS klass', 'PanelData.cls', true]
        ];
        this.showPanelSettings(fieldNames, dataManager.newsPanelEditSettingsURL);
    }
});

// hantera dubbelklick på sidan
LUL.NewsEditor.onDblClick = function(e) {
    LUL.EditorPanel.onDblClick(e, 'div.newsPanel');
}

// skapar ny textpanel och öppnar editorn för den
LUL.NewsEditor.createNew = function(marker, insertBefore) {
    function success(res, id) {
        Ext.get('newsPanelX').set({
            id: 'newsPanel' + id,
            cls: 'newsPanel'
        });
        Ext.DomHelper.append('newsPanel' + id, {
            tag: 'div',
            id: 'newsPanel' + id + 'Title',
            cls: 'newsPanelTitle',
            html: 'Ny nyhetspanel'
        });
        Ext.get('newsPanel' + id).on('dblclick', LUL.NewsEditor.onDblClick);
        newsPanelHandler.initPanel(Ext.get('newsPanel' + id));
    }

    LUL.EditorPanel.createNew(
        marker,
        insertBefore,
        { tag: 'div', id: 'newsPanelX' },
        dataManager.createNewsPanelURL,
        'newsPanel',
        success
    );
}

// laddar en dold panel...
LUL.NewsEditor.loadHiddenPanel = function(marker, insertBefore, dragData) {
    function success(response, id) {
        Ext.DomHelper.insertAfter(marker, {
            tag: 'div',
            id: 'newsPanel' + id,
            cls: 'newsPanel',
            html: newsPanelTPL.apply({ id: id, PanelData: dragData.panelData })
        });

        Ext.get('newsPanel' + id).on('dblclick', LUL.NewsEditor.onDblClick);
        newsPanelHandler.initPanel(Ext.get('newsPanel' + id));
    }

    LUL.EditorPanel.loadHidden(
        marker,
        insertBefore,
        dragData,
        success
    );
}

// skapar en ny kopia av en panel
LUL.NewsEditor.loadExistingPanel = function(marker, insertBefore, dragData) {
    function success(response, id) {
        var html = newsPanelTPL.apply({ id: id, PanelData: dragData.panelData });

        Ext.DomHelper.insertBefore(insertBefore, {
            tag: 'div',
            id: 'newsPanel' + id,
            cls: 'newsPanel',
            html: html
        });

        Ext.get('newsPanel' + id).on('dblclick', LUL.NewsEditor.onDblClick);
        newsPanelHandler.initPanel(Ext.get('newsPanel' + id));
    }

    LUL.EditorPanel.loadExisting(
        marker,
        insertBefore,
        dragData,
        success
    );
}
