﻿///<reference path="Extjs_Intellisense.js" />

Ext.namespace('LUL');

var linkPanelTPL = new Ext.XTemplate(
    '<tpl for="PanelData">',
        // titel
        '<div id="linkPanel{parent.id}Title" class="title">{name}</div>',
        '<div class="addIcon"></div>',
        // länkar
        '<tpl for="Links">',
            '<div class="link">',
            '<a href="{href}" target="{[(values.target==null||values.target=="")?parent.target:values.target]}">{name}</a>',
            '</div>',
        '</tpl>',
    '</tpl>'
);

// redigeringspanel för länkar
LUL.LinkEditor = Ext.extend(LUL.EditorPanel, {

    initComponent: function() {
        LUL.LinkEditor.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.editLink(record);
            } else {
                if (!this.removedRecords) this.removedRecords = new Array();
                record.data.removed = true;
                this.removedRecords.push(record);
                this.grid.getStore().remove(record);
            }
        }, this);

        this.grid = new Ext.grid.GridPanel({
            hideHeaders: true,
            store: new Ext.data.JsonStore({
                root: 'Links',
                data: this.data.PanelData,
                fields: ['id', 'name', 'href', 'target']
            }),
            //autoExpandColumn: 'name',
            viewConfig: {
                forceFit: true
            },
            columns: [
                { id: 'name', header: 'Titel', dataIndex: 'name' },
                action
            ],
            plugins: [
                action
            ],
            tbar: [
                { text: 'Lägg till', iconCls: 'icon-plus', handler: function() { this.addLink(this.grid.getStore()); }, scope: this }
            ]
        });
        this.grid.on('rowdblclick', function(grid, row) {
            this.editLink(grid.getStore().getAt(row));
        }, this);

        this.add(this.grid);

        this.setTitle(this.data.PanelData.name);

        if (document.selection && document.selection.createRange().htmlText == '') document.selection.clear();

        // hoppa direkt till "lägg till länk"?
        if (this.extra == 'add') this.addLink(this.grid.getStore());
    },

    showLinkWindow: function(title, init, ok) {
        var url = new Ext.form.TextField({ fieldLabel: 'Url', name: 'href', width: 250 });
        var form = new Ext.form.FormPanel({
            labelAlign: 'top',
            items: [
                new Ext.form.TextField({ fieldLabel: 'Titel', name: 'name', width: 250 }),
                url,
                new Ext.form.TextField({ fieldLabel: 'Mål', name: 'target', width: 250 })
            ]
        });
        var win = new Ext.Window({
            title: title,
            width: 290,
            height: 250,
            layout: 'fit',
            hideBorders: true,
            bodyStyle: 'padding: 10px; background: white',
            modal: true,
            items: [
                form
            ],
            buttons: [
                { text: 'OK', handler: function() { ok.call(this, form.form); win.close(); } },
                { text: 'Avbryt', handler: function() { win.close(); } }
            ],
            tbar: [
                { text: 'Testa länk', iconCls: 'icon-folder-link', qtip: 'Öppnar angiven länk i nytt fönster', handler: function() { window.open(url.getValue()) } }
            ]

        });
        win.show();

        if (init) init.call(this, form.form);
    },

    addLink: function(store) {
        this.showLinkWindow(
            'Lägg till länk',
        // init
            function(form) {
                form.setValues({ href: 'http://' });
            },
        // ok
            function(form) {
                var LinkRecord = Ext.data.Record.create(store.fields.items);
                var link = new LinkRecord({ id: 0, name: '', href: '', target: '' });
                form.updateRecord(link);
                store.add(link);
            }
        );
    },

    editLink: function(record) {
        this.showLinkWindow(
            'Redigera länk', 
        // init
            function(form) {
                form.loadRecord(record);
            },
        // ok
            function(form) {
                form.updateRecord(record);
            }
        );
    },

    /*onMaximize: function() {
    this.setWidth(400, true);
    },*/

    onSave: function() {
        var allData = [];
        var modified = [];
        this.grid.getStore().each(function(r) {
            if (r.dirty) modified.push(r);
            allData.push(r.data);
        });
        if (this.removedRecords) modified = modified.concat(this.removedRecords);

        var modifiedData = [];
        for (var i = 0; i < modified.length; i++) {
            modifiedData.push(modified[i].data);
        }

        var p = this;

        function success(response) {
            var res = Ext.util.JSON.decode(response.responseText);
            if (res.success) {
                p.getEl().unmask();
                LUL.LinkEditor.superclass.onSave.call(p);

                // fixa id för nya
                for (var i = 0; i < modified.length; i++) {
                    if (modified[i].data.id == 0) {
                        var index = p.grid.store.indexOf(modified[i]);
                        var id = res.ids[index].id;
                        allData[index].id = id;
                    }
                }

                // uppdatera data
                p.data.PanelData.Links = allData;
                p.removedRecords = null;

                linkPanelTPL.overwrite(p.editElement, p.data);
                linkPanelHandler.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.editLinksURL,
            success: success,
            failure: failure,
            params: { id: this.data.PanelData.id, modified: mod }
        });
    },

    onClose: function() {
        LUL.LinkEditor.superclass.onClose.call(this);
        Ext.get('linkPanel' + this.data.id + 'Title').dom.innerHTML = this.data.PanelData.name;
        linkPanelHandler.initPanel(this.editElement);
    },

    onPanelSettings: function() {
        var me = this;
        var fieldNames = [
            ['Namn', 'PanelData.name', false, 'Panelens namn & titel'],
            ['Mål', 'PanelData.target', false, 'Länkmål ("blank" för nytt fönster)'],
            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.linkPanelEditSettingsURL);
    }
});

// hantera dubbelklick på sidan
LUL.LinkEditor.onDblClick = function(e) {
    LUL.EditorPanel.onDblClick(e, 'div.linkPanel');
}

// skapar ny textpanel och öppnar editorn för den
LUL.LinkEditor.createNew = function(marker, insertBefore) {
    function success(res, id) {
        Ext.get('linkPanelX').set({
            id: 'linkPanel' + id,
            cls: 'linkPanel'
        });
        Ext.DomHelper.append('linkPanel' + id, {
            tag: 'div',
            id: 'linkPanel' + id + 'Title',
            cls: 'linkPanelTitle',
            html: 'Ny länkpanel'
        });
        Ext.get('linkPanel' + id).on('dblclick', LUL.LinkEditor.onDblClick);
    }

    LUL.EditorPanel.createNew(
        marker,
        insertBefore,
        { tag: 'div', id: 'linkPanelX' },
        dataManager.createLinkPanelURL,
        'linkPanel',
        success
    );
}

// laddar en dold panel...
LUL.LinkEditor.loadHiddenPanel = function(marker, insertBefore, dragData) {
    function success(response, id) {
        Ext.DomHelper.insertAfter(marker, {
            tag: 'div',
            id: 'linkPanel' + id,
            cls: 'linkPanel',
            html: linkPanelTPL.apply({ PanelData: dragData.panelData })
        });

        Ext.get('linkPanel' + id).on('dblclick', LUL.LinkEditor.onDblClick);
    }

    LUL.EditorPanel.loadHidden(
        marker,
        insertBefore,
        dragData,
        success
    );
}

// skapar en ny kopia av en panel
LUL.LinkEditor.loadExistingPanel = function(marker, insertBefore, dragData) {
    function success(response, id) {
        var html = linkPanelTPL.apply({ id: id, PanelData: dragData.panelData });

        Ext.DomHelper.insertBefore(insertBefore, {
            tag: 'div',
            id: 'linkPanel' + id,
            cls: 'linkPanel',
            html: html
        });

        Ext.get('linkPanel' + id).on('dblclick', LUL.LinkEditor.onDblClick);
    }

    LUL.EditorPanel.loadExisting(
        marker,
        insertBefore,
        dragData,
        success
    );
}
