YUI().use("widget", "io-base", function(Y) {

    var Lang = Y.Lang,
        Widget = Y.Widget,
        Node = Y.Node;

    /* FeedViewer constructor */
    if (typeof KSU == "undefined" || !KSU) {
       KSU = {};
    }
    if (!KSU.widget) {
       KSU.widget = {};
    }

    KSU.widget.FeedViewer = function(config) {
        KSU.widget.FeedViewer.superclass.constructor.apply(this, arguments);
    };

    // Copy the constructor function into a local variable just for convenience.
    var FeedViewer = KSU.widget.FeedViewer;

    /*
     * Required NAME static field, to identify the Widget class and
     * used as an event prefix, to generate class names etc. (set to the
     * class name in camel case).
     */
    FeedViewer.NAME = "feedviewer";

    /*
     * The attribute configuration for the Spinner widget. Attributes can be
     * defined with default values, get/set functions and validator functions
     * as with any other class extending Base.
     */
    FeedViewer.ATTRS = {
        // The URL of the feed.
        urlFeed: {
            value: ""
        },

        subscribeLink: {
            value: ""
        },

        // The URL of a human-readable page with the feed's content.
        urlPage: {
            value: ""
        },

        // The title of the feed source.
        title: {
            value: ""
        },

        maxItems: {
            value: 999,
            validator: function(val) {
                return this._validateMaxItems(val);
            }
        },

        urlIcon: {
            value: "../images/icons/rss.jpg"
        }

    };


    /*
     * The HTML_PARSER static constant is used by the Widget base class to populate
     * the configuration for the spinner instance from markup already on the page.
     */
    FeedViewer.HTML_PARSER = {
       title: function(contentBox) {
          return contentBox.one("h5").get("innerHTML");
       }
    };

var getValue = function(el, tagname) {

   var result = "";

   try {
      result = el.getElementsByTagName(tagname)[0].firstChild.nodeValue;
   } catch (e) {
      /* nothing */
   }

   return result;
};


/**
 * Display retrieved RSS data.
 */
var displayFeed = function(transactionID, response) {
   var i;
   var item;
   var items;
   var title, link, html, displaycount, contentbox, insertbox;

   items = response.responseXML.getElementsByTagName('item');
   html = "";
   displaycount = this.get('maxItems');
   if (displaycount > items.length) {
      displaycount = items.length;
   }
   for (i = 0; i < displaycount; i++) {
      item = items[i];
      title = getValue(item, 'title');
      if (title) {
         link = getValue(item, 'link');
         if (link) {
            title = "<a href=\"" + link + "\">" + title + "</a>";
         }
         html += "<li>" + title + "</li>";
     }
   }

   contentbox = this.get('contentBox');
   insertbox = contentbox.one(".yui-feedviewer-insert");
   if (!insertbox) {
      insertbox = Node.create("<div class='yui-feedviewer-insert'>");
      contentbox.appendChild(insertbox);
   }
   insertbox.setContent("<ul>" + html + "</ul>\n");
};

var failure = function(response, ctx) {
   //alert("Failure");
   // At the moment, nothing -- let empty content shine through
};

/* FeedViewer extends the base Widget class */
    Y.extend(FeedViewer, Widget, {

        addIcon: function() {

           var title, icon, urlicon, urlfeed, a;

           /*
            * Don't bother of there is no URL to an icon.
            */
           urlicon = this.get('urlIcon');
           if (!urlicon) {
              return;
           }
           title = this.get('boundingBox').one('h5');
           icon = Node.create("<img>");
           icon.set('src', urlicon);
           icon.set('alt', "subscribe");
           urlfeed = this.get('subscribeLink') || this.get('urlFeed');
           if (urlfeed) {
              // Wrap the icon with a link to the feed
              a = Node.create("<a>").set('href', urlfeed);
              a.appendChild(icon);
              icon = a;
           }
           title.appendChild(icon);

        },

        /*
         * renderUI is part of the lifecycle introduced by the
         * Widget class. Widget's renderer method invokes:
         *
         *     renderUI()
         *     bindUI()
         *     syncUI()
         *
         * renderUI is intended to be used by the Widget subclass
         * to create or insert new elements into the DOM.
         *
         */
        renderUI : function() {
            Y.io(this.get('urlFeed'),
               {on: {success: displayFeed, failure: failure},
                context: this
               }
            );

            this.addIcon();
        },

        /*
         * value attribute default validator. Verifies that
         * the value being set is a valid number and not negative.
         */
        _validateMaxItems: function(val) {
            return (Lang.isNumber(val) && val > 0);
        }
    });

});

