Ext.namespace('dynamitec');

dynamitec.App = function(){
    var Singleton = Ext.extend(Object, {
        _pages: {},
        _currentPage: '',
        
        init: function(pages, page){
            if (window.location.pathname != '/') {
                window.location.href = window.location.protocol + '//' + window.location.hostname + '/#' + window.location.pathname.substr(1);
                return;
            }
            if (window.location.hash != '') {
                for (var i = 0; i < pages.length; i++) {
                    if (pages[i].url == window.location.hash.substr(1)) {
                        page = window.location.hash.substr(1);
                    }
                }
            }
            
            Ext.get('page-content').setStyle('display', 'none');
            
            Ext.QuickTips.init();
            Ext.QuickTips.enable();
            
            Ext.History.init();
            
            Ext.History.addListener('change', function(token){
                var tabPanel = Ext.getCmp('pageTabs');
                
                if (token) {
                    token = 'page-' + token;
                }
                else {
                    token = 'page-index';
                }
                tabPanel.setActiveTab(token);
            });
            
            new Ext.Viewport({
                layout: 'ux.center',
                border: false,
                items: {
                    layout: 'fit',
                    //bodyStyle: 'padding:20px 0;',
                    width: 780,
                    border: false,
                    items: {
                        layout: 'border',
                        border: false,
                        items: [{
                            region: 'north',
                            border: false,
                            height: 110,
                            html: '<img src="/client/images/titelleiste.jpg" />'
                        }, {
                            region: 'center',
                            layout: 'fit',
                            border: false,
                            items: this._initPages(pages, page)
                        }]
                    }
                }
            });
        },
        
        _initPages: function(pages, page){
            var activeItem = 0;
            var items = [];
            for (var i = 0; i < pages.length; i++) {
                if (pages[i].url == page) {
                    activeItem = i;
                }
                
                this._pages[pages[i].url] = {
                    actions: {
                        firstPage: new Ext.Action({
                            text: 'Erste Seite',
                            iconCls: 'icon-control-first',
                            disabled: true,
                            handler: function(){
                                var pageObject = this._pages[this._currentPage];
                                pageObject.getParams.start = 0;
                                this._loadContent(this._currentPage);
                            },
                            scope: this
                        }),
                        previousPage: new Ext.Action({
                            text: 'Vorherige Seite',
                            iconCls: 'icon-control-previous',
                            disabled: true,
                            handler: function(){
                                var pageObject = this._pages[this._currentPage];
                                pageObject.getParams.start -= pageObject.getParams.limit;
                                this._loadContent(this._currentPage);
                            },
                            scope: this
                        }),
                        nextPage: new Ext.Action({
                            text: 'Nächste Seite',
                            iconCls: 'icon-control-next',
                            disabled: true,
                            handler: function(){
                                var pageObject = this._pages[this._currentPage];
                                pageObject.getParams.start += pageObject.getParams.limit;
                                this._loadContent(this._currentPage);
                            },
                            scope: this
                        }),
                        lastPage: new Ext.Action({
                            text: 'Letzte Seite',
                            iconCls: 'icon-control-last',
                            disabled: true,
                            handler: function(){
                                var pageObject = this._pages[this._currentPage];
                                var pageCount = Math.ceil(pageObject.total / pageObject.getParams.limit);
                                pageObject.getParams.start = (pageCount - 1) * pageObject.getParams.limit;
                                this._loadContent(this._currentPage);
                            },
                            scope: this
                        })
                    },
                    getParams: {
                        start: 0,
                        limit: 15
                    },
                    type: pages[i].type
                }
                var pageObject = this._pages[pages[i].url];
                
                items.push({
                    id: 'page-' + pages[i].url,
                    layout: 'fit',
                    title: pages[i].title,
                    bodyStyle: 'text-align:left;',
                    autoScroll: true,
                    tbar: new Ext.Panel({
                        bodyStyle: 'text-align:left;',
                        border: false,
                        items: new Ext.Toolbar({
                            items: [pageObject.actions.firstPage, '-', pageObject.actions.previousPage, '-', pageObject.actions.nextPage, '-', pageObject.actions.lastPage]
                        })
                    }),
                    bbar: new Ext.Panel({
                        bodyStyle: 'text-align:left;',
                        border: false,
                        items: new Ext.Toolbar({
                            items: [pageObject.actions.firstPage, '-', pageObject.actions.previousPage, '-', pageObject.actions.nextPage, '-', pageObject.actions.lastPage]
                        })
                    })
                });
            }
            
            return new Ext.TabPanel({
                id: 'pageTabs',
                border: false,
                activeTab: activeItem,
                items: items,
                listeners: {
                    tabchange: function(tabPanel, tab){
                        this._currentPage = tab.id.substr(5);
                        
                        if (!this._pages[this._currentPage].tab) {
                            this._pages[this._currentPage].tab = tab;
                            
                            this._loadContent(this._currentPage);
                        }
                        
                        Ext.History.add(this._currentPage);
                    },
                    scope: this
                }
            
            });
        },
        
        _loadContent: function(page){
            var pageObject = this._pages[page];
            
            Ext.MessageBox.wait('Bitte warten...');
            Ext.Ajax.request({
                url: '/api/page',
                success: this._loadContentSuccess,
                scope: this,
                params: {
                    json: Ext.util.JSON.encode({
                        page: page,
                        start: pageObject.getParams.start,
                        limit: pageObject.getParams.limit
                    })
                },
                disableCaching: true
            });
        },
        
        _loadContentSuccess: function(response, options){
            var responseDecoded = Ext.util.JSON.decode(response.responseText);
            
            var pageObject = this._pages[responseDecoded.page];
            pageObject.total = responseDecoded.total;
            pageObject.getParams.start = responseDecoded.start;
            pageObject.getParams.limit = responseDecoded.limit;
            pageObject.mainData = responseDecoded.mainData;
            if (responseDecoded.sidebarData) {
                pageObject.sidebarData = responseDecoded.sidebarData;
            }
            if (responseDecoded.galleryData) {
                pageObject.galleryData = responseDecoded.galleryData;
            }
            
            pageObject.actions.firstPage.disable();
            pageObject.actions.previousPage.disable();
            pageObject.actions.nextPage.disable();
            pageObject.actions.lastPage.disable();
            if (pageObject.getParams.start > 0) {
                pageObject.actions.firstPage.enable();
                pageObject.actions.previousPage.enable();
            }
            if (pageObject.total > pageObject.getParams.start + pageObject.getParams.limit) {
                pageObject.actions.nextPage.enable();
                pageObject.actions.lastPage.enable();
            }
            
            Ext.MessageBox.hide();
            this._showContent(responseDecoded.page);
        },
        
        _loadContentFailure: function(response, options){
            Ext.MessageBox.hide();
        },
        
        _showContent: function(page){
            var pageObject = this._pages[page];
            
            if (!pageObject.mainDataStore) {
                pageObject.mainDataRecord = Ext.data.Record.create([{
                    name: 'id'
                }, {
                    name: 'title'
                }, {
                    name: 'content'
                }]);
                
                pageObject.mainDataReader = new Ext.data.ArrayReader({
                    id: 0
                }, pageObject.mainDataRecord);
                
                pageObject.mainDataStore = new Ext.data.GroupingStore({
                    reader: pageObject.mainDataReader,
                    data: [],
                    groupField: 'title',
                    remoteGroup: true,
                    sortInfo: {
                        field: 'id',
                        direction: 'ASC'
                    }
                });
                
                var trackMouseOver = false;
                if (pageObject.type == 'gallery') {
                    trackMouseOver = true;
                }
                pageObject.mainDataGrid = new Ext.grid.GridPanel({
                    bodyStyle: 'text-align: left;',
                    border: false,
                    disableSelection: true,
                    trackMouseOver: trackMouseOver,
                    hideHeaders: true,
                    store: pageObject.mainDataStore,
                    colModel: new Ext.grid.ColumnModel([{
                        header: 'title',
                        dataIndex: 'title',
                        renderer: function(value, metadata, record, rowIndex, colIndex, store){
                            return '<span style="display:none;">' + rowIndex + ': </span>' + value;
                        }
                    }, {
                        header: 'content',
                        dataIndex: 'content',
                        renderer: function(value){
                            return '<div style="padding-right:3px;padding-bottom:3px;">' + value + '</div>';
                        }
                    }]),
                    view: new Ext.grid.GroupingView({
                        autoFill: true,
                        forceFit: true,
                        hideGroupedColumn: true,
                        showGroupName: false,
                        scrollOffset: 30
                    }),
                    listeners: {
                        rowclick: function(grid, rowIndex, e){
                            var pageObject = this._pages[this._currentPage];
                            if (pageObject.type == 'gallery') {
                                var maxRatio = 0;
                                for (var i = 0; i < pageObject.galleryData[rowIndex].length; i++) {
                                    var imageWidth = pageObject.galleryData[rowIndex][i].width;
                                    var imageHeight = pageObject.galleryData[rowIndex][i].height;
                                    var ratio = imageWidth / imageHeight;
                                    if (ratio > maxRatio) {
                                        maxRatio = ratio;
                                    }
                                }
                                var thumbnailWidth = Math.ceil(maxRatio * 66);
                                
                                var galleryTemplate = new Ext.XTemplate('<tpl for=".">', '<div class="thumb-wrap">', '<div class="thumb loading-indicator" style="width:' + thumbnailWidth + 'px"><img src="/api/gallerythumbnail/?id={id}"></div>', '</div>', '</tpl>', '<div class="x-clear"></div>');
                                var galleryWindow = new Ext.Window({
                                    title: '<div style="text-align:left">' + pageObject.mainData[rowIndex].title + '</div>',
                                    bodyStyle: 'text-align: left;',
                                    width: 700,
                                    height: 480,
                                    layout: 'fit',
                                    modal: true,
                                    items: new Ext.Panel({
                                        id: 'images-view',
                                        autoScroll: true,
                                        bodyStyle: 'text-align: left;',
                                        layout: 'fit',
                                        items: new Ext.DataView({
                                            autoWidth: true,
                                            store: pageObject.galleryDataStore[rowIndex],
                                            tpl: galleryTemplate,
                                            overClass: 'x-view-over',
                                            itemSelector: 'div.thumb-wrap',
                                            emptyText: 'Es existieren keine Bilder in diesem Album',
                                            listeners: {
                                                click: function(dataView, index, node, e){
                                                    var actionPreviousImage = new Ext.Action({
                                                        text: 'Vorheriges Bild',
                                                        handler: function(){
                                                            index--;
                                                            actionShowImage.execute();
                                                        },
                                                        disabled: true,
                                                        scope: this
                                                    });
                                                    
                                                    var actionNextImage = new Ext.Action({
                                                        text: 'Nächstes Bild',
                                                        handler: function(){
                                                            index++;
                                                            actionShowImage.execute();
                                                        },
                                                        disabled: true,
                                                        scope: this
                                                    });
                                                    
                                                    var actionShowImage = new Ext.Action({
                                                        handler: function(firstDisplay, fxAnchors){
                                                            actionPreviousImage.disable();
                                                            actionNextImage.disable();
                                                            
                                                            var imageWidth = pageObject.galleryData[rowIndex][index].width;
                                                            var imageHeight = pageObject.galleryData[rowIndex][index].height;
                                                            if (imageWidth > imageWindow.getInnerWidth()) {
                                                                imageHeight = imageHeight / (imageWidth / imageWindow.getInnerWidth());
                                                                imageWidth = imageWindow.getInnerWidth();
                                                            }
                                                            if (imageHeight > imageWindow.getInnerHeight()) {
                                                                imageWidth = imageWidth / (imageHeight / imageWindow.getInnerHeight());
                                                                imageHeight = imageWindow.getInnerHeight();
                                                            }
                                                            Ext.get('images-view-fullsize').update('<img src="/api/galleryimage/?id=' + pageObject.galleryData[rowIndex][index].id + '" id="image-view-fullsize-' + index + '" width="' + imageWidth + '" height="' + imageHeight + '">', false, function(e){
                                                                var fullsizeImage = Ext.get('images-view-fullsize');
                                                                fullsizeImage.setY(imageWindow.body.getY() + (imageWindow.getInnerHeight() - imageHeight) / 2);
                                                                fullsizeImage.setX(imageWindow.body.getX() + (imageWindow.getInnerWidth() - imageWidth) / 2);
                                                                fullsizeImage.fadeIn({
                                                                    concurrent: false,
                                                                    duration: 0.7,
                                                                    callback: function(){
                                                                        imageWindow.setTitle('<div style="text-align:left">Bild ' + (index + 1) + ' von ' + pageObject.galleryData[rowIndex].length + '</div>');
                                                                        
                                                                        if (index > 0) {
                                                                            actionPreviousImage.enable();
                                                                        }
                                                                        if (index < pageObject.galleryData[rowIndex].length - 1) {
                                                                            actionNextImage.enable();
                                                                        }
                                                                    },
                                                                    scope: this
                                                                });
                                                            });
                                                        },
                                                        scope: this
                                                    });
                                                    
                                                    var imageWindow = new Ext.Window({
                                                        modal: true,
                                                        width: '766px',
                                                        height: '0px',
                                                        layout: 'fit',
                                                        items: new Ext.Panel({
                                                            html: '<div id="images-view-fullsize" style="text-align:left;"></div>'
                                                        }),
                                                        bbar: new Ext.Panel({
                                                            bodyStyle: 'text-align: left;',
                                                            border: false,
                                                            items: new Ext.Toolbar({
                                                                items: [actionPreviousImage, actionNextImage]
                                                            })
                                                        }),
                                                        listeners: {
                                                            show: function(window){
                                                                (function(){
                                                                    actionShowImage.execute();
                                                                }).defer(this, 1000);
                                                            },
                                                            scope: this
                                                        }
                                                    });
                                                    imageWindow.show();
                                                    imageWindow.setHeight(Ext.getBody().getHeight() - 100);
                                                    imageWindow.setPosition((Ext.getBody().getWidth() - 766) / 2, 50);
                                                },
                                                scope: this
                                            }
                                        })
                                    
                                    })
                                });
                                galleryWindow.show();
                            }
                        },
                        scope: this
                    }
                });
                
                if (pageObject.galleryData) {
                    pageObject.galleryDataStore = [];
                    for (var i = 0; i < pageObject.galleryData.length; i++) {
                        pageObject.galleryDataStore[i] = new Ext.data.Store({
                            reader: new Ext.data.ArrayReader({
                                id: 0
                            }, Ext.data.Record.create([{
                                name: 'id'
                            }, {
                                name: 'views'
                            }])),
                            data: []
                        });
                    }
                }
                
                if (pageObject.sidebarData && pageObject.sidebarData.length > 0) {
                    pageObject.sidebarDataRecord = Ext.data.Record.create([{
                        name: 'id'
                    }, {
                        name: 'title'
                    }, {
                        name: 'content'
                    }]);
                    
                    pageObject.sidebarDataReader = new Ext.data.ArrayReader({
                        id: 0
                    }, pageObject.sidebarDataRecord);
                    
                    pageObject.sidebarDataStore = new Ext.data.GroupingStore({
                        reader: pageObject.sidebarDataReader,
                        data: [],
                        groupField: 'title',
                        remoteGroup: true,
                        sortInfo: {
                            field: 'id',
                            direction: 'ASC'
                        }
                    });
                    
                    pageObject.sidebarDataGrid = new Ext.grid.GridPanel({
                        bodyStyle: 'text-align: left;',
                        border: false,
                        disableSelection: true,
                        trackMouseOver: false,
                        hideHeaders: true,
                        store: pageObject.sidebarDataStore,
                        colModel: new Ext.grid.ColumnModel([{
                            header: 'title',
                            dataIndex: 'title',
                            renderer: function(value, metadata, record, rowIndex, colIndex, store){
                                return '<span style="display:none;">' + rowIndex + ': </span>' + value;
                            }
                        }, {
                            header: 'content',
                            dataIndex: 'content',
                            renderer: function(value){
                                return '<div style="padding-right:3px;padding-bottom:3px;">' + value + '</div>';
                            }
                        }]),
                        view: new Ext.grid.GroupingView({
                            autoFill: true,
                            forceFit: true,
                            hideGroupedColumn: true,
                            showGroupName: false,
                            scrollOffset: 30
                        })
                    });
                    
                    pageObject.tab.add({
                        layout: 'border',
                        border: false,
                        items: [{
                            region: 'center',
                            layout: 'fit',
                            border: false,
                            items: pageObject.mainDataGrid
                        }, {
                            region: 'east',
                            layout: 'fit',
                            border: false,
                            width: 220,
                            minWidth: 220,
                            maxWidth: 220,
                            items: pageObject.sidebarDataGrid
                        }]
                    });
                    pageObject.tab.doLayout();
                    
                    var sidebarData = [];
                    for (var i = 0; i < pageObject.sidebarData.length; i++) {
                        var sidebarDataset = pageObject.sidebarData[i];
                        sidebarData.push([i + 1, sidebarDataset.title, sidebarDataset.content]);
                    }
                    pageObject.sidebarDataStore.loadData(sidebarData);
                }
                else {
                    pageObject.tab.add(pageObject.mainDataGrid);
                    pageObject.tab.doLayout();
                }
            }
            
            var mainData = [];
            for (var i = 0; i < pageObject.mainData.length; i++) {
                var mainDataset = pageObject.mainData[i];
                mainData.push([i + 1, mainDataset.title, mainDataset.content]);
            }
            pageObject.mainDataStore.loadData(mainData);
            
            if (pageObject.galleryData) {
                var galleryData = [];
                for (var i = 0; i < pageObject.galleryData.length; i++) {
                    galleryData[i] = [];
                    for (var j = 0; j < pageObject.galleryData[i].length; j++) {
                        var galleryDataset = pageObject.galleryData[i][j];
                        galleryData[i].push([galleryDataset.id, galleryDataset.view_count]);
                    }
                    pageObject.galleryDataStore[i].loadData(galleryData[i]);
                }
            }
        }
    });
    
    return new Singleton();
}();
