var isIE;
var loginDisplayed;
var lkoginDiv;
var lastSearchQuery;



/**
 * Initializes the page, objects, and actions.
 */
function init()
{
	// later used for ie compatibility
	isIE = (document.getElementsByTagName("body")[0].textContent == undefined);
	loginDisplayed = false;
	//signup, login events
	$('btnregister').onclick = popSignUp;
	$('btnlogin').onclick = popLogin;
	//updateLatest(0, 1, 9); // 0 means all, 1 means first page, 9 means # of rows per page
	//updateRandomClips(4);
	//popSignUp();
	initLoginDiv();
	attachSearchBoxActions();
	attachMenuActions();
	attachSubmenuActions()
	updateDidYouKnow();
	collapseSubmenus();
	populateTopSearches();
	displayMenu(false);
	createUserMenu();
	$('switch').onclick = siteOff;
	document.onclick = function() { displayMenu(false); }
	attachUserMenuActions();
}

function attachUserMenuActions()
{
	$('uname').onmouseover = function() { displayMenu(true); }	
}

function initVideoPage(tags)
{
	if (!$('moviepage')) return;

	$('centercol').appendChild($('moviepage'));
	$('up').onclick = clickUp;
	$('down').onclick = clickDown;
	$('postcommentbutton').onclick = postComment;
	
	// Insert the right column infobox.
	var rightcol = $('rightcol')
	var infobox = $('right_col_infobox');
	rightcol.insertBefore(infobox, rightcol.childNodes[0]);

	// Populate tags.
	var arrTags = tags.split(" ");
//	alert(arrTags);

	for (var i = 0; i < arrTags.length-1; ++i) 
	{
		addTag(arrTags[i]);
		$('infobox_tagspan').innerHTML += ' ';
	}
	
	showComments();

	$('watchUrlField').value = window.location;
	$('watchUrlField').onclick = function() { this.select(); }

	var vidUrl = encodeURIComponent(window.location);
	var desc = $('movie_description').innerHTML;
	var vidTitle = $('movie_title').innerHTML;

	var diggUrl = "http://digg.com/submit?url=" + vidUrl + "&title=" + vidTitle + "&bodytext=" + desc + "&media=video&topic=odd_stuff";
	var googleUrl = "http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk=" + vidUrl + "&title=" + vidTitle;
	var deliciousUrl = "http://del.icio.us/post?url=" + vidUrl + "&title=" + vidTitle;
	var facebookUrl = "http://www.facebook.com/share.php?u=" + vidUrl + "&t=" + vidTitle;
	var myspaceUrl = "http://www.myspace.com/Modules/PostTo/Pages/?u=" + vidUrl + "&t=" + vidTitle + "&c=" + desc;
	var liveUrl = "https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url=" + vidUrl + "&title=" + vidTitle + "&top=1";
	var yahooUrl = "http://bookmarks.yahoo.com/toolbar/savebm?opener=tb&u=" + vidUrl + "&d=" + desc;
	var stumbleUrl = "http://www.stumbleupon.com/submit?url=" + vidUrl + "&title=" + vidTitle;
	
	$('linkDownload').onclick = function() { window.open(window.location + '.flv', "Download", "menubar=no,width=1,height=1,toolbar=no,scrollbars=no"); }
	$('linkDigg').onclick = function() { window.open(diggUrl, "Digg", "menubar=no,width=1024,height=500,toolbar=no,scrollbars=yes"); }
	$('linkGoogle').onclick = function() { window.open(googleUrl, "GoogleBookmark", "menubar=no,width=1024,height=500,toolbar=no,scrollbars=yes"); }
	$('linkDelicious').onclick = function() { window.open(deliciousUrl, "Delicious", "menubar=no,width=1024,height=500,toolbar=no,scrollbars=yes"); }
	$('linkFacebook').onclick = function() { window.open(facebookUrl, "FacebookShare", "menubar=no,width=1024,height=500,toolbar=no,scrollbars=yes"); }
	$('linkMyspace').onclick = function() { window.open(myspaceUrl, "MyspacePost", "menubar=no,width=1024,height=500,toolbar=no,scrollbars=yes"); }
	$('linkLive').onclick = function() { window.open(liveUrl, "LiveFavorites", "menubar=no,width=1024,height=500,toolbar=no,scrollbars=yes"); }
	$('linkYahoo').onclick = function() { window.open(yahooUrl, "YahooBookmark", "menubar=no,width=1024,height=500,toolbar=no,scrollbars=yes"); }
	$('linkStumbleupon').onclick = function() { window.open(stumbleUrl, "StumbleThis", "menubar=no,width=1024,height=500,toolbar=no,scrollbars=yes"); }
	$('linkBookmark').onclick = bookmark;
}

function addTag(tag)
{
	var theA = document.createElement('a');
	theA.href = '/videos/search/' + tag;
	theA.innerHTML = tag;
	$('infobox_tagspan').appendChild(theA);
}

function initLoginDiv()
{
	loginDiv = $('loginbox');
	$('close').onclick = closeLoginDiv;
	$('login').onclick = login;
	$('signupUname').onkeypress = function(event)
	{
		if (event.keyCode == 13) // enter pressed
			login();
	};
	
	$('signupPwd').onkeypress = $('signupUname').onkeypress;
	
	
	$('home').removeChild($('loginbox'));
}

function clickUp()
{
	new Ajax.Request("/rateVideos.php",
	{
		method: "post",
		parameters:
		{
			action: "up"
		},
		onSuccess: function(transport)
		{
			processClickUp(transport);
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

function processClickUp(transport)
{
	var result = transport.responseText;
	if (result == 'UnregisteredUserException')
	{
		alert('Please log in before rating this video.');
	}
	else if (result == 'UnidentifiedVideoException')
	{
		alert('Something went wrong!');
	}
	else if (result == 'AlreadyRatedException')
	{
		alert("You can't give your rating more than once per video. Sorry!");
	}
	else
	{
		var totalUps = $('totalthumbsup_number');
		var sign = totalUps.innerHTML.substr(0, 1);
		var currTotalThumbsup = parseInt(totalUps.innerHTML.substr(2));
		if (sign == '+')
		{
			totalUps.innerHTML = "+ " + (currTotalThumbsup + 1);
		}
		else
		{
			var newTotalThumbsup = -currTotalThumbsup + 1;
			if (newTotalThumbsup == 0)
			{
				totalUps.innerHTML = "+ 0";
			}
			else if (newTotalThumbsup > -1)
			{
				totalUps.innerHTML = "+ " + (currTotalThumbsup + 1);
			}
			else
			{
				totalUps.innerHTML = "- " + (currTotalThumbsup - 1);
			}
		}
		$('infoUserRating').innerHTML = totalUps.innerHTML;
	}
}

function clickDown()
{
	new Ajax.Request("/rateVideos.php",
	{
		method: "post",
		parameters: {
			action: "down"
		},
		onSuccess: function(transport)
		{
			processClickDown(transport);
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

function processClickDown(transport)
{
	var result = transport.responseText;
	if (result == 'UnregisteredUserException')
	{
		alert('Please log in before rating this video.');
	}
	else if (result == 'UnidentifiedVideoException')
	{
		alert('Something went wrong!');
	}
	else if (result == 'AlreadyRatedException')
	{
		alert("You can't give your rating more than once per video. Sorry!");
	}
	else
	{
		var totalUps = $('totalthumbsup_number');
		var sign = totalUps.innerHTML.substr(0, 1);
		var currTotalThumbsup = parseInt(totalUps.innerHTML.substr(2));
		if (sign == '+')
		{
			if (currTotalThumbsup == 0)
				totalUps.innerHTML = "- 1";
			else
				totalUps.innerHTML = "+ " + (currTotalThumbsup - 1);
		}
		else
		{
			var newTotalThumbsup = -currTotalThumbsup - 1;
			totalUps.innerHTML = "- " + -(newTotalThumbsup);
		}
		$('infoUserRating').innerHTML = totalUps.innerHTML;
	}
}

/**
 * Sends login info to authenticate.php
 */
function login()
{
	this.blur();
	var uname = hex_md5($('loginboxcontent').signupUname.value);
	var pwd = hex_md5($('loginboxcontent').signupPwd.value);
	var pRemember = parseInt($('remember').checked ? 1 : 0);
	
	//alert('uname: ' + uname);
	//alert('pwd: ' + pwd);
	var url = "/authenticate.php";

	new Ajax.Request(url,
	{
		method: "post",
		parameters: {
			username: uname,
			response: pwd,
			remember: pRemember
		},
		onSuccess: function(transport)
		{
			processLogin(transport);
			attachUserMenuActions();
			$('userbar').appendChild($('usermenu'));
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

/**
 * Actually processes login.
 * result == 1 means admin
 * result  > 1 means regular user
 * result == 0 means login failed 
 */
function processLogin(transport)
{
	var uid = parseInt(transport.responseText);
	var uname = transport.responseText.split(':')[1];
	//alert(uid);
	if (uid > 0)
	{
		// Get rid of the stuff in login box
		closeLoginDiv();
		$('loginbar').style.display = 'none';
		var userprofilebox = $('user_profile_box');
		var divUserbar = document.createElement('div');
		var divUname = document.createElement('span');
		divUserbar.id = 'userbar';
		divUname.id = 'uname';
		divUname.innerHTML = uname;
		divUserbar.innerHTML += 'Welcome, ';
		divUserbar.appendChild(divUname);
		divUserbar.innerHTML += '!';
		attachUserMenuActions()
		
		userprofilebox.insertBefore(divUserbar, userprofilebox.childNodes[0]);
	}
	else
	{
		alert("User does not exist or the password is incorrect.");
		return;
	}
}

/**
 * Updates div#latest with the search results
 */
function doSearch(query, pageno)
{
	updateLatestVideos(0, pageno, 9, query);
}

/**
 * Ajax call for XML to update the #latest div of the main page.
 */
function updateLatestVideos(pCategory, pPage, pRowsPerPage, pQuery)
{
//	alert(pCategory + ', ' + pPage + ', ' + pRowsPerPage + ', ' + pQuery);
//	alert(pCategory + ', ' + pPage + ', ' + pRowsPerPage + ', ' + pQuery);
	if ($('right_col_infobox'))
		$('rightcol').removeChild($('right_col_infobox'));
	
	new Ajax.Request('/catalog.php',
	{
		method: "get",
		parameters: {
			category:		pCategory,
			pageno:			pPage,
			rowsPerPage:	pRowsPerPage,
			query:			pQuery
		},
		onSuccess: function(transport)
		{
			delayForIE(function() { processUpdateLatestVideos(transport, pPage, pCategory, pQuery); });
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

/**
 * Parses XML generated by catalog.php to populate the #latest div.
 */
function processUpdateLatestVideos(transport, curPage, category, query)
{
	var result = transport.responseXML;
	if (!result)
	{
		alert("Could not retrieve video listing!");
		return;
	}
	var videos = result.getElementsByTagName("videos")[0];
	if (!videos)
	{
		alert("No videos to list!");
		return;
	}
	
	// Remove any possibly existing .movie divs
	removeChildren($('centercol'))
	var divLatest = document.createElement('div');
	divLatest.id = 'latest';
	divLatest.className = category + 'videos';
	$('centercol').appendChild(divLatest);

	videoClips = videos.getElementsByTagName("video");
	var video;
	for (var i = 0; video = videoClips[i]; ++i)
	{
		var vid = video.getAttribute('vid');
		var timestamp = convertTimestamp(video.getAttribute('timestamp'));
		var category = video.getAttribute('category');
		var thumbsup = video.getAttribute('thumbsup');
		var thumbsdown = video.getAttribute('thumbsdown');
		var views = video.getAttribute('views');
		var filename = video.getAttribute('filename');
		// (isIE) ? FF : IE
		var vidtitle = (isIE) ? video.getElementsByTagName('title')[0].text : video.getElementsByTagName('title')[0].textContent;
		var desc = (isIE) ? video.getElementsByTagName('description')[0].text : video.getElementsByTagName('description')[0].textContent;
		var vidurl = '/videos/' + getCatName(category)
			+ '/' /*+ timestamp.getFullYear() + '/' + (timestamp.getMonth()) + '/' */ + filename;
		var thumbsrc = '/thumbs/' + getCatName(category)
			+ '/' /* + timestamp.getFullYear() + '/' + (timestamp.getMonth()) + '/' */ + filename + '.jpg';
		var comments = video.getAttribute('comments');

		var thediv = document.createElement('div');
		thediv.className = 'movie';

		var aThumb = document.createElement('a');
		aThumb.href = vidurl;
		aThumb.className = 'thumbnail_link';
		var thumb = document.createElement('img');
		var daysSinceFeatured = ago(timestamp);
		thumb.className = 'thumb';
		thumb.src = thumbsrc;
		thumb.alt = vidtitle;
		thumb.title = vidtitle;
		aThumb.appendChild(thumb);

		var p1 = document.createElement('p');
		var strongtitle = document.createElement('strong');
		strongtitle.className = "moviethumb_title"
		strongtitle.innerHTML = "<a href='" + vidurl + "'>" + vidtitle + "</a>";
		var spancategory = document.createElement('span');
		spancategory.innerHTML = "Category: ";
		var cat = document.createElement('span');
		cat.className = 'category';
		cat.innerHTML = getHumanFriendlyCatName(category);
		var spanfeatured = document.createElement('span');
		spanfeatured.innerHTML = 'Featured: ';
		var featured = document.createElement('span');
		featured.className = 'time_posted';
		featured.innerHTML = formatDaysAgo(daysSinceFeatured);
		var pDesc = document.createElement('p');
		pDesc.className = "movie_description"
		pDesc.innerHTML = '<br />' + desc;
		p1.appendChild(strongtitle);
		p1.innerHTML += "<br />";
		p1.appendChild(spancategory);
		p1.appendChild(cat);
		p1.innerHTML += " | ";
		p1.appendChild(spanfeatured);
		p1.appendChild(featured);
		p1.appendChild(pDesc);
		var commentsAndUserRatings = document.createElement('span');
		commentsAndUserRatings.className = 'comments_and_userratings';
		var numComments = document.createElement('span');
		numComments.innerHTML = "Comments: ";
		numComments.className = 'numComments';
		var userrating = document.createElement('span');
		userrating.innerHTML = "User Rating: ";
		userrating.className = 'userRating';
		commentsAndUserRatings.appendChild(numComments);
		commentsAndUserRatings.innerHTML += comments + " | ";
		commentsAndUserRatings.appendChild(userrating);
		//p2.appendChild(numComments);
		//p2.innerHTML += comments + " | ";
		//p2.appendChild(userrating);

		var numRating = (thumbsup - thumbsdown);

		commentsAndUserRatings.innerHTML += ((numRating > 0) ? '+' : '') + numRating + " ";
		commentsAndUserRatings.innerHTML += " ";
		thediv.appendChild(aThumb);
		thediv.appendChild(p1);
		thediv.appendChild(commentsAndUserRatings);
		$('latest').appendChild(thediv);
	}
	$('latest').appendChild(getPagination(videos, curPage, 'videos', query));
	//$('latest').appendChild(pRightLink);
	//$('latest').appendChild(pLatestPicks);
}

/**
 * Ajax call for XML to update the #latest div of the main page.
 */
function updateRandomClips(limit)
{
	new Ajax.Request('/catalog.php',
	{
		method: "get",
		parameters: {
			rand:  limit
		},
		onSuccess: function(transport)
		{
			processUpdateRandom(transport);
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

/**
 * Parses XML generated by catalog.php to populate the #random_vids_clips div.
 */
function processUpdateRandom(transport)
{
	var result = transport.responseXML;
	if (!result)
	{
		alert("Could not retrieve video listing!");
		return;
	}
	var videos = result.getElementsByTagName("videos")[0];
	if (!videos)
	{
		alert("No videos to list!");
		return;
	}

	videos = videos.getElementsByTagName("video");
	var video;
	for (var i = 0; video = videos[i]; ++i)
	{
		
		var vid = video.getAttribute('vid');
		var timestamp = convertTimestamp(video.getAttribute('timestamp'));
		var category = video.getAttribute('category');
		var thumbsup = video.getAttribute('thumbsup');
		var thumbsdown = video.getAttribute('thumbsdown');
		var rating = thumbsup - thumbsdown;
		
		var views = video.getAttribute('views');
		var filename = video.getAttribute('filename');
		var vidtitle = (isIE) ? video.getElementsByTagName('title')[0].text : video.getElementsByTagName('title')[0].textContent;
		var desc = (isIE) ? video.getElementsByTagName('description')[0].text : video.getElementsByTagName('description')[0].textContent

		var vidurl = '/videos/' + getCatName(category)
			+ '/' /*+ timestamp.getFullYear() + '/' + (timestamp.getMonth()) + '/' */
			+ filename
		var thumbsrc = '/thumbs/' + getCatName(category)
			+ '/' /* + timestamp.getFullYear() + '/' + (timestamp.getMonth()) + '/' */
			+ filename + 'RC.jpg';

		var divRandomVidsClip = document.createElement('div');
			divRandomVidsClip.className = 'random_vids_clip';
		var divBox = document.createElement('div');
			divBox.className = 'random_vids_clips_box';
			var alink = document.createElement('a');
				alink.href = vidurl;
			var thumbnail = document.createElement('img');
				thumbnail.src = thumbsrc;
			alink.appendChild(thumbnail);
			divBox.appendChild(alink);
		var aTitle = document.createElement('a');
			aTitle.className = 'random_vids_clips_title';
			aTitle.innerHTML = summarize(vidtitle, 25);
			aTitle.href = vidurl;
		var divStats = document.createElement('div');
			divStats.className = 'random_vids_clips_stats';
			var daysSinceFeatured = ago(timestamp);
			var temp = formatDaysAgo(daysSinceFeatured).split(' ');
			var spanDateAdded = document.createElement('span');
				spanDateAdded.className = 'random_date_added';
				spanDateAdded.innerHTML = temp[0];
			var spanRating = document.createElement('span');
				spanRating.classname = 'random_rating';
				spanRating.innerHTML = (rating < 0) ? -rating : rating;
			divStats.appendChild(spanDateAdded);
			divStats.innerHTML += ' ' + (temp[1] + ' ' + temp[2]) + ' |' + ((rating < 0) ? ' - ' : ' + ');
			divStats.appendChild(spanRating);
		var divDescription = document.createElement('div');
			divDescription.className = 'random_vids_clips_description';
			divDescription.innerHTML = summarize(desc, 100);
		
		divRandomVidsClip.appendChild(divBox);
		divRandomVidsClip.appendChild(aTitle);
		divRandomVidsClip.appendChild(divStats);
		divRandomVidsClip.appendChild(divDescription);
		//var divcaption = document.createElement('div');
		//divcaption.className = 'caption';
		//var pcaption = document.createElement('p');
		//var thea = document.createElement('a');
		//thea.href = vidurl; //video link
		//thea.innerHTML = desc;
		//pcaption.appendChild(thea);
		//divcaption.appendChild(pcaption);
		//thediv.appendChild(thumb);
		//thediv.appendChild(divcaption);
		$('random_vids_clips').appendChild(divRandomVidsClip);
	}
}

/**
 * Returns div#pagination of pagination strip
 */
function getPagination(xml, curPage, type, query)
{
	var curPage = parseInt(xml.getAttribute('curpage'));
	var lastPage = parseInt(xml.getAttribute('lastpage'));
	if (lastPage < 2) return;
	var theDiv = document.createElement('div');
	theDiv.id = 'pagination';
	var elipses = document.createElement('span');
	elipses.innerHTML = '...&nbsp;';
	elipses.id = 'elipses';
	var i;

	if (curPage > 5)
	{
		theDiv.appendChild(nthPageDiv(1, curPage, type, query));
		theDiv.appendChild(elipses);
		for (i = curPage - 3; i <= curPage && i < lastPage; ++i)
		{
			theDiv.appendChild(nthPageDiv(i, curPage, type));
		}
		for (i = curPage + 1; i <= curPage + 3 && i < lastPage; ++i)
		{
			theDiv.appendChild(nthPageDiv(i, curPage, type, query));
		}
	}
	else
	{
		for (i = 1; i <= curPage + 3 && i < lastPage; ++i)
		{
			theDiv.appendChild(nthPageDiv(i, curPage, type, query));
		}
	}
	if (curPage < lastPage - 4)
	{
		theDiv.appendChild(elipses.cloneNode(true));
	}
	theDiv.appendChild(nthPageDiv(lastPage, curPage, type, query));
	return theDiv;

}

/**
 * Returns span#npage .pages of the n-th page. 
 */
function nthPageDiv(n, curPage, type, query)
{                             
	var contentType = $('latest').className.replace(/[\-0-9]*/, '');
	var theSpan = document.createElement('span');
	theSpan.id = (n == curPage) ? "curpage" : n + "page";
	theSpan.className = 'pages';
	theSpan.innerHTML = n;
	theSpan.style.disabled = true;

	if (n != curPage && type == "videos")
	{
		if (query && query != '')
		{
			theSpan.onclick = function()
			{
				window.location = '/' + contentType + "/search/" + query + '/' + parseInt(n);
			}
		}
		else
		{
			theSpan.onclick = function()
			{
				window.location = "/" + contentType + '/' + getCatName($('latest').className) + "/" + parseInt(n);
			}
		}
	}
	else if (n != curPage && type == "comments")
	{
		theSpan.onclick = function()
		{
			showComments(parseInt(n));
		}
	}
	return theSpan;
}

/*
#################################
# 
#	Page View Rewrite 
#
# -2 : Most Viewed
# -1 : Editor's Picks
#  0 : All
#  1 : Cool
#  2 : Pwned
#  3 : Funny
#  4 : WTF
*/
function getCatName(n)
{
	switch (parseInt(n))
		{
		case -4: return 'top_rated';
		case -41: return 'top_rated_daily';
		case -42: return 'top_rated_weekly';
		case -43: return 'top_rated_monthly';
		case -3: return 'most_discussed';
		case -31: return 'most_discussed_daily';
		case -32: return 'most_discussed_weekly';
		case -33: return 'most_discussed_monthly';
		case -2: return 'most_viewed';
		case -21: return 'most_viewed_daily';
		case -22: return 'most_viewed_weekly';
		case -23: return 'most_viewed_monthly';
		case -1: return 'editors_picks';
		case 0 : return 'all';
		case 1 : return 'too_cool';
		case 2 : return 'pwned';
		case 3 : return 'funny';
		case 4 : return 'wtf';
	}
}

function getHumanFriendlyCatName(n)
{
	if (n == "editors_picks")
		return "editor's picks";
	else
		return getCatName(n).replace('_', ' ');
}

// Create a div overlay for a gray-ed out effect.
// Then, pop another div with stuff in it for sign-up (e.g., img verifier).
function popSignUp()
{
	divOverlay = document.createElement('div');
	divOverlay.id = 'divOverlay';
	divOverlay.style.position = 'fixed';
	divOverlay.style.width = '100%' //window.screen.width + 'px';
	divOverlay.style.height = '100%' //window.screen.height + 'px';
	divOverlay.style.left = '0px';
	divOverlay.style.top = '0px';
	divOverlay.style.backgroundColor = 'gray';
	divOverlay.className = 'trans50';

	$('home').appendChild(divOverlay);
	
	// registerbox contains the actual signup form
	var registerbox = $('registerbox');
	registerbox.className = 'trans75';
	registerbox.style.display = 'block';
	$('close_registerbox').onclick = closeSignupDiv;
	$('regRefreshButton').onclick = refreshAuthImg;
	$('regRegisterButton').onclick = signup;
	refreshAuthImg();

	$('home').appendChild(registerbox);

	disableMovieDiv(true);
}

function closeSignupDiv()
{
	$('registerbox').style.display = 'none';
	$('home').removeChild($('divOverlay'));
	disableMovieDiv(false);
}

function disableMovieDiv(doHide)
{
	var moviediv = $('moviediv');
	if (moviediv)
		$('moviediv').style.display = doHide ? 'none' : 'block';
}

function refreshAuthImg()
{
	$('authimg').setAttribute('src', '/authimg.php?x=' + Math.random());
	$('signupAuthImg').value = '';
}

function popLogin()
{
	var divOverlay = document.createElement('div');
	divOverlay.id = 'divOverlay';
	divOverlay.style.position = 'fixed';
	divOverlay.style.width = '100%'
	divOverlay.style.height = '100%'
	divOverlay.style.left = '0px';
	divOverlay.style.top = '0px';
	divOverlay.style.backgroundColor = 'gray';
	divOverlay.className = 'trans50';

	$('home').appendChild(divOverlay);
	$('home').appendChild(loginDiv);
	loginDiv.style.display = 'block';

	disableMovieDiv(true);
}

function closeLoginDiv()
{
	$('home').removeChild($('loginbox'));
	$('home').removeChild($('divOverlay'));
	disableMovieDiv(false);
}

function signup()
{
	var alphnumericRegex	= /^([a-zA-Z0-9_-]+){5,12}$/;
	var unameVerify 	= alphnumericRegex.test($('signupUname').value);
	var pwdVerify 		= alphnumericRegex.test($('signupPwd').value);
	var emailRegex 		= /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	var emailVerify 	= emailRegex.test($('signupEmail').value);
	var doubleDigitRegex 	= /^[0-9]{1,2}$/;
	var month		= parseInt($('signupDOBMonth').value);
	var day			= parseInt($('signupDOBDay').value);
	var year		= parseInt($('signupDOBYear').value);
	var monthVerify		= doubleDigitRegex.test(month);
	var dayVerify		= doubleDigitRegex.test(day);
	var fourDigitRegex	= /^[0-9]{4}$/;
	var yearVerify		= fourDigitRegex.test(year);
	var today		= new Date();

	displayStatusMessage('');
	if (!unameVerify)
	{
		displayStatusMessage('Username should be alphanumeric only! (5~12 chars)');
	}
	else if (!pwdVerify)
	{
		displayStatusMessage('Password should be alphanumeric only! (5~12 chars)');
	}
	else if ($('signupPwd').value != $('signupVerifyPwd').value)
	{
		displayStatusMessage('Please verify your password!');
	}
	else if (!emailVerify)
	{
		displayStatusMessage('Incorrect e-mail address format!');
	}
	else if (!(monthVerify && dayVerify && yearVerify) || (month < 1 || month > 12) || (day < 1 || day > 31) || year < 1900)
	{
		displayStatusMessage('Date of birth must be in the MM DD YYYY format');
	}
	else if (!(year < today.getFullYear() - 12 || (year == (today.getFullYear() - 12) && (month < today.getMonth() || (month == today.getMonth && day < today.getDate())))))
	{
		displayStatusMessage('You must be 13+ years sign up at WhatTheFudge.TV');
	}
	else if (!$('signupFemale').checked && !$('signupMale').checked)
	{
		displayStatusMessage('Please check either Male or Female for the gender.');
	}
	else if (!$('termscheck').checked)
	{
		displayStatusMessage('You must agree with the terms of service!');
	}
	else
	{
		signupAjax();
		return;
	}
	refreshAuthImg();
}

/**
 * Ajax call to registeruser.php
 */
function signupAjax()
{
	// image verified, so register
	var pUname = $('signupUname').value;
	var pPwd = hex_md5($('signupPwd').value);
	var pEmail = $('signupEmail').value;
	var pImgCode = $('signupAuthImg').value;

	new Ajax.Request('/registerUser.php',
	{
		method: "post",
		parameters: {
			uname:		pUname,
			pwd:		pPwd,
			email:		pEmail,
			imgcode:	pImgCode
		},
		onSuccess: function(transport)
		{
			processSignup(transport)
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

/**
 * responseText ==-1 means image verification failed
 * responseText == 0 means no user w/ same username (ignoring case) was found, so successful
 * responseText != 0 means there is a duplicate username, so fail.
 */
function processSignup(transport)
{
	if (transport.responseText == 1)
	{
		closeSignupDiv();
		alert('Thank you for registering! You can now log in to WhatTheFudge.TV.');
		return;
	}
	else if (transport.responseText == -1)
	{
		displayStatusMessage('Image verification failed! Please retry.');
	}
	else if (transport.responseText == -2)
	{
		displayStatusMessage($('signupUname').value + ' already exists!');
	}
	else if (transport.responseText == -3)
	{
		displayStatusMessage($('signupEmail').value + ' is already used!');
	}
	else
	{
		displayStatusMessage('Unknown error! Please try again. (refresh?)');
	}
	refreshAuthImg();
}

/**
 * Displays msg on #statusStrip and refreshes #authImg
 */
function displayStatusMessage(msg)
{
	$('statusStrip').innerHTML = msg;
}

/**
 * Shows video clip
 */
function showClip()
{
	var divMoviePage = Builder.node('div',
	{ id: 'moviepage' }, [
		Builder.node('div', { id: 'movie_title' }),
		Builder.node('div', { id: 'movie_description' }),
		Builder.node('div', { id: 'moviediv' })
	]);

	$('centercol').appendChild(divMoviePage);
	$('movie_title').innerHTML += 'Hello, World!';
	$('movie_description').innerHTML += 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam congue, dui aliquet viverra porttitor, lectus ante volutpat pede, in varius nisi massa ut elit. Phasellus at sem. Ut lacinia suscipit mauris. Nam scelerisque magna sit amet tellus. Aliquam tempus, lectus quis venenatis suscipit, velit massa auctor justo, vitae pulvinar nisl. <br /><br /> Duis vel quam. Sed dolor. Donec luctus tincidunt metus. Proin. ';
	$('moviediv').innerHTML += '<a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.';

	var s1 = new SWFObject("/player/mediaplayer.swf", "mediaplayer", "440", "354", "8");
	s1.addParam("allowfullscreen", "true");
	s1.addVariable("file", "/player/video.flv");
	s1.addVariable('callback', '/vidcallback.php?vid=1010');
	s1.write("moviediv");
}

function updateDidYouKnow()
{
	var url = '/randomfact.php?x=' + Math.random();
	new Ajax.Request(url,
	{
		method: "get",
		onSuccess: function(transport)
		{
			processUpdateDidYouKnow(transport);
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

function processUpdateDidYouKnow(transport)
{
	var result = transport.responseText.split("|");
	var imgfile = result[0];
	var fact = result[1];
	$('didyouknowimg').src = '/img/facts/' + imgfile + '.gif';
	$('randomfact').innerHTML = fact;
}

function attachSearchBoxActions()
{
	// make the search box have cool auto-focus effect =)
	var searchBox = $('searchBox');
	searchBox.value = 'Enter Search';

//	searchBox.onmouseout = function() {
	//		searchBox.blur();
	//		if (this.value=='')
	//			this.value='Enter Search';
	//	};

	searchBox.onfocus = function()
	{
		if (this.value == 'Enter Search')
			this.value = '';
	};
	
	searchBox.onblur = function()
	{
		lastSearchQuery = this.value;
		this.value = 'Enter Search';
	};
	
	searchBox.onkeypress = function(event)
	{
		;
		if (this.value != null && this.value != '' && this.value != 'Enter Search' && event.keyCode == 13) // enter pressed
			window.location = '/videos/search/' + searchBox.value;
	};
	
	// search button event
	$('btnSearch').onclick = function()
	{
		if (lastSearchQuery != null && lastSearchQuery != '' && lastSearchQuery != 'Enter Search')
			window.location = '/videos/search/' + lastSearchQuery;
	};
	
	// WTF button event
	$('btnRandom').onclick = function() { window.location ='/videos/wtf/wtf/'; }
}

function attachMenuActions()
{
	$('menuHome').onclick           = function() { window.location = '/'; }
	$('menuCategories').onclick		= function() { toggleMenu('Categories', this); };
	$('menuEditorsPicks').onclick   = function() { window.location = '/videos/editors_picks'; };
	$('menuTopRated').onclick       = function() { toggleMenu('TopRated', this); };
	$('menuHighestViews').onclick   = function() { toggleMenu('HighestViews', this); };
	$('menuMostDiscussed').onclick  = function() { toggleMenu('MostDiscussed', this); };
}

function toggleMenu(menuName, menu)
{
	var submenu = $('sub' + menuName);
	var menustate = submenu.style.display;
	collapseSubmenus();
	if (menustate == 'none')
	{
		submenu.style.display = 'block';
		menu.childNodes[0].innerHTML = '&lt;';
	}
	else if (menustate == 'block')
	{
		submenu.style.display = 'none';
		menu.childNodes[0].innerHTML = '&gt;';
	}
}

function attachSubmenuActions()
{
	$('CategoriesFunny').onclick    = function() { window.location = '/videos/funny'; }
	$('CategoriesWTF').onclick    = function() { window.location = '/videos/wtf'; }
	$('CategoriesPwned').onclick    = function() { window.location = '/videos/pwned'; }
	$('CategoriesTooCool').onclick	= function() { window.location = '/videos/too_cool'; }

	$('TopRatedDaily').onclick      = function() { window.location = '/videos/top_rated_daily'; }
	$('TopRatedWeekly').onclick     = function() { window.location = '/videos/top_rated_weekly'; }
	$('TopRatedMonthly').onclick    = function() { window.location = '/videos/top_rated_monthly'; }
	$('TopRatedAllTime').onclick    = function() { window.location = '/videos/top_rated'; }

	$('HighestViewsDaily').onclick      = function() { window.location = '/videos/most_viewed_daily'; }
	$('HighestViewsWeekly').onclick     = function() { window.location = '/videos/most_viewed_weekly'; }
	$('HighestViewsMonthly').onclick    = function() { window.location = '/videos/most_viewed_monthly'; }
	$('HighestViewsAllTime').onclick    = function() { window.location = '/videos/most_viewed'; }
	
	$('MostDiscussedDaily').onclick      = function() { window.location = '/videos/most_discussed_daily'; }
	$('MostDiscussedWeekly').onclick     = function() { window.location = '/videos/most_discussed_weekly'; }
	$('MostDiscussedMonthly').onclick    = function() { window.location = '/videos/most_discussed_monthly'; }
	$('MostDiscussedAllTime').onclick    = function() { window.location = '/videos/most_discussed'; }

	$('menuSubmitContent').onclick	     = function() { alert("This feature is being implemented. Thanks for your patience!"); }
}

function collapseSubmenus()
{
	setSubmenus(false); // false means don't expand => collapse
}

function expandSubmenus()
{
	setSubmenus(true); // true means do expand => expand
}

function setSubmenus(expand)
{
	var arrSubmenus = ['Categories', 'EditorsPicks', 'TopRated', 'HighestViews', 'MostDiscussed'];
	for (var i = 0; i < arrSubmenus.length; ++i)
	{
		var submenu = $('sub' + arrSubmenus[i]);
		var menu = $('menu' + arrSubmenus[i]);
		submenu.style.display = (expand) ? 'block' : 'none';
		menu.childNodes[0].innerHTML = (expand) ? '&lt;' : '&gt;';
	}
}

function populateVideoPageFields(pVid)
{
	var url = "/catalog.php";
	new Ajax.Request(url,
	{
		method: "get",
		parameters: {
			vid: pVid
		},
		onSuccess: function(transport)
		{
			processPopulateVideoPageFields(transport);
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

function showComments(page)
{
	$('comments').insertBefore($('post_comment'), $('show_comments'));
	if (!page || page < 1) page = 1;
	removeChildren($('show_comments'));
	new Ajax.Request("/comments.php",
	{
		method: "get",
		parameters:
		{
			pageno: page
		},
		onSuccess: function(transport)
		{
			delayForIE(function() { processShowComments(transport); });
			
			var commentsXML = transport.responseXML;
			var comments = commentsXML.getElementsByTagName("comments")[0];
			$('show_comments').appendChild(getPagination(comments, page, 'comments'));
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

function processShowComments(transport)
{
	var xml = transport.responseXML;
	var commentsXML = xml.getElementsByTagName("comments")[0];
	var comments = commentsXML.getElementsByTagName("comment");

	if (!comments) return;
	// workaround for ie; when refreshing, the comments are "undefined" unless we give it some time. wtf?

	for (var i = 0; i < comments.length; ++i)
	{
		var thecomment = comments[i];
		addComment(0, thecomment)
	}
}

function addComment(replytocid, thecomment)
{
	var cid = thecomment.getAttribute('cid');
	var uname = thecomment.getAttribute('uname');
	var timestamp = convertTimestamp(thecomment.getAttribute('timestamp'));
	var replytocid = thecomment.getAttribute('replytocid');
	var txtComment = (isIE) ? thecomment.getElementsByTagName('txtComment')[0].text : thecomment.getElementsByTagName('txtComment')[0].textContent;

	var isReply = (replytocid != 0) ? true : false;

	var comments2 = document.createElement('div');
	comments2.className = (isReply) ? 'replycomments' : 'comments2';
	comments2.id = cid + "comment"
	var comments_leftside = document.createElement('div');
	comments_leftside.className = 'comments_leftside';
	var img = document.createElement('img');
	img.src = "/img/bg/redwing.jpg";
	comments_leftside.appendChild(img);
	var comments_rightside = document.createElement('div');
	comments_rightside.className = 'comments_rightside';
	var info = document.createElement('p');
	info.className = 'info';
	var user = document.createElement('span');
	user.className = 'user';
	user.innerHTML = uname;
	var time = document.createElement('span');
	time.className = 'time';
	time.innerHTML = getCalendarDate(timestamp) + " " + getClockTime(timestamp);
	info.appendChild(user);
	info.appendChild(time);
	var cmt = document.createElement('p');
	cmt.className = 'cmt';
	cmt.innerHTML = txtComment;

	comments_rightside.appendChild(info);
	comments_rightside.appendChild(cmt);
	// We only add the reply button to original comments.
	if (!isReply)
	{
		var reply_comment = document.createElement('div');
		reply_comment.className = 'reply_comment';
		reply_comment.id = cid + "reply";
		reply_comment.innerHTML = 'REPLY';
		reply_comment.onclick = function()
		{
			reply(parseInt(this.id));
		}
		comments_rightside.appendChild(reply_comment);
	}
	comments2.appendChild(comments_leftside);
	comments2.appendChild(comments_rightside);

	$('show_comments').appendChild(comments2);

	if (!isReply)
	{
		var replies = thecomment.getElementsByTagName('replies')[0].getElementsByTagName('reply');
		for (var i = 0; i < replies.length; ++i)
		{
			addComment(cid, replies[i]);
		}
	}

}

function showReplies(cid)
{
	// Put the commenting box at the top, and clear the className.
	$('comments').insertBefore($('post_comment'), $('show_comments'));
	new Ajax.Request("/comments.php",
	{
		method: "get",
		parameters:
		{
			pageno: 1,
			replytocid: cid
		},
		onSuccess: function(transport)
		{
			processShowComments(transport, cid);
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

function postComment()
{
	var pComment;
	if ($('reply_area'))
		pComment = getTextArea($('reply_area'));
	else if ($('replytextarea'))
		pComment = getTextArea($('replytextarea'));
		
	pComment = trim(pComment);
	if (pComment == '')
	{
		alert("Please type your comment before posting!");
		return;
	}
	
	var url = "/comments.php";
	new Ajax.Request(url,
	{
		method: "get",
		parameters: {
			comment: pComment,
			replytocid: $('postcommentbutton').className
		},
		onSuccess: function(transport)
		{
			processPostComment(transport);
		},
		onFailure: function()
		{
			alert("Error!");
		}
	});
}

function processPostComment(transport)
{
	var result = transport.responseText;
	if (result == -3)
		alert("You cannot reply to a reply!");
	else if (result == -2)
		alert("Please type your comment before posting!");
	else if (result == -1)
		alert("You are not even watching a video!");
	else if (result == 0)
		alert("Please log in before posting.");
	else if (result == 1)
	{
		//alert("Thank you for posting your comment.");
		showComments();
		// Increment the infobox's comment count by 1.
		$('infoComments').innerHTML = parseInt($('infoComments').innerHTML) + 1;
		// Remove the cancel button.
		$('cancelreplybutton').style.display = 'none';
		// Turn the replytextarea to reply_area to change the size back. (if applicable)
		if ($('replytextarea'))
			$('replytextarea').id = 'reply_area';
		$('postcommentbutton').className = null;
	}
	
	setTextArea($('reply_area'), "");
	setTextArea($('replytextarea'), "");
}

function reply(replytocid)
{
	var thisComment = $(replytocid + 'comment');
	// Actually does insertAfter (because of thisComment.nextSibling
	if ($('reply_area'))
	{
		setTextArea($('reply_area'), "");
		$('reply_area').id = 'replytextarea';
	}
	
	$('cancelreplybutton').style.display = 'block';
	$('cancelreplybutton').onclick = function() { 
		var commentingTool = $('post_comment');
		var divider = $('dividerBeforeFirstComment');
		var comments = $('comments');
		comments.insertBefore(commentingTool, divider.nextSibling);		
		this.style.display = 'none';
		setTextArea($('replytextarea'), "");
		$('replytextarea').id = 'reply_area';
		$('postcommentbutton').className = null;
  }
  $('show_comments').insertBefore($('post_comment'), thisComment.nextSibling);
	$('postcommentbutton').className = replytocid;
}

///**
//  * Tag stuff
//  */
//function populateTopTags()
//{
//	new Ajax.Request("/toptags.php",
//	{
//		method: "GET",
//		parameters:
//		{
//			numtags: 5
//		},
//		onSuccess: function(transport)
//		{
//			processPopulateTopTags(transport.responseXML);
//		},
//		onFailure: function()
//		{
//			alert("Error retrieving top tags!");
//		}
//	});
//}
//
//function processPopulateTopTags(xml)
//{
//	var taglist	= $('topsearchtags_list');
//	var tagsxml	= xml.getElementsByTagName("tags")[0];
//	var tags 	= tagsxml.getElementsByTagName("tag");
//
//	for (var i = 0; i < tags.length; ++i)
//	{
//		var tagListItem = document.createElement('li');
//		var tag = tags[i];
//		// Workaround for non-working <ol> numbering.
//		tagListItem.innerHTML  = i+1 + '. ';
//		var aTagname = document.createElement('a');
//		aTagname.id = (i+1) + 'toptag';
//		aTagname.innerHTML = (isIE) ? tag.text : tag.textContent;
//		aTagname.href = "/videos/search/" + aTagname.innerHTML;
//		tagListItem.appendChild(aTagname);
//		taglist.appendChild(tagListItem);
//	}
//}

/**
  * Tag stuff
  */
function populateTopSearches()
{
	new Ajax.Request("/topsearches.php",
	{
		method: "GET",
		parameters:
		{
			numqueries: 5
		},
		onSuccess: function(transport)
		{
			processPopulateTopSearches(transport.responseXML);
		},
		onFailure: function()
		{
			alert("Error retrieving top search queries!");
		}
	});
}

function processPopulateTopSearches(xml)
{
	var querylist	= $('topsearchqueries_list');
	var queryxml	= xml.getElementsByTagName("queries")[0];
	var queries 	= queryxml.getElementsByTagName("query");

	for (var i = 0; i < queries.length; ++i)
	{
		var queryListItem = document.createElement('li');
		var query = queries[i];
		// Workaround for non-working <ol> numbering.
		queryListItem.innerHTML  = i+1 + '. ';
		var aQueryname = document.createElement('a');
		aQueryname.id = (i+1) + 'topsearch';
		aQueryname.innerHTML = (isIE) ? query.text : query.textContent;
		aQueryname.href = "/videos/search/" + aQueryname.innerHTML;
		queryListItem.appendChild(aQueryname);
		querylist.appendChild(queryListItem);
	}
}

function siteOff()
{
	disableMovieDiv(true);
			
	divOverlay = document.createElement('div');
	divOverlay.id = 'divOverlay';
	divOverlay.style.position = 'fixed';
	divOverlay.style.width = '100%' //window.screen.width + 'px';
	divOverlay.style.height = '100%' //window.screen.height + 'px';
	divOverlay.style.left = '0px';
	divOverlay.style.top = '0px';
	divOverlay.style.backgroundColor = 'white';
	divOverlay.className = 'trans0';

	var emptyImg = document.createElement('img');
	emptyImg.src = "/img/bg/whitespace.gif";
	emptyImg.title = "Click to return to WhatTheFudge.TV";
	emptyImg.alt = "Click to return to WhatTheFudge.TV";
	emptyImg.width = document.width;
	emptyImg.height = document.height;
	divOverlay.appendChild(emptyImg);
	
	// frame does not work.
	//var frame = document.createElement('frame');
	//frame.src='http://www.google.com';
	//frame.name='content';
	//frame.location = 'http://www.google.com';
	//divOverlay.appendChild(frame);

	var currentTitle = document.title;
	document.title = '';
	divOverlay.onclick = function() 
	{
		siteOn(currentTitle);
	}
	$('home').appendChild(divOverlay);
}

function siteOn(currentTitle)
{
	var divOverlay = $('divOverlay');
	if (divOverlay)
	{
		$('home').removeChild(divOverlay);
		disableMovieDiv(false);
		document.title = currentTitle;
	}
}

function displayMenu(displayMenu)
{
	if (displayMenu)
		$('usermenu').style.display = 'block';
	else
		$('usermenu').style.display = 'none';
}

function createUserMenu()
{
	var menu = $('usermenu');
	addMenuOption(menu, 'optProfiles', 'Profile', function() { alert('Coming Soon...'); });
	addMenuOption(menu, 'optLogout', 'Logout', logout);
  $('userbar').appendChild(menu);
}

function addMenuOption(menu, optionId, optionText, optionEvent)
{
	var opt = document.createElement('li');
			opt.id = optionId;
			opt.className = 'menuOption';
			opt.onclick = optionEvent;
			opt.innerHTML = optionText;
	menu.appendChild(opt);
}

function logout()
{
	new Ajax.Request('/logout.php',
	{
		method: "get",

		onSuccess: function(transport)
		{
			window.location.reload();
		},
		onFailure: function()
		{
			window.location.reload();
		}
	});
}

/**************************************************************************
 *                  U T I L I T Y      F U N C T I O N S                  *
 **************************************************************************/


function setTextArea(txtArea, newText)
{
	if (txtArea)
	{
		if (isIE)
			txtArea.firstChild.innerHTML = '';
		else
			txtArea.value = '';
	}
}

function getTextArea(txtArea)
{
	if (txtArea)
	{
		if (isIE)
			return txtArea.firstChild.innerHTML;
		else
			return txtArea.value;
	}
	return "";
}

function trim(str)
{
	//alert('[' + str + ']');
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

function getClockTime(date)
{
	var hour   = date.getHours();
	var minute = date.getMinutes();
	var second = date.getSeconds();
	var ap = "am";
	if (hour   > 11) ap = "pm";        
	if (hour   > 12) hour = hour - 12;  
	if (hour   == 0) hour = 12;          
	if (hour   < 10) hour   = "0" + hour; 
	if (minute < 10) minute = "0" + minute;
	if (second < 10) second = "0" + second;
	var timeString = hour +
		':' +
		minute +
		':' +
		second +
		"" +
		ap;
	return timeString;
}

function getCalendarDate(date)
{
	var months = new Array(13);
	months[0]  = "Jan.";
	months[1]  = "Feb.";
	months[2]  = "Mar.";
	months[3]  = "Apr.";
	months[4]  = "May";
	months[5]  = "Jun.";
	months[6]  = "Jul.";
	months[7]  = "Aug.";
	months[8]  = "Sept.";
	months[9]  = "Oct.";
	months[10] = "Nov.";
	months[11] = "Dec.";
	var monthnumber = date.getMonth();
	var monthname   = months[monthnumber];
	var monthday    = date.getDate();
	var year        = date.getYear();
	if(year < 2000) { year = year + 1900; }
	var dateString = monthname +
		' ' +
		monthday +
		', ' +
		year;
	return dateString;
}

function ago(timestamp)
{
	var now = new Date();

	var millisPerDay = 1000 * 60 * 60 * 24;
	var millisPerHour = 1000 * 60 * 60;
	var millisPerMinute = 1000 * 60;
	var millisPerSecond = 1000
	var diffDays = Math.floor((now.getTime() - timestamp.getTime()) / (millisPerDay));
	var diffHours = Math.floor((now.getTime() - timestamp.getTime()) / (millisPerHour));
	var diffMinutes = Math.floor((now.getTime() - timestamp.getTime()) / (millisPerMinute));
	var diffSeconds = Math.floor((now.getTime() - timestamp.getTime()) / (millisPerSecond));
	
	//alert(timestamp.getTime() + ', ' + now.getTime());

	//alert('this day: ' + (now.getMonth()+1) + ', ' + 'timestamp month: ' + timestamp.getMonth());
	//alert(diff);

	//return diffDays;
	if (diffSeconds < 60)
		return [1, 'm'];
	else if (diffMinutes < 60)
		return [diffMinutes, 'm'];
	else if (diffHours < 24)
		return [diffHours, 'h'];
	else
		return [diffDays, 'd'];
}

function formatDaysAgo(daysSinceFeatured)
{
	var timeComponent = daysSinceFeatured[0];
	var dateComponent = daysSinceFeatured[1];
	//alert(dateComponent);
	
	timeUnit = 'day';

	if (dateComponent == 'h')
		timeUnit = 'hour';
	else if (dateComponent == 'm')
		timeUnit = 'minute';
	else if (dateComponent == 's')
		timeUnit = 'second'

	return pluralize(timeComponent, timeUnit) + " ago";
}

/**
 * q is the quantity, n is the name (noun).
 */
function pluralize(q, n)
{
	return (q > 1) ? (q + ' ' + n + 's') : (q + ' ' + n);
}

/**
 * Parses MySQL DateTime string and returns Javascript Date object.
 * Input has to be in this format: 2007-06-05 15:26:02
 */
function convertTimestamp(timestamp)
{
	var regex = /^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
	var parts = timestamp.replace(regex, "$1 $2 $3 $4 $5 $6").split(' ');
	return new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
}

/**
 * Summarizes string s by appending "..." after the number of characters defined by the limit.
 */
function summarize(s, limit)
{
	var newString = s;
	if (!limit || limit < 0) limit = 100;
	if (s.length > limit)
		newString = s.substring(0, limit) + "...";
	return newString;
}

/**
 * Removes all children of the rootElement.
 */
function removeChildren(rootElement)
{
	var numChildren = rootElement.childNodes.length

	for (var i = 0; i < numChildren; ++i)
	{
		var node = rootElement.lastChild; 
		rootElement.removeChild(node);
	}
}

/**
 * Bookmark functio for different browsers.
 */

/* Modified to support Opera */
function bookmark()
{
	var pageTitle = document.title;
	var url = window.location; 
	
	if (window.sidebar) // firefox
		window.sidebar.addPanel(pageTitle, url, "");
	else if(window.opera && window.print) // opera
	{ 
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',pageTitle);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if(document.all) // ie
		window.external.AddFavorite(url, pageTitle);
}

/**
 * IE is stupid, because apparently, it requires some "sleep time" for the ajax callbacks when refreshing the page.
 * Therefore, in order to workaround this stupidity, we're sleeping for 150ms, here.
 */
function delayForIE(func)
{
	if (!isIE)
		setTimeout(func, 150);
	else
		func();
}
