Retweet = {};
Retweet.Button = Class.create({
	initialize: function(element, options){
		if(!window.BitlyClient){
			console.error('this widget needs the bitly javascript client!');
		}
	
		this.element = $(element);
		this.options = Object.extend({
			getShortenUrl: function(){ return window.location.href;}
		}, options || {});
		this.onReady();
	},
	shortenUrl: function(){
		BitlyClient.shorten(this.options.getShortenUrl(this), 'Retweet.CallBacks.onShortenUrl');
	},
	onReady: function(){
		this.waitForShortenUrl(this.onShortenUrl.bindAsEventListener(this));
		this.waitForStats(this.onStatsReceived.bindAsEventListener(this));
		this.shortenUrl();
	},
	waitForShortenUrl: function(callback){
		document.observe('bitly:shortenurl', callback);
	},
	waitForStats: function(callback){
		document.observe('bitly:stats', callback);
	},
	onStatsReceived: function(event){
		if(!this.statsReceived && event.memo.response.results.hash == this.element.identify().substr(1)){
			var result = event.memo.response.results.clicks;
			if(result){
				this.statsReceived = true;
				this.element.down('span.retweet-button a').update(this.element.down('span.retweet-button a').innerHTML + ' (' +result+ ' clicks)');
			}
		}
	},
	getStatsForUrl: function(){
		BitlyClient.stats(this.bitlyUrl, 'Retweet.CallBacks.onStats');
	},
	onShortenUrl: function(event){
		if(!this.gotShortenUrl){
			var result;
			for (var r in event.memo.response.results) {
				if(r == this.options.getShortenUrl(this)){
					result = event.memo.response.results[r];
					result['longUrl'] = r;
					break;
				}
			}
			if(result){
				this.gotShortenUrl = true;
				this.bitlyUrl = result['shortUrl'];
				this.element.writeAttribute('id', 'b' + result['hash']);
				if(this.element.down('h2 a')){
					var text = this.element.down('h2 a').innerHTML;
				}else{
					var text = this.element.down('h2').innerHTML;
				}
				this.element.down('span.retweet-button').update("<a href=\"http://twitter.com/home/?status=RT+%40pvda "+ escape(text) + ' ' + result['shortUrl'] + "\" class=\"btn-retweet\">Retweet</a>");
				this.getStatsForUrl();
			}
		}
	}
});

Retweet.CallBacks = {
	onShortenUrl: function(data){
		document.fire('bitly:shortenurl', {
			response: data
		});
	},
	onStats: function(data){
		document.fire('bitly:stats', {
			response: data
		});
	}
};

