function TwitterFeed(refreshRate) {
	if (refreshRate == null) {
		refreshRate = 5000;
	}
	this.init();
	
	if (refreshRate > 0) {
		var self = this;
		setInterval(function(){ self.init(true); }, refreshRate);
	}
}

TwitterFeed.prototype = {
	// accepts either a numeric user id or search string
	feedList: [/*'77105008',*/ '#goforth'],
	feed: [],
	count: 0,
	initialLoadTotal: 10,
	i: 0,
	
	init: function(refreshFeed) {
		$('#tweets').html(getLoader());
		var self = this;
		if (parseInt(this.feedList[self.i]) > 0) {
			query = 'http://twitter.com/statuses/user_timeline/'+ this.feedList[self.i] +'.json?callback=?';
			type = 'user';
		} else {
			query = 'http://search.twitter.com/search.json?lang=en&q=+'+ escape(this.feedList[self.i]) +'&callback=?';
			type = 'search';
		}
		
		$.getJSON(query,
			function(data) {
				if (refreshFeed == true) {
					$('#sideNav #tweets').empty();
					self.count = 0;
				}
				var resultset = data;
				if (type == 'search') {
					resultset = data.results;
				}
				$.each(resultset, function(i, item) {
					if (type == 'user') {
						item.created_at = self.fixDate(item.created_at);
					}
					item.datesort = new Date(Date.parse(item.created_at)).getTime();
					item.type = type;
					self.feed.push(item);
				});
				
				if (self.i < self.feedList.length-1) {
					self.i++;
					self.init();
				} else {
					self.feed.sort(comparator);
					self.populate(self.initialLoadTotal);
				}
			}
		);
	},
	
	fixDate: function(date) {
		var olddate = date.split(' ');
		return olddate[0] +' '+ olddate[1] +' '+ olddate[2] +' '+ olddate[5] +' '+ olddate[3] +' '+ olddate[4];
	},
	
	populate: function(total) {
		if(this.feed.length > 0) {
			$('#sideNav #tweets').empty();
			var self = this;
			$.each(this.feed, function(i, item) {
				var date = self.parseDate(item.created_at);

				if (item.type == 'search') {
					self.tweetDiv(item.from_user, item.profile_image_url, item.from_user, item.text, item.id, date);
				} else {
					self.tweetDiv(item.user.screen_name, item.user.profile_image_url, item.user.name, item.text, item.id, date);
				}
				
				self.count++;
				if (self.count == total || i == self.feed.length-1) {
					return false;
				}
			});
		} else {
			$('#sideNav #tweets').html('');
		}
	},
	
	tweetDiv: function(screen_name, profile_image_url, username, text, id, date) {
		$('#sideNav #tweets').append('<div class="tweet"><div class="image"><a href="http://www.twitter.com/'+ screen_name +'" target="_blank"><img src="'+ profile_image_url +'" /></a></div>'
			   +'<div class="text"><p><a href="http://www.twitter.com/'+ screen_name +'" class="title" target="_blank">'+ username +'</a> '+ this.parseText(text) +'</p>'
			   +'<a href="http://twitter.com/'+ screen_name +'/status/'+ id +'" class="date" target="_blank">'+ date.dateString +' '+ date.timeString +'</a></div></div><br />');
	},
	
	parseText: function(text) {
		return text != null ? text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) { return url.link(url); }) : '';
	},
	
	parseDate: function(date) {
		var dateObj = {};
		var d = new Date(Date.parse(date));
		var hour = d.getHours();
		if (hour > 12) hour -= 12;
		
		dateObj.dateString = (d.getMonth()+1) +'/'+ d.getDate() +'/'+ d.getFullYear().toString();
		dateObj.timeString = hour +':'+ this.formatNumber(d.getMinutes()) + (d.getHours() < 12 && d.getHours() > 0 ? ' AM' : ' PM');
		
		return dateObj;
	},
	
	formatNumber: function(num) {
		return num < 10 ? '0'+num : num;	
	}
};

function comparator(a, b)
{
	if (a.datesort == b.datesort) {
		return 0;
	}
	return b.datesort < a.datesort ? -1 : 1;
}




var drawers = {
	
	currentClue: 1,
	lastClue: 1,
	
	init: function(id) {
		this.currentClue = id;
		this.loadClue();
	},
	
	show: function(page) {
		
		var url = '';
		
		switch (page) {
			case 'help':
				$('#helpLink').hide();
				$('#drawerContent').html(getLoader());
				$('#drawers').removeClass('home').removeClass('quiz');
				url = '/fortune/help/format/html';
			break;
			
			case 'main':
				$('#drawerContent').html(getLoader());
				this.hideElements();
				$('#drawers').addClass('home').removeClass('quiz');
				url = '/fortune/main';
			break;
			
			case 'quiz':
				$('.clue').removeClass('selected');
				this.hideElements();
				$('#drawers').addClass('quiz').removeClass('home');
				$('#drawerContent').html(getLoader());
				url = '/fortune/final/format/html';
				comments.loadPage(99, 1);
			break;
			
		}
		
		$('#drawerContent').load(BASE_URL + url);
	},
	
	hideElements: function() {
		$('#helpLink').hide();
		$('#drawerTop').hide();
		$('#btnPrevClue').height(1);
		$('#btnNextClue').height(1);
	},
	
	loadClue: function(id) {
		if (id != null) {
			this.currentClue = id;
		}
		
		if (this.currentClue == this.lastClue) {
			$('#btnNextClue').height(1);
		} else {
			$('#btnNextClue').height(22);
		}
		
		if (this.currentClue == 1) {
			$('#btnPrevClue').height(1);
		} else {
			$('#btnPrevClue').height(22);
		}
		
		$('#drawerContent').html(getLoader());
		$('#helpLink').show();
		$('#drawerTop').show();
		$('#drawers').removeClass('home').removeClass('quiz');
		$('#drawerContent').load(BASE_URL +'/fortune/clue/'+ this.currentClue);
		$('.clue').removeClass('selected');
		comments.loadPage(this.currentClue, 1);
	},
	
	nextClue: function() {
		this.currentClue++;
		if (this.currentClue > this.lastClue) {
			this.currentClue = this.lastClue;
		} else {
			this.loadClue(this.currentClue);
		}
	},
	
	prevClue: function() {
		this.currentClue--;
		if (this.currentClue < 1) {
			this.currentClue = 1;
		} else {
			this.loadClue(this.currentClue);
		}
	}
	
};

ClueMedia = {};
ClueMedia.lightbox;
ClueMedia.show = function(clue_id)
{
	doubleTrack('GO_Clue_'+ drawers.currentClue +'_media_gallery');

	/*if (ClueMedia.lightbox)
	{
		return ClueMedia.lightbox.show();
	}*/

	Gallery.mediaList = [];
	Gallery.currentMedia = 0;
	Ajax.HTML(
		'/fortune/clue/media/'+clue_id,
		{
			success: function(html)
			{
				ClueMedia.lightbox = new WK.Lightbox(html);
				ClueMedia.lightbox._destroyOnHide = true;
				ClueMedia.lightbox._onHide = Gallery.killVideo;
				ClueMedia.lightbox.show();
				Gallery.init();
			}
		}
	);
}

var Gallery = Gallery || {};
var Gallery = {
	
	mediaList: [],
	currentMedia: 0,
	active: false,
	
	init: function() {
		if (this.mediaList.length <= 1) {
			$('#gallery .prev').hide();
			$('#gallery .next').hide();
		}
		this.active = true;
		this.showMedia(this.currentMedia);
	},
	
	showMedia: function(index) {
		this.currentMedia = index;
		
		if (this.mediaList[index].indexOf('.flv') > -1) {
			var video = '<div id="galleryVieoContainer"><div id="flashVideo"></div></div><script type="text/javascript">swfobject.embedSWF('
			+ BASE_URL +'"/swf/videoplayer_fortune_pop.swf", "flashVideo", "447", "258", "9.0.0", "",'
			+ '{ flvURL:"'+ this.mediaList[index] +'", imageOffURL:"'+ this.videoImage(this.mediaList[index]) +'", videoWidth:"447", videoHeight:"258", trackingCode:"GO_Video_player_clue_'+ drawers.currentClue +'lightbox" },'
			+ '{ bgcolor: "#000000", menu: "false" , allowfullscreen: "true",  allowscriptaccess: "always" },{});</script>';

			$('#gallery .mediaContainer').html(video);
	
		} else {
			var image = this.mediaList[index];
			var img = new Image();
			$('#gallery .mediaContainer').html(getLoader());
			$(img).load(function () {
				//$(this).hide();
				$('#gallery .mediaContainer').html(this);
				//$(this).fadeIn('slow');
				//$('#gallery .mediaContainer').show();
			})
			
			.attr('src', image);
		}
		$('#gallery #imageNav .pagination a').removeClass('selected');
		$('#gallery #imageNav .pagination #link'+ this.currentMedia).addClass('selected');
		
	},
	
	videoImage: function(str) {
		return str.substring(0, str.lastIndexOf('.flv')) + '.jpg';
	},
	
	prev: function() {
		this.showMedia(this.count(-1));
	},
	
	next: function() {
		this.showMedia(this.count(1));
	},
	
	refresh: function() {
		this.showMedia(this.currentMedia);
	},
	
	count: function(offset) {
		this.currentMedia += offset;
		if (this.currentMedia < 0) {
			this.currentMedia = this.mediaList.length-1;
		}
		if (this.currentMedia > this.mediaList.length-1) {
			this.currentMedia = 0;
		}
		return this.currentMedia;
	},
	
	killVideo: function() {
		$('#gallery .mediaContainer').html('');
	}
};


/** CHARITY NOMINATION **/
CharityNomination = {};
CharityNomination.lightbox;
CharityNomination.show = function()
{

	Ajax.HTML(
		'/fortune/charity',
		{
			success: function(html)
			{
				CharityNomination.lightbox = new WK.Lightbox(html);
				CharityNomination.lightbox._absolute = true;
				CharityNomination.lightbox._destroyOnHide = true;
				CharityNomination.lightbox.show();
			}
		}
	);
}

CharityNomination.submit = function()
{
	$.post(BASE_URL+'/fortune/charity/format/html', $('#charityNominationForm').serialize(), function(data) {
		$('#charityNomination').html(data);
		doubleTrack('GO_Clue_Charity_Nomination_Submit');
		CharityNomination.lightbox.center();
		CharityNomination.lightbox._popupElt.addClass('topMargin');
	});
	
	return false;
}

/** CHARITY MORE **/
CharityMore = {};
CharityMore.lightbox;
CharityMore.show = function()
{
	
	Ajax.HTML(
		'/fortune/charitymore',
		{
			success: function(html)
			{
				CharityMore.lightbox = new WK.Lightbox(html);
				CharityMore.lightbox.show();
			}
		}
	);
}



var comments = {
	
	currentPage: 1,
	clueId: 1,
	totalPages: 1,
	maxLength: 240,
	
	init: function(clueId, totalPages) {
		this.clueId = clueId;
		this.totalPages = totalPages;
		//this.loadPage(this.clueId, 1);
		this.renderNav();
		$('#commentForm #comment').change(function(event) { comments.postCount(this); })
								  .keyup(function(event) { comments.postCount(this); })
								  .focus(function(event) { comments.postCount(this); })
								  .blur(function(event) { comments.postCount(this); });
	},
	
	loadPage: function(clueId, page) {
		$('.commentNav').empty();
		this.clueId = clueId;
		this.currentPage = page;
		var self = this;
		$('#commentBody #comments').html(getLoader());
		$('#commentBody #comments').load(BASE_URL +'/fortune/comments/'+ clueId +'/'+ page, function() { self.renderNav(); });
		$('#clue_id').val(clueId);
		$('#commentForm').attr('action', BASE_URL +'/fortune/'+ clueId);
	},
	
	loadMore: function() {
		this.currentPage++;
		$('.commentNav').html(getLoader());
		var self = this;
		$.ajax({
			type: 'GET',
			url: BASE_URL +'/fortune/comments/'+ this.clueId +'/'+ this.currentPage,
			success: function(result) {
				$('#commentBody #comments').append(result);
				self.renderNav();
			}
		});
		
	},
		
	renderNav: function() {
		if (this.currentPage >= this.totalPages || this.totalPages == 1) {
			this.currentPage = this.totalPages;
			$('.commentNav').empty();
		} else {
			$('.commentNav').html('<a href="javascript:void(0);" onclick="comments.loadMore();" class="header">More</a>');
		}
	},
	
	postCount: function(field) {
		if (field.value.length > this.maxLength) {
			field.value = field.value.substring(0, this.maxLength);
		} else {
			$('#postComment #counter').html(this.maxLength - field.value.length);
		}
	},
	
	remove: function(comment_id) {
		var self = this;
		$.post(BASE_URL+'/fortune/comments', { 'comment_id':comment_id }, function(data) {
			$('#comment'+comment_id).fadeOut();
		});
	},
	
	submit: function() {
		if ($('#commentForm #comment').val() != '') {
			$('#commentForm #commentSubmit').html(getLoader());
			
			var self = this;
			$.post(BASE_URL+'/fortune', $('#commentForm').serialize(), function(data) {
				self.loadPage(self.clueId, 1);
				$('#commentForm #comment').val('');
				$('#postComment #counter').html(self.maxLength);
				$('#commentForm #commentSubmit').html('<a href="javascript:void(0);" class="header" onclick="comments.submit();">Submit</a>');
				doubleTrack('GO_Clue_'+ self.clueId +'_post_comment');
			});
			
		}
	}
	
};



Story = {};
Story.lightbox;
Story.show = function()
{
	if (Story.lightbox)
	{
		return Story.lightbox.show();
	}

	Ajax.HTML(
		'/fortune/story',
		{
			success: function(html)
			{
				Story.lightbox = new WK.Lightbox(html);
				Story.lightbox._absolute = true;
				Story.lightbox.show();
			}
		}
	);
}

Rules = {};
Rules.lightbox;
Rules.show = function()
{
	if (Rules.lightbox)
	{
		return Rules.lightbox.show();
	}

	Ajax.HTML(
		'/fortune/rules',
		{
			success: function(html)
			{
				Rules.lightbox = new WK.Lightbox(html);
				Rules.lightbox.show();
			}
		}
	);
}




function submitLocation() {
	doubleTrack('GO_Clue_'+ drawers.currentClue +'_submit_answer');
	if ($('#clueLocationForm #location').val() == '') {
		$('#clueMessage').html('<p id="locationIncorrect">Incorrect</p>');
	} else {
		$('#clueMessage').html(getLoader());
		$.post(BASE_URL+'/fortune/clueverify', $('#clueLocationForm').serialize(), function(data) {
			var response = data.response;
			if (response.status == 'valid') {
				drawers.loadClue(response.clue.id);
			} else {
				$('#clueMessage').html('<p id="locationIncorrect">Incorrect</p>');
			}
		}, 'json');
	}
}

function getLoader() {
	return '<div class="loading">Loading</div>';
}


