/**
 * Create a RSS feed.
 * 
 * The Widget inserts a RSS feed into the target element on which the widget is executed on.
 * 
 * ### Examples
 * The Widget is executed on a pageelement and is called with passing the chosen services. In this example an RSS feed from heise.de is implemented. 10 complete articles (including images, no snippets) are shown in standard layout.
 * 
 * JavaScript:
 * 
 *     
 *     jQuery.ready({
 *     		plugin: [ 'de_epages.externalcontent.ui.rss' ],
 *     		DOM:    true
 *     	}, function($){
 *     		var widget = de_epages('<div>').externalcontentUiRss({
 *     			url: "http://www.heise.de/newsticker/heise-atom.xml",
 *     			numberOfEntrie: 10,
 *     			onlyHeadlines: false,
 *     			onlySnippets: false,
 *     			removeImages: false,
 *     			layout: "standard"
 *     		});
 *     });
 * 
 * 
 * @class jQuery.ui.externalcontentUiRss
 * @extends jQuery.widget
 * 
 * @uses de_epages
 * @uses jQuery.ui.widget
 * @uses jQuery.tmpl
 * @since 6.15.0
 */

/**
 * @cfg {String} [url] A reference to the target page to receive the RSS feed.
 */

/**
 * @cfg {Integer} [numberOfEntrie] Defines the number of shown articles of the RSS feed.
 */

/**
 * @cfg {Boolean} [onlyHeadlines] Specifies whether to display only headlines/titles of entries.
 */

/**
 * @cfg {Boolean} [onlySnippets] Specifies whether to display only a snippet version (less than 120 characters) of an entry.
 */

/**
 * @cfg {Boolean} [removeImages] Specifies whether to remove *img* tags from entry's content.
 */

/**
 * @cfg {String} [layout] Defines how to display the total number of likes. Values: 'box', 'default'
 */

/**
 * See `jQuery.ui.externalcontentUiRss` for details.
 * 
 * @param {Object} [options] A map of additional options to pass to the method.
 * @param {String} [url] A reference to the target page to receive the RSS feed.
 * @param {Integer} [numberOfEntrie] Defines the number of shown articles of the RSS feed.
 * @param {Boolean} [onlyHeadlines] Specifies whether to display only headlines/titles of entries.
 * @param {Boolean} [onlySnippets] Specifies whether to display only a snippet version (less than 120 characters) of an entry.
 * @param {Boolean} [removeImages] Specifies whether to remove *img* tags from entry's content.
 * @param {String} [layout] Defines how to display the total number of likes. Values: 'box', 'default'
 * 
 * @method externalcontentUiRss
 * @member jQuery
 * 
 * @since 6.15.0
 */

/*
 * @copyright   © Copyright 2006-2012, epages GmbH, All Rights Reserved.
 *
 * @module      de_epages.externalcontent.ui.rss
 *
 * @revision    $Revision: 1.4 $
 */
/*jslint nomen: true*/
/*global define, window*/
define('de_epages/externalcontent/ui/rss', [
	'jquery/ui/widget',
	'ep',
	'de_epages',
	'$tmpl!./rss'
], function ($, ep, de_epages, template) {
	'use strict';
    // Constants.
    var gClassNames = 'ep-gadget-rss',

        // Class names for template layout
        layoutClassNames = {
            'box': 'box',
            'default': 'default'
        },

        // Icon path
        rssIcon = ep.config.storeRoot + '/SF/Gadgets/rss-icon.png',

        // Cache deferred object (AJAX)
        deferred;

    // The actual widget.
    $.widget('ui.externalcontentUiRss', {

        options: {
            url: '',
            // (Valid) url to (valid) rss feed.
            onlyHeadlines: false,
            // If true, display only headlines/titles of entries.
            onlySnippets: false,
            // If true, display only a snippet version (<120 characters) of an entry.
            showImages: true,
            // If false, remove *img* tags from entry's content.
            numberOfEntries: null,
            // Integer specifying the number of entries shown.
            // If null, all (<= 100) available entries will be shown.
            layout: 'default'
            // String specifying the layout template used to render the feed.
            // possible values are 'box' and 'default'.
        },

        _create: function () {
            var self = this,
                o = self.options;

            // Load Google Loader API.
            if (!deferred) {
                if (window.google && window.google.load) {
                    deferred = $.Deferred().resolve();
                } else {
                    deferred = $.ajax({
                        url: 'https://www.google.com/jsapi',
                        dataType: 'script',
                        cache: true // We would not want to load the same *script* twice.
                    });
                }
            }

            // Load Google Feed API.
            deferred.done(function () {
                window.google.load('feeds', '1', {
                    callback: $.proxy(self._createFeed, self)
                });
            });
        },

        _createFeed: function () {
            var o = this.options,
                // Create *feed* object with url *o.url*.
                feed = new window.google.feeds.Feed(o.url);

            // Return feed entries stored by Google that are no longer in the feed XML.
            feed.includeHistoricalEntries();
            // Set the number of feed entries loaded by this feed to *o.numberOfEntries*. -1 means that all (<= 100) available entries will be shown.
            feed.setNumEntries(o.numberOfEntries || -1);
            // Finally, load the entries.
            feed.load($.proxy(this._onFeedLoad, this));
        },

        _onFeedLoad: function (result) {
            var o = this.options,
                renderedTemplate;

            if (result.error) {
                this.destroy();
            } else {
                renderedTemplate = this.renderedTemplate = template(result.feed, {
                    rssIcon: rssIcon,
                    onlySnippets: o.onlySnippets,
                    onlyHeadlines: o.onlyHeadlines,
                    layout: layoutClassNames[o.layout],
                    gClassNames: gClassNames
                });
                if (!o.showImages) {
                    renderedTemplate.find('img').not('[src="' + rssIcon + '"]').remove();
                }

                renderedTemplate.appendTo(this.element);

                // Move css link tag to head
                renderedTemplate.tmplItem('elements').style.appendTo('head');
            }
        },

        /**
         * This method removes the container on which the RSS feed has been appended to.
         * 
         * @method destroy
         * @member jQuery.ui.externalcontentUiRss
         * 
         * @since 6.15.0
         */
        destroy: function () {
            // Remove all traces of the widget.
            if (this.renderedTemplate) {
                this.renderedTemplate.remove();
            }
            this._superApply(arguments);
        }

    });

	return de_epages;

});