/*
 * Twitter Widget with multiple accounts.
 * @website http://ronakpatel.net
 * @author Ronak Patel
 * @email rspatel@gmail.com
 * @version 1.1
 *
 * 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,
  _showImages: false,
  _imageHeight: 48,
  _imageWidth: 48,

  init: function(usernames, count, title, showImages, imageHeight, imageWidth) {        
    if (this.errorCheck(usernames, count, title, showImages, imageHeight, imageWidth)) {
      this._usernames = usernames.split(',');
      this._count = count;				
      this._showImages = showImages;
      this._imageHeight = imageHeight;
      this._imageWidth = imageWidth;
      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>'
        + ' by @<a href="http://twitter.com/'
        + username + '">' + username + '</a>)</span>';
      var profileImg = this._tweets[i].user.profile_image_url;
      list.appendChild(this.createListItem(text, relTime, 
         username, profileImg));
    }
  },

  sortTweetsByDate: function(a, b) {    
    var c = a.created_at.split(' ');
    var d = b.created_at.split(' ');
    var x = Date.parse(c[1]+' '+c[2]+', '+c[5]+' '+c[3]);
    var y = Date.parse(d[1]+' '+d[2]+', '+d[5]+' '+d[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 'just now';
    else if (delta < 120) 
      return 'a minute ago';
    else if (delta < 3600)
      return (parseInt(delta/60)).toString()+' minutes ago';
    else if (delta < 7200)
      return 'an hour ago';
    else if (delta < 86400)
      return (parseInt(delta/3600)).toString()+' hours ago';
    else if (delta < 172800)
      return '1 day ago';
    else 
      return (parseInt(delta/86400)).toString()+' days ago';		
  },

  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, username, profileImg) {
    var li = document.createElement('li');
    li.style.margin = '3px';
    if (this._showImages) {
      li.style.minHeight = this._imageHeight;
      li.innerHTML = '<div><a style="float:left;margin-right:2px"' 
        +'href="http://twitter.com/' + username 
        + '"><img width="'+this._imageWidth
        + '" height="'+this._imageHeight
        + '" style="border:none" src="' + profileImg + '"></a>'
        + '<span>' + text + '</span>' 
        + relativeTime + '</div>';
    } else {
      li.innerHTML = '<span>' + text + '</span>' + relativeTime;
    }
    
    return li;
  },
  
  callback: function(json) {
    this.addTweets(json);    
  },
  
  errorCheck: function(usernames, count, title, showImages, imageHeight, imageWidth) {
    if (usernames == undefined ||
        count == undefined ||
        title == undefined ||
        showImages == undefined ||
        imageHeight == undefined ||
        imageWidth == undefined ||
        this.$('rpnet_twitterWidget') == undefined ||
        this.$('rpnet_twTitle') == undefined ||
        this.$('rpnet_twList') == undefined)
      return false;
    else
      return true;
  }
};

var rpnet_tw = rpnet.TwitterWidget;
rpnet_tw.init(rpnetTwitAttrs.usernames, 
              rpnetTwitAttrs.count, 
              rpnetTwitAttrs.title,
              rpnetTwitAttrs.showImages,
              rpnetTwitAttrs.imageHeight,
              rpnetTwitAttrs.imageWidth);

