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();
	},
	dataPath : "",
	shortenUrl: function(){
		new Ajax.Request(Retweet.dataPath + "/" + this.element.identify(), {
			onSuccess: this.onShortenUrl.bind(this),
			onFailure: this.onShortenUrl.bind(this),
			contentType: "application/json",
			evalJS: true
		});
	},
	onReady: function(){
		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(transport){
		console.log(transport);
		var bitlyObjects = transport.responseText.evalJSON();
		if(bitlyObjects){
			var bitlyObject = Object.values(bitlyObjects.results)[0];
			this.bitlyUrl = bitlyObject.shortUrl;
			this.gotShortenUrl = true;
			this.element.writeAttribute('id', 'b' + bitlyObject.hash);
			if(this.element.down('.retweet-text')) {
				var text = this.element.down('.retweet-text').innerHTML;
			} else 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 "+ Url.encode(text) + ' ' + this.bitlyUrl + "\" class=\"btn-retweet\">Retweet</a>");
			this.getStatsForUrl();
		}
	}
});

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


