Y(['connection', 'json', 'datasource'], function () {

  var gadget_social = {
    onshow: {},
    showrss: function (el, url) {
      //if (!Y.loaded['connection']) return;
      //if (!Y.loaded['json']) return;

      function rss_item_html (i, rootnode) {
        var link, title, stamp;
        try {
          title = document.createTextNode(
            i.getElementsByTagName('title')[0].firstChild.nodeValue
          );
        }
        catch (e) { return };

        link = document.createElement('a');
        try {
          if (rootnode == 'feed') { // atom
            link.href = i.getElementsByTagName('link')[0].getAttribute('href');
            stamp = i.getElementsByTagName('updated')[0].firstChild.nodeValue;
            // ISO 8601
            stamp = stamp.match(/(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)Z/);
            stamp.shift(); stamp[1]--; stamp = new Date(Date.UTC.apply({}, stamp));
          }
          else { // rss 2.0
            link.href = i.getElementsByTagName('link')[0].firstChild.nodeValue;
            stamp = new Date(i.getElementsByTagName('pubDate')[0].firstChild.nodeValue);
          }
          link.target = "_blank";
          stamp = '<br>'+YAHOO.util.Date.format(stamp, {format: "%a %b %d %Y %I:%M%p %Z"});
        }
        catch (e) { stamp = '' };

        var sp = document.createElement('span');
        sp.className = 'stamp';
        sp.innerHTML = stamp;

        link.appendChild(title);
        link.appendChild(sp);
        return link;
      }

      function xml_from_text (t) {
        if (window.DOMParser) {
          return (new DOMParser()).parseFromString(t, "text/xml");
        }
        else {
          var xml = new ActiveXObject("Microsoft.XMLDOM");
          xml.async = "false";
          xml.loadXML(t);
          return xml;
        } 
      };

      function rss_place_html (el, rss) {

        var item, items, i = 0,
            html = document.createElement('div'),
            item_html;

        if (rss.nodeName == 'feed') { // atom
            items = rss.getElementsByTagName('entry');
        }
        else { // assume RSS 2.0
            items = rss.getElementsByTagName('item');
        }

        while (item = items[i++]) {
          if (item_html = rss_item_html(item, rss.nodeName)) {
            html.appendChild(item_html);
            html.appendChild(document.createElement('br'));
            html.appendChild(document.createElement('br'));
          };
          if (9 < i) break;
        }
        el.innerHTML = html.innerHTML;
      }

      YAHOO.util.Connect.asyncRequest(
        'GET', url, {
          success: function (o) {
            try {
              rss_place_html(o.argument[0], xml_from_text(o.responseText).documentElement);
            } catch (e) {
              o.argument[0].innerHTML = "<a>No items in this feed at the moment.</a>";
            }
          },
          failure: function (o) {
            o.argument[0].innerHTML = "<a>This feed is down at the moment, sorry.</a>";
          },
          argument: [el]
        }
      );
    }
  };

  var container = D.get('gadget_social_container');
  YAHOO.util.Connect.asyncRequest(
    'GET', '/:gadgets:social', {
      success: function (o) {
        try {
          var social = YAHOO.lang.JSON.parse(o.responseText);
          social = social["Social"];
          var feed, i = 0;
          while (feed = social[i++]) {
            if (feed['user'] == '') break;
            var s = document.createElement('span');
            s.id = 'gadget_social_'+feed['id'];
            s.feedurl = feed['url'];
            D.addClass(s, feed['class']);
            D.setStyle(s, 'color', feed['color']);

            switch (feed['type']) {
              case 'feed':
                s.innerHTML = '<img src="'+feed['icon']+'" alt="" border="0"> '+feed['user'];
                if (feed['userid'].match(/\S/))
                  gadget_social.onshow[s.id] = gadget_social.showrss;
                else 
                  gadget_social.onshow[s.id] = function (el) { el.innerHTML = 'This feed is being retrieved. Please check back soon.' }
                break;
              case 'link':
                s.innerHTML = '<a class="gadget_social_headlink" target="_blank" href="'+feed['url']+'"><img src="'+feed['icon']+'" border="0"> '+feed['user']+' <img src="/lib/img/external_link.png"></a>'
                break;
              default:
                s.innerHTML = '<img src="'+feed['icon']+'" border="0"> User '+feed['userid'];
                break;
            }

            container.appendChild(s);
            container.appendChild(document.createElement('br'));
          }

          function present (el) {
            if (D.hasClass(el, 'gadget_social_n')) return;
            var im = el.getElementsByTagName('img')[0];
            if (el.is_open) {
              var div = document.createElement('div');
              div.id = el.id+'_display';
              div.innerHTML = '<img halign="center" src="/lib/img/loading_flower_15x15.gif">';
              div.style.padding = '8px';
              D.insertAfter(div,el);
              var onshow = gadget_social.onshow[el.id];
              if (onshow) onshow(div, el.feedurl);
            }
            else {
              var div = D.get(el.id+'_display');
              if (div) el.parentNode.removeChild(div);
            }
          }
          var soc_links = D.getElementsBy(
            function (el) { return el.id.match(/^gadget_social/) },
            'span', 'gadget_social',
            function (el) {
              el.is_open = D.hasClass(el, 'gadget_social_o'); present(el)
            }
          );
          E.on(soc_links, 'click', function () {
            this.is_open = !this.is_open; present(this)
          });

        } catch (e) {
          o.argument[0].innerHTML =  "Feeds are down at the moment, sorry.";
        }
      },
      failure: function (o) {
        o.argument[0].innerHTML =  "Feeds are down at the moment, sorry.";
      },
      argument: [container]
    }
  );
});

