$(document).ready(function() {
	var username = $("#username").val();
	
	//Get View Count for the profile page...
	$.getJSON("/data/DataRequest.aspx", { op:"GetDocumentViewCount", type:"json", Path:username }, function(data) {
		$("#viewCount").html(data.Map.Item.value);
	});
	
	//Get StatusUpdate
	$.getJSON("/data/DataRequest.aspx", { op:"GetProfileStatusUpdate", type:"json", Username:username }, function(data) {
		if(data.Map.Item[0].value != null)
		{
			$('#StatusUpdate').html(data.Map.Item[0].value);
			$('#DateStatusUpdate').html(formatDate(data.Map.Item[1].value.split(' ')[0]));
			$('#StatusUpdateTable').css({ display:"" });
		}
		else
		{
			$('#StatusUpdate').html("Let your connections know what you're up to by typing a quick update.");
			$('#DateStatusUpdate').html("");				
		}
	});
	
	//Latest Posts
	$.getJSON("/data/DataRequest.aspx", { op:"GetProfileLatestPostsForUserName", type:"json", UserName:username }, function(data) {
		var html = "";
		if(data.Rowset.Map.Item || data.Rowset.Map.length > 0)
		{
			html = "<table class=\"LatestPostsTable\" cellspacing=\"0\">";
			for(var i in data.Rowset.Map)
			{
				var item = data.Rowset.Map[i].Item;
				if(item == null)
					item = data.Rowset.Map.Item;
				
				var id = null;
				var date = null;
				var title = null;
				var views = null;
				var replies = null;
										
				for(var x in item)
				{						
					if(item[x].name == "id")
						id = item[x].value;
					if(item[x].name == "date")
					{
						date = item[x].value;
						date = convertUnixtime(date);
					}
					if(item[x].name == "title")
					{
						title = item[x].value;
						if(title.length > 40)
							title = title.substr(0, 37) + "...";
					}
					if(item[x].name == "views")
						views = item[x].value;
					if(item[x].name == "replies")
					{
						replies = item[x].value;
						if(replies > 0)
							replies = " - " + replies;
						else
							replies = "";
					}
				}
				
				html += "<tr><td class=\"LatestPostsDate\">" + date + "</td>";
				html += "<td class=\"LatestPostsTitle\"><a href=\"/discussion/viewtopic.php?t=" + id + "\">" + title + "</a>&nbsp;(&nbsp;" + views + " views " + replies + ")</td></tr>";
			}
			html += "</table>";
			
			$('#LatestPostsContentArea').html(html);
			$('#LatestPostsArea').css({ display:"" });
		}
		else
		{
			$('#LatestPostsArea').css({ display:"none" });
		}
	});
	
	$("#ProfileButton, #ProfileEditMenu").hover(
		function() {
			$("#ProfileEditMenu").css("top", (29));
			$("#ProfileEditMenu").css("left", $("#ProfileButton").offset.left);
			$("#ProfileEditMenu").show();
		}, 
		function() {
			$("#ProfileEditMenu").hide();
		}
	);
	
	//Affiliate Ads
	GetRandomAffiliateAd();	
	
});

//Format Date for StatusUpdate
function formatDate(targetDate)
{
	var now = new Date();
	var target = new Date(targetDate);
	var diff = Math.floor((now.getTime() - target.getTime()) / (1000*60*60*24));
	if(diff >= 30)
		targetDate = "Over 1 month ago";
	else if(diff >= 21)
		targetDate = "3 weeks ago";
	else if(diff >= 14)
		targetDate = "2 weeks ago";
	else if(diff >= 7)
		targetDate = "1 week ago";
	else if(diff == 6)
		targetDate = "6 days ago";
	else if(diff == 5)
		targetDate = "5 days ago";
	else if(diff == 4)
		targetDate = "4 days ago";
	else if(diff == 3)
		targetDate = "3 days ago";
	else if(diff == 2)
		targetDate = "2 days ago";
	else if(diff == 1)
		targetDate = "Yesterday";
	else
		targetDate = "Today";
	
	return targetDate + ": ";
}

//Convert UNIX timestamps for PHPBB Posts
function convertUnixtime(timestamp)
{
	var myDate = new Date(timestamp * 1000);
	var month = myDate.getMonth() + 1;
	var day = myDate.getDate();
	var year = myDate.getFullYear();
	return (month + "/" + day + "/" + year);
}

// RatingWidget class used for creating instances of the ratings widget.
// _id (The NAME of the variable created)
// _rating (The initial rating for this widget)
// _path (The path to the document being rated)
// _username (The username of the viewing user)
// _isOwner (Whether the viewing user is the owner or not (Owners cannot rate their own content))
// _displayStyle (Whether the display style of the widget is 'horizontal' or 'vertical')
function RatingWidget(_id, _rating, _path, _username, _isOwner, _displayStyle)
{
	this.rating				= _rating;					//The rating for this widget.
	this.id					= _id;						//Unique id of the widget object.
	this.path				= _path;					//Path to the document being rated.
	this.username			= _username;				//Username of user who is RATING this document.
	this.isOwner			= _isOwner.toLowerCase();	//Whether the widget is being viewed by the owner or not.
	this.displayStyle		= _displayStyle;			//The display style is either 'horizontal' or 'vertical'.
	this.cssstyle			= this.displayStyle == "horizontal" ? "float: left; width: 80px; text-align: right; padding-right: 6px; font-size: 12px; color: #000000; font-weight: bold;" : "font-size: 12px; color: #000000; font-weight: bold;";
		
	this.setRating			= _setRating;				//Function to set the rating of this widget.
	this.ratingHover		= _ratingHover;				//Function to handle rollovers.
	this.rateDocument		= _rateDocument;			//Function to rate the document.
	this.ratingLogin		= _ratingLogin;
	
	//This is called upon creation of a RatingWidget object to initialize it.
	this.Initialize = function()
	{
		if(this.rating < 0 || this.rating > 5)
			this.rating = 0.0;
		
		if(this.isOwner == "true" || this.isOwner == "anonymous")	//VIEW State
		{
			viewState(this.id, this.displayStyle, this.cssstyle, this.isOwner);
			this.setRating(this.rating);
		}
		else						//EDIT State
		{
			editState(this.id, this.displayStyle, this.cssstyle);
			this.setRating(this.rating);
		}
	}

	function viewState(_id, _displayStyle, _cssstyle, _isOwner)
	{
		if(_displayStyle == "horizontal")
		{
			var	temp = "<div id=\"" + _id + "ratingTitle\" style=\"" + _cssstyle + "\">Rating:</div>\n";
			temp += "<table id=\"" + _id + "star_\" cellspacing=\"0\" class=\"star_ratings\" style=\"position: relative; top: -3px;\">\n";
		}
		else
		{
			var	temp = "<div id=\"" + _id + "ratingTitle\" style=\"" + _cssstyle + "\">Rating:</div>\n";
			temp += "<table id=\"" + _id + "star_\" cellspacing=\"0\" class=\"star_ratings\">\n";
		}
		temp += "<tr>\n";
		if(_isOwner == "anonymous")
		{
			temp += "<td id=\"" + _id + "star_1\" class=\"star_empty\" onmouseover=\"javascript: " + _id + ".ratingLogin(this, '" + _id + "');\" onmouseout=\"javascript: ToggleObjectVisibility('" + _id + "_ratingLogin');\"><a href=\"/login/login.aspx?from=" + escape(document.URL) + "\"><img border=\"0\" src=\"/images/spacer.gif\" class=\"star_spacer\"></a></td>\n";
			temp += "<td id=\"" + _id + "star_2\" class=\"star_empty\" onmouseover=\"javascript: " + _id + ".ratingLogin(this, '" + _id + "');\" onmouseout=\"javascript: ToggleObjectVisibility('" + _id + "_ratingLogin');\"><a href=\"/login/login.aspx?from=" + escape(document.URL) + "\"><img border=\"0\" src=\"/images/spacer.gif\" class=\"star_spacer\"></a></td>\n";
			temp += "<td id=\"" + _id + "star_3\" class=\"star_empty\" onmouseover=\"javascript: " + _id + ".ratingLogin(this, '" + _id + "');\" onmouseout=\"javascript: ToggleObjectVisibility('" + _id + "_ratingLogin');\"><a href=\"/login/login.aspx?from=" + escape(document.URL) + "\"><img border=\"0\" src=\"/images/spacer.gif\" class=\"star_spacer\"></a></td>\n";
			temp += "<td id=\"" + _id + "star_4\" class=\"star_empty\" onmouseover=\"javascript: " + _id + ".ratingLogin(this, '" + _id + "');\" onmouseout=\"javascript: ToggleObjectVisibility('" + _id + "_ratingLogin');\"><a href=\"/login/login.aspx?from=" + escape(document.URL) + "\"><img border=\"0\" src=\"/images/spacer.gif\" class=\"star_spacer\"></a></td>\n";
			temp += "<td id=\"" + _id + "star_5\" class=\"star_empty\" onmouseover=\"javascript: " + _id + ".ratingLogin(this, '" + _id + "');\" onmouseout=\"javascript: ToggleObjectVisibility('" + _id + "_ratingLogin');\"><a href=\"/login/login.aspx?from=" + escape(document.URL) + "\"><img border=\"0\" src=\"/images/spacer.gif\" class=\"star_spacer\"></a></td>\n";
		}
		else
		{
			temp += "<td id=\"" + _id + "star_1\" class=\"star_empty\"><img src=\"/images/spacer.gif\" class=\"star_spacer\"></td>\n";
			temp += "<td id=\"" + _id + "star_2\" class=\"star_empty\"><img src=\"/images/spacer.gif\" class=\"star_spacer\"></td>\n";
			temp += "<td id=\"" + _id + "star_3\" class=\"star_empty\"><img src=\"/images/spacer.gif\" class=\"star_spacer\"></td>\n";
			temp += "<td id=\"" + _id + "star_4\" class=\"star_empty\"><img src=\"/images/spacer.gif\" class=\"star_spacer\"></td>\n";
			temp += "<td id=\"" + _id + "star_5\" class=\"star_empty\"><img src=\"/images/spacer.gif\" class=\"star_spacer\"></td>\n";
		}
		temp += "</tr>\n";
		temp += "</table>\n";
		if(_isOwner == "anonymous")
			temp += "<div id=\"" + _id + "_ratingLogin\" class=\"ACPWindow\" style=\"width: 255px; height: 32px; padding: 4px; display: none; visibility: hidden;\">You must be logged in to rate content. Click to login.</div>";		
		document.write(temp);
	}

	function editState(_id, _displayStyle, _cssstyle)
	{
		if(_displayStyle == "horizontal")
		{
			var	temp = "<div id=\"" + _id + "ratingTitle\" style=\"" + _cssstyle + "\">Rating:</div>\n";
			temp += "<table id=\"" + _id + "star_\" cellspacing=\"0\" class=\"star_ratings\" onmouseout=\"javascript: " + _id + ".setRating(" + _id + ".rating);\" style=\"position: relative; top: -3px;\">\n";
		}
		else
		{
			var	temp = "<div id=\"" + _id + "ratingTitle\" style=\"" + _cssstyle + "\">Rating:</div>\n";
			temp += "<table id=\"" + _id + "star_\" cellspacing=\"0\" class=\"star_ratings\" onmouseout=\"javascript: " + _id + ".setRating(" + _id + ".rating);\">\n";
		}
		temp += "<tr>\n";
		temp += "<td id=\"" + _id + "star_1\" class=\"star_empty\" onmouseover=\"javascript: " + _id + ".ratingHover(this, '1');\"><a id=\"" + _id + "star_a_1\" onclick=\"javascript: " + _id + ".rateDocument('1'); return false;\" href=\"#\"><img src=\"/images/spacer.gif\" alt=\"Click to rate\" class=\"star_spacer\"></a></td>\n";
		temp += "<td id=\"" + _id + "star_2\" class=\"star_empty\" onmouseover=\"javascript: " + _id + ".ratingHover(this, '2');\"><a id=\"" + _id + "star_a_2\" onclick=\"javascript: " + _id + ".rateDocument('2'); return false;\" href=\"#\"><img src=\"/images/spacer.gif\" alt=\"Click to rate\" class=\"star_spacer\"></a></td>\n";
		temp += "<td id=\"" + _id + "star_3\" class=\"star_empty\" onmouseover=\"javascript: " + _id + ".ratingHover(this, '3');\"><a id=\"" + _id + "star_a_3\" onclick=\"javascript: " + _id + ".rateDocument('3'); return false;\" href=\"#\"><img src=\"/images/spacer.gif\" alt=\"Click to rate\" class=\"star_spacer\"></a></td>\n";
		temp += "<td id=\"" + _id + "star_4\" class=\"star_empty\" onmouseover=\"javascript: " + _id + ".ratingHover(this, '4');\"><a id=\"" + _id + "star_a_4\" onclick=\"javascript: " + _id + ".rateDocument('4'); return false;\" href=\"#\"><img src=\"/images/spacer.gif\" alt=\"Click to rate\" class=\"star_spacer\"></a></td>\n";
		temp += "<td id=\"" + _id + "star_5\" class=\"star_empty\" onmouseover=\"javascript: " + _id + ".ratingHover(this, '5');\"><a id=\"" + _id + "star_a_5\" onclick=\"javascript: " + _id + ".rateDocument('5'); return false;\" href=\"#\"><img src=\"/images/spacer.gif\" alt=\"Click to rate\" class=\"star_spacer\"></a></td>\n";
		temp += "</tr>\n";
		temp += "</table>\n";
		document.write(temp);
	}
		
	//Rate a document.
	//rating (0-5 number indicating the desired rating)
	function _rateDocument(rating)
	{
		if(rating == null || (rating < 0 || rating > 5))
			return;
		
		var widget = this;
		
		$.getJSON("/data/DataRequest.aspx", { op:"RateProfileDocument", type:"json", Path:this.path, UserName:this.username, Rating:rating }, function(data) {
			widget.rating = data.rating.value;
			widget.setRating(widget.rating);
		});
		/*function customHandler(node, myAjaxRequest)
		{
				
		}					
		var myRequest = new AjaxRequestObject();
		myRequest.url = "/data/DataRequest.aspx";
		myRequest.postParameters = "op=RateDocument&Path=" + this.path + "&UserName=" + this.username + "&Rating=" + rating;
		myRequest.requestType = "POST";
		myRequest.widget = this;
		myRequest.customHandler = customHandler;
		myRequest.startRequest();*/
	}

	//Used to set the rating of the widget
	//rating (0-5 number indicating the desired rating)
	function _setRating(rating)
	{
		for(var i = 1; i <= 5; i++)
		{
			var star = document.getElementById(this.id + "star_" + i);
			if(i <= Math.floor(rating))
			{
				star.className = "star_red";
			}
			else if(i <= Math.ceil(rating))
			{
				var fraction = rating.split(".")[1];
				if(fraction <= 3)
					star.className = "star_1_fifth";
				if(fraction > 3 && fraction <= 5)
					star.className = "star_2_fifth";
				if(fraction > 5 && fraction <= 7)
					star.className = "star_3_fifth";
				if(fraction > 7)
					star.className = "star_4_fifth";
			}
			else if(i >= Math.ceil(rating))
			{
				star.className = "star_empty";
			}
		}		
		document.getElementById(this.id + "ratingTitle").innerHTML = "Rating:";
	}

	//Used when hovering over stars to update the color of the stars and the text.
	//star (star object we are hovering over)
	//starNumber (number of the star we are hovering over)
	function _ratingHover(star, starNumber)
	{
		for(var i = 1; i <= 5; i++)
		{
			var star = document.getElementById(star.id.substr(0, (star.id.length - 1)) + i);
			if(i <= starNumber)
				star.className = "star_yellow";
			else if(i > starNumber)
				star.className = "star_empty";
		}		
		var ratingTitle = document.getElementById(this.id + "ratingTitle");
		switch(starNumber)
		{
			case "1":
				ratingTitle.innerHTML = "I hate it"; break;
			case "2":
				ratingTitle.innerHTML = "I don't like it"; break;
			case "3":
				ratingTitle.innerHTML = "It's OK"; break;
			case "4":
				ratingTitle.innerHTML = "I like it"; break;
			case "5":
				ratingTitle.innerHTML = "I love it"; break;
		}	
	}
	
	function _ratingLogin(star, id)
	{
		var target = document.getElementById(id + "_ratingLogin");
		target.style.top = (getTotalOffsetTop(star) + 25) + "px";
		target.style.left = (getTotalOffsetLeft(star) - 150) + "px";
		target.style.display = "";
		target.style.visibility = "visible";
	}
	
	function getTotalOffsetLeft(sourceObject)
	{
		if(sourceObject.nodeName == "BODY" || sourceObject.nodeName == "HTML")
			return sourceObject.offsetLeft;
		else
			return sourceObject.offsetLeft + getTotalOffsetLeft(sourceObject.offsetParent);
	}
				
	function getTotalOffsetTop(sourceObject)
	{
		if(sourceObject.nodeName == "BODY" || sourceObject.nodeName == "HTML")
			return sourceObject.offsetTop;
		else
			return sourceObject.offsetTop + getTotalOffsetTop(sourceObject.offsetParent);
	}
}
	
function ToggleObjectVisibility(sourceId, targetId, displayType)
{
	if(displayType == null)
		displayType = "block";
		
	var source = document.getElementById(sourceId);
	var target = document.getElementById(targetId);
	
	if(source != null)
	{
		source.style.display = "none";
		source.style.visibility = "hidden";
	}
	if(target != null)
	{
		target.style.display = displayType;
		target.style.visibility = "visible";
	}
}

///////////////////////////////////////////////////////////
// COMMENTS ///////////////////////////////////////////////
///////////////////////////////////////////////////////////
function postComment()
{
	var object = $('#COMMENT_SELECTED');
	var submit = $('#BPostComment');
	var textarea = $('#TAComment');
	$('#commentMessage').hide("fast");	
	if(textarea.attr("disabled") == undefined)
	{
		submit.hide("fast");
		textarea.attr("disabled", "true");
		object.hide("fast");
	}
	else
	{
		submit.show("fast");
		textarea.removeAttr("disabled");
		object.show("fast");
	}
}

function submitComment(path, commenter, source, _commentSelected, _commentCollapsed)
{	
	source = $("#" + source.id);
	source.attr("disabled", "true");
	$('#BPostComment').attr("disabled", "true");
	$('#BPostComment').hide("fast");	
	output = source.val();
	output = output.replace(new RegExp(/\r\n/g), "<br/>");
	output = output.replace(new RegExp(/\n/g), "<br/>");
	output = output.replace(new RegExp(/\r/g), "<br/>");
	output = output.replace(new RegExp('&', 'gi'), "&amp;");
	output = output.replace(new RegExp('>', 'gi'), "&gt;");
	output = output.replace(new RegExp('<', 'gi'), "&lt;");
	source.val("Saving comment...");
	$.get("/data/DataRequest.aspx", { op:"AddComment", Path:path, CommenterUserName:commenter, Comment:output }, function(data) {
		source.val("");		
		$("#COMMENT_SELECTED").hide("fast");
		if(data != null)
		{			
			if(data.childNodes[0].nodeName == "xml")
				val = data.childNodes[1].childNodes[0].childNodes[0].nodeValue;
			else
				val = data.childNodes[0].childNodes[0].childNodes[0].nodeValue;
			if(val == "OK")
			{
				source.removeAttr("disabled");
				$("#commentMessage").show("fast");
				$("#BPostComment").removeAttr("disabled").show("fast");
			}			
		}
	});
}

function deleteComment(path, ownerUserName, commentID)
{
	if(commentID != null)
	{
		if(confirm("Are you sure you want to delete this comment?"))
		{
			$.get("/data/DataRequest.aspx", { op:"DeleteComment", Path:path, UserName:ownerUserName, CommentID:commentID }, function(data) {
				if(data != null)
				{
					if(data.childNodes[0].childNodes[0].childNodes[0].nodeValue == "OK")
					{
						var comment = $('#Comment_' + commentID);
						comment.hide("fast").next("div.CommentApproveDelete").hide("fast").next("div.CommentDivider").hide("fast");
					}
				}
			});
		}
	}
	return false;
}

function approveComment(path, ownerUserName, commentID)
{
	if(commentID != null)
	{
		var comment = $('#Approve_' + commentID);
		var originalSource = comment.html();
		comment.html("approve | ");
		
		$.get("/data/DataRequest.aspx", { op:"ApproveComment", Path:path, UserName:ownerUserName, CommentID:commentID }, function(data) {
			if(data != null)
			{
				if(data.childNodes[0].childNodes[0].childNodes[0].nodeValue == "OK")
					comment.html("approved | ");
				else
					comment.html(originalSource);
			}
		});
	}
	return false;
}