/**
 * Twit
 *  jQuery Plugin to Display Twitter Tweets on a Blog.
 *  http://code.google.com/p/jquery-twit/
 *
 * Copyright (c) 2010 Yusuke Horie
 *
 * Released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Since  : 0.1.0 - 08/26/2009
 * Version: 0.2.0 - 02/17/2010
 */
(function(jQuery){

  var _i = 0;

  /** public methods **/

  jQuery.fn.twit = function (user, options) {
    if (typeof user != 'string') return this;

    var
      opts = jQuery.extend({}, jQuery.fn.twit.defaults, options),
      c = jQuery.isFunction(opts.callback) ? opts.callback: _callback,
      url = 'http://twitter.com/statuses/user_timeline/' + user + '.json',
      params = {};

    opts.user = user;
    params.count = opts.count;

    return this.each(function(i, e) {
      var $e = $(e);
      if (!$e.hasClass('twit')) $e.addClass('twit');

      jQuery.ajax({
        url: url,
        data: params,
        dataType: 'jsonp',
        success: function (o) {
          c.apply(this, [(o.results) ? o.results: o, e, opts]);
        }
      });
    });
  };

  jQuery.fn.twit.defaults = {
    user: null,
    callback: null,
    icon: true,
    username: true,
    text: true,
    count: 200,
    limit: 7,
    label: '',
    title: ''
  };

  /** private method **/

  var _callback = function (o, e, opts) {
    var $this = $(e);
    if (!o || o.length == 0 || $this.length == 0) return false;
    $this.data('_inc', 1);
    _i++;

    var username = o[0].user.screen_name,
        icon = o[0].user.profile_image_url;

    var h = '';
      
    h += '<ul class="twitBody" id="twitList' + _i + '">' + _build(o, $this, opts) + '</ul>';

    $this.html(h);

    $('a.twitEntryShow', '#twitList' + _i).live('click', function (e) {
      e.preventDefault();
      var $t = $(this);

      $t.parent().fadeOut(400, function () {
        var i = $this.data('_inc');
        i++;
        $this.data('_inc', i);

        if ($t.hasClass('twitEntryAll')) {
          $t.die('click');
          var start = (i*opts.limit) - opts.limit;
          $(this).after(_build(o, $this, opts, start, o.length)).remove();
        } else {
          $(this).after(_build(o, $this, opts)).remove();
        }
      });
    });

  };

  var _build = function (o, $t, opts, s, e) {
    var
      h = '',
      inc = $t.data('_inc'),
      start = s || (inc*opts.limit) - opts.limit,
      end = e || ((o.length > start + opts.limit) ? start + opts.limit: o.length);

    for (var i=start; i<end; i++) {
      var
        t = o[i],
        username = t.user.screen_name,
        icon = t.user.profile_image_url;
      
      h += '<li class="twitEntry">';
      if (opts.text) {
    	  var created = t.created_at;
    	  var text = t.text
        
          .replace(/(https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/, function (u) {
            var shortUrl = (u.length > 30) ? u.substr(0, 30) + '...': u;
            return '<a href="' + u + '" target="_blank">' + shortUrl + '</a>';
          })
          .replace(/@([a-zA-Z0-9_]+)/g, '@<a href="http://twitter.com/$1">$1</a>')
          .replace(/(?:^|\s)#([^\s\.\+:!]+)/g, function (a, u) {
            return ' <a href="http://twitter.com/search?q=' + encodeURIComponent(u) + '" target="_blank">#' + u + '</a>';
          });
    	h += ' <div class="twit_content">'
    	h += ' <a class="tweet_avatar" href="http://twitter.com/'+t.user.screen_name+'"><img src="'+t.user.profile_image_url+'" height="30" width="30" alt="'+t.user.screen_name+'" title="'+t.user.screen_name+'" border="0"/></a>';
    	h += ' <p class="twit_screenname">' + t.user.screen_name + '</p>';
        h += ' <p class="twit_text">' + text + '</p>';
        h += ' <p class="twit_createdAt">' + _relative_time(created) + '</p>';
        
        h += ' </div>';

      }

      h += '</li>';
    }
    return h;
  };

  var _parse_date = function (date_str) {
	  // The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
	  // cannot handle in IE. We therefore perform the following transformation:
	  // "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
	  return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
  };
  
  var _relative_time = function (time_value) 
  {
	  	var parsed_date = _parse_date(time_value);
	  	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	  	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	  	var r = '';
	  	if (delta < 60) {
		r = 'vor ' + delta + ' Sekunde';
	  	} else if(delta < 120) {
		r = 'vor einer Minute';
	  	} else if(delta < (45*60)) {
		r = 'vor ' + (parseInt(delta / 60, 10)).toString() + ' Minuten';
	  	} else if(delta < (2*60*60)) {
		r = 'vor einer Stunde';
	  	} else if(delta < (24*60*60)) {
		r = 'vor ' + (parseInt(delta / 3600, 10)).toString() + ' Stunden';
	  	} else if(delta < (48*60*60)) {
		r = 'vor einem Tag';
	  	} else {
		r = 'vor '+(parseInt(delta / 86400, 10)).toString() + ' Tagen';
	  	}
	  	return r;
	}
  
})(jQuery);
