dojo.ready(function() {
	dojo.extend(dojox.image.SlideShow, {
		hasNav: false,
		autoStart: true,
		titleTemplate: '',
		crossFade: true,

		showImage: function(index, /* Function? */callback){
			// summary:
			//		Shows the image at index 'index'.
			// index: Number
			//		The position of the image in the data store to display
			// callback: Function
			//		Optional callback function to call when the image has finished displaying.

			if (this.crossFade) {
				var _this = this;
				var current = this.largeNode.getElementsByTagName("div");
				this.imageIndex = index;

				// ensure the image is loaded
				if (!_this.images[index]) {
					_this._loadImage(index);
				}

				if (current && current.length > 0) {
					// add it with opacity 0
					dojo.style(_this.images[index], "opacity", 0);
					dojo.style(_this.images[index], "position", "absolute");
					_this.largeNode.appendChild(_this.images[index]);

					// cross fade existing image -> new
					dojox.fx.crossFade({
						nodes: [_this.largeNode.firstChild,_this.largeNode.lastChild],
						duration: _this.crossFadeDuration,
						onEnd: function() {
							while (_this.largeNode.children.length > 1) {
								_this.largeNode.removeChild(_this.largeNode.firstChild);
							}
							_this._currentImage = _this.images[index]._img;
							_this._fitSize();
						}
					}).play();

				} else {
					// remove placeholder
					while (_this.largeNode.firstChild) {
						_this.largeNode.removeChild(_this.largeNode.firstChild);
					}

					// add image
					dojo.style(_this.images[index], "opacity", 1);
					dojo.style(_this.images[index], "position", "absolute");

					_this.largeNode.appendChild(_this.images[index]);
					_this._currentImage = _this.images[index]._img;
					_this._fitSize();

					// FIXME - for some reason _fitSize is getting a height of 0
					// here so we hardcode it to the height of the slideshow
					if (_this.innerWrapper.style.height != _this.imageHeight + "px") {
						dojo.style(_this.innerWrapper, "height", _this.imageHeight + "px");
					}
				}

    			callback();

			} else {
				this.inherited(arguments);
			}
		}
	});
});

dojo.require("dojo.fx");

dojo.provide('fabric.TwitterWidget');
dojo.declare('fabric.TwitterWidget', null, {
	elementID: null,
	accountID: null,
	listID: null,
	tweetIDs: [],
	tweets: [],
	includeReplies: false,
	includeRetweets: false,
	autoUpdate: false,
	cycle: false,
	timer: null,
	activeTweetID: null,
	includeUsername: false,

	constructor: function(params){
		this.elementID = params['id'];
		if (params['accountID']) {
			this.accountID = params['accountID'];
		}
		if (params['listID']) {
			this.listID = params['listID'];
		}
		if (params['includeReplies']) {
			this.includeReplies = params['includeReplies'];
		}
		if (params['includeRetweets']) {
			this.includeReplies = params['includeRetweets'];
		}
		if (params['autoUpdate']) {
			this.autoUpdate = params['autoUpdate'];
		}
		if (params['cycle']) {
			this.cycle = params['cycle'];
		}
		if (params['includeUsername']) {
			this.includeUsername = params['includeUsername'];
		}

		this.parse();

		if (dojo.isOpera) {
			// seems to fail on the animations, so we skip for now
		} else {
			if (this.cycle) {
				this.startCycle();

			} else if (this.autoUpdate) {
				var _this = this;
			    this.timer = setInterval(function() {
			    	_this.update();
			    }, 30000);
			}
		}
	},

	parse: function(){
		var _this = this;
		dojo.query("#" + this.elementID + " .tweet").forEach(function(node, index, arr){
			tweetID = node.id.replace('tweet_', '');
			_this.tweetIDs.push(tweetID);
		});
	},

	getNewTweets: function(){
		var _this = this;
		dojo.xhrGet({
		    url: this.updateURL(),
		    handleAs:"json",
		    timeout: 10000,
		    load: function(data){
				_this.tweets = data;
		    }
		});
	},

	updateURL: function(){
		var url = '';
		if (this.accountID) {
			url = '/twitter/feed/account/' + this.accountID + '.json';
		} else if (this.listID) {
			url = '/twitter/feed/list/' + this.listID + '.json';
		}

		// add options
		url += '?includeRetweets=' + this.includeRetweets + '&includeReplies=' + this.includeReplies + '&limit=';
		if (this.cycle) {
			url += 20;
		} else {
			url += 5;
		}

		return url;
	},

	update: function(){
		this.getNewTweets();
		for (x = 4; x >= 0; x--) {
			if (_this.tweetIDs.indexOf(data[x]['tweetID']) == -1) {
				_this.addTweet(data[x]);
				_this.removeLastTweet(data[x]);
			}
		}
	},

	startCycle: function(){

		this.getNewTweets();

		var _this = this;
		this.timer = setInterval(function() {
			_this.cycleTweets();
		}, 6000);
	},

	cycleTweets: function(){
		// get the tweet to add
		if (this.activeTweetID) {
			nextTweet = this.nextTweet(this.activeTweetID);
		} else {
			nextTweet = this.tweets[this.tweets.length - 1];
		}

		if (nextTweet) {
			this.addTweet(nextTweet);
			this.activeTweetID = nextTweet.tweetID;

			if (dojo.query('#' + this.elementID + ' .tweet').length > 6) {
				this.removeLastTweet();
			}
		}
	},

	buildTweetHTML: function(tweet){
		tweetDate = new Date(tweet.createdAt *1000);

		avatar = '';
		if (tweet['avatarURL']) {
			avatar = '<a href="http://twitter.com/' + tweet['accountUsername'] + '"><img src="' + tweet['avatarURL'] + '" alt=""></a>';
		}

		username = '';
		if (this.includeUsername) {
			username = '<a href="http://twitter.com/' + tweet['accountUsername'] + '">' + tweet['accountUsername'] + '</a>: ';
		}

		twContainer = dojo.create('div', {className: 'tweet', id: 'tweet_' + tweet['tweetID'], style: 'display: none;opacity: 0;'});
		twContainerInner = dojo.create('div', {className: 'inner', innerHTML: avatar + username + this.formattedTweetText(tweet.text) + '<br>'});
		dojo.place(dojo.create('span', {className: 'date', innerHTML: tweet['timeAgo']}), twContainerInner);
		dojo.place(twContainerInner, twContainer)

		return twContainer;
	},

	nextTweet: function(tweetID){
		if (this.tweets.length > 1) {
			for (x = 0; x < this.tweets.length; x++) {
				if (this.tweets[x].tweetID == tweetID) {
					if (x > 0) {
						return this.tweets[x - 1];
					} else {
						return this.tweets[this.tweets.length - 1];
					}
				}
			}
		}
	},

	addTweet: function(tweet){
		tweetHTML = this.buildTweetHTML(tweet);
		dojo.place(tweetHTML, this.elementID, 'first');
		dojo.fx.chain([
			dojo.fx.wipeIn({node: 'tweet_' + tweet.tweetID, duration: 600}),
			dojo.fadeIn({node: 'tweet_' + tweet.tweetID, duration: 350})
		]).play();

		this.tweetIDs.push(tweet['tweetID']);
	},

	removeLastTweet: function(){
		tweetID = dojo.byId(this.elementID).lastChild.id.replace('tweet_', '');
		dojo.destroy(dojo.byId(this.elementID).lastChild);
	},

	formattedTweetText: function(text){
		return text;
	}
});

