var FeedWindow;
var rssItemsCount;
var rssItemsURL;
var rssItemsName;

function PopulateConfigWindow() {
    FeedWindow.CreateWindow();
}

function RSSItem () {
    /* rss List */
    this.rssList  = [];
    this.rssCount = 0;
    this.rssTpl   = new Ext.Template(
            '<p><strong>{pubDate} - <a href="{link}" target="_blank">{title}</a></strong><br />',
            '{description}',
            '</p>'
    );
    this.headerTpl = new Ext.Template(
        '<p><strong>{pubDate} - <a href="{link}" target="_blank">{title}</a></strong><br />',
            '{description}',
        '</p>'
    );
}

 function PluginRSSFeed(url,count){
     rssItemsURL = url;
     rssstore.setBaseParam('feed',url);
     rssItemsCount = count;
     rssstore.load();
 }

function cleanDate(str){
    var mill = Date.parse(str);
    var date = new Date(mill);
    return date.format("m/d/Y");
}

RSSItem.prototype.process = function(e) {
    this.rssCount = e.items.length;

    var maxcount = (e.items.length > rssItemsCount) ? rssItemsCount : e.items.length;

    for(var x=0;x<maxcount;x++){
        e.items[x].data.pubDate = cleanDate(e.items[x].data.pubDate);
        this.rssTpl.append("rssfeed", e.items[x].data);
    }
}

Ext.onReady(function(){

/***/
    //../plugins/dashboard/rssreader/feed-proxy.php
    rssstore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'index.php?fuse=home&action=DoDashboardPluginAction&plugin=rssreader&pluginAction=feedproxy'
        }),
        reader: new Ext.data.XmlReader(
            {record: 'item'},
            ['title', 'author', {name:'pubDate', type:'date'}, 'link', 'description', 'content']
        )
    });
    rssstore.setDefaultSort('pubDate', "DESC");
    rssstore.on('load', function(sm, index, record){
        rssItem = undefined;
	rssItem = new RSSItem();
        rssItem.process(sm.data);

        if(rssItemsName!=undefined){
            $('rssfeedlink').innerHTML = "<a href='"+rssItemsURL+"'>"+rssItemsName+"</a>";
            $('rssfeedlinkimage').innerHTML = "<a href='"+rssItemsURL+"' target='_blank'><img alt='"+rssItemsName+"' src='../images/rss.gif' width='16' height='11' border='0' /></a>";
        }
    }, this, {buffer:250});


    var feedstore = new Ext.data.JsonStore({
            id: "feedstore",
            root: 'items',
            totalProperty: 'totalcount',
            idProperty: 'url',
            remoteSort: true,
            baseParams: {
            filter: "",
            customerid: "0"
        },
        fields: [
                'url','text'
        ],
        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
                url: 'index.php?fuse=home&action=DoDashboardPluginAction&plugin=rssreader&pluginAction=getFeeds'
        })
    });
    var feedUrl = new Ext.form.ComboBox({
        id: 'feed-url',
        fieldLabel: 'Enter the URL of the feed to show',
        emptyText: 'http://example.com/blog/feed',
        width: 400,
        validationEvent: false,
        validateOnBlur: false,
        msgTarget: 'under',
        triggerAction: 'all',
        displayField: 'url',
        mode: 'local',
        tpl: new Ext.XTemplate(
                '<tpl for="."><div class="x-combo-list-item" qtip="{url}">',
                '<strong>{text}</strong>',
                '<div class="x-clear"></div>',
                '</div></tpl>'),
        store: feedstore
    });
    feedstore.load();

    var pluginconfigwindow = new Ext.FormPanel({
        labelAlign:'top',
        border: false,
        height: 90,
        items:[
                {
                    border: false,
                    layout:'column',
                    style:'padding-top:10px;',
                    items:[
                        {
                            border: false,
                            columnWidth:.90,
                            layout: 'form',
                            items: [feedUrl]
                        },
                        {
                            border: false,
                            columnWidth:.10,
                            layout: 'form',
                            items: [{
                                style:'padding-left:6px;',
                                border: false,
                                xtype:'numberfield',
                                hideLabel : false,
                                fieldLabel: lang('Items'),
                                name: 'rssitems',
                                value: '2',
                                emptyText: '2',
                                maxLength: 1,
                                id:'rssitems',
                                width:25
                            }]
                        }
                    ]
                }
        ],
        bodyStyle:'background:transparent;padding-top:10px;padding-left:10px;'
    });

    function FeedWindowConfig(update){
        if(this instanceof FeedWindowConfig){
            this.update = update;
            this.CreateWindow = createWindow;
            this.LoadFields = loadFields;
        }else{
            return new FeedWindowConfig();
        }
    }
    FeedWindow = new FeedWindowConfig();

    function loadFields(){

    }

    function createWindow(){

        win = new Ext.Window({
            title:"RSS Viewer",
            width:480,
            shadow:false,
            autoHeight:true,
            modal:true,
            closeAction:'hide',
            plain: true,
            items: [pluginconfigwindow],
            buttons: [
                {
                    text: 'Update',
                    handler: function(){
                        additionalPostBody = "";
                        if(feedUrl.selectedIndex==-1){
                            additionalPostBody = "&newfeed=1";
                            rssItemsURL = feedUrl.getValue();
                            rssItemsName = "Rss Feed";
                        }else{
                            rssItemsURL = feedUrl.getStore().data.items[feedUrl.selectedIndex].data.url;
                            rssItemsName = feedUrl.getStore().data.items[feedUrl.selectedIndex].data.text;
                        }
                        rssItemsCount = Ext.get('rssitems').getValue();
                        new Ajax.Request('index.php?fuse=home&action=DoDashboardPluginAction&plugin=rssreader&pluginAction=editRssURL',
                            {
                                postBody    : 'count='+rssItemsCount+'&url='+encodeURIComponent(rssItemsURL)+'&name='+rssItemsName+additionalPostBody,
                                onComplete  : RSSUpdated
                            }
                        );
                        win.hide();
                    }
                },
                    {
                    text: 'Close',
                    handler: function(){
                        win.hide();
                    }
                }]
        });
        pluginconfigwindow.getForm().reset();
        win.show(this);
    }

    function RSSUpdated(t){
         $('rssfeed').innerHTML = "";
         rssstore.setBaseParam('feed',rssItemsURL);
         rssstore.load();
    }



});
