
var log;

window.addEvents({

	domready: function()
	{
	
		// log = new Log('debug');
		
		if ($('tweets'))
		{
			new Request.Twitter('ionizecms', {
				data: { count: 2 },
				onSuccess: function(tweets)
				{
					for (var i = tweets.length; i--; )
					{
						var date = tweets[i].created_at;
						date = date.substr(-4) + ' ' + date.substr(0, date.indexOf('+'));
					
						new Element('p', {
							'class': 'tweet',
							'html': '<span class="tweetdate" >' + date + '</span>' + tweets[i].text
						}).inject('tweets', 'top');
					}
				}
			}).send();
		}
	}
		
});


Request.Twitter = new Class({

  Extends: Request.JSONP,

  options: {
    linkify: true,
    url: 'http://twitter.com/statuses/user_timeline/{term}.json',
    data: {
      count: 5
    }
  },
  
  initialize: function(term, options){
    this.parent(options);
    this.options.url = this.options.url.substitute({term: term});
  },
  
  success: function(data, script){
    if (this.options.linkify) data.each(function(tweet){
      tweet.text = this.linkify(tweet.text);
//      tweet.created_at = 'dede';
    }, this);
    
    // keep subsequent calls newer
    if (data[0]) this.options.data.since_id = data[0].id;
    
    this.parent(data, script);
  },
  
  linkify: function(text){
    // modified from TwitterGitter by David Walsh (davidwalsh.name)
    // courtesy of Jeremy Parrish (rrish.org)
    return text.replace(/(https?:\/\/[\w\-:;?&=+.%#\/]+)/gi, '<a href="$1">$1</a>')
               .replace(/(^|\W)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
               .replace(/(^|\W)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>');
  }
  
});

Log = new Class({

	el:null,

	initialize: function(id, cl)
	{
		var cl = (cl) ? cl : '' ;
		
		this.el = new Element('div',
		{
			'id':id,
			'class':cl
		});

		$$('body').adopt(this.el);
	},

	log:function(key, value, clean)
	{
	
		if (clean== true)
			this.el.set('html', key + ' :: ' + '<b>' + value + '</b><br/>');
		else
			this.el.set('html', this.el.get('html') + key + ' :: ' + '<b>' + value + '</b><br/>');
	}
});

