//Copyright (C) Ejbloo - http://www.ejbloo.com

//Important Variables/Constants
window.g_remote = "http://www.ejbloo.com";
window.loginBoxIsVisible = false;

window.max_comment_textarea_length = 500;

$(document).ready(function(){
	
	//Add top message, but check to see if it's already been closed
	var msg_cookie = "done_showing_top_bar_message";
	if(false && !cookie_isset(msg_cookie))
	{
		$("body").prepend("<div id='ejbloo_top_bar_message'>Hello! Here's some important information! Ejbloo.com may go down temporarily today as we switch servers. Sorry for the potential inconvenience!<br /><div id='close_top_bar_message'>Click here to close this message.</div></div>");
		
		$("#close_top_bar_message").click(function(){
			document.cookie = msg_cookie + "=true;path=/";
			$(this).parent().slideUp(300);
		});
		$("#ejbloo_top_bar_message").slideDown(400);
	}
	
	//Navbar Highlight
	$("#nav-" + window.site_loc + " a").css('background-position', '0px -72px');
	
	//Cookie Check
	if(!are_cookies_enabled())
	{
		$("#no_cook").css({'border': '1px solid black', 'padding': '5px', 'margin': '0px 10px 20px 10px', 'background-color': 'white'}).html("Please enable cookies in your browser for full Ejbloo.com functionality.<br /><br />Some Ejbloo.com site features will not work until cookies have been enabled.");
	}
	//Make Login Box Items Initially Invisible
	$("#username_text, #login_username, #password_text, #login_password, #closeLogin, #goLogin, #forgot_password_link").css('visibility', 'hidden');
	
	$("#nav-login").click(showOrHideLoginBox);
	$("#closeLogin").click(hideLoginBox);
	$("#goLogin").click(login);
	
	$('#login_username').keydown(function(e) {
		if (e.keyCode == '13')
		{
			e.preventDefault();
			$('#login_password').focus();
		}
	});
	
	$('#login_password').keydown(function(e) {
		if (e.keyCode == '13')
		{
			e.preventDefault();
			login();
		}
	});
	
	//If on the Home Page
	if($(".home_paint_play_story_div").length != 0)
	{
		//Set up EJPaint, EJPlay and EJStory home page animation code!
		//Using: recent_paintings_arr, recent_songs_arr, recent_stories_arr
		
		preloadAndAnimateHomePageLatestContent();
	}
	
	//If on a Flash page
	if($("#flashContent").length != 0)
	{
		var user_flash_version_object = swfobject.getFlashPlayerVersion();
		var user_flash_version = user_flash_version_object.major + "." + user_flash_version_object.minor + "." + user_flash_version_object.release;
		$("#flashContent").html("<div class='error_div acenter'><br /><a href='http://www.adobe.com/go/getflash'><img src='http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a><br /><br />This page requires Flash Player version 10.0 or higher (10.1+ recommended).<br /><br />Your detected Flash Player version is: " + user_flash_version + "<br /><br /></div>");
	}
	
	
	//If On Videos Page
	if($('#episode_list div a').length != 0)
	{
		window.selectedEpisode = $('.ep_selected a').attr('name');
		
		window.episode_html_arr = new Array('Not An Episode');
		window.episode_html_arr[1] = "<object data='http://www.youtube.com/v/XH9LT3WbqFI?fs=1&amp;hl=en_US&amp;rel=0' type='application/x-shockwave-flash' width='560' height='340'><param name='movie' value='http://www.youtube.com/v/XH9LT3WbqFI?fs=1&amp;hl=en_US&amp;rel=0' /></object>";
		window.episode_html_arr[2] = "<object data='http://www.youtube.com/v/TXRMeDuvm3Y?fs=1&amp;hl=en_US&amp;rel=0' type='application/x-shockwave-flash' width='560' height='340'><param name='movie' value='http://www.youtube.com/v/TXRMeDuvm3Y?fs=1&amp;hl=en_US&amp;rel=0' /></object>";
		
		
		//JS Hover Code (jQuery CSS Compensation)
		$('#episode_list div a').hover( function(){
			$(this).css('background-color', '#9999FF');
		},
		function(){
			if($(this).attr('name') != window.selectedEpisode)
			{
				$(this).css('background-color', '#000000');
			}
		});
		
		$('#episode_list div a').each(function(){
			$(this).click(function(){
				var prev_selection = window.selectedEpisode;
				
				if($(this).attr('name') != prev_selection)
				{
					//Un-Highlight previously selected
					$('#episode_list div a[name="' + prev_selection + '"]').css('background-color', 'black').css('border', 'none');
					
					//Put Box Around Newly Selected
					$(this).css('border', '1px solid white');
					
					//Update selectedEpisode
					window.selectedEpisode = $(this).attr('name');
					
					$("#youtube_video_container").html(window.episode_html_arr[window.selectedEpisode]);
				}
				
				return false;
			});
		});
	}
	
	//If on a page with comments
	if($('#comment_div').length != 0)
	{
		bindCommentEventHandlers();
	}
	
	//Fix for when a user presses the back button, but is not logged in anymore (no longer displaying login content)
	//Reload the page
	if($('#nav-profile').length != 0 && !cookie_isset('login1'))
	{
		window.location.reload();
	}
	
});

function are_cookies_enabled()
{
	var cookieEnabled = (navigator.cookieEnabled) ? true : false;

	if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
	{ 
		document.cookie="cookie_test=";
		cookieEnabled = (document.cookie.indexOf("cookie_test") != -1) ? true : false;
		//clear the set cookie
		var cookie_date = new Date();  // current date & time
		cookie_date.setTime (cookie_date.getTime() - 1);
		document.cookie = "logged_in=;expires=" + cookie_date.toGMTString();
	}
	return (cookieEnabled);
}

function showOrHideLoginBox()
{
	if(window.loginBoxIsVisible)
	{
		hideLoginBox();
	}
	else
	{
		showLoginBox();
	}
	return false;
}

function showLoginBox()
{
	$("#login_username").val("");
	$("#login_password").val("");
	$('#login_error_text').html("");
	
	$('#nav-login').blur();
	
	$("#login_box").slideDown(150, function(){
		$("#username_text, #login_username, #password_text, #login_password, #closeLogin, #goLogin, #forgot_password_link").css('visibility', 'visible');
		$('#login_username').focus();
	});
	
	window.loginBoxIsVisible = true;
	
	return false; //necessary for direct calls
}

function hideLoginBox()
{
	$("#username_text, #login_username, #password_text, #login_password, #closeLogin, #goLogin, #forgot_password_link").css('visibility', 'hidden');
	$("#login_box").slideUp(150);
	
	window.loginBoxIsVisible = false;
	
	$("#login_username").val("");
	$("#login_password").val("");
	$('#login_error_text').html("");
	
	$('#nav-login').blur();
	
	return false; //necessary for direct calls
}

function login()
{
	$('#login_error_text').html("Logging in...");
	
	if($('#login_password').val() == "" || $('#login_username').val() == "")
	{
		$('#login_error_text').html("Incorrect username or password.");
		return false;
	}
	
	var u = $('#login_username').val().toLowerCase();
	var h = SHA256($('#login_password').val());
	
	$.ajax({
	    url: g_remote + '/html_components/login_auth.php',
	    type: 'POST',
	    data: {username: u, p_hash: h},
	    dataType: 'text',
	    timeout: 10000,
	    error: function(){
			$('#login_error_text').html("There was an error connecting to the server.");
	    },
	    success: function(data){
	        if(data.substring(0, 7) == "success")
	        {
	        	if(window.refreshAfterLogin)
				{
					window.location.reload();
				}
				else
				{
					swapHTMLAddLoginContent(data.substring(7));
				}
	        }
	        else
	        {
				$("#login_password").val("");
	        	$('#login_error_text').html(data);
	        }
	    }
	});
	return false;
}

function swapHTMLAddLoginContent(returned_username)
{
	//Overall Page
	$('#nav-register').attr("id","nav-profile");
	$('#nav-profile').attr('href', g_remote + '/user/' + returned_username);
	$('#nav-profile').html("Profile");
	$("#nav-login").unbind('click');
	$('#nav-login').attr("id","nav-logout");
	$('#nav-logout').html("Log Out");
	$('#nav-logout').attr('href', g_remote + '/logout.php/');
	
	//EJPaint
	if($("#my_paintings_links_span").length != 0)
	{
		$('#my_paintings_links_span').html("<a class='ejbutton' href='" + g_remote + "/user/" + returned_username + "/paintings'>My Paintings</a> <a class='ejbutton' href='" + g_remote + "/user/" + returned_username + "/saved_paintings'>My Saved Paintings</a>");
	}
	
	//EJPlay
	if($("#my_songs_links_span").length != 0)
	{
		$('#my_songs_links_span').html("<a class='ejbutton' href='" + g_remote + "/user/" + returned_username + "/songs'>My Songs</a> <a class='ejbutton' href='" + g_remote + "/user/" + returned_username + "/saved_songs'>My Saved Songs</a>");
	}
	
	//EJStory
	if($("#my_stories_links_span").length != 0)
	{
		$('#my_stories_links_span').html("<a class='ejbutton' href='" + g_remote + "/user/" + returned_username + "/stories'>My Stories</a>");
	}
	
	//Comments
	if($("#comment_div").length != 0)
	{
		reloadCommentDiv();
	}
	
	setTimeout(hideLoginBox, 200);
}

function myjshtmlspecialchars(input_string)
{
	//var new_str = input_string.replace(new RegExp( "&(?!amp;)", "g" ), "&amp;"); //ampersand, but not already existing &amp;
	var new_str = input_string.replace(new RegExp( "&", "g" ), "&amp;"); //all ampersands -->validating pure user input
	new_str = new_str.replace(new RegExp( "<", "g" ), "&lt;"); //less than
	new_str = new_str.replace(new RegExp( ">", "g" ), "&gt;"); //greater than
	new_str = new_str.replace(new RegExp( "\"", "g" ), "&quot;"); //double quote
	new_str = new_str.replace(new RegExp( "'", "g" ), "&#039;"); //single quote
	return new_str;
}

/*
 //Not using the myjshtmlspecialchars_decode function at this time.
function myjshtmlspecialchars_decode(input_string)
{
	var new_str = input_string.replace(new RegExp( "&amp;", "g" ), "&"); //ampersand, but not already existing &amp;
	new_str = new_str.replace(new RegExp( "&lt;", "g" ), "<"); //less than
	new_str = new_str.replace(new RegExp( "&gt;", "g" ), ">"); //greater than
	new_str = new_str.replace(new RegExp( "&quot;", "g" ), "\""); //double quote
	new_str = new_str.replace(new RegExp( "&#039;", "g" ), "'"); //single quote
	return new_str;
}
*/

function newLineToBr(the_string)
{
	return the_string.replace(new RegExp( "\\n", "g" ), "<br />");
}

/*
 //Not currently used, but worth keeping
function spaceToNBSP(the_string)
{
	//Do not replace single spaces - but do replace double, triple, etc. spaces - with &nbsp;
	return the_string.replace(/(<=\s)\x20|\x20(?=\s)/g, "&nbsp;");
}
*/

function timestampToRelativeTimeString(timestamp)
{
	var now = Math.round(new Date().getTime()/1000);
	var timeDifference = now-timestamp;
	
	if (timeDifference<60)//< 1 min
		{
			if(timeDifference == 1)
			{
				timeDescriptionWord = " second ago ";
			}
			else
			{
				timeDescriptionWord = " seconds ago ";
			}
		}
		else if (timeDifference<60*60)//< 60 mins
		{
			timeDifference = Math.round(timeDifference/60);
			if(timeDifference == 1)
			{
				timeDescriptionWord = " minute ago ";
			}
			else
			{
				timeDescriptionWord = " minutes ago ";
			}
		}
		else if (timeDifference<60*60*24)//< 1 day
		{
			timeDifference = Math.round(timeDifference/3600);
			if(timeDifference == 1)
			{
				timeDescriptionWord = " hour ago ";
			}
			else
			{
				timeDescriptionWord = " hours ago ";
			}
		}
		else if (timeDifference<60*60*24*7)//< 7 days 
		{
			timeDifference = Math.round(timeDifference/86400);
			if(timeDifference == 1)
			{
				timeDescriptionWord = " day ago ";
			}
			else
			{
				timeDescriptionWord = " days ago ";
			}
		}
		else if (timeDifference<60*60*24*31)//< 31 days (this will be a rough estimate for months)
		{
			timeDifference = Math.round(timeDifference/604800);
			if(timeDifference == 1)
			{
				timeDescriptionWord = " week ago ";
			}
			else
			{
				timeDescriptionWord = " weeks ago ";
			}
		}
		else if (timeDifference<60*60*24*365)//< 365 days (1 year)
		{
			timeDifference = Math.round(timeDifference/2629744); //this will convert to months using a rough average of all of the months.
			if(timeDifference == 1)
			{
				timeDescriptionWord = " month ago ";
			}
			else
			{
				timeDescriptionWord = " months ago ";
			}
		}
		else
		{
			timeDifference = Math.round(timeDifference/31556926); //this will convert to months using a rough average of the last 100 or so years, taking into account leap year differences.
			if(timeDifference == 1)
			{
				timeDescriptionWord = " year ago ";
			}
			else
			{
				timeDescriptionWord = " years ago ";
			}
		}
	
	return (timeDifference + timeDescriptionWord);
}

//From http://www.webtoolkit.info/ - Original code by Angel Marin, Paul Johnston.
function SHA256(s){
 
	var chrsz   = 8;
	var hexcase = 0;
 
	function safe_add (x, y) {
		var lsw = (x & 0xFFFF) + (y & 0xFFFF);
		var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
		return (msw << 16) | (lsw & 0xFFFF);
	}
 
	function S (X, n) { return ( X >>> n ) | (X << (32 - n)); }
	function R (X, n) { return ( X >>> n ); }
	function Ch(x, y, z) { return ((x & y) ^ ((~x) & z)); }
	function Maj(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)); }
	function Sigma0256(x) { return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); }
	function Sigma1256(x) { return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); }
	function Gamma0256(x) { return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); }
	function Gamma1256(x) { return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); }
 
	function core_sha256 (m, l) {
		var K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2);
		var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);
		var W = new Array(64);
		var a, b, c, d, e, f, g, h, i, j;
		var T1, T2;
 
		m[l >> 5] |= 0x80 << (24 - l % 32);
		m[((l + 64 >> 9) << 4) + 15] = l;
 
		for ( var i = 0; i<m.length; i+=16 ) {
			a = HASH[0];
			b = HASH[1];
			c = HASH[2];
			d = HASH[3];
			e = HASH[4];
			f = HASH[5];
			g = HASH[6];
			h = HASH[7];
 
			for ( var j = 0; j<64; j++) {
				if (j < 16) W[j] = m[j + i];
				else W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);
 
				T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
				T2 = safe_add(Sigma0256(a), Maj(a, b, c));
 
				h = g;
				g = f;
				f = e;
				e = safe_add(d, T1);
				d = c;
				c = b;
				b = a;
				a = safe_add(T1, T2);
			}
 
			HASH[0] = safe_add(a, HASH[0]);
			HASH[1] = safe_add(b, HASH[1]);
			HASH[2] = safe_add(c, HASH[2]);
			HASH[3] = safe_add(d, HASH[3]);
			HASH[4] = safe_add(e, HASH[4]);
			HASH[5] = safe_add(f, HASH[5]);
			HASH[6] = safe_add(g, HASH[6]);
			HASH[7] = safe_add(h, HASH[7]);
		}
		return HASH;
	}
 
	function str2binb (str) {
		var bin = Array();
		var mask = (1 << chrsz) - 1;
		for(var i = 0; i < str.length * chrsz; i += chrsz) {
			bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);
		}
		return bin;
	}
 
	function Utf8Encode(string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	}
 
	function binb2hex (binarray) {
		var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
		var str = "";
		for(var i = 0; i < binarray.length * 4; i++) {
			str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
			hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
		}
		return str;
	}
 
	s = Utf8Encode(s);
	return binb2hex(core_sha256(str2binb(s), s.length * chrsz));
 
}

function promptToClose()
{
	if(clickedOnApp == true)
	{
  		return ("If you close this page, you will lose any unsaved changes.");
	}
}

function setClickedOnAppToTrue()
{
	window.clickedOnApp = true;
}

function setClickedOnAppToFalse()
{
	window.clickedOnApp = false;
}

//Message cookie checking function used for site-wide informational messages
//Function based on http://www.elated.com/articles/javascript-and-cookies/

function cookie_isset(cookie_name)
{
  var result = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if (result)
  {
    return true;
  }
  else
  {
    return false;
  }
}

//** Comment JS *//

function rebindCommentEventHandlers()
{
	$(".login_link").unbind('click.comment_handlers');
	$("#comment_textarea").unbind('keypress.comment_handlers');
	$("#comment_textarea").unbind('keyup.comment_handlers');
	$("#submit_comment_button").bind('click.comment_handlers');
	$(".comment_prev_link").unbind('click.comment_handlers');
	$(".comment_next_link").unbind('click.comment_handlers');
	$('.c_delete_link').bind('click.comment_handlers');
	
	bindCommentEventHandlers();
}

function bindCommentEventHandlers()
{
	if($(".login_link").length != 0)
	{
		$(".login_link").bind('click.comment_handlers', showOrHideLoginBox);
	}
	
	//Add comment textarea char count updaters
	if($('#comment_textarea').length != 0)
	{		
		//Immediately update char counts:
		$("#comment_textarea").parent().children("#comment_box_char_count").html((max_comment_textarea_length-($("#comment_textarea").val().length)) + ' Characters Left');
		
		//Then bind a function that continues to update the char counts:
		$("#comment_textarea").bind('keypress.comment_handlers keyup.comment_handlers', function(){
			var chars_left = max_comment_textarea_length-($("#comment_textarea").val().length);
			
			if(chars_left < 0)
			{
				//Crop to max_profile_info_textarea_length
				$("#comment_textarea").val($("#comment_textarea").val().substring(0, max_comment_textarea_length));
				chars_left = 0;
			}
			
			$("#comment_textarea").parent().children("#comment_box_char_count").html((chars_left) + ' Characters Left');
		});
		
		
		//And then add stuff for the submit_comment_button
		$("#submit_comment_button").bind('click.comment_handlers', function(){
			
			var the_comment_text = $("#comment_textarea").val();
			var error = -1;
			
			if(the_comment_text.length == 0)
			{
				error = "You need to enter some text before submitting this comment.";
			}
			else if(the_comment_text.length > max_comment_textarea_length)
			{
				error = "Comments can only have a maximum of " + max_comment_textarea_length + " characters. Your comment currently has " + the_comment_text.length + " characters."
			}
			
			if(error == -1)
			{
				$.ajax({
					url: g_remote + '/comment_stuff/add_comment.php',
					type: 'POST',
					data: {js:true, comment_text:the_comment_text, comment_type:window.comment_type, comment_parent_id:window.comment_parent_id},
					dataType: 'text',
					timeout: 10000,
					error: function(){
						alert('There was an error connecting to the server.');
					},
					success: function(data){
						if(data == 'true')
						{
							reloadCommentDiv();
							//And update the current comment count, if there's a printed comment count on the page
							if($("#com_count_container").length != 0)
							{
								//parseInt parses the first int in the string
								var com_num = parseInt($("#com_count_container").html());
								com_num++;
								$("#com_count_container").html(com_num + (com_num == 1 ? ' Comment' : ' Comments'));
							}
						}
						else
						{
							//Check if error_div already exists within the form
							if($('#comment_textarea').siblings(".error_div").length != 0)
							{
							$('#comment_textarea').siblings(".error_div").html(data);
							}
							else
							{
								$("#comment_textarea").parent().prepend("<div class='error_div'>" + data + "</div>")
							}
						}
					}
				});
			}
			else
			{
				//Check if error_div already exists within the form
				if($('#comment_textarea').siblings(".error_div").length != 0)
				{
				$('#comment_textarea').siblings(".error_div").html(error);
				}
				else
				{
					$("#comment_textarea").parent().prepend("<div class='error_div'>" + error + "</div>")
				}
			}
			
			return false;
		});
		
		//If there are any delete comment links, add click handlers for them too
		if($('.c_delete_link').length != 0)
		{
			$('.c_delete_link').bind('click.comment_handlers', function(){
				if(confirm("Are you sure that you want to delete this comment?\n\nThis action cannot be undone."))
				{
					var the_comment_id = $(this).attr('name');
					
					var comment_to_delete = $(this).parent().parent().parent();
					comment_to_delete.css('opacity', .5);
					
					$.ajax({
						url: g_remote + '/comment_stuff/delete_comment.php',
						type: 'POST',
						data: {js:true, comment_id:the_comment_id, comment_type:window.comment_type, comment_parent_id:window.comment_parent_id, page:window.page},
						dataType: 'text',
						timeout: 10000,
						error: function(){
							alert('There was an error connecting to the server.');
						},
						success: function(data){
							//And update the current comment count, if there's a printed comment count on the page
							if(data == 'true' && $("#com_count_container").length != 0)
							{
								//parseInt parses the first int in the string
								var com_num = parseInt($("#com_count_container").html());
								if(com_num > 0)
								{
									com_num--;
								}
								$("#com_count_container").html(com_num + (com_num == 1 ? ' Comment' : ' Comments'));
							}
							
							reloadCommentDiv();
						}
					});
				}
				
				return false;
			});
		}
		
		//Comment prev link handler
		if($('.comment_prev_link').length != 0)
		{
			$(".comment_prev_link").bind('click.comment_handlers', function(){
				$("#comment_stack").css('opacity', .5);
				
				if(window.page > 1)
				{
					window.page--;
				}
				reloadCommentDiv();
				
				return false;
			});
		}
		
		//Comment next link handler
		if($('.comment_next_link').length != 0)
		{
			$(".comment_next_link").bind('click.comment_handlers', function(){
				$("#comment_stack").css('opacity', .5);
				
				window.page++;
				reloadCommentDiv();
				
				return false;
			});
		}
	}
}

function reloadCommentDiv()
{
	$.ajax({
		url: g_remote + '/comment_stuff/get_comment_div_contents.php',
		type: 'POST',
		data: {comment_type:window.comment_type, comment_parent_id:window.comment_parent_id, page:window.page, ejpaint_replay_page:window.ejpaint_replay_page},
		dataType: 'text',
		timeout: 10000,
		error: function(){
			alert('There was an error connecting to the server.');
		},
		success: function(data){
			$("#comment_stack").css('opacity', 1); //not actually required (new html is generated), but possibly here for the future
			$("#comment_div").html(data);
			rebindCommentEventHandlers();
		}
	});
}

//JSON-parsing code (json-sans-eval) from: http://code.google.com/p/json-sans-eval/
window.jsonParse=function(){var r="(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)",k='(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';k='(?:"'+k+'*")';var s=new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|"+r+"|"+k+")","g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),u={'"':'"',"/":"/","\\":"\\",b:"\u0008",f:"\u000c",n:"\n",r:"\r",t:"\t"};function v(h,j,e){return j?u[j]:String.fromCharCode(parseInt(e,16))}var w=new String(""),x=Object.hasOwnProperty;return function(h,
j){h=h.match(s);var e,c=h[0],l=false;if("{"===c)e={};else if("["===c)e=[];else{e=[];l=true}for(var b,d=[e],m=1-l,y=h.length;m<y;++m){c=h[m];var a;switch(c.charCodeAt(0)){default:a=d[0];a[b||a.length]=+c;b=void 0;break;case 34:c=c.substring(1,c.length-1);if(c.indexOf("\\")!==-1)c=c.replace(t,v);a=d[0];if(!b)if(a instanceof Array)b=a.length;else{b=c||w;break}a[b]=c;b=void 0;break;case 91:a=d[0];d.unshift(a[b||a.length]=[]);b=void 0;break;case 93:d.shift();break;case 102:a=d[0];a[b||a.length]=false;
b=void 0;break;case 110:a=d[0];a[b||a.length]=null;b=void 0;break;case 116:a=d[0];a[b||a.length]=true;b=void 0;break;case 123:a=d[0];d.unshift(a[b||a.length]={});b=void 0;break;case 125:d.shift();break}}if(l){if(d.length!==1)throw new Error;e=e[0]}else if(d.length)throw new Error;if(j){var p=function(n,o){var f=n[o];if(f&&typeof f==="object"){var i=null;for(var g in f)if(x.call(f,g)&&f!==n){var q=p(f,g);if(q!==void 0)f[g]=q;else{i||(i=[]);i.push(g)}}if(i)for(g=i.length;--g>=0;)delete f[i[g]]}return j.call(n,
o,f)};e=p({"":e},"")}return e}}();

//** Home Page Animation Code **//

function preloadAndAnimateHomePageLatestContent()
{
	//Preload the specified EJPaint images (to avoid delays/flashes)
	for(var i = 0; i < recent_paintings_arr.length; i++)
	{
		var tempImage = new Image();
		tempImage.src = g_remote + "/ejpaint/" + window.recent_paintings_arr[i]['image_larger_thumb'];
	}
	
	//Set up counters and array length counts
	window.recent_paintings_arr_counter = recent_paintings_arr.length-1;
	window.num_home_page_paintings_in_loop = recent_paintings_arr.length;
	
	window.recent_songs_arr_counter = recent_songs_arr.length-1;
	window.num_home_page_songs_in_loop = recent_songs_arr.length;
	
	window.recent_stories_arr_counter = recent_stories_arr.length-1;
	window.num_home_page_stories_in_loop = recent_stories_arr.length;
	
	//Set the intervals for repeated function calls
	setInterval(displayNextHomePagePainting, 4300);
	setInterval(displayNextHomePageSong, 4000);
	setInterval(displayNextHomePageStory, 4600);
}

function displayNextHomePagePainting()
{
	if(window.recent_paintings_arr_counter == 0)
	{
		window.recent_paintings_arr_counter = window.num_home_page_paintings_in_loop;
	}
	
	//Image And Link Swap Code
	$(".home_latest_painting").each(function(index){
		var painting_arr_index = index + (window.recent_paintings_arr_counter%window.num_home_page_paintings_in_loop);
		if(painting_arr_index >= window.num_home_page_paintings_in_loop)
		{
			//Keep the counter small.
			painting_arr_index = painting_arr_index-window.num_home_page_paintings_in_loop;
		}
		
		$(this).delay(index*300).animate({
			'opacity': '0'
		  }, 500, function() {
			// Fade Out Animation Complete!
			
			//Change attributes
			$(this).attr('src', g_remote + "/ejpaint/" + window.recent_paintings_arr[painting_arr_index]['image_larger_thumb']);
			$(this).parent().attr('href', g_remote + "/ejpaint/view_painting.php?image_id=" + window.recent_paintings_arr[painting_arr_index]['image_id']);
			//Fade Back In!
			$(this).animate({
				'opacity': '1'
			  }, 500, function() {
				// Animation complete.
			});
		});
	});
	
	window.recent_paintings_arr_counter--;	
}

function displayNextHomePageSong()
{
	if(window.recent_songs_arr_counter == 0)
	{
		window.recent_songs_arr_counter = window.num_home_page_songs_in_loop;
	}
	
	$(".home_ejplay_table tr td div").each(function(index){
		
		var song_arr_index = index + (window.recent_songs_arr_counter%window.num_home_page_songs_in_loop);
		if(song_arr_index >= window.num_home_page_songs_in_loop)
		{
			//Keep the counter small.
			song_arr_index = song_arr_index-window.num_home_page_songs_in_loop;
		}
		
		$(this).delay(index*200).animate({
			'opacity': '0'
		  }, 200, function() {
			// Fade Out Animation Complete!
			
			$(this).html("<a href='" + g_remote + "/ejplay/play_song.php?song_id=" + window.recent_songs_arr[song_arr_index]['song_id'] + "'>" + window.recent_songs_arr[song_arr_index]['song_title'] + "</a>");
			
			//Fade Back In!
			$(this).animate({
				'opacity': '1'
			  }, 200, function() {
				// Animation complete.
			});
		});
	});
	
	window.recent_songs_arr_counter--;
}

function displayNextHomePageStory()
{
	if(window.recent_stories_arr_counter == 0)
	{
		window.recent_stories_arr_counter = window.num_home_page_stories_in_loop;
	}
	
	$(".home_latest_story").each(function(index){
		
		var story_arr_index = index + (window.recent_stories_arr_counter%window.num_home_page_stories_in_loop);
		if(story_arr_index >= window.num_home_page_stories_in_loop)
		{
			//Keep the counter small.
			story_arr_index = story_arr_index-window.num_home_page_stories_in_loop;
		}
		
		$(this).delay(index*200).animate({
			'opacity': '0'
		  }, 200, function() {
			// Fade Out Animation Complete!
			
			$(this).html("<div><a href='" + g_remote + "/ejstory/view_story.php?story_id=" + window.recent_stories_arr[story_arr_index]['story_id'] + "'>" + window.recent_stories_arr[story_arr_index]['title'] + "</a></div><div>" + window.recent_stories_arr[story_arr_index]['description'] + "</div><div>Last Modified By: <a href='" + g_remote + "/user/" + window.recent_stories_arr[story_arr_index]['last_modified_by'] + "'>" + window.recent_stories_arr[story_arr_index]['last_modified_by'] + "</a></div>");
			
			//Fade Back In!
			$(this).animate({
				'opacity': '1'
			  }, 200, function() {
				// Animation complete.
			});
		});
	});
	
	window.recent_stories_arr_counter--;
}
