//comment.js

function checkCommentEdit (e) {
	var method	= 'edit';
	Comment.checkEdit(e, method);
}

function checkCommentDelete (e) {
	var method	= 'delete';
	Comment.checkEdit(e, method);
}

function addComment() {
	Comment.addComment();
}

/*-------------------
 Comment Section Class
--------------------*/

var Comment = {};

/*-----------------
 Comment elements
-------------------*/

Comment.getCommentElement = function () {
	return $('comments');
}

Comment.getCommentElementShadow = function () {
  return $('commentShadow');
}

Comment.getCommentButton = function() {
  return $('Comment_Button');
}

Comment.getCommentNumberElem = function() {
  return $('commentsNumber');	
}

Comment.getCommentBase = function () {
	var commentBase = 'comment-';
	return commentBase;
}

/*-----------------
 Data accessors
-------------------*/

Comment._commentText;

Comment.setText = function (commentText) {
	Comment._commentText = commentText;
}

Comment.getText = function () {
	return Comment._commentText;
}

//Comment status controls when certain events can or cannot occur
Comment._status;

Comment.setStatus = function (status) {
	Comment._status = status;
}

Comment.getStatus = function () {
	return Comment._status;
}

//Number of comments
Comment._numComments;

Comment.setNumComments = function (numComments) {

	// When the number of comments isn't explicitly set
	// fetch it from the element
	if (numComments) {
		Comment._numComments = numComments;	
	} else {
		var commentsNumberObj	= Comment.getCommentNumberElem();
		var numCommentsText		= commentsNumberObj.innerHTML.strip();
		var numComments			= Number(numCommentsText);	
		Comment._numComments 	= numComments;	
	}

}

Comment.getNumComments = function () {
	return Comment._numComments;
}

Comment.updateNumComments = function (numToAdd) {
	//Set and get current values
	Comment.setNumComments();
	var numComments 	= Comment.getNumComments();
	var totalComments	= numComments + numToAdd;

	//Update the element to reflect the new values
	var commentsNumberObj	= Comment.getCommentNumberElem();
	commentsNumberObj.innerHTML = totalComments;
}

//Sets the listeners for all of the comments
Comment.setCollection = function () {
	
	//Set root element for comment section
	var commentRoot 	= Comment.getCommentElement();

	//Set element for individual comments 
	var commentChildren = Element.childElements(commentRoot);

	//Standard string for comment
	var commentBase		= Comment.getCommentBase();

	//Set regular expression 
	var commentIdRegEx	= new RegExp(commentBase);	

	//Comment base strings
	var deleteBase		= commentBase + 'delete-';
	var editBase		= commentBase + 'edit-';
	var replyBase		= commentBase + 'reply-';
	
	//Loop through the elements and set listener
	for (var i = 0; i < commentChildren.length; i++) {
		var currentNode = commentChildren[i].id.toString();	
		
		if (currentNode.match(commentIdRegEx)) {			

			var commentId = Comment.parseCommentId(currentNode);

			//Install deletion
			var deleteButton = $(deleteBase + commentId);
			if (deleteButton) {			
				deleteButton.observe('mouseover', toggleImage);
				deleteButton.observe('mouseout', toggleImage);		
				deleteButton.observe('click', checkCommentDelete);
			}
			
			//Install edit 
			var editButton = $(editBase + commentId);
			if (editButton) {			
				editButton.observe('mouseover', toggleImage);
				editButton.observe('mouseout', toggleImage);
				editButton.observe('click', checkCommentEdit);
			}
							
			//Install reply
			var replyButton = $(replyBase + commentId);
			if (replyButton) {
				replyButton.observe('mouseover', toggleImage);
				replyButton.observe('mouseout', toggleImage);			
				replyButton.observe('click', commentReply);
			}					
		}
	}
		
}

//Parse the comment id 
Comment.parseCommentId = function (commentElmId) {

	//Parse out the components
	var commentComponents	= commentElmId.split('-');
	
	//The id is always the last element
	var commentId			= commentComponents.pop();

	return commentId;
}

//Verify that the user has permission to create or edit comments
Comment.checkEdit = function (e, method) {

	//Verify user
	Security.verifyUser();
	var validUser = Security.getValidUser();
	
	if (validUser == 0) {	
		Security.displayLoginMessage();
		return;
	}
	
	//Get the source element from the event
	var commentElmObj 		= getSourceElement(e);

	//Get the id of the object
	var commentElmId		= commentElmObj.id;	
	
	//Request verification
	var	url					= 'cgi-bin/ajax.cgi?';
	var action				= 'verify_comment_author';
	var commentId			= Comment.parseCommentId(commentElmId);
	
	//Fetch data when we have a valid comment id
	if (commentId) {
		var status = Comment.getStatus();
		
		if (status) {
			return;
		} else {
			Comment.setStatus('verify');
		}
		
		document.body.style.cursor = 'wait';
				
		new Ajax.Request(url,   {
			method: 'get',
			parameters: {'action': action, 'comments_id' : commentId},
			onSuccess: function(transport){
	    		var textResponse = transport.responseText || 'No response text from server';
	    		if (textResponse == 1) {
	    			
	    			//Determine which method to use
	    			if (method == 'edit') {
		    			Comment.displayEdit(commentId);	
	    			} else if (method == 'delete') {
	    				Comment.deleteComment(commentId);
	    			} else {
						//Display error message
					    ErrorMessage.setHeader('System Error: Method Not Specified');
					    ErrorMessage.setMessage('The method was not specified for the requested action.');
					    ErrorMessage.displayMessage();	    			
	    			}
	    		} else {
	    			//Clear progress indicators
	    			Comment.setStatus(null);
	    			document.body.style.cursor = 'auto';
					
					//Display error message
				    ErrorMessage.setHeader('Error: Cannot Edit or Delete Comment');
				    ErrorMessage.setMessage("You can't edit or delete a comment you didn't create.");
				    ErrorMessage.displayMessage();
				    
				    return;	    			
	    		} 
			},
			onFailure: function(){ alert('System Error: Unable to edit comment'); }
		});	
	}

}

Comment.addComment = function() {
	
	//Verify that user has permission to create comments
	Security.verifyUser();
	var validUser = Security.getValidUser();
	
	if (validUser == 0) {		
		Security.displayLoginMessage();
	} else {
		//Fetch user's name and profile image
		//STUB
		
		//Remove no comment message if it exists
		if ($('noComments')) {
			$('noComments').remove();
		}
			
		//Insert new element
		var commentBalloonElm = Comment.getTemplate();
		Element.insert('commentToolBar', {after: commentBalloonElm});
	
		Comment.adjustShadow();	
	}
			
}

Comment.insertComment = function(commentElmId) {

	//commentId is the random number generated by the add button
	var commentElmIdObj	= $(commentElmId);
	
	//commentIdValue is the actual comment_id stored in the data base
	var commentIdValue	= commentElmIdObj.value;
	
	//Get the comment text
	var commentTextId	= 'commentTextId-' + commentElmId;
	var commentTextObj	= $(commentTextId);
	var commentText		= commentTextObj.value;
	
	//Get the reply to value if it exists
	var commentsReplyToId	= 'commentReplyToId-' + commentElmId;
	var commentsReplyObj	= $(commentsReplyToId);
	var commentsReplyValue	= commentsReplyObj.value;
	
	//Get the storyId
	Story.setStoryId();
	var storyId = Story.getStoryId();
		
	var url 	= 'cgi-bin/ajax.cgi?';
	var action	= 'save_comment';
	
	new Ajax.Request(url, {
    	method:'post',
		parameters: {'action': action, 'story_id': storyId, 'comment_id': commentIdValue, 'comments_reply_to_id': commentsReplyToId, 'comments_text': commentText},
    	onSuccess: function(transport){
    		var commentId = transport.responseText || 'No response text';
    		    		
    		if (commentId) {
		    	Comment.displayNewComment(commentElmId, commentId);
    		} else {
    			alert('System Error: Your comment could not be saved. Please try again later.');
    		}

	    },
    	onFailure: function(){ alert('System Error: No text was retrieved') }
	});

}

//Delete Comment
Comment.deleteComment = function (commentId) {
		
		//Request verification
		var	url					= 'cgi-bin/ajax.cgi?';
		var action				= 'delete_comment';
		
		document.body.style.cursor = 'wait';
				
		new Ajax.Request(url,   {
			method: 'post',
			parameters: {'action': action, 'comments_id' : commentId},
			onSuccess: function(transport){
	    		var textResponse = transport.responseText || 'No response text from server';
	    		if (textResponse == 1) {
					var commentBase	= Comment.getCommentBase();
					$(commentBase + commentId).remove();

	    			//Clear progress indicators
	    			Comment.adjustShadow();
	    			Comment.setStatus(null);
	    			document.body.style.cursor = 'auto';

	    		} else {
	    			//Clear progress indicators
	    			Comment.setStatus(null);
	    			document.body.style.cursor = 'auto';
					
					//Display error message
				    ErrorMessage.setHeader('System Error: Cannot Delete Comment');
				    ErrorMessage.setMessage('A system error occured preventing the deletion of the comment.');
				    ErrorMessage.displayMessage();
				    
				    return;	    			
	    		} 
			},
			onFailure: function(){ alert('System Error: Unable to edit comment'); }
		});	

}

//Cancel creating a new comment
Comment.cancelComment = function(commentElmId) {

	var commentObj			= $('comment-' + commentElmId);	
	commentObj.remove();	

	Comment.setNumComments();
	var numComments = Comment.getNumComments();

	Comment.setNumComments();
	var numComments = Comment.getNumComments();

	if (numComments == 0) {
		Element.insert('commentToolBar', {after: '<div id="noComments" class="dialogText">No comments have been made on this story. Be the first to make a comment!</div>'});
	}
	
	Comment.adjustShadow();

}

/*----------------
Comment Display Functions
-----------------*/

Comment.hideNumComments = function () {
	var commentsNumberObj = Comment.getCommentNumberElem();
	if (commentsNumberObj) {
 		commentsNumberObj.style.display = 'none';		
	}
}

//Template for new comments
Comment.getTemplate = function (replyToId, authorName, authorImgURL) {
	
	var todaysDate	= getTodaysDate();
	
	if (!replyToId) {
		replyToId = 0;
	}
	
	//Set default user data
	if (!authorImgURL) {
		authorImgURL = '../images/User_Icon_Small.gif';
	}
	
	if(!authorName) {
		authorName = 'You';
	}
	
	//The commentElmId is a temporary number that is not the actual comment_id
	var randomNum		= Numbers.getRandomNumber();
	var commentElmId	= randomNum;

	//Build the template		
	var commentTemplate = ''; 
	commentTemplate += '<div id="comment-' + commentElmId + '">';
	commentTemplate += '	<div id="' + commentElmId + '" class="commentBalloon">';
	commentTemplate += '		<div class="commentTop">&nbsp;</div>';
	commentTemplate += '		<div id="comment-entry-' + commentElmId + '" class="comment-entry">';
	commentTemplate += '			<textarea name="comments_text" id="commentTextId-' + commentElmId + '" cols="33" rows="3"></textarea></div>';
	commentTemplate += '		<div class="commentBottom">&nbsp;';
	commentTemplate += '			<input type="hidden" name="comment_id" id="' + commentElmId + '" value="0"/>';
	commentTemplate += '			<input type="hidden" name="comments_reply_to_id" id="commentReplyToId-' + commentElmId + '" value="' + replyToId + '"/>';
	commentTemplate += '		</div>';
	commentTemplate += '	</div>';
							
	commentTemplate += '	<div id="comment-info-' + commentElmId + '" class="commentData">';
	commentTemplate += '		<div class="commentAuthor">' + authorName + '</div>';
	commentTemplate += '		<div class="commentDateAdded">Posted: ' + todaysDate + '</div>';
	commentTemplate += '		<div class="commentAuthorIcon"><img src="' + authorImgURL + '" alt="Image of ' + authorName + '"/></div>';
	commentTemplate += '	</div>';
							
	commentTemplate += '	<div id="commentCreate-'+ commentElmId + '" class="commentCreate">';
	commentTemplate += '		<input type="button" name="saveComment" value="Save" class="widgetButton" onclick="new Comment.insertComment(\'' + commentElmId + '\')">';
	commentTemplate += '		<input type="button" name="cancelComment" value="Cancel" class="widgetButton" onclick="new Comment.cancelComment(\'' + commentElmId + '\')">';	
	commentTemplate += '	</div>';
							
	commentTemplate += '	<div id="commentStatusId-'+ commentElmId + '" class="commentStatus">';
	commentTemplate += '		&nbsp;';
	commentTemplate += '	</div>';
	commentTemplate += '</div>';
		
	return commentTemplate;

}

Comment.displayNewComment = function(commentElmId, commentId) {
	
	var commentElmIdObj	= $(commentElmId);	
	commentElmIdObj.value = commentId;		

	//Get the comment text
	var commentTextId	= 'commentTextId-' + commentElmId;
	var commentTextObj	= $(commentTextId);
	var commentText		= commentTextObj.value;
	
	//Change from a form object to standard text
	var commentBodyObj	= $('comment-entry-' + commentElmId);
	commentBodyObj.innerHTML = commentText;

	//Delete the save button
	var commentCreationId	= 'commentCreate-' + commentElmId;
	var commentCreateObj	= $(commentCreationId);
	
	commentCreateObj.remove();	
	Comment.adjustShadow();

	Comment.updateNumComments(1);
	
}

Comment.areCommentsDisplayed = function() {
	var commentElement 	= Comment.getCommentElement();
	var commentDisplay	= commentElement.getStyle('display');
	return commentDisplay;
}

Comment.toggleComments = function(e) {

	var image = getSourceElement(e);

	var cSDisplayed 	= Comment.areCommentsDisplayed();
		
	if(cSDisplayed == 'none') {
		Comment.displayComments(image);
		hideBalloonBox();
	} else {
		Comment.hideComments(image);
		Comment.buttonOff();
	}
	
	try {
		Comment.setCollection();
	} catch (e) {
		//die silently
	}
		
}

Comment.turnCommentsButtonOn = function() {
	
	//Resets the image to the original "on" by using the image name
	var commentButtonObj	= Comment.getCommentButton();
	var commentButtonName	= commentButtonObj.name;
	var imageSource			= '../images/' + commentButtonName + '_On.gif';
	commentButtonObj.src	= imageSource;	

}

// Requires a unique method since rollover handler would simply
// turn the image off when the comments are still displayed
Comment.turnCommentsButtonOff = function() {

	var cSDisplayed 		= Comment.areCommentsDisplayed();

	if(cSDisplayed == 'none') {
		Comment.buttonOff();
	}
	
}

//Turns off the comment button without an evaluation of 
//whether or not the comments are displayed
Comment.buttonOff = function() {
		//Resets the image to the original "off" by using the image name
		var commentButtonObj	= Comment.getCommentButton();
		var commentButtonName	= commentButtonObj.name;
		var imageSource			= '../images/' + commentButtonName + '.gif';
		commentButtonObj.src	= imageSource;	
}


Comment.displayComments = function() {

	var commentElem			= Comment.getCommentElement();
	var commentShadowElem	= Comment.getCommentElementShadow();
	
	// Create story object 
	var storyElem			= Story.getStoryElement();
	var storyShadowElem		= Story.getStoryShadowElement();
	var shadowExtra			= 3;

	//Show button first to indicate status change
	Comment.turnCommentsButtonOn();

	//Bring comment section into view 
	new Effect.Appear(commentElem);

	//Set parameters of comment object
	commentHeight			= commentElem.getHeight();
	storyHeight				= storyElem.getHeight();
		
	//Position comment shadow before the comment so that it shows up correctly
	commentShadowElem.setStyle({height: (commentHeight + shadowExtra) + 'px'});
	storyShadowElem.setStyle({height: (storyHeight + shadowExtra)  + 'px'});

	//And then the shadow
	commentShadowElem.setStyle({opacity: 0.2});
	commentShadowElem.style.display = 'block';
	storyShadowElem.setStyle({opacity: 0.2});
	storyShadowElem.style.display = 'block';
	storyElem.setStyle({border: 'solid #DDDDDD 1px'});
	storyElem.setStyle({paddingLeft: '9px'});
	storyElem.setStyle({paddingTop: '0px'});

}

Comment.hideComments = function(image) {

	var commentElem			= Comment.getCommentElement();
	var commentShadowElem	= Comment.getCommentElementShadow();
	
	var storyElem			= Story.getStoryElement();
	var storyShadowElem		= Story.getStoryShadowElement();

	new Effect.Fade(commentElem);
	new Effect.Fade(storyShadowElem);
	new Effect.Fade(commentShadowElem);
	Comment.turnCommentsButtonOff();
	storyElem.setStyle({border: 'solid #DDDDDD 0px'});
	storyElem.setStyle({paddingLeft: '10px'});
	storyElem.setStyle({paddingTop: '1px'});

}

Comment.adjustShadow = function() {
	
	//Adjust comment shadow
	var commentElem			= Comment.getCommentElement();
	var commentShadowElem	= Comment.getCommentElementShadow();
	var commentHeight		= commentElem.getHeight();
	var shadowExtra			= 3;

	commentShadowElem.setStyle({height: (commentHeight + shadowExtra) + 'px'});

}

Comment.clearEdit = function (e) {

	var commentBase	= Comment.getCommentBase();
	var commentId	= Comment.getCommentId();
	var commentObj	= Comment.getCommentObj(commentId);
		
	if (commentObj) {
		commentObj.setStyle({backgroundColor : '#FFFFFF'});
	}	
}

Comment.getButtonTemplate = function (commentId) {

	var buttonTemplate	= '<div id="commentCreate-'+ commentId + '" class="commentCreate">';
	buttonTemplate		+= '		<input type="button" name="saveComment" value="Save" class="widgetButton" onclick="new Comment.update(\'' + commentId + '\')">';
	buttonTemplate		+= '		<input type="button" name="cancelComment" value="Cancel" class="widgetButton" onclick="new Comment.cancelEdit(\'' + commentId + '\')">';	
	buttonTemplate		+= '</div>';

	return buttonTemplate;

}

Comment.update = function (commentId) {

	//Verify that user has permission to edit comments
	Security.verifyUser();
	var validUser = Security.getValidUser();
	
	if (validUser == 0) {	
		Security.displayLoginMessage();
		return;
	}
		
	//Request verification
	var	url					= 'cgi-bin/ajax.cgi?';
	var action				= 'update_comment';
	var commentText			= $('commentTextId-' + commentId).value;
		
	//Fetch data when we have a valid comment id
	if (commentId) {
		var status = Comment.getStatus();
		
		if (status == 'update') {
			return;
		} else {
			Comment.setStatus('update');
		}
		
		document.body.style.cursor = 'wait';
		
		new Ajax.Request(url,   {
			method: 'post',
			parameters: {'action': action, 'comments_id' : commentId, 'comments_text' : commentText},
			onSuccess: function(transport){
	    		var textResponse = transport.responseText || 'No response text from server';
	    		if (textResponse) {
	    			Comment.displaySave(commentId);		
	    		} else {
					Comment.invalid(commentId);
	    		}
			},
			onFailure: function(){ alert('System Error: Unable to edit comment'); }
		});	
	} else {
	    ErrorMessage.setHeader('System Error: No Comment Id');
	    ErrorMessage.setMessage('A system error has occured as no Comment Id is available. Please contact the system administrator.');
    	ErrorMessage.displayMessage();
    	return;
	}

}

Comment.displaySave = function (commentId) {
	
	//Keep the user from overzealously clicking
	var status = Comment.getStatus();
		
	if (status != 'update') {
		return;
	} else {
		Comment.setStatus(null);
	}

	//Set up the base elements
	var commentBase		= Comment.getCommentBase();
	var commentElm		= $(commentBase + commentId);
	var commentEntryElm	= $(commentBase + 'entry-' + commentId);
	
	//Get current data for editing and save for later
	var commentText			= $('commentTextId-' + commentId).value;
	commentEntryElm.innerHTML = commentText;

	//Update the page
	Comment.adjustShadow();
	document.body.style.cursor = 'auto';

}

Comment.displayEdit = function (commentId) {

	//Keep the user from overzealously clicking
	var status = Comment.getStatus();
		
	if (status == 'edit') {
		return;
	} else {
		Comment.setStatus('edit');
	}

	//Set up the base elements
	var commentBase		= Comment.getCommentBase();
	var commentElm		= $(commentBase + commentId);
	var commentEntryElm	= $(commentBase + 'entry-' + commentId);
	var commentInfoElm	= $(commentBase + 'info-' + commentId);
	
	//Get current data for editing and save for later
	var commentText 	= commentEntryElm.innerHTML;
	Comment.setText(commentText); //Allows for retrieval should the user cancel
	
	//Create comment field
	var commentField	= '<textarea name="comments_text" id="commentTextId-' + commentId + '" cols="33" rows="3">' + commentText + '</textarea>';
	commentEntryElm.innerHTML = commentField;
	
	//Add save and cancel buttons
	var buttonTemplate	= Comment.getButtonTemplate(commentId);

	//Update the page
	Element.insert(commentInfoElm, {after: buttonTemplate});
	Comment.adjustShadow();
	document.body.style.cursor = 'auto';

	
}

Comment.cancelEdit = function (commentId) {

	//Set up the base elements
	var commentBase		= Comment.getCommentBase();
	var commentElm		= $(commentBase + commentId);
	var commentEntryObj	= $(commentBase + 'entry-' + commentId);
	var commentCreate	= $('commentCreate-' + commentId);
	
	//Get current data for editing
	var commentText 	= 	Comment.getText();
	commentEntryObj.innerHTML = commentText;

	//Delete save and cancel buttons
	Element.remove(commentCreate);
	new Effect.Highlight(commentElm, {duration: 0.75});		
	Comment.adjustShadow();

	Comment.setStatus(null);

}





