﻿// visa "ny sida"-fönstret
Ext.override(LUL.Admin.Manager, {
    addPage: function() {
        if (loginManager.loggedIn) {
            this.reset = function() {
                this.nextButton.show();
                this.prevButton.hide();
                this.finishButton.hide();
                this.addPageWin.setTitle('Lägg till sida - Steg 1 av 2 - Välj sidmall');
                this.addPageWin.getLayout().setActiveItem(0);
            }

            this.next = function() {
                var view = this.selectTemplatePanel.view;
                if (view.getSelectionCount() == 1) {
                    this.pageSettingsPanel.template.setValue(view.getSelectedRecords()[0].data.id);
                    this.prevButton.show();
                    this.finishButton.show();
                    this.nextButton.hide();
                    this.addPageWin.setTitle('Lägg till sida - Steg 2 av 2 - Sidinställningar');
                    this.addPageWin.getLayout().setActiveItem(1);
                    this.pageSettingsPanel.nameField.focus();
                }
            }

            this.prev = function() {
                this.reset();
            }

            this.finish = function() {
                function success(form, action) {
                    if (action.result.success) {
                        this.addPageWin.hide();
                        // öppna sida efter skapande?
                        if (this.pageSettingsPanel.openAfter.getValue()) {
                            document.location = 'Default.aspx?page=' + action.result.path;
                        } else {
                            // annars lägger vi till länk
                            var link = '<div class="menuPanelLinkDiv">'
                            link += '<a href="Default.aspx?page=' + adminManager.pageData.path + this.pageSettingsPanel.nameField.getValue() + '" class="menuPanelLink">';
                            link += this.pageSettingsPanel.titleField.getValue() + '</a></div>';
                            Ext.DomHelper.append(Ext.get('menuPanel'), link);
                        }
                    } else {
                        alert('Sidan kunde inte läggas till');
                    }
                }

                this.pageSettingsPanel.formPanel.form.submit({ waitMsg: 'Sparar', success: success, scope: this });
            }

            function cancel() {
                this.addPageWin.hide();
            }

            if (!this.addPageWin) {
                this.cancelButton = new Ext.Toolbar.Button({ text: 'Avbryt', handler: cancel, scope: this, iconCls: 'icon-cancel' });
                this.prevButton = new Ext.Toolbar.Button({ text: 'Föregående', handler: this.prev, scope: this, iconCls: 'icon-prev' });
                this.nextButton = new Ext.Toolbar.Button({ text: 'Nästa', handler: this.next, scope: this, iconCls: 'icon-next' });
                this.finishButton = new Ext.Toolbar.Button({ text: 'Slutför', handler: this.finish, scope: this, iconCls: 'icon-ok' });

                this.statusBar = new Ext.StatusBar({
                    text: '',
                    items: [
                            this.cancelButton, this.prevButton, this.nextButton, this.finishButton
                        ]
                });

                this.selectTemplatePanel = new LUL.Admin.SelectTemplatePanel();
                this.pageSettingsPanel = new LUL.Admin.PageSettingsPanel({ url: dataManager.createPageURL, statusBar: this.statusBar });

                this.addPageWin = new Ext.Window({
                    title: '',
                    width: 450,
                    height: 380,
                    closeAction: 'hide',
                    layout: 'card',
                    activeItem: 0,
                    hideBorders: true,
                    modal: true,
                    bodyStyle: 'text-align: left',
                    items: [
                            this.selectTemplatePanel,
                            this.pageSettingsPanel
                        ],
                    bbar: this.statusBar/*,
                        buttons: [
                            this.cancelButton, this.prevButton, this.nextButton, this.finishButton
                        ]*/
                });

                this.selectTemplatePanel.pscope = this;
            } else {
                this.pageSettingsPanel.nameField.setValue('');
                this.pageSettingsPanel.titleField.setValue('');
            }
            this.addPageWin.show('adminAddPageLink');
            this.reset();
        }
    }
});

LUL.Admin.SelectTemplatePanel = Ext.extend(Ext.Panel, {
    id: 'newPagePanel',
    width: 'auto',
    height: 'auto',
    layout: 'fit',
    bodyStyle: 'padding: 10px; overflow-y: auto',

    initComponent: function() {
        LUL.Admin.SelectTemplatePanel.superclass.initComponent.call(this);

        var tpl = new Ext.XTemplate(
            '<tpl for=".">',
                '<div class="thumb-wrap" id="NewPage{id}">',
                '<div class="thumb"><img src="Templates/{id}.gif"/></div>',
                '<span>{description}</span>',
                '</div>',
            '</tpl>',
            '<div class="x-clear"></div>'
        );

        this.view = new Ext.DataView({
            store: dataManager.getFetchTemplateStore(),
            tpl: tpl,
            singleSelect: true,
            overClass: 'x-view-over',
            itemSelector: 'div.thumb-wrap',
            emptyText: 'Finns inga sidmallar i systemet'
        });

        this.view.on('dblclick', this.next, this);
        this.view.store.load();

        this.add(this.view);
    },

    next: function() {
        this.pscope.next.call(this.pscope);
    }
});

LUL.Admin.PageSettingsPanel = Ext.extend(Ext.Panel, {
    id: 'pageSettingsPanel',
    width: 'auto',
    height: 'auto',
    layout: 'fit',
    bodyStyle: 'padding: 10px',
    hideBorders: true,

    initComponent: function() {
        LUL.Admin.PageSettingsPanel.superclass.initComponent.call(this);

        if (!this.statusBar) this.statusBar = null;

        this.template = new Ext.form.Hidden({ name: 'template' });
        this.openAfter = new Ext.form.Checkbox({ fieldLabel: 'Öppna sidan', anchor: '100%', checked: true });
        this.nameField = new LUL.TextField({
            fieldLabel: 'Namn', name: 'name', anchor: '100%', allowBlank: false, statusBar: this.statusBar,
            tooltip: 'Namnet används som del i sökvägen till sidan'
        });
        this.titleField = new LUL.TextField({
            fieldLabel: 'Titel', name: 'title', anchor: '100%', allowBlank: false, statusBar: this.statusBar,
            tooltip: 'Sidans titel, visas även på länkar till sidan'
        });

        var comboStore = new Ext.data.JsonStore({
            url: dataManager.fetchHeadersURL,
            root: 'rows',
            fields: ['id', 'name']
        });

        var tryCount = 0;

        comboStore.on('load', function(store, records, options) {
            tryCount = 0;
            headerCombo.setValue(records[0].data.name);
            headerCombo.hiddenField.value = records[0].data.id;
        });

        comboStore.on('loadexception', function(e) {
            if (++tryCount < 20)
                this.load();
            else
                Ext.Msg.alert('Kommunikationsfel', 'Kunde inte ladda sidhuvuddata (20 försök misslyckades), stäng dialogrutan och försök igen');
        });

        headerCombo = new Ext.form.ComboBox({
            name: 'headerCombo',
            editable: false,
            hiddenName: 'header',
            width: 200,
            listWidth: 200,
            fieldLabel: 'Sidhuvud',
            valueField: 'id',
            displayField: 'name',
            //typeAhead: true,

            triggerAction: 'all',
            forceSelection: true,
            store: comboStore
        });

        headerCombo.on('render', function() {
            comboStore.load();
        });

        // alternativ som alltid är med
        var items = [
            this.nameField,
            this.titleField,
            headerCombo
        ];

        this.headerCombo = headerCombo;

        // bara med vid ny sida
        if (!this.edit) {
            items = items.concat([
                this.template,
            //                { html: 'Vilket sidhuvud som ska visas överst på sidan', border: false, style: 'margin-bottom: 5px; font-style: italic' },
                this.openAfter
            ]);
        }

        this.formPanel = new Ext.form.FormPanel({
            labelAlign: 'top',
            items: items,
            url: this.url
        });

        this.add(this.formPanel);
    }
});
