//---------------------------  COMMENTS JS STUFF  --------------------------------

// COMMENTS: an object containing functions and attributes necessary to
// handle the progressive AJAX loading of comments
//
// NOTE: Also checks to see if comments exist and only performs
// 		the functionality if they were detected on the page!
//
// Charlie Markovich - 5/12/08

var memberId = null;
var contentId = null;

/*** captcha related ***/
var coID;

/*** form descriptor values ***/
var nameDescriptor = "Your name";
var uwordDescriptor = "Enter the code shown below";

/*** submit button text ***/
var memberSubmitButton = "Sign In & Post Comment";
var nonMemberSubmitButton = "Post Comment";

/*** required for comment retrieval ***/
var totalCommentsFound = 0;
var totalCommentsShowing = 50;
var totalCommentsPosted = 0;
var commentSetSize = 50; // Total comments limit set per query

/*** how to load first set (server-side vs ajax) ***/
var loadInitialSet = false; // if false, will load via ajax
if (loadInitialSet == false) { totalCommentsShowing = 0; }

/*** store the form submission link ***/
var submitActive = false;


// an easier way to stick in a captcha (with room for improvement)
Captcha = {
	Load: function(el) {
		if($(el)){
			var captchaID = (Math.floor(Math.random()*191))+1;
			$(el).innerHTML = '<img src="http://images.eonline.com/static/redcarpet/globes2007/everywhere/shoutouts/images/'+captchaID+'.jpg" border="0" alt="" />'
							+ '<input type="hidden" value="'+captchaID+'" id="'+el+'_captchaID" class="hidden" />';
		}
	}
}

Comments = {
	AddFormDescriptors: function() {
		// adds form descriptors in the input fields themselves
		if ($('comment_guest')) {
			$('name').value = nameDescriptor;
			Event.observe('name', 'focus', function() {
				$('name').value = '';
			});
			Event.observe('name', 'blur', function() {
				if ($('name').value == '') {
					$('name').value = nameDescriptor;
				}
			});
			
			$('uword').value = uwordDescriptor;
			Event.observe('uword', 'focus', function() {
				$('uword').value = '';
			});
			Event.observe('uword', 'blur', function() {
				if ($('uword').value == '') {
					$('uword').value = uwordDescriptor;
				}
			});
		}
	},
	ChangeButtonStatus: function() {
		// changes submit button text depending on if user is logging in or not
		var buttonText = document.getElementById("anonPostButton");
		buttonText.innerHTML = (document.user_comments.passwd.value.length > 0) ? memberSubmitButton : nonMemberSubmitButton;
	},
	DisableSubmitButton: function() {
		$("anonPostButton").innerHTML = "Posting...";
		$("comment_text").addClassName("disabled");
	},
	EnableSubmitButton: function() {
		$("anonPostButton").innerHTML = "Post Comment";
		$("comment_text").removeClassName("disabled");
	},
	Init: function() {
		// First check that the comments module is somewhere in the DOM (determined by an element with id="comments_set")
		// if comments module exists, we activate the necessary parts and return true (success)
		// if comments module does not exist, skip the activation and return false (failure)
		var myCommentsModule = $('comments_set');

		if (myCommentsModule){
			totalCommentsFound = $('totalComments').value;

			// Register the event listener for the more comments button and set to load if so
			if ($('display_next_link')) { Event.observe('display_next_link', 'click', this.GetMore); };
		
			// load first set via ajax if not loaded server-side
			if (loadInitialSet == false && totalCommentsFound > 0) { this.GetFirst(); };
		
			Captcha.Load('comment_captcha');	// Initialize the captcha module
			Comments.AddFormDescriptors();		// create the form field descriptors and add them to the DOM

			return true;	// success!
		} else {
			return false;	// failure (no comments module found in the DOM)
		}
	},
	GetFirst: function() {
		commentSetSize = 50;
		totalCommentsShowing = 0;
		totalCommentsPosted = 0;
		GetComments.TogglePreloader();
		GetComments.GetNextPage();
	},
	GetMore: function() {
		GetComments.TogglePreloader();
		GetComments.GetNextPage();
	}
}

//To send/edit a comment
PostComments = {
	Save: function(blog, url, contentDBID, memberId, commentId) {
		if(submitActive != true) {	// check to see if a submission is already taking place
			submitActive = true;
			Comments.DisableSubmitButton();	// disable the submit button to prevent duplicate submissions
			var isMemberComment = false;
			var isValid = true;
			if ($('comments_message')) {
				$('comments_message').remove();
			}
		    Delete_Cookie("PostCookie","/",".eonline.com");
			SetCookie("PostCookie",coID,5,"/",".eonline.com");
			var captchaId = '';
			var captchaEntry = '';
			if ($('uword')) {
				captchaEntry = hex_md5(document.getElementById('uword').value);
				captchaId = $F('comment_captcha_captchaID');
			}
			if($('commentTextArea').value == '') {
				alert('You must enter a comment.');
				isValid = false;
			}
			var nextIndex = parseInt(totalCommentsFound)+1+totalCommentsPosted;
			var pars = 'mode=save'+'&contentDBID='+escape(contentDBID)+'&commentId='+escape(commentId)
					  +'&memberId='+escape(memberId)+'&pageURL='+escape(url)+'&blog='+escape(blog)+'&nextIndex='+escape(nextIndex)
					  +'&captchaId='+escape(captchaId)+'&comment='+escape($('commentTextArea').value);
			if($('usrEmail') && $('passwd')) {
				if ($('passwd').value != '') isMemberComment = true;
				pars= pars+'&memberEmail='+$('usrEmail').value+'&password='+$('passwd').value;
			}
			if ($('name') && !isMemberComment) {
				if($('name').value == 'Your name') {
					alert('You must enter a username.');
					isValid = false;
					Comments.EnableSubmitButton();	// enable the submit button to allow submitting again
					submitActive = false;
				}
				if($('uword').value == 'Enter the code shown below' || $('uword').value == '') {
					alert('You must enter a valid captcha entry.');
					isValid = false;
					Comments.EnableSubmitButton();	// enable the submit button to allow submitting again
					submitActive = false;
				}
				pars= pars+'&username='+$('name').value+'&captcha='+captchaEntry;
			}
			if(isValid) {
				new Ajax.Updater('comments_set', '/uberblog/includes/jsp/editComment.jsp?'+pars, {
					method:'post',
					postBody:pars,
					insertion: Insertion.Bottom,
					onComplete: function() {
						Captcha.Load('comment_captcha');	// reload the captcha after a submission
						if ($('uword')) $('uword').value = '';				// clear the captcha word field
						new Effect.Highlight('comments_message');
					},
					onSuccess: function() {
						$('commentTextArea').value = '';	// clear the textarea
						totalCommentsPosted++;
						$$('.total_comments').each(function(e) {
							e.update(parseInt(totalCommentsFound)+1);
						});
						if(isMemberComment) {
							$('comment_guest').hide();
							$('comment_member').hide();
						};
						alert("Thanks! Your comment has been sent to our moderators for review.");
						Comments.EnableSubmitButton();	// enable the submit button to allow submitting again
						submitActive = false;
					},
					onFailure: function() {
						Comments.EnableSubmitButton();	// enable the submit button to allow submitting again
						submitActive = false;
					}
				});
			}
		}
	},
	Delete: function(commentId) {
		var pars = 'commentId='+commentId+'&mode=delete';
		new Ajax.Request('/uberblog/includes/jsp/editComment.jsp?'+pars);
	},
	ReportAbuse: function(commentId) {
		var confirmReport = "Report this comment as inappropriate?\n\nIf you feel this comment is inappropriate and feel it should be removed from the E! Online site, let us know by clicking 'OK' below. This will notify us and we can take appropriate action.";
		var pars = 'commentId='+commentId+'&mode=report';
		if (confirm(confirmReport)) {
			new Ajax.Request('/uberblog/includes/jsp/editComment.jsp?'+pars, {
				onComplete: function() {
					alert ("Thank you for your input\n\nThis commment has been reported.  We will review this information and take appropriate action");
					$('report_'+commentId).update('This comment has been reported.');
					$('report_'+commentId).removeAttribute('href');
					$('report_'+commentId).addClassName('reported');
				}
			});
		}
	},
	GiveProps: function(commentId) {
		var pars = 'commentId='+commentId+'&mode=props';
		new Ajax.Request('/uberblog/includes/jsp/editComment.jsp?'+pars);
	}
}

GetComments = {

	CalculateNextSetSize: function(){
		// check to see if the comments remaining are less than the commentSetSize
		var commentsRemaining = totalCommentsFound - totalCommentsShowing; 
		if (commentsRemaining < commentSetSize) {
			commentSetSize = commentsRemaining;
		}
	},

	GetNextPage: function(){
		contentId = $('contentId').value;
		memberId = $('memberId').value;
		new Ajax.Updater('display_next_set', '/uberblog/chatter/includes/jsp/getPageOfComments.jsp', {
			method: 'get',
			insertion: Insertion.Before,
			onComplete: function(){
				GetComments.TogglePreloader();
				totalCommentsShowing = totalCommentsShowing + commentSetSize;
				var linkText = "Im empty";
				var commentsRemaining = (totalCommentsFound > totalCommentsShowing) ? totalCommentsFound - totalCommentsShowing : 0;
				if (commentsRemaining > 0){
					GetComments.CalculateNextSetSize();
					linkText = "Show the next " + (totalCommentsShowing + 1) + " - " + (totalCommentsShowing + commentSetSize) + " of " + totalCommentsFound + " comments";
					$('display_next_link').innerHTML = linkText;
				} else {
					commentSetSize = 50;
					totalCommentsShowing = 0;
					totalCommentsPosted = 0;
					$('display_next_set').hide();
				}
			},
			parameters: {offset: totalCommentsShowing, length: commentSetSize, memberId: memberId, contentId: contentId}
		});
	},

	// If more comments available then display the preloader animation
	TogglePreloader : function(/*resultsShowing, totalResults*/){
		if ($('preloader_graphic').style.display == "block"){
			$('preloader_graphic').style.display = 'none';
		} else {
			$('preloader_graphic').style.display = 'block';
		}
	}
}

//------------------------Cookie Stuff---------------------------
function Get_Cookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ){
		return null;
	}
	if ( start == -1 ) return null; 
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
}

	// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
function SetCookie(cookieName,cookieValue,nDays, path, domain) {
 	var today = new Date();
 	var expire = new Date();
 	if (nDays==null || nDays==0) nDays=1;
 		expire.setTime(today.getTime() + 3600000*24*nDays);
 		document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString()+";path="+path+";domain="+domain;
}
//----------------------End Cookie Stuff---------------------------


	// Register the listeners after the page has been fully loaded
//	Event.observe( window, 'load', Comments.Init);
