/*
 * Ext JS Library 2.1
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

FeedViewer = {};
var feedOpenAll = false;
var feedFirst = true;
Ext.onReady(function(){
    Ext.QuickTips.init();

    //Ext.state.Manager.setProvider(new Ext.state.SessionProvider({state: Ext.appState}));

    var tpl = Ext.Template.from('preview-tpl', {
        compiled:true,
        getBody : function(v, all){
            return Ext.util.Format.stripScripts(v || all.description);
        }
    });
    FeedViewer.getTemplate = function(){
        return tpl;
    }
});

// This is a custom event handler passed to preview panels so link open in a new window
FeedViewer.LinkInterceptor = {
    render: function(p){
        p.body.on({
            'mousedown': function(e, t){ // try to intercept the easy way
                t.target = '_blank';
                soundManager.play('default');
            },
            'click': function(e, t){ // if they tab + enter a link, need to do it old fashioned way
                if(String(t.target).toLowerCase() != '_blank'){
                    e.stopEvent();
                    window.open(t.href);
                }
                soundManager.play('default');
            },
            delegate:'a'
        });
    }
};

//FeedGrid
FeedGrid = function(viewer, config) {
    feedFirst = true;
    this.viewer = viewer;
    Ext.apply(this, config);

    this.store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'FeedProxy.ashx'
        }),

        reader: new Ext.data.XmlReader(
            { record: 'item' },
            ['title', 'author', { name: 'pubDate', type: 'date' }, 'link', 'description', 'content']
        )
    });
    this.store.setDefaultSort('pubDate', "DESC");

    this.columns = [{
        id: 'title',
        header: resTitleHeader,
        dataIndex: 'title',
        sortable: true,
        width: 420,
        renderer: this.formatTitle
    }, {
        header: resAuthor,
        dataIndex: 'author',
        width: 100,
        hidden: true,
        sortable: true
    }, {
        id: 'last',
        header: resDate,
        dataIndex: 'pubDate',
        width: 150,
        renderer: this.formatDate,
        sortable: true
}];

        FeedGrid.superclass.constructor.call(this, {
            region: 'center',
            id: 'topic-grid',
            loadMask: { msg: resLoadingFeed },

            sm: new Ext.grid.RowSelectionModel({
                singleSelect: true
            }),

            viewConfig: {
                forceFit: true,
                enableRowBody: true,
                showPreview: true,
                getRowClass: this.applyRowClass
            }
        });

        this.on('rowcontextmenu', this.onContextClick, this);
    };

Ext.extend(FeedGrid, Ext.grid.GridPanel, {

    onContextClick : function(grid, index, e){
        if(!this.menu){ // create context menu on first right click
            this.menu = new Ext.menu.Menu({
                id:'grid-ctx',
                items: [{
                    text: resViewInNewTab,
                    iconCls: 'new-tab',
                    scope:this,
                    handler: function() {
                        this.viewer.openTab(this.ctxRecord);
                    }
                },{
                    iconCls: 'new-win',
                    text: resGoToPost,
                    scope:this,
                    handler: function() {
                        soundManager.play('newwindow');
                        window.open(this.ctxRecord.data.link);
                    }
                },'-',{
                    iconCls: 'refresh-icon',
                    text: resRefresh,
                    scope:this,
                    handler: function() {
                        soundManager.play('default');
                        this.ctxRow = null;
                        this.store.reload();
                    }
                }]
            });
            this.menu.on('hide', this.onContextHide, this);
        }
        e.stopEvent();
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
        this.ctxRow = this.view.getRow(index);
        this.ctxRecord = this.store.getAt(index);
        Ext.fly(this.ctxRow).addClass('x-node-ctx');
        this.menu.showAt(e.getXY());
    },

    onContextHide : function(){
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
    },

    loadFeed : function(url) {
        this.store.baseParams = {
            feed: url
        };
        this.store.load();
    },

    togglePreview: function(show) {
        this.view.showPreview = show;
        this.view.refresh();
    },

    // within this function "this" is actually the GridView
    applyRowClass: function(record, rowIndex, p, ds) {
        if (this.showPreview) {
            var xf = Ext.util.Format;
            p.body = '<p>' + xf.ellipsis(xf.stripTags(record.data.description), 200) + '</p>';
            return 'x-grid3-row-expanded';
        }
        return 'x-grid3-row-collapsed';
    },

    formatDate : function(date) {
        if (!date) {
            return '';
        }
        var now = new Date();
        var d = now.clearTime(true);
        var notime = date.clearTime(true).getTime();
        if (notime == d.getTime()) {
            return resToday + ' ' + date.dateFormat('g:i a');
        }
        d = d.add('d', -6);
        if (d.getTime() <= notime) {
            return date.dateFormat('D g:i a');
        }
        return date.dateFormat('n/j g:i a');
    },

    formatTitle: function(value, p, record) {
        return String.format(
                '<div class="topic"><b>{0}</b><span class="author">{1}</span></div>',
                value, record.data.author, record.id, record.data.forumid
                );
    }
});

//Panel
MainPanel = function() {
    this.preview = new Ext.Panel({
        id: 'preview',
        region: 'south',
        cls: 'preview',
        autoScroll: true,
        listeners: FeedViewer.LinkInterceptor,

        tbar: [{
            id: 'tab',
            text: resViewInNewTab,
            iconCls: 'new-tab',
            disabled: true,
            handler: this.openTab,
            scope: this
        },
        '-',
        {
            id: 'win',
            text: resGoToPost,
            iconCls: 'new-win',
            disabled: true,
            scope: this,
            handler: function() {
                soundManager.play('newwindow');
                window.open(this.gsm.getSelected().data.link);
            }
}],

            clear: function() {
                this.body.update('');
                var items = this.topToolbar.items;
                items.get('tab').disable();
                items.get('win').disable();
            }
        });

        this.grid = new FeedGrid(this, {
            tbar: [{
                text: resOpenAll,
                tooltip: { title: resOpenAll, text: resOpenAllInTabs },
                iconCls: 'tabs',
                handler: this.openAll,
                scope: this
            },
        '-',
        {
            split: true,
            text: resReadingPane,
            tooltip: { title: resReadingPane, text: resShowMoveHidePane },
            iconCls: 'preview-bottom',
            handler: this.movePreview.createDelegate(this, []),
            menu: {
                id: 'reading-menu',
                cls: 'reading-menu',
                width: 100,
                items: [{
                    text: resBottom,
                    checked: true,
                    group: 'rp-group',
                    checkHandler: this.movePreview,
                    scope: this,
                    iconCls: 'preview-bottom'
                }, {
                    text: resRight,
                    checked: false,
                    group: 'rp-group',
                    checkHandler: this.movePreview,
                    scope: this,
                    iconCls: 'preview-right'
                }, {
                    text: resHide,
                    checked: false,
                    group: 'rp-group',
                    checkHandler: this.movePreview,
                    scope: this,
                    iconCls: 'preview-hide'
}]
                }
            },
        '-',
        {
            pressed: true,
            enableToggle: true,
            text: resSummary,
            tooltip: { title: resPostSummary, text: resViewShortSummary },
            iconCls: 'summary',
            scope: this,
            toggleHandler: function(btn, pressed) {
                this.grid.togglePreview(pressed);
            }
}]
        });

        MainPanel.superclass.constructor.call(this, {
            id: 'main-tabs',
            activeTab: 0,
            region: 'center',
            margins: '0 5 5 0',
            resizeTabs: true,
            tabWidth: 150,
            minTabWidth: 120,
            enableTabScroll: true,
            plugins: new Ext.ux.TabCloseMenu(),
            items: {
                id: 'main-view',
                layout: 'border',
                title: resLoading,
                hideMode: 'offsets',
                items: [
                this.grid, {
                    id: 'bottom-preview',
                    layout: 'fit',
                    items: this.preview,
                    height: 250,
                    split: true,
                    border: false,
                    region: 'south'
                }, {
                    id: 'right-preview',
                    layout: 'fit',
                    border: false,
                    region: 'east',
                    width: 350,
                    split: true,
                    hidden: true
}]
                }
            });

            this.gsm = this.grid.getSelectionModel();

            this.gsm.on('rowselect', function(sm, index, record) {
                if (feedFirst)
                    feedFirst = false;
                else
                    soundManager.play('default');
                FeedViewer.getTemplate().overwrite(this.preview.body, record.data);
                var items = this.preview.topToolbar.items;
                items.get('tab').enable();
                items.get('win').enable();
            }, this, { buffer: 250 });

            this.grid.store.on('beforeload', this.preview.clear, this.preview);
            this.grid.store.on('load', this.gsm.selectFirstRow, this.gsm);

            this.grid.on('rowdblclick', this.openTab, this);
        };

Ext.extend(MainPanel, Ext.TabPanel, {

    loadFeed: function(feed) {
        this.grid.loadFeed(feed.url);
        Ext.getCmp('main-view').setTitle(feed.text);
    },

    movePreview: function(m, pressed) {
        if (!m) { // cycle if not a menu item click
            var readMenu = Ext.menu.MenuMgr.get('reading-menu');
            readMenu.render();
            var items = readMenu.items.items;
            var b = items[0], r = items[1], h = items[2];
            if (b.checked) {
                r.setChecked(true);
            } else if (r.checked) {
                h.setChecked(true);
            } else if (h.checked) {
                b.setChecked(true);
            }
            return;
        }
        if (pressed) {
            soundManager.play('default');
            var preview = this.preview;
            var right = Ext.getCmp('right-preview');
            var bot = Ext.getCmp('bottom-preview');
            var btn = this.grid.getTopToolbar().items.get(2);
            switch (m.text) {
                case resBottom:
                    right.hide();
                    bot.add(preview);
                    bot.show();
                    bot.ownerCt.doLayout();
                    btn.setIconClass('preview-bottom');
                    break;
                case resRight:
                    bot.hide();
                    right.add(preview);
                    right.show();
                    right.ownerCt.doLayout();
                    btn.setIconClass('preview-right');
                    break;
                case resHide:
                    preview.ownerCt.hide();
                    preview.ownerCt.ownerCt.doLayout();
                    btn.setIconClass('preview-hide');
                    break;
            }
        }
    },

    openTab: function(record) {
        if (!feedOpenAll) soundManager.play('default');
        record = (record && record.data) ? record : this.gsm.getSelected();
        var d = record.data;
        var id = !d.link ? Ext.id() : d.link.replace(/[^A-Z0-9-_]/gi, '');
        var tab;
        if (!(tab = this.getItem(id))) {
            tab = new Ext.Panel({
                id: id,
                cls: 'preview single-preview',
                title: d.title,
                tabTip: d.title,
                html: FeedViewer.getTemplate().apply(d),
                closable: true,
                listeners: FeedViewer.LinkInterceptor,
                autoScroll: true,
                border: true,

                tbar: [{
                    text: resGoToPost,
                    iconCls: 'new-win',
                    handler: function() {
                        window.open(d.link);
                    }
}]
                });
                this.add(tab);
            }
            this.setActiveTab(tab);
        },

        openAll: function() {
            soundManager.play('default');
            feedOpenAll = true;
            this.beginUpdate();
            this.grid.store.data.each(this.openTab, this);
            this.endUpdate();
            feedOpenAll = false;
        }
    });

Ext.ux.TabCloseMenu = function() {
    var tabs, menu, ctxItem;
    this.init = function(tp){
        tabs = tp;
        tabs.on('contextmenu', onContextMenu);
    }

    function onContextMenu(ts, item, e){
        if(!menu){ // create context menu on first right click
            menu = new Ext.menu.Menu([{
                id: tabs.id + '-close',
                text: resCloseTab,
                handler: function() {
                    soundManager.play('default');
                    tabs.remove(ctxItem);
                }
            },{
                id: tabs.id + '-close-others',
                text: resCloseOtherTabs,
                handler: function() {
                    soundManager.play('default');
                    tabs.items.each(function(item){
                        if(item.closable && item != ctxItem){
                            tabs.remove(item);
                        }
                    });
                }
            }]);
        }
        ctxItem = item;
        var items = menu.items;
        items.get(tabs.id + '-close').setDisabled(!item.closable);
        var disableOthers = true;
        tabs.items.each(function(){
            if(this != item && this.closable){
                disableOthers = false;
                return false;
            }
        });
        items.get(tabs.id + '-close-others').setDisabled(disableOthers);
        menu.showAt(e.getPoint());
    }
};