/*
 * Twitter Widget with multiple accounts.
 * @website http://ronakpatel.net
 * @author Ronak Patel
 * @email rspatel@gmail.com
 *
 * Feel free to modify or use this code
 * as you like. I just ask that you give
 * a link back to me at http://ronakpatel.net
 * Thanks!
 *
 * The regular expressions and getRelativeTime
 * function used below have been taken from 
 * Twitter's (twitter.com) javascript widget.
 *
 * Instructions for setting up the widget can be found at:
 * http://www.ronakpatel.net/2009/04/05/twitter-widget-that-streams-multiple-accounts/
 */

if (!rpnet) 
  var rpnet = {};
if (!rpnet.TwitterWidget)
  rpnet.TwitterWidget = {};
  
rpnet.TwitterWidget = {
  _usernames: '',
  _count: '',
  _tweets: [],
  _receivedCount: 0,

  init: function(usernames, count, title) {
    this._usernames = usernames.split(',');
    this._count = count;				
    var body = document.body;
    if (title == '')
      this.$('rpnet_twitterWidget').removeChild(this.$('rpnet_twTitle'));
    else 
      this.$('rpnet_twTitle').innerHTML = title;	
    
    for (var i = 0, n = this._usernames.length; i < n; i++) {
      var url = this.createJSONUrl(
      this._usernames[i], this._count, 'rpnet_tw.callback');
      var s = this.createScriptTag('tw'+i, url);	
      body.appendChild(s);
    }
  },

  $: function(id) {
    return document.getElementById(id);
  },

  addTweets: function(tweets) {		
    for (var i = 0, n = tweets.length; i < n; i++) 
      this._tweets.push(tweets[i]);
      
    this.incReceivedCount();
  },

  incReceivedCount: function() {
    this._receivedCount++;
    
    if (this._receivedCount == this._usernames.length)
      this.createList();				
  },

  createList: function() {
    var list = this.$('rpnet_twList');
    this._tweets.sort(this.sortTweetsByDate);
    this._tweets = this._tweets.slice(0, this._count+1);
    
    for (var i = 0, n = this._tweets.length; i < n; i++) {
      var text = this._tweets[i].text;
      text = text.replace(
        /((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g,
        function(s) { return '<a href="'+s+'">'+s+'</a>'; });
      text = text.replace(
        /\B@([_a-z0-9]+)/ig,
        function(s) {
          return s.charAt(0)
          +'<a href="http://www.twitter.com/'
          +s.substring(1)+'">'+s.substring(1)+'</a>';
        });
      var username = this._tweets[i].user.screen_name;
      var relTime = ' <span style="font-size:85%">(<a href="http://twitter.com/'
        + username + '/statuses/' + this._tweets[i].id + '">' 
        + this.getRelativeTime(this._tweets[i].created_at) + '</a>'
        + ' por @<a href="http://twitter.com/'
        + username + '">' + username + '</a>)</span>';
      list.appendChild(this.createListItem(text, relTime));
    }
  },

  sortTweetsByDate: function(a, b) {
    var a = a.created_at.split(' ');
    var b = b.created_at.split(' ');
    var x = Date.parse(a[1]+' '+a[2]+', '+a[5]+' '+a[3]);
    var y = Date.parse(b[1]+' '+b[2]+', '+b[5]+' '+b[3]);
    
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
  },

  getRelativeTime: function(createdAt) {
    var t = createdAt.split(' ');
    var createdAt = Date.parse(t[1]+' '+t[2]+', '+t[5]+' '+t[3]);		
    var current = new Date();
    var delta = parseInt((current.getTime() - createdAt)/1000);		
    delta = delta + (current.getTimezoneOffset() * 60);

    if (delta < 60) 
      return 'hace menos de un minuto';
    else if (delta < 120) 
      return 'hace un minuto';
    else if (delta < 3600)
      return 'hace '+(parseInt(delta/60)).toString()+' minutos';
    else if (delta < 7200)
      return 'hace una hora';
    else if (delta < 86400)
      return 'hace '+(parseInt(delta/3600)).toString()+' horas';
    else if (delta < 172800)
      return 'ayer';
    else 
      return 'hace '+(parseInt(delta/86400)).toString()+' dias';		
  },

  createJSONUrl: function(username, count, callback) {
    return 'http://twitter.com/statuses/user_timeline/'
      + username + '.json?' + 'count=' + count
      + '&callback=' + callback;									
  },

  createScriptTag: function(id, url) {
    var script = document.createElement('script');
    script.id = id;
    script.type = 'text/javascript';
    script.src = url;
    
    return script;
  },
  
  createListItem: function(text, relativeTime) {
    var li = document.createElement('li');
    li.innerHTML = '<span>' + text + '</span>' + relativeTime;
    
    return li;
  },
  
  callback: function(json) {
    this.addTweets(json);
  }
};

var rpnet_tw = rpnet.TwitterWidget;
rpnet_tw.init(rpnetTwitAttrs.usernames, 
              rpnetTwitAttrs.count, 
              rpnetTwitAttrs.title);


