﻿///<reference path="Extjs_Intellisense.js" />

Ext.namespace('LUL');
       
var filePanelTPL = new Ext.XTemplate(
    '<tpl for="PanelData">',
        // titel
        '<div id="filePanel{parent.id}Title" class="title">{name}</div>',
        // länkar
        '<tpl for="Files">',
            '<div class="file">',
                '<div class="fileIcon">',
                '<a href="{path}" target="blank">',
                '<img src="{IconUrl}" />',
                '</a>',
                '</div>',
                '<div class="fileTitle">{title}</div>',
                '<div class="fileDesc">{description}</div>',
                '<div class="fileClear"></div>',
            '</div>',
        '</tpl>',
        '<div class="x-clear"></div>',
    '</tpl>'
);

var fileTPL = new Ext.XTemplate(
    '<tpl for=".">',
        '<div class="file">',
            '<div class="fileIcon">',
            '<img src="{IconUrl}" />',
            '</div>',
            '<div class="fileText">',
            '<div class="fileTitle">{title}</div>',
            '<div class="fileDesc">{description}</div>',
            '</div>',
            '<div class="fileClear"></div>',
        '</div>',
    '</tpl>'
);

// redigeringspanel för miniatyrer
LUL.FileEditor = Ext.extend(LUL.EditorPanel, {

    bodyStyle: 'padding: 10px; overflow-y: auto',

    constructor: function(c) {
        var ee = Ext.get(c.editId);
        c.height = ee.getHeight() + 52;
        if (c.height < 200) c.height = 200;

        LUL.FileEditor.superclass.constructor.call(this, Ext.apply(c, {
            tbar: [
                    { id: c.editId + 'Upload', text: 'Ladda upp', iconCls: 'icon-plus', tooltip: 'Lägger till en fil från din dator' },
                    { text: 'Bläddra', iconCls: 'icon-folder', handler: this.browseFile, scope: this, tooltip: 'Välj bland filer som finns i systemet, går även att ladda upp flera filer på en gång' },
                    { xtype: 'tbseparator' },
                    { text: 'Ta bort', iconCls: 'icon-minus', handler: this.removeFile, scope: this, tooltip: 'Ta bort markerad fil' }
                ]
        }));
    },

    initComponent: function() {
        LUL.FileEditor.superclass.initComponent.call(this);

        this.root = this.data.PanelData;

        // koppla swfupload till uppladdningsknappen
        this.on('render', function() {
            this.folderPath = 'Files/Files/FilePanel' + this.root.id;
            LUL.initDirectUpload(this.editId, this.folderPath, 'Alla filer', '*.*', this.uploadComplete, this);
        }, this);

        // lägg in paneldatat i store
        this.store = new Ext.data.JsonStore({
            root: 'Files',
            data: this.root,
            fields: ['id', 'title', 'path', 'IconUrl', 'description']
        });

        // överför viss data från panelen till varje thumbnail
        /*this.store.each(function(r) {
        r.data.size = this.root.size;
        r.data.target = this.root.target;
        }, this);*/

        this.view = new Ext.DataView({
            singleSelect: true,
            store: this.store,
            overClass: 'x-over',
            selectedClass: 'x-selected',
            itemSelector: 'div.file',
            tpl: fileTPL,
            emptyText: 'Inga filer tillagda',
            plugins: [
                new Ext.DataView.LabelEditor({ labelSelector: 'div.fileTitle', dataIndex: 'title' }),
                new Ext.DataView.LabelEditor({
                    labelSelector: 'div.fileDesc',
                    dataIndex: 'description',
                    autoSize: true,
                    cls: ''
                },
                    new Ext.form.TextArea({
                        allowBlank: true,
                        growMin: 90,
                        growMax: 240,
                        grow: true,
                        selectOnFocus: false
                    })
               )
            ]
        });

        this.view.on('dblclick', this.openFile, this);
        this.add(this.view);

        this.setTitle(this.root.name);

        if (document.selection && document.selection.createRange().htmlText == '') document.selection.clear();
    },

    // öppna bild vid dubbelklick
    openFile: function(view, index, node, e) {
        window.open(this.store.getAt(index).data.path);
    },

    // uppladdning klar, lägg till fil   
    uploadComplete: function(file) {
        var path = this.folderPath + '/' + file.name;
        var FileRecord = Ext.data.Record.create(this.store.fields.items);

        // välj rätt ikon
        var iconExtensions = ['bmp', 'doc', 'docx', 'gif', 'jpeg', 'jpg', 'pdf', 'swf', 'tif', 'tiff', 'txt', 'xls', 'xlsx'];
        var extension = path.substring(path.lastIndexOf('.') + 1);
        var iconUrl = 'Panels/FilePanel/Icons/other.gif';
        if (iconExtensions.indexOf(extension) > -1) iconUrl = 'Panels/FilePanel/Icons/' + extension + '.gif';

        var title = file.name.substring(0, file.name.lastIndexOf('.'));
        var file = new FileRecord({ id: 0, title: title, description: 'Ingen beskrivning', path: path, IconUrl: iconUrl });
        file.dirty = true;
        file.added = true;
        this.store.add(file);
    },

    // fil vald vid bläddring, lägg till
    browseFile: function() {
        this.browser = new LUL.FileBrowser({
            type: 'file',
            panelPath: 'Files/Files/FilePanel' + this.root.id,
            callback: function(path) {
                var FileRecord = Ext.data.Record.create(this.store.fields.items);

                var title = path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
                // välj rätt ikon
                var iconExtensions = ['bmp', 'doc', 'docx', 'gif', 'jpeg', 'jpg', 'pdf', 'swf', 'tif', 'tiff', 'txt', 'xls', 'xlsx'];
                var extension = path.substring(path.lastIndexOf('.') + 1);
                var iconUrl = 'Panels/FilePanel/Icons/other.gif';
                if (iconExtensions.indexOf(extension) > -1) iconUrl = 'Panels/FilePanel/Icons/' + extension + '.gif';

                //this.folderPath + '/_thumbnail_' + this.root.size + '_' + file.name + '.jpg';

                var file = new FileRecord({ id: 0, title: title, description: 'Ingen beskrivning', path: path, IconUrl: iconUrl });
                file.dirty = true;
                file.added = true;
                this.store.add(file);
            }
        }, this);
    },

    // ta bort fil
    removeFile: function() {
        if (this.view.getSelectionCount() > 0) {
            var r = this.view.getSelectedRecords()[0];
            // markera som borttagen bara om den inte nyss lagts till...
            if (!r.added) {
                if (!this.removedRecords) this.removedRecords = new Array();
                this.removedRecords.push(r);
                r.data.removed = true;
            }
            this.store.remove(r);
        }
    },

    // spara ändringar
    onSave: function() {
        // fyll på listor med modifierade och borttagna filer
        var allData = [];
        var modified = [];
        this.store.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.FileEditor.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.store.indexOf(modified[i]);
                        var id = res.ids[index].id;
                        allData[index].id = id;
                    }
                }

                // uppdatera data
                p.root.Files = allData;
                p.removedRecords = null;

                filePanelTPL.overwrite(p.editElement, p.data);
            }
        }

        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.editFilesURL,
            success: success,
            failure: failure,
            params: { id: this.root.id, modified: mod }
        });
    },

    onClose: function() {
        LUL.FileEditor.superclass.onClose.call(this);
        Ext.get('filePanel' + this.data.id + 'Title').dom.innerHTML = this.root.name;
    },

    onPanelSettings: function() {
        var me = this;
        var fieldNames = [
            ['Namn', 'PanelData.name', false, 'Panelens namn & titel'],
            ['CSS stilmall', 'PanelData.style', true],
            ['CSS klass', 'PanelData.cls', true]
        ];
        this.showPanelSettings(fieldNames, dataManager.filePanelEditSettingsURL);
    }
});

// hantera dubbelklick på sidan
LUL.FileEditor.onDblClick = function(e) {
    LUL.EditorPanel.onDblClick(e, 'div.filePanel');
}

// skapar ny textpanel och öppnar editorn för den
LUL.FileEditor.createNew = function(marker, insertBefore) {
    function success(res, id) {
        Ext.get('filePanelX').set({
            id: 'filePanel' + id,
            cls: 'filePanel'
        });
        Ext.DomHelper.append('filePanel' + id, {
            tag: 'div',
            id: 'filePanel' + id + 'Title',
            cls: 'title',
            html: 'Ny miniatyrpanel'
        });
        Ext.get('filePanel' + id).on('dblclick', LUL.FileEditor.onDblClick);
//        newsPanelHandler.initPanel(Ext.get('filePanel' + id));
    }

    LUL.EditorPanel.createNew(
        marker,
        insertBefore,
        { tag: 'div', id: 'filePanelX' },
        dataManager.createFilePanelURL,
        'filePanel',
        success
    );
}

// laddar en dold panel...
LUL.FileEditor.loadHiddenPanel = function(marker, insertBefore, dragData) {
    function success(response, id) {
        Ext.DomHelper.insertAfter(marker, {
            tag: 'div',
            id: 'filePanel' + id,
            cls: 'filePanel',
            html: filePanelTPL.apply({ id: id, PanelData: dragData.panelData })
        });

        Ext.get('filePanel' + id).on('dblclick', LUL.FileEditor.onDblClick);
//        newsPanelHandler.initPanel(Ext.get('newsPanel' + id));
    }

    LUL.EditorPanel.loadHidden(
        marker,
        insertBefore,
        dragData,
        success
    );
}
