var refreshRate = 30000;
var cHash = "";
var lcURL = "";
var twitter_cookie = "twitter_formatting";
var twitter_cookie_age = "7";


if ( getCookie(twitter_cookie) == "on" ) {
	setCookie(twitter_cookie, "on", twitter_cookie_age);
	var twitter_formatting = true;
} else {
	setCookie(twitter_cookie, "off", twitter_cookie_age);
	var twitter_formatting = false;
}



$(document).ready(function() {


	// Live Content auto-refreshing

	if ( $(".LiveContent").length > 0 ) {
	
		LC_title = $(".LiveContent").attr('rel');
	
		// // console.log( LC_title );
	
		LC_split = LC_title.split(",")

		LC_numvars = LC_split.length;
		
		
		// set url segments to default.
		cHash = "_";
		cLast = "_";
		cLimit = "20";
		
		
		// If we have configuration variables
		
		// parse them out.
		
		if (LC_numvars > 0) {
		
		
			$.each( LC_split, function(i, n){
		
				cName = $.trim(n.split(":")[0]);
				cVal = $.trim(n.split(":")[1]);
		
			
				switch ( cName ) {
		
					case "hashtag": { cHash = cVal; break; }
					case "last": { cLast = cVal; break; }
					case "limit": { cLimit = cVal; break; }				
		
				}
				
				
				
				if (cLast == "_") {
					cLast = $(".LiveContent .tweet:first").attr('rel');
				}
				
				// console.log( "cLast: " + cLast );
		
			});	
		
		}
		
		
		// Set variable defaults	
		
		if (cHash.length <= 0) { cHash = "_"; /* console.log( "set hash to default" ); */ }
		if (cLast.length <= 0) { cLast = "_"; /* console.log( "setting last to default" ); */ }
		if (cLimit.length <= 0) { cLimit = "20"; /* console.log( "results are default" ); */ }
		

		lcURL = "/media/twitter_live_new_tweets/" + cHash + "/" + cLast + "/" + cLimit + "/";

	
		
		setTimeout("autoRefreshLC(lcURL)", refreshRate);
	
	}






	// Live content hashtag filtering
	// navigation controls	
	$(".mxnowNavLinks .navlink").click(function () { 
	
			$(".LiveContentWrap .LiveContent .tweet .status, .LiveContentWrap .LiveContent .tweet .date").fadeTo("fast", "0.35");
	
			lcURL = lcURL.replace(eval("/"+cHash+"/i"), $(this).attr("rel"));
			
			cHash = $(this).attr("rel");

			
				
      what_feed = "/media/twitter_live_new_tweets/" + $(this).attr("rel") + "/_/25/";
      
      $(".LiveContentWrap .LiveContent").load(what_feed, function(){
				cLast = $(".LiveContent .tweet:first").attr('rel');
				
				lcURL = "/media/twitter_live_new_tweets/" + cHash + "/" + cLast + "/" + cLimit + "/";
				
				LC_title = "hashtag:" + cHash + ", limit:" + cLimit
				
				$(".LiveContent").attr("rel", LC_title);
      });
      
      $(".mxnowNavLinks .navlink").removeClass("on");
      
      $(".mxnowNavLinks .navlink[rel='" + $(this).attr("rel") + "']").addClass("on");
      
    

      
      return false;
      
  });


	
	// Handle Twitter formatting
	
	
	$("#TwitterFormatting").append("<span id='TwitterFormatToggle'></span>")
		.css("cursor", "pointer")
		.hover(
      function () {
        $(this).addClass("over");
      }, 
      function () {
        $(this).removeClass("over");
      }
    );
	




	if ( !twitter_formatting ) {			//-- Toggle starting tweets v
		$("#TwitterFormatting").html("See original Tweets");
	
		$(".tweet .tf").fadeToggle("slow");
		
		$(".tweet.tf_on").each(function (i) {
			toggleTwitterFormatting( $(this) );								
		});

		$(".creditation, .hashtags").fadeIn("slow");		
		
		setCookie(twitter_cookie, "off", twitter_cookie_age);
	} else {													//-- Toggle starting tweets ^
		$("#TwitterFormatting").html("Remove Twitter formatting");
	}


	// Toggle
	$("#TwitterFormatting").click(function () {
	
		$(".tweet .tf").fadeToggle("slow");
		
    
    if ( twitter_formatting ) {

			$(".tweet").each(function (i) {
				toggleTwitterFormatting( $(this) );								
			});

			$(".creditation, .hashtags").fadeIn("slow");
			
			$("#TwitterFormatting").html("See original Tweets");
			setCookie(twitter_cookie, "off", twitter_cookie_age);
			twitter_formatting = false;
		} else {
			$(".creditation, .hashtags").fadeOut("slow", function () { $(this).remove(); });
			
			
			// Set all classes to twitter formatting ON
			$(".tweet.tf_off").each(function (i) {
				$(this).removeClass("tf_off")
					.addClass("tf_on");
			});

			$("#TwitterFormatting").html("Remove Twitter formatting");			
			setCookie(twitter_cookie, "on", twitter_cookie_age);
			twitter_formatting = true;
		}
		
		
	});
	
	
		
});	// End Document ready












// ------------------------
// Twitter formatting toggle function

function toggleTwitterFormatting( tweetObj ) {

	$(tweetObj).find(".status").after("<div class='creditation clearfix'></div>")
	
	$(tweetObj).children(".creditation").append("<a class='tweet_author'>" + $.trim($(tweetObj).find(".tweet_author").html().replace(":", "")) + "</a><wbr>")
		
		
	$(tweetObj).find(".at_reply").each(function (n) {
	
		if ( $(this).prev().eq(0).hasClass("rt") ) {
			$(this)
				.parent()
				.parent()
				.children(".creditation")
				.append("<span class='rt' title='Retweeted'>rt:</span><wbr>");						
		} else {
			$(this)
				.parent()
				.parent()
				.children(".creditation")
				.append("<span class='reply_to' title='Replied to'>&gt;</span><wbr>");				
		}
		
		$(this)
			.parent()
			.parent()
			.children(".creditation")
			.append("<span class='at_reply'>" + $.trim($(this).html().replace(":", "").replace("@", "").replace("\<wbr\>", "")) + "</span>");
	});
	
	
	$(tweetObj).children(".creditation").after("<div class='hashtags clearfix'></div>");
			
	
	$(tweetObj).find(".tweet_hashtag").each(function (n) {
		$(this)
			.parent()
			.parent()
			.children(".hashtags")
			.append("<span class='tweet_hashtag'>" + $.trim($(this).html().replace("#", "").replace("\<wbr\>", "")) + "</span>");
	
		
		
		num_hashtags = $(this).parent().parent().find(".status .tweet_hashtag").length;
		
		
		if ( n < (num_hashtags - 1) ) {
			$(this)
				.parent()
				.parent()
				.children(".hashtags")
				.append(", ");
		}
	
	});


	if ( $(tweetObj).hasClass("tf_on") ) {	
		$(tweetObj).removeClass("tf_on")
			.addClass("tf_off");
	}
	
	
}












// ------------------------
// Fade toggle function
jQuery.fn.fadeToggle = function(speed, easing, callback) {
	return this.animate({opacity: 'toggle'}, speed, easing, callback);
}; 



// ------------------------
// Auto refreshing function

autoRefreshLC = function(feed_url) {
	
	$.ajax({
	
		url: feed_url,
		dataType: "html",
		cache: false,
		success: function(html) {
			num_new_tweets = 0;
			new_tweets = html;
			
			
			if ( html != "0" ) {
						
				num_new_tweets = $(html).find(".status").length;
				
				// console.log( "New Tweets: " + num_new_tweets );
			} else {
				// console.log("same old content. :(");
			}
			
				
				
						
			
			if ( num_new_tweets > 0 ) {
			
				here_down = ((cLimit - 1) - num_new_tweets);
			
				if (num_new_tweets >= cLimit ) {
					$(".LiveContent .tweet").fadeOut("slow", function () {
						$(this).remove();
					});
											
					$(new_tweets).filter(".tweet").each( function() {
						$(".LiveContent").prepend( "<div class='tweet new on tf_on'>" + $(new_tweets).html() + "</div>" );
						
						$(".LiveContent .tweet.new").slideDown("medium")
						.removeClass("new");
					});
				} else {
					$(".LiveContent .tweet").eq(here_down).nextAll().fadeOut("slow", function () {
						$(this).remove();
					});				
					
					$(new_tweets).filter(".tweet").each( function() {
						$(".LiveContent").prepend( "<div class='tweet new on tf_on' rel='" + $(new_tweets).filter(".tweet").attr("rel") + "'>" + $(new_tweets).html() + "</div>" );
						
						$(".LiveContent .tweet.new").slideDown("medium")
							.removeClass("new");
					});
				}
				
	
	
				if ( !twitter_formatting ) {
		
					$(".tweet.tf_on .tf").fadeOut("slow");
					
					$(".tweet.tf_on").each(function (i) {
						toggleTwitterFormatting( $(this) );								
					});
			
					$(".creditation, .hashtags").fadeIn("slow");					
					
					setCookie(twitter_cookie, "on", twitter_cookie_age);
		
				}	
	
	
				cLast = $(".LiveContent .tweet:first").attr('rel');
				
			
				
				// Build new status (rel) string
				lcURL = "/media/twitter_live_new_tweets/" + cHash + "/" + cLast + "/" + cLimit + "/";
	
	
	
	
			} else {
			
				// console.log( "NOT adding tweets" );
				
			}

			
			
			
			// Re-call auto refresh function
			setTimeout("autoRefreshLC(lcURL)", refreshRate);
		}
	
	});
}







// ------------------------
// Get cookie value
function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
			{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";", c_start);
			if (c_end == -1) c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
			}
		}
		
	return "";
}





// ------------------------
// Set cookie
function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate( exdate.getDate() + expiredays );
	document.cookie = c_name+ "=" + escape(value) +
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}