//##########################################################################################

var CommentSaved = false; // set when an AJAX comment save has completed
var CommentDeleted = false; // set when an AJAX comment delete has completed

//##########################################################################################

//place our event hook
window.onload = function() {
	CommentButtons();

	var test = PageTemplate.GetNodesByAttribute("data-label", "fit_to_width").GetNodes();
	for(var i=0; i < test.length; i++){
		text = test[i].getAttribute("data-message");
		test[i].innerHTML = fitStringToWidth(text, BrowserWindow.GetElementWidth(test[i]));
	}
};

function CommentButtons(){
	//find the submit comment button
	var SubmitCommentButton = PageTemplate.GetNodesByAttribute("data-field", "submit_comment_button").GetNode();
	if(SubmitCommentButton){
		SubmitCommentButton.onclick = function(Event) {
			//get event
			Event = BrowserWindow.GetEvent(Event);
			
			//get the text of the reply
			var CommentText = PageTemplate.GetNodesByAttribute("data-field", "comment_text").GetNode().value;
			
			//get the value of the "recieve notifications" checkbox
			var ReceiveNotifications = PageTemplate.GetNodesByAttribute("data-label", "conversation_notifications").GetNode().checked;
			if(ReceiveNotifications == false) ReceiveNotifications = 'no';

			//set comment saved flag
			CommentSaved = false;
			
			//add the comment
			AjaxSaveComment(CommentText, ReceiveNotifications);
			
			//wait for the comment to be saved
			for(var i = 0; i < 1000000; i++){
				if(CommentSaved) break;
			}
			
			//clear out the box
			PageTemplate.GetNodesByAttribute("data-field", "comment_text").GetNode().value = "";
			
			return false;
		};
	}
	
	//find the remove comment buttons
	var RemoveButtons = PageTemplate.GetNodesByAttribute("data-field", "remove_button").GetNodes();
	for(var i = 0 ; i < RemoveButtons.length ; i++) {
		RemoveButtons[i].onclick = function(Event) {
			if(confirm("Are you sure to remove this comment and all its reply comments?")){
				//get event
				Event = BrowserWindow.GetEvent(Event);
	
				//get the parent comment id
				var CommentID = Event.Target.getAttribute("data-comment-id");
				
				//set comment saved flag
				CommentDeleted = false;
				
				//add the comment
				AjaxDeleteComment(CommentID);
				
				//wait for the comment to be saved
				for(var i = 0; i < 1000000; i++){
					if(CommentDeleted) break;
				}
				
				return false;
			}
		};
	}

	//find the remove reply comment buttons
	var RemoveReplyButtons = PageTemplate.GetNodesByAttribute("data-field","remove_reply_comment_button").GetNodes();
	for(var i = 0 ; i < RemoveReplyButtons.length ; i++) {
		RemoveReplyButtons[i].onclick = function(Event) {
			if(confirm("Are you sure to remove this comment reply?")){
				//get event
				Event = BrowserWindow.GetEvent(Event);
	
				//get the parent comment id
				var ReplyID = Event.Target.getAttribute("data-reply-id");
				
				//set comment saved flag
				CommentDeleted = false;
				
				//add the comment
				AjaxDeleteReply(ReplyID);
				
				//wait for the comment to be saved
				for(var i = 0; i < 1000000; i++){
					if(CommentDeleted) break;
				}
				
				return false;
			}
		};
	}

	//find the submit reply comment buttons
	var SubmitReplyButtons = PageTemplate.GetNodesByAttribute("data-field","submit_reply_comment_button").GetNodes();
	for(var i = 0 ; i < SubmitReplyButtons.length ; i++) {
		SubmitReplyButtons[i].onclick = function(Event) {
			//get event
			Event = BrowserWindow.GetEvent(Event);

			//get the parent comment id
			var ParentCommentID = Event.Target.getAttribute("data-profile-comment-id");
			
			if(ParentCommentID) {
				//get the text of the reply
				var Attributes = new Object();
				Attributes['data-field'] = 'reply_comment_text';
				Attributes['data-profile-comment-id'] = ParentCommentID;
				var ReplyText = PageTemplate.GetNodesByAttributes(Attributes).GetNode().value;
					
				//get the value of the "recieve notifications" checkbox
				var ReceiveNotification = 'no';
				var Attributes = new Object();
				Attributes['data-label'] = 'reply_conversation_notifications';
				Attributes['data-profile-comment-id'] = ParentCommentID;
				ReceiveNotification = PageTemplate.GetNodesByAttributes(Attributes).GetNode().value;
				if(ReceiveNotification != "yes" && ReceiveNotification != "no") ReceiveNotification = 'no';
	
				//set comment saved flag
				CommentSaved = false;
				
				//add the comment
				AjaxSaveReply(ParentCommentID, ReplyText, ReceiveNotification);
			}
			
			//wait for the comment to be saved
			for(var i = 0; i < 1000000; i++){
				if(CommentSaved) break;
			}
			
			return false;
		};
	}

	//find reply links
	var ReplyCommentLinks = PageTemplate.GetNodesByAttribute("data-label", "reply_comment_link").GetNodes();
	for(var i = 0 ; i < ReplyCommentLinks.length ; i++) {
		ReplyCommentLinks[i].onclick = function(Event) {	
			//get event
			Event = BrowserWindow.GetEvent(Event);

			//get the list id
			var ItemID = Event.Target.getAttribute("data-profile-comment-id");
			
			//get the initial visibility of the link clicked on
			var Attributes = new Object();
			Attributes['data-label'] = 'add_reply_comment_div';
			Attributes['data-id'] = ItemID;
			var ProfileComment = PageTemplate.GetNodesByAttributes(Attributes).GetNode();
			
			//get the initial visibility for toggling later
			var InitialVisibility = "none";
			if(ProfileComment){
				InitialVisibility = ProfileComment.style.display;
			}
			
			//close all of the comment boxes
			var ProfileComments = PageTemplate.GetNodesByAttribute('data-label', 'add_reply_comment_div').GetNodes();
			for(var i = 0; i < ProfileComments.length; i++){
				ProfileComments[i].style.display = 'none';
			}
			
			//get the reply comment div and check it
			if(ProfileComment && InitialVisibility == "none"){
				ProfileComment.style.display = "block";
			}
			
			//get the initial visibility of the link clicked on
			var Attributes = new Object();
			Attributes['data-field'] = 'reply_comment_text';
			Attributes['data-profile-comment-id'] = ItemID;
			var ReplyText = PageTemplate.GetNodesByAttributes(Attributes).GetNode();
			if(ReplyText) ReplyText.focus();
			
			return false;
		}
	};

	//find the see more comment replies links
	var SeeMoreRepliesLinks = PageTemplate.GetNodesByAttribute("data-label","more_reply_comments_link").GetNodes();
	for(var i = 0 ; i < SeeMoreRepliesLinks.length ; i++) {
		SeeMoreRepliesLinks[i].onclick = function(Event) {
			//get event
			Event = BrowserWindow.GetEvent(Event);

			//get the parent comment id
			var ParentCommentID = Event.Target.getAttribute("data-id");
			//get the divs for this id

			var Attributes = new Object();
			Attributes['data-label'] = 'comments_reply_div';
			Attributes['data-id'] = ParentCommentID;
			var ReplyDivs = PageTemplate.GetNodesByAttributes(Attributes).GetNodes();

			//get the visibility status of the first one
			for(var i = 0; i < ReplyDivs.length; i++){
				ReplyDivs[i].style.display = "block";
			}
			
			var Attributes = new Object();
			Attributes['data-label'] = 'more_reply_comments_row';
			Attributes['data-id'] = ParentCommentID;
			PageTemplate.GetNodesByAttributes(Attributes).GetNode().style.display = 'none';

			return false;
		};
	}

	//find the stop notifications buttons
	var StopNotificationsButtons = PageTemplate.GetNodesByAttribute("data-field","stop_notifications_button").GetNodes();
	for(var i = 0 ; i < StopNotificationsButtons.length ; i++) {
		StopNotificationsButtons[i].onclick = function(Event) {
			if(confirm("Are you sure you want to remove this notification?")){
				//get event
				Event = BrowserWindow.GetEvent(Event);
	
				//get the parent comment id
				var CommentID = Event.Target.getAttribute("data-id");
			
				//set comment saved flag
				CommentSaved = false;
				
				//add the comment
				AjaxStopNotifications(CommentID);
				
				//wait for the comment to be saved
				for(var i = 0; i < 1000000; i++){
					if(CommentSaved) break;
				}
			}
			
			return false;
		};
	}
}

function fitStringToWidth(str,width,className) {
	// str    A string where html-entities are allowed but no tags.
	// width  The maximum allowed width in pixels
	// className  A CSS class name with the desired font-name and font-size. (optional)
	// ----
	// _escTag is a helper to escape 'less than' and 'greater than'
	function _escTag(str){
		if(str){
			return str.replace("<","&lt;").replace(">","&gt;");
		}
	}

	//Create a span element that will be used to get the width
	var span = document.createElement("span");

	//Allow a classname to be set to get the right font-size.
	if (className) span.className=className;
	span.style.display='inline';
	span.style.visibility = 'hidden';
	span.style.padding = '0px';
	document.body.appendChild(span);

	var result = _escTag(str); // default to the whole string
	span.innerHTML = result;

	// Check if the string will fit in the allowed width. NOTE: if the width
	// can't be determinated (offsetWidth==0) the whole string will be returned.
	if (span.offsetWidth > width) {
		var posStart = 0, posMid, posEnd = str.length, posLength;
	
		// Calculate (posEnd - posStart) integer division by 2 and
		// assign it to posLength. Repeat until posLength is zero.
		while (posLength = (posEnd - posStart) >> 1) {
			posMid = posStart + posLength;
	
			//Get the string from the begining up to posMid;
			span.innerHTML = _escTag(str.substring(0,posMid)) + '&hellip;';
		
			// Check if the current width is too wide (set new end)
			// or too narrow (set new start)
			if ( span.offsetWidth > width ) posEnd = posMid; else posStart=posMid;
		}
		
		result = _escTag(str.substring(0,posStart));
	}
	
	if(result != _escTag(str)) result += "&hellip;";

	document.body.removeChild(span);
	
	if(!result) result = '';
	
	return result;
 }


//##########################################################################################
//### ajax functions #######################################################################
//##########################################################################################

function AjaxComments() {
	//create ajax object
	var AjaxComments = new WebLegs.HTTPDriver();
	
	//loading handler
	AjaxComments.Loading = function() {
		PageTemplate.GetNodesByAttribute("data-label", "comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submit_comment_button").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-label", "reply_comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "reply_comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submitreply__comment_button").SetAttribute("disabled", "disabled");
	};
	
	//complete handler
	AjaxComments.Complete = function(Response) {
		var aVariable = Response.responseText.replace('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">','');
		if(AjaxComments.IsSuccess()) {
			//show results
			PageTemplate.GetNodesByAttribute("data-label", "profile_comments").SetInnerHTML(aVariable);
			
			CommentButtons();
		}
		else {
			//get response and show in pop-up
			PageTemplate.GetNodesByAttribute("data-label", "categories").SetInnerHTML('** server error **');
			
			//open error in window
			var ErrorWindow = window.open('','Error','status=no,scrollbars=yes,resizable=yes,width=640,Height=480');
			ErrorWindow.document.write(Response.responseText);
		}

		PageTemplate.GetNodesByAttribute("data-label", "comment_spinner").SetInnerHTML("");
		PageTemplate.GetNodesByAttribute("data-field", "comment_text").RemoveAttribute("disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submit_comment_button").RemoveAttribute("disabled");
		PageTemplate.GetNodesByAttribute("data-label", "reply_comment_spinner").SetInnerHTML("");
		PageTemplate.GetNodesByAttribute("data-field", "reply_comment_text").RemoveAttribute("disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submitreply__comment_button").RemoveAttribute("disabled");
	};
	
	//get the profile user name
	var RegEx = new RegExp(".*/profile/(.*)/(.*)\\.html");
	var Matches = RegEx.exec(window.location);
	var ProfileUsername = Matches[1];
	var ProfileTab = Matches[2];
	
	//make the http request
	AjaxComments.Get("/profile/" + ProfileUsername + "/ajax-comments.html?t=" + ProfileTab);
}

//##########################################################################################

function AjaxSaveComment(CommentText, ReceiveNotifications) {
	//create ajax object
	var AjaxSaveComment = new WebLegs.HTTPDriver();
	
	//loading handler
	AjaxSaveComment.Loading = function() {
		PageTemplate.GetNodesByAttribute("data-label", "comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submit_comment_button").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-label", "reply_comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "reply_comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submitreply__comment_button").SetAttribute("disabled", "disabled");
	};
	
	//complete handler
	AjaxSaveComment.Complete = function(Response) {
		var aVariable = Response.responseText.replace('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">','');
		if(AjaxSaveComment.IsSuccess()) {
			//refresh the comments
			AjaxComments();
		}
		else {
			//get response and show in pop-up
			PageTemplate.GetNodesByAttribute("data-label", "categories").SetInnerHTML('** server error **');
			
			//open error in window
			var ErrorWindow = window.open('','Error','status=no,scrollbars=yes,resizable=yes,width=640,Height=480');
			ErrorWindow.document.write(Response.responseText);
		}
	};
	
	//get the profile user name
	var RegEx = new RegExp(".*/profile/(.*)/.*\\.html");
	var Matches = RegEx.exec(window.location);

	var ProfileUsername = Matches[1];

	//make the http request
	AjaxSaveComment.Get("/profile/" + ProfileUsername + "/ajax-save-comment.html?comment_text=" + encodeURIComponent(CommentText) + "&notify=" + ReceiveNotifications);
}

//##########################################################################################

function AjaxSaveReply(ParentCommentID, ReplyText, ReceiveNotification) {
	//create ajax object
	var AjaxSaveReply = new WebLegs.HTTPDriver();
	
	//loading handler
	AjaxSaveReply.Loading = function() {
		PageTemplate.GetNodesByAttribute("data-label", "comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submit_comment_button").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-label", "reply_comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "reply_comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submitreply__comment_button").SetAttribute("disabled", "disabled");
	};
	
	//complete handler
	AjaxSaveReply.Complete = function(Response) {
		var aVariable = Response.responseText.replace('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">','');
		if(AjaxSaveReply.IsSuccess()) {
			//refresh the comments
			AjaxComments();
		}
		else {
			//get response and show in pop-up
			PageTemplate.GetNodesByAttribute("data-label", "categories").SetInnerHTML('** server error **');
			
			//open error in window
			var ErrorWindow = window.open('','Error','status=no,scrollbars=yes,resizable=yes,width=640,Height=480');
			ErrorWindow.document.write(Response.responseText);
		}
	};
	
	//get the profile user name
	var RegEx = new RegExp(".*/profile/(.*)/.*\\.html");
	var Matches = RegEx.exec(window.location);

	var ProfileUsername = Matches[1];

	//make the http request
	AjaxSaveReply.Get("/profile/" + ProfileUsername + "/ajax-save-reply.html?parent_comment_id=" + ParentCommentID + "&reply_text=" + encodeURIComponent(ReplyText) + "&notify=" + ReceiveNotification);
}

//##########################################################################################

function AjaxDeleteReply(ReplyID) {
	//create ajax object
	var AjaxDeleteReply = new WebLegs.HTTPDriver();
	
	//loading handler
	AjaxDeleteReply.Loading = function() {
		PageTemplate.GetNodesByAttribute("data-label", "comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submit_comment_button").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-label", "reply_comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "reply_comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submitreply__comment_button").SetAttribute("disabled", "disabled");
	};
	
	//complete handler
	AjaxDeleteReply.Complete = function(Response) {
		var aVariable = Response.responseText.replace('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">','');
		if(AjaxDeleteReply.IsSuccess()) {
			//refresh the comments
			AjaxComments();
		}
		else {
			//get response and show in pop-up
			PageTemplate.GetNodesByAttribute("data-label", "categories").SetInnerHTML('** server error **');
			
			//open error in window
			var ErrorWindow = window.open('','Error','status=no,scrollbars=yes,resizable=yes,width=640,Height=480');
			ErrorWindow.document.write(Response.responseText);
		}
	};
	
	//get the profile user name
	var RegEx = new RegExp(".*/profile/(.*)/.*\\.html");
	var Matches = RegEx.exec(window.location);

	var ProfileUsername = Matches[1];

	//make the http request
	AjaxDeleteReply.Get("/profile/" + ProfileUsername + "/ajax-delete-reply.html?reply_id=" + ReplyID);
}

//##########################################################################################

function AjaxDeleteComment(CommentID) {
	//create ajax object
	var AjaxDeleteComment = new WebLegs.HTTPDriver();
	
	//loading handler
	AjaxDeleteComment.Loading = function() {
		PageTemplate.GetNodesByAttribute("data-label", "comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submit_comment_button").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-label", "reply_comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "reply_comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submitreply__comment_button").SetAttribute("disabled", "disabled");
	};
	
	//complete handler
	AjaxDeleteComment.Complete = function(Response) {
		var aVariable = Response.responseText.replace('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">','');
		if(AjaxDeleteComment.IsSuccess()) {
			//refresh the comments
			AjaxComments();
		}
		else {
			//get response and show in pop-up
			PageTemplate.GetNodesByAttribute("data-label", "categories").SetInnerHTML('** server error **');
			
			//open error in window
			var ErrorWindow = window.open('','Error','status=no,scrollbars=yes,resizable=yes,width=640,Height=480');
			ErrorWindow.document.write(Response.responseText);
		}
	};
	
	//get the profile user name
	var RegEx = new RegExp(".*/profile/(.*)/.*\\.html");
	var Matches = RegEx.exec(window.location);

	var ProfileUsername = Matches[1];

	//make the http request
	AjaxDeleteComment.Get("/profile/" + ProfileUsername + "/ajax-delete-comment.html?comment_id=" + CommentID);
}

//##########################################################################################

function AjaxStopNotifications(CommentID) {
	//create ajax object
	var AjaxStopNotifications = new WebLegs.HTTPDriver();
	
	//loading handler
	AjaxStopNotifications.Loading = function() {
		PageTemplate.GetNodesByAttribute("data-label", "comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submit_comment_button").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-label", "reply_comment_spinner").SetInnerHTML('<img src="/_IMAGES/ajax_loading_small.gif" />');
		PageTemplate.GetNodesByAttribute("data-field", "reply_comment_text").SetAttribute("disabled", "disabled");
		PageTemplate.GetNodesByAttribute("data-field", "submitreply__comment_button").SetAttribute("disabled", "disabled");
	};
	
	//complete handler
	AjaxStopNotifications.Complete = function(Response) {
		var aVariable = Response.responseText.replace('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">','');
		if(AjaxStopNotifications.IsSuccess()) {
			//refresh the comments
			AjaxComments();
		}
		else {
			//get response and show in pop-up
			PageTemplate.GetNodesByAttribute("data-label", "categories").SetInnerHTML('** server error **');
			
			//open error in window
			var ErrorWindow = window.open('','Error','status=no,scrollbars=yes,resizable=yes,width=640,Height=480');
			ErrorWindow.document.write(Response.responseText);
		}
	};
	
	//get the profile user name
	var RegEx = new RegExp(".*/profile/(.*)/.*\\.html");
	var Matches = RegEx.exec(window.location);

	var ProfileUsername = Matches[1];

	//make the http request
	AjaxStopNotifications.Get("/profile/" + ProfileUsername + "/ajax-stop-notifications.html?comment_id=" + CommentID);
}

//##########################################################################################
