﻿///<reference path="Extjs_Intellisense.js" />

Ext.namespace('LUL');
        
var thumbnailPanelTPL = new Ext.XTemplate(
    '<tpl for="PanelData">',
        // titel
        '<div id="thumbnailPanel{parent.id}Title" class="title">{name}</div>',
        // länkar
        '<tpl for="Thumbnails">',
            '<div class="thumbnail">',
                '<div class="thumbImage">',
                '<a href="{path}" target="parent.target">',
                '<img src="{ThumbUrl}" width="{parent.size}" height="{[Math.floor(parent.size * 3 / 4)]}" />',
                '</a>',
                '</div>',
                '<div class="thumbnailTitle">{title}</div>',
                '<div class="thumbnailDesc">{description}</div>',
                '<div class="thumbnailClear"></div>',
            '</div>',
        '</tpl>',
        '<div class="x-clear"></div>',
    '</tpl>'
);

var thumbnailTPL = new Ext.XTemplate(
    '<tpl for=".">',
        '<div class="thumbnail">',
        //'<div class="thumb-wrap">',
            //'<a href="path" target="target">',
            //'<div class="thumbnail"><img src="{ThumbUrl}" width="{size}" height="{size}" /></div>',
            '<div class="thumbImage">',
            '<img src="{ThumbUrl}" width="{size}" height="{[Math.floor(values.size * 3 / 4)]}" />',
            '</div>',
            //'</a>',
            '<div class="thumbText">',
            '<div class="thumbnailTitle">{title}</div>',
            '<div class="thumbnailDesc">{description}</div>',
            '</div>',
            '<div class="thumbnailClear"></div>',
        '</div>',
    '</tpl>'
);

// redigeringspanel för miniatyrer
LUL.ThumbnailEditor = 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.ThumbnailEditor.superclass.constructor.call(this, Ext.apply(c, {
            tbar: [
                    { id: c.editId + 'Upload', text: 'Ladda upp', iconCls: 'icon-plus', tooltip: 'Lägger till en minatyr från din dator' },
                    { text: 'Bläddra', iconCls: 'icon-folder', handler: this.changeImage, scope: this, tooltip: 'Välj bland bilder som finns i systemet, går även att ladda upp flera bilder på en gång' },
                    { xtype: 'tbseparator' },
                    { text: 'Ta bort', iconCls: 'icon-minus', handler: this.removeImage, scope: this, tooltip: 'Ta bort markerad miniatyr' }
                ]
        }));
    },

    initComponent: function() {
        LUL.ThumbnailEditor.superclass.initComponent.call(this);

        this.root = this.data.PanelData;

        // koppla swfupload till uppladdningsknappen
       // this.on('render', function() { this.setupSwfUpload(); }, this);

        this.on('render', function() {
            // koppla swfupload till uppladdningsknappen
            this.folderPath = 'Files/Images/ThumbnailPanel' + this.root.id;
            //this.folderPath = 'Files/Pages/' + adminManager.pageData.id;
            LUL.initDirectUpload(this.editId, this.folderPath, 'Bildfiler', '*.bmp;*.jpg;*.gif;*.png', this.uploadComplete, this, this.root.size);
        }, this);

        // lägg in paneldatat i store
        this.store = new Ext.data.JsonStore({
            root: 'Thumbnails',
            data: this.root,
            fields: ['id', 'title', 'path', 'ThumbUrl', '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-thumbnail-over',
            selectedClass: 'x-thumbnail-selected',
            itemSelector: 'div.thumbnail',
            tpl: thumbnailTPL,
            emptyText: 'Inga miniatyrer tillagda',
            plugins: [
                new Ext.DataView.LabelEditor({ labelSelector: 'div.thumbnailTitle', dataIndex: 'title' }),
                new Ext.DataView.LabelEditor({
                    labelSelector: 'div.thumbnailDesc',
                    dataIndex: 'description',
                    autoSize: true,
                    cls: ''
                },
                    new Ext.form.TextArea({
                        allowBlank: true,
                        growMin: 90,
                        growMax: 240,
                        grow: true,
                        selectOnFocus: false
                    })
               )
            ]
        });

        this.view.on('dblclick', this.openThumb, this);

        this.add(this.view);

        this.setTitle(this.root.name);

        if (document.selection && document.selection.createRange().htmlText == '') document.selection.clear();
    },

    // hosta igång flashuppladdningen
    /*setupSwfUpload: function() {
        this.folderPath = 'Files/Images/ThumbnailPanel' + this.root.id;
        var id = Ext.id();
        var em = Ext.get(this.editId + 'Upload').child('em');
        em.setStyle({
            position: 'relative',
            display: 'block'
        });
        em.createChild({
            tag: 'div',
            id: id
        });
        this.suo = new SWFUpload({
            button_placeholder_id: id,
            button_width: 70,
            button_height: 18,
            button_cursor: SWFUpload.CURSOR.HAND,
            button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,

            flash_url: '/Lib/SwfUpload/swfupload.swf',
            upload_url: dataManager.uploadFileURL,
            post_params: { 'path': this.folderPath, 'size': this.root.size },
            file_post_name: 'Filedata',
            file_size_limit: '1048576', //100MB
            file_queue_limit: '0',
            file_types: '*.*',
            file_types_description: 'Bildfiler',
            file_upload_limit: '0',

            file_dialog_complete_handler: this.startUpload.createDelegate(this),
            upload_complete_handler: this.uploadComplete.createDelegate(this)
        }, this);

        Ext.get(this.suo.movieName).setStyle({
            position: 'absolute',
            top: 0,
            left: 0
        });
    },

    // öppna bild vid dubbelklick
    openThumb: function(view, index, node, e) {
        window.open(this.store.getAt(index).data.path);
    },

    // börja uppladdning via flash
    startUpload: function() {
        this.suo.startUpload();
    },*/

    // uppladdning klar, lägg till miniatyr
    uploadComplete: function(file) {
        var path = this.folderPath + '/' + file.name;
        var ThumbnailRecord = Ext.data.Record.create(this.store.fields.items);
        var thumbUrl = this.folderPath + '/_thumbnail_' + this.root.size + '_' + file.name + '.jpg';
        var title = file.name.substring(0, file.name.lastIndexOf('.'));
        var thumbnail = new ThumbnailRecord({ id: 0, title: title, description: 'Ingen beskrivning', path: path, ThumbUrl: thumbUrl, size: this.root.size, target: this.root.target });
        thumbnail.dirty = true;
        this.store.add(thumbnail);
    },

    /*uploadComplete: function(file) {
        this.data.path = this.folderPath + '/' + file.name;
        var img = Ext.get(this.editId + 'Image');
        var p = this;
        img.dom.onload = function() {
            p.setHeight(img.getHeight() + 52);
        }
        img.dom.src = this.data.path;
    },*/

    // bild vald vid bläddring, lägg till miniatyr
    changeImage: function() {
        this.browser = new LUL.FileBrowser({
            type: 'image',
            panelPath: 'Files/Images/ThumbnailPanel' + this.root.id,
            callback: function(path) {
                var ThumbnailRecord = Ext.data.Record.create(this.store.fields.items);
                var thumbnail = new ThumbnailRecord({ id: 0, title: 'Ny miniatyr', description: 'Ingen beskrivning', path: path, ThumbUrl: path, size: this.root.size, target: this.root.target });
                thumbnail.dirty = true;
                this.store.add(thumbnail);
            }
        }, this);        
    },

    // ta bort miniatyr
    removeImage: function() {
        if (this.view.getSelectionCount() > 0) {
            var r = this.view.getSelectedRecords()[0];
            if (!this.removedRecords) this.removedRecords = new Array();
            this.removedRecords.push(r);
            r.data.removed = true;
            this.store.remove(r);
        }
    },

    // spara ändringar
    onSave: function() {
        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.ThumbnailEditor.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.Thumbnails = allData;
                p.removedRecords = null;

                thumbnailPanelTPL.overwrite(p.editElement, p.data);
                //                thumbnailPanelHandler.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.editThumbnailsURL,
            success: success,
            failure: failure,
            params: { id: this.root.id, modified: mod }
        });
    },

    onClose: function() {
        LUL.ThumbnailEditor.superclass.onClose.call(this);
        Ext.get('thumbnailPanel' + this.data.id + 'Title').dom.innerHTML = this.root.name;
        //        newsPanelHandler.initPanel(this.editElement);
    },

    onPanelSettings: function() {
        var me = this;
        var fieldNames = [
            ['Namn', 'PanelData.name', false, 'Panelens namn & titel'],
            ['Länk-mål', 'PanelData.target', true, 'Länkmål ("blank" för nytt fönster)'],
            ['Miniatyrstorlek', 'PanelData.size', false, 'Miniatyrernas bredd i pixlar'],
            ['CSS stilmall', 'PanelData.style', true],
            ['CSS klass', 'PanelData.cls', true]
        ];
        this.showPanelSettings(fieldNames, dataManager.thumbnailPanelEditSettingsURL);
    }
});

// hantera dubbelklick på sidan
LUL.ThumbnailEditor.onDblClick = function(e) {
    LUL.EditorPanel.onDblClick(e, 'div.thumbnailPanel');  
}

// skapar ny textpanel och öppnar editorn för den
LUL.ThumbnailEditor.createNew = function(marker, insertBefore) {
    function success(res, id) {
        Ext.get('thumbnailPanelX').set({
            id: 'thumbnailPanel' + id,
            cls: 'thumbnailPanel'
        });
        Ext.DomHelper.append('thumbnailPanel' + id, {
            tag: 'div',
            id: 'thumbnailPanel' + id + 'Title',
            cls: 'title',
            html: 'Ny miniatyrpanel'
        });
        Ext.get('thumbnailPanel' + id).on('dblclick', LUL.ThumbnailEditor.onDblClick);
//        newsPanelHandler.initPanel(Ext.get('thumbnailPanel' + id));
    }

    LUL.EditorPanel.createNew(
        marker,
        insertBefore,
        { tag: 'div', id: 'thumbnailPanelX' },
        dataManager.createThumbnailPanelURL,
        'thumbnailPanel',
        success
    );
}

// laddar en dold panel...
LUL.ThumbnailEditor.loadHiddenPanel = function(marker, insertBefore, dragData) {
    function success(response, id) {
        Ext.DomHelper.insertAfter(marker, {
            tag: 'div',
            id: 'thumbnailPanel' + id,
            cls: 'thumbnailPanel',
            html: thumbnailPanelTPL.apply({ id: id, PanelData: dragData.panelData })
        });

        Ext.get('thumbnailPanel' + id).on('dblclick', LUL.ThumbnailEditor.onDblClick);
//        newsPanelHandler.initPanel(Ext.get('newsPanel' + id));
    }

    LUL.EditorPanel.loadHidden(
        marker,
        insertBefore,
        dragData,
        success
    );
}
