// keep track of intervals via words
var intervals = {};

// output debug info to the console
//var debug = true;

// keep track of feeds via output elementids
var feeds = {};

// display the tweet
var showTweet = function (word, elementid) {
	// provides a random layer (50/50)
	if (Math.ceil(Math.random()*2) == 1) {
		var tweet = tweets.get(word, elementid);

		if (tweet) {
		// makes sure theres a tweet to show, and also flips a coin (makes it look more live)
			var container = $("#" + elementid);
			var children = $("#" + elementid + " li");

			if (children.length >= 5) {
				$(children[children.length - 1]).fadeOut("slow", function () {
					$(this).remove();
				});
			}
			var wordRegex = new RegExp("(.*)((?:i|\")\s*)?(" + word + ")(.*)?", "i");
			
			// record tweet
			tweets.lastTweet(word, tweet.tweetid);
			
			// identify keyword
			tweet.tweet = tweet.tweet.replace(wordRegex, '<small>$1</small><br />$2<span class="word">$3</span>$4');
			
			// strip links
			tweet.tweet = tweet.tweet.replace(/(http:\/\/(?:(?:[-\w]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?)/ig, '');
			
			// strip twitter names
			tweet.tweet = tweet.tweet.replace(/@([a-z][a-z0-9]{1,70}(?![^\s[a-z]]))/ig, '');
			
			$(container).prepend('<li style="display: none;">' + tweet.tweet + '</li>')
			$("#" + elementid + " li").fadeIn("slow");
			
			if (typeof debug != 'undefined') console.log('displaying tweet for "' + word + '", there are ' + tweets.stack[word].length + ' tweets left');
		} else {
			if (typeof debug != 'undefined') console.warn(' trouble displaying tweet for "' + word + '", there are ' + tweets.stack[word].length + ' tweets left. ' + intervals[word].failedattempts + ' failed attempts');
		}
	}
	
	if ($("#feeds div.container ul#" + elementid + " li").length == 0 || (typeof tweets.stack[word] != 'undefined' && tweets.stack[word].length == 0)) {
		$("#feeds div.container ul#" + elementid).addClass("loading");
	} else {
		$("#feeds div.container ul#" + elementid).removeClass("loading");
	}
};

// show a feed
var showFeed = function (word, elementid) {
	// set the text in the tweet box
	
	var safeelementid = elementid.replace(/[^a-z]/i,"");
	
	if (typeof feeds[safeelementid] != 'undefined') {
		window.clearInterval(intervals[feeds[safeelementid]]['interval']);
	}
	
	feeds[safeelementid] = word;
	// create interval object
	if (typeof intervals[word] == 'undefined') {
		intervals[word] = {
			failedattempts: 0,
			ready: true,
			interval: window.setInterval("showTweet('" + word + "','" + elementid + "')", 3000)
		};
	} else {
		intervals[word].interval = window.setInterval("showTweet('" + word + "','" + elementid + "')", 3000);
	}
	
	// instantly show
	showTweet(word,elementid);
	
	// underline the current feeds
	$("#feeds ul.words li").css('text-decoration','none')
	var i;
	for (i in feeds) {
		$("#feeds ul.words li." + feeds[i]).css('text-decoration','underline');
	}
};

	var limitChars = function (textid, limit, infoid)
	{
		var text = $('#' + textid).val();	
		var textlength = text.length;
		if (textlength == 0) {
			$('#' + infoid).html((limit - textlength));
			$('#' + infoid).css('color','#ff0000');
			return false;
		} else if (textlength > limit) {
			$('#' + infoid).html((limit - textlength));
			$('#' + infoid).css('color','#ff0000');
			return false;
		} else {
			$('#' + infoid).html((limit - textlength));
			$('#' + infoid).css('color','#19b8d0');
			return true;
		}
	};
		

$(document).ready(function(){
	/*
	* form
	*/
	$("#inner-content #info #tweetbox div.login input.username").bind("focus blur",function (e) {
		if (e.type == 'focus' && this.value == 'username') {
			this.value = '';
		} else if (e.type == 'blur' && this.value == '') {
			this.value = 'username';
		}
	});
	
	$("#inner-content #info #tweetbox div.login input.password").bind("focus blur",function (e) {
		if (e.type == 'focus' && this.value == 'password') {
			this.value = '';
		} else if (e.type == 'blur' && this.value == '') {
			this.value = 'password';
		}
	});
	
	$('#tweet').bind("keypress keyup keydown change",function(){
		limitChars('tweet', 140, 'remaining-characters');
	}).keypress();
	
	$("#inner-content #info #tweetbox p.submit-container span.submit").click(function () {
		var username = $("#inner-content #info #tweetbox div.login input.username").val();
		var password = $("#inner-content #info #tweetbox div.login input.password").val();
		var tweet = $("#inner-content #info #tweetbox textarea#tweet").val();
		
		var word = tweet.match(/(fearless|food|joy|inspired|hope|love)/i);
		if (word) {
			if (typeof tweets.stack[word[1]] == 'undefined') {
				tweets.stack[word[1]] = new Array();
			}
			tweets.stack[word[1]].push({tweet: tweet, tweetid: "internal"});
		}
		
		$.ajax({
			type: "POST",
			url:  "ajax.php",
			dataType: 'json',
			
			data: {
				method: 'postTweet',
				username: username,
				password: password,
				tweet: tweet
			},
			
			success: function(json){
				var messagebox = $("#inner-content #info #tweetbox p.submit-container span.message");
				messagebox.hide();
				messagebox.fadeIn("slow");
				
				if (json.success == 'false') {
					messagebox.css("color", "red");
					messagebox.html(json.error);
					
					$("#inner-content #info #tweetbox div.login input.password").val('');
				} else {
					messagebox.css("color", "green");
					messagebox.html('successfully posted tweet');
					
					$("#inner-content #info #tweetbox div.login input.username").val('username');
					$("#inner-content #info #tweetbox div.login input.password").val('password');
					$("#inner-content #info #tweetbox textarea#tweet").val('#FeedYourInspiration');
				}
				window.setTimeout(function () {messagebox.fadeOut("slow"); }, 3000);
			},
			
			beforeSend: function(){

			},
			
			complete: function(){

			}
		});
	});
	
	/*
	* feed
	*/
	$('#feeds ul.words li.fearless').click(function() {
		showFeed('fearless','julie');
		var tweet = $('#inner-content #info #tweetbox textarea#tweet').val();
		tweet = tweet.replace(/(\s+)?#(fearless|food|joy|inspired|hope|love|FeedYourInspiration)/gi, '') + ' #fearless #FeedYourInspiration';
		$('#inner-content #info #tweetbox textarea#tweet').val(tweet);
		limitChars('tweet', 140, 'remaining-characters');
	});
	$('#feeds ul.words li.food').click(function() {
		showFeed('food','julie');
		var tweet = $('#inner-content #info #tweetbox textarea#tweet').val();
		tweet = tweet.replace(/(\s+)?#(fearless|food|joy|inspired|hope|love|FeedYourInspiration)/gi, '') + ' #food #FeedYourInspiration';
		$('#inner-content #info #tweetbox textarea#tweet').val(tweet);
		limitChars('tweet', 140, 'remaining-characters');
	});
	$('#feeds ul.words li.joy').click(function() {
		showFeed('joy','julie');
		var tweet = $('#inner-content #info #tweetbox textarea#tweet').val();
		tweet = tweet.replace(/(\s+)?#(fearless|food|joy|inspired|hope|love|FeedYourInspiration)/gi, '') + ' #joy #FeedYourInspiration';
		$('#inner-content #info #tweetbox textarea#tweet').val(tweet);
		limitChars('tweet', 140, 'remaining-characters');
	});
	$('#feeds ul.words li.inspired').click(function() {
		showFeed('inspired','julia');
		var tweet = $('#inner-content #info #tweetbox textarea#tweet').val();
		tweet = tweet.replace(/(\s+)?#(fearless|food|joy|inspired|hope|love|FeedYourInspiration)/gi, '') + ' #inspired #FeedYourInspiration';
		$('#inner-content #info #tweetbox textarea#tweet').val(tweet);
		limitChars('tweet', 140, 'remaining-characters');
	});
	$('#feeds ul.words li.hope').click(function() {
		showFeed('hope','julia');
		var tweet = $('#inner-content #info #tweetbox textarea#tweet').val();
		tweet = tweet.replace(/(\s+)?#(fearless|food|joy|inspired|hope|love|FeedYourInspiration)/gi, '') + ' #hope #FeedYourInspiration';
		$('#inner-content #info #tweetbox textarea#tweet').val(tweet);
		limitChars('tweet', 140, 'remaining-characters');
	});
	$('#feeds ul.words li.love').click(function() {
		showFeed('love','julia');
		var tweet = $('#inner-content #info #tweetbox textarea#tweet').val();
		tweet = tweet.replace(/(\s+)?#(fearless|food|joy|inspired|hope|love|FeedYourInspiration)/gi, '') + ' #love #FeedYourInspiration';
		$('#inner-content #info #tweetbox textarea#tweet').val(tweet);
		limitChars('tweet', 140, 'remaining-characters');
	});
	
	/*
	* share
	*/
	share.url = 'http://feedyourinspiration.com';
	share.title = 'Julia & Julia Feed your inspiration ';
	share.description = 'Feed your inspiration with Julie & Julia!';
	share.tweet = 'Feed your inspiration with Julie & Julia! - http://feedyourinspiration.com/';
	
	
	/*
		please ignore... google chrome workaround for timeouts and tracking
	*/
	$('span.share img').each(function() {
		$(this).bind('click', function () {
			if (typeof s == "object") {
				var property = s.prop4.substring(s.prop4.lastIndexOf(':') + 1);
				sCode.trackOutboundClick(share.send($(this).attr('class')), property + '_' + $(this).attr('class') + '_button');
			}
		});
		$(this).bind('click', function () {
			window.open(share.send($(this).attr('class')), $(this).attr('class'));
		});
	});
	
	/*
	* init
	*/
	showFeed('food','julie');
	showFeed('inspired','julia');
	
});
