/**
 * friendfeed/lifestream.js
 *
 * Copyright (c) 2009 Kyo Nagashima <kyo@hail2u.net>
 * This library licensed under MIT license:
 * http://opensource.org/licenses/mit-license.php
 */
var show_friendfeed = function(ls, options) {
   // var ls = $('#lifestream');
   if (!ls) {
     ls = $('#lifestream');
   } else {
     ls = $(ls);
   }
   if (!options) options = {};
   var title = options.title;
   var entry_num  = options.entry_num || 20;
   ls.empty()
     .append($("<p/>")
       .append($("<em/>")
         .append($('<a/>')
           .attr({
             href: 'http://friendfeed.com/yuanying'
           })
           .append("データを取得中…"))));

   var entries = [];
   var success = 0;
   var error = 0;

   $.getJSON("http://friendfeed.com/api/feed/user?callback=?", 
     {
       nickname: "yuanying",
       num:      entry_num
     }, function (data) {
       var urlRegexp = /https?(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/g;
       var replyRegexp = /@(\w+)/g;
       var twitPicRegexp = /http\:\/\/twitpic\.com\/([0-9a-zA-Z]+)/;
       ls.empty();
       if (title) ls.append($('<h2/>').append(title));
       $.each(data.entries, function(){
         this.date = new Date(parseW3CDTF(this.published));
         this.time = this.date.getTime();

         var div = $('<div/>');
         // Title
         var title = this.title;
         if (title.length > 140) {
           title = title.substr(0,140) + '...';
         }
         title = title.replace(urlRegexp, "<a class='tw_link' href='$&'>$&</a>");
         if (this.service.profileUrl.indexOf("http://twitter.com/yuanying") == 0 ) {
           title = title.replace(replyRegexp, "<a class='reply' href='http://twitter.com/$1'>@$1</a>");
         }
         div.append($('<p/>').append(title));
         // Media
         if (this.media.length > 0) {
           var p = null;
           for (var i=0; i<this.media.length; i++) {
             var media = this.media[i];
             if (media.title) {
               // TODO
             } else {
               media.title = '';
             }
             if (media.thumbnails != null && media.thumbnails.length > 0) {
               if (p == null) p = $('<p/>').appendTo(div);
               for (var j=0; j<media.thumbnails.length; j++) {
                 var tb = media.thumbnails[j];
                 addThumbnailsTo(p, {
                   link: media.link,
                   src: tb.url,
                   width: tb.width,
                   height: tb.height,
                   title: media.title
                 });
               }
             }
           }
         }
         // for TwitPic
         var m = twitPicRegexp.exec(title);
         if (m) {
           addThumbnailsTo($('<p/>').appendTo(div), {
             link: m[0],
             src: "http://twitpic.com/show/thumb/" + m[1],
             width: 75,
             height: 75,
             title: this.title
           });
         }
         // Service
         var ss = $('<p/>');
         ss.attr({
           'class': 'service'
         }).append($('<a/>')
           .attr({href: this.service.profileUrl})
           .append($('<img/>')
             .attr({ width: 16, height: 16, src: this.service.iconUrl, 'class': 'icon'})
           )
         ).append($('<a/>')
           .attr({href: this.link})
           .append(this.date.toString())
         );
         div.append(ss);

         div.appendTo(ls);
       });
       ls.append($('<p/>')
         .attr({
           'class': 'more'
         })
         .append($('<a/>')
           .attr({
             href: 'http://friendfeed.com/yuanying'
           })
           .append('More...')
         )
       );
     }
   );
 }

function addThumbnailsTo(p, options) {
  if (options == null) options = {};
  if (options['link']) {
    p = $('<a/>')
      .attr({
        href: options['link']
      }).appendTo(p);
  }
    
  p.append($('<img/>')
    .attr({
      src: options['src'],
      width: options['width'],
      height: options['height'],
      alt: options['title'],
      title: options['title'],
      'class': 'thumbnail'
    })
  );
}

function parseW3CDTF (datestring) {
  if (typeof datestring === "string") {
    var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})Z$/.exec(datestring);
    if (a) {
      return [a[1], "/", a[2], "/", a[3], " ", a[4], " UTC"].join("");
    }
  }

  return datestring;
}

function getServiceIcon (s) {
  var url;

  switch (s.profileUrl) {
    case "http://twitter.com/yuanying":
      url = "twitter.com/";
    break;
    case "http://b.hatena.ne.jp/yuanying/":
      url = "b.hatena.ne.jp/";
    break;
    case "http://github.com/":
      url = "github.com/";
    break;
    case "http://www.fraction.jp/":
      url = "www.fraction.jp/";
    break;
    case "http://www.flickr.com/photos/29683030%40N07/":
    case "http://www.flickr.com/photos/yuanying/":
      url = "www.flickr.com/";
    break;
    // case "http://subtech.g.hatena.ne.jp/h2u/":
    //   url = "g.hatena.ne.jp/";
    // break;
    default:
      url = "friendfeed.com/";
    break;
  }

  return "http://www.faviconiac.com/favicon/" + url;
}
