// Global variables
// t is a global time set to clear the rating's message window
var timerComments;
// comment2Update keeps track of which comment has been updated by the user
var comment2Update;

// timerAjaxComments is a global timer set to keep track of how long it is
// taking for the Geogad server to respond. If it is longer than some
// prefered value, the program redirects the user input to another operation.
var timerAjaxComments;

// From http://jehiah.cz/archive/javascript-isdefined-function
function isDefinedComments(variable)
{
return (!(!( variable||false )));
}

// Found this code at 
// http://javascript.crockford.com/memory/leak.html
function purgeComment(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}

// Recursively delete a node and its children
// Found this simple code at 
// http://www.mikechambers.com/blog/2006/01/24/removing-html-element-children-with-javascript
function removeChildrenRecursivelyComments(nodeName) {

   var node = document.getElementById(nodeName);
   if (!node) return;
 
   while (node.hasChildNodes()) {
	removeChildrenRecursivelyComments(node.firstChild);
        purge(node.firstChild);
   	node.removeChild(node.firstChild);
   }

}


function isAjaxSupportedComment() {
// Check if request can be created by is not used
   var request = null;
   if(typeof window.XMLHttpRequest != 'undefined')
   {
     request = new XMLHttpRequest();
   }
   else if(typeof window.ActiveXObject != 'undefined')
   {
     try { request = new ActiveXObject('Microsoft.XMLHTTP'); }
     catch(err) { request = null; }
   }
   if (request != null)
   	return(true); 
   else 
   	return(false); 
}


// Preload mousechange images
image1 = new Image();
image1.src = "images/upgreen.jpg";

image2 = new Image();
image2.src = "images/upgray.jpg";

image3 = new Image();
image3.src = "images/downred.jpg";

image4 = new Image();
image4.src = "images/downgray.jpg";


function showBannedComment(commentId) {

// Hide the current banned title and show the hidden banned title
   var visibleTitle = document.getElementById("bannedBlockShow"+commentId);
   var invisibleTitle = document.getElementById("bannedBlockHide"+commentId);

// Switch titles
   visibleTitle.style.visibility = "hidden";
   visibleTitle.style.display = "none" ;
   invisibleTitle.style.visibility = "visible";
   invisibleTitle.style.display = "inline" ;

// Show the banned comment
   var comment = document.getElementById("commentInfo"+commentId);
   comment.style.visibility = "visible";
   comment.style.display = "inline" ;

}

function hideBannedComment(commentId) {

// Hide the current banned title and show the hidden banned title
   var visibleTitle = document.getElementById("bannedBlockHide"+commentId);
   var invisibleTitle = document.getElementById("bannedBlockShow"+commentId);

// Switch titles
   visibleTitle.style.visibility = "hidden";
   visibleTitle.style.display = "none" ;
   invisibleTitle.style.visibility = "visible";
   invisibleTitle.style.display = "inline" ;

// Show the banned comment
   var comment = document.getElementById("commentInfo"+commentId);
   comment.style.visibility = "hidden";
   comment.style.display = "none" ;

}

function clearCommentTitleMessage(id) {
	var rt = document.getElementById(id);
	rt.innerHTML = "";
}

function alreadyRatedCommentMessage(id) {
	window.clearTimeout(timerComments);
	var rt = document.getElementById(id);
	rt.innerHTML = '<span style="font-size: 100%;color:rgb(255,0,0);">You have already rated.</span>';
	timerComments = window.setTimeout('clearCommentTitleMessage("'+id+'")', 2000);  
}

function login2RateCommentMessage(id) {
	window.clearTimeout(timerComments);
	var rt = document.getElementById(id);
	rt.innerHTML = '<span class="regLink"><a href="login">Log in</a></span> to rate.';
	timerComments = window.setTimeout('clearCommentTitleMessage("'+id+'")', 5000); 
}

function login2MarkSpamMessage(id) {
	window.clearTimeout(timerComments);
	var rt = document.getElementById(id);
	rt.innerHTML = '<span class="regLink"><a href="login">Log in</a></span> to mark spam.';
	timerComments = window.setTimeout('clearCommentTitleMessage("'+id+'")', 5000); 
}

function login2ReplyMessage(id) {
	window.clearTimeout(timerComments);
	var rt = document.getElementById(id);
	rt.innerHTML = '<span class="regLink"><a href="login">Log in</a></span> to reply.';
	timerComments = window.setTimeout('clearCommentTitleMessage("'+id+'")', 5000); 
}

function commentClearMessage(id) {
	commentClearTimers();
	var rt = document.getElementById(id);
	rt.innerHTML = '';
}

function commentEmptyMessage(id) {
	commentClearTimers();
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="newCommentMessageBox"><div style="text-align: center" ><span class="yellowBackground redfont">Type in a comment.</span></div></div>';
	timerComments = window.setTimeout('commentClearMessage("'+id+'")', 7000); 
}

function commentSuccess(id) {
	commentClearTimers();
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="newCommentMessageBox"><div style="text-align: center" ><span class="blueText">Thanks for commenting!</span></div></div>';
	timerComments = window.setTimeout('commentClearMessage("'+id+'")', 7000); 
}

function commentWaitMessage(id) {
	commentClearTimers();
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="newCommentMessageBox"><div style="text-align: center" ><span class="blueText">Sending....</span></div></div>';
}

function commentProblemMessage(id) {
	commentClearTimers();
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="newCommentMessageBox"><div style="text-align: center" ><span class="yellowBackground redfont">Problem sending comment. Please try again later.</span></div></div>';
	timerComments = window.setTimeout('commentClearMessage("'+id+'")', 7000); 
}

function commentProblemDisplayMessage(message, id) {
	commentClearTimers();
	var rt = document.getElementById(id);
	rt.innerHTML = '<div class="newCommentMessageBox"><div style="text-align: center" ><span class="yellowBackground redfont">'+message+'</span></div></div>';
	timerComments = window.setTimeout('commentClearMessage("'+id+'")', 7000); 
}

function commentClearTimers() {
// free callback timer here
   window.clearTimeout(timerComments);
   window.clearTimeout(timerAjaxComments);
}

function commentRatingSentMessage(id) {
// Send message to user
   commentClearTimers();
   var rt = document.getElementById(id);
   rt.innerHTML = 'Rating sent!';
   timerComments = window.setTimeout('clearCommentTitleMessage("'+id+'")', 10000); 
}

function handleReturnComments(data) {
	// do nothing
}

function getThisCommentRating(data) {
   if (data != null) {
	// The user's rating data was accepted and stored by Geogad. Now display new information.
	JGetCommentInfo.getCommentRating(comment2Update, updateCommentRating);
   }
}

function updateCommentRating(data) {
   if (data != null) {
	var temp = parseInt(data, 10);
        var rt = document.getElementById('comment'+comment2Update+'RatingCount');
        rt.innerHTML = temp+"&nbsp;";	
   }
}


function CommentPoorRating(nickname, commentId) {

// Set global variable so that the comment can be updated in the future
   comment2Update = commentId;

   var id = 'titleMessage' + commentId;
	
// Send data to Geogad server
   JGetCommentInfo.createCommentRating(commentId, nickname, false, true, false, getThisCommentRating);

// Create anonymous function fo display the already rated message function
   var functionDemo = new Function("alreadyRatedCommentMessage('"+id+"'); return (false);")
   
// Change input to prevent user from rating again
    var img1 = document.getElementById("poorComment"+commentId);
    img1.setAttribute("onclick", "");
    img1.setAttribute("onmouseover", functionDemo);
    img1.setAttribute("onmouseout", "");
    img1.setAttribute("alt", "You have already rated");
    var img2 = document.getElementById("goodComment"+commentId);
    img2.setAttribute("onclick", "");
    img2.setAttribute("onmouseover", functionDemo);
    img2.setAttribute("onmouseout", "");
    img2.setAttribute("alt", "You have already rated");

    commentRatingSentMessage(id);

}

function CommentGoodRating(nickname, commentId) {  

// Set global variable so that the comment can be updated in the future
   comment2Update = commentId;

   var id = 'titleMessage' + commentId;
	
// Send data to Geogad server
   JGetCommentInfo.createCommentRating(commentId, nickname, true, false, false, getThisCommentRating);
   
// Create anonymous function fo display the already rated message function
   var functionDemo = new Function("alreadyRatedCommentMessage('"+id+"'); return (false);")
   
// Change input to prevent user from rating again
    var img1 = document.getElementById("poorComment"+commentId);
    img1.setAttribute("onclick", "");
    img1.setAttribute("onmouseover", functionDemo);
    img1.setAttribute("onmouseout", "");
    img1.setAttribute("alt", "You have already rated");
    var img2 = document.getElementById("goodComment"+commentId);
    img2.setAttribute("onclick", "");
    img2.setAttribute("onmouseover", functionDemo);
    img2.setAttribute("onmouseout", "");
    img2.setAttribute("alt", "You have already rated");

    commentRatingSentMessage(id);
}

function CommentSpam(nickname, commentId) {

// Set global variable so that the comment can be updated in the future
   comment2Update = commentId;
   var id = 'titleMessage' + commentId;
	
// Send data to Geogad server
   JGetCommentInfo.createCommentRating(commentId, nickname, false, false, true, handleReturnComments);
   
// Create anonymous function fo display the already rated message function
   var functionDemo = new Function("alreadyRatedCommentMessage('"+id+"'); return (false);")
   
// Change input to prevent user from rating again
    var img1 = document.getElementById("poorComment"+commentId);
    img1.setAttribute("onclick", "");
    img1.setAttribute("onmouseover", functionDemo);
    img1.setAttribute("onmouseout", "");
    img1.setAttribute("alt", "You have already rated");
    var img2 = document.getElementById("goodComment"+commentId);
    img2.setAttribute("onclick", "");
    img2.setAttribute("onmouseover", functionDemo);
    img2.setAttribute("onmouseout", "");
    img2.setAttribute("alt", "You have already rated");

// Delete the (Spam) and (Reply) links
    var link = document.getElementById("spamComment"+commentId);
    removeChildrenRecursivelyComments(link);
    var link = document.getElementById("replyComment"+commentId);
    removeChildrenRecursivelyComments(link);

// Hide comments and show "Marked as spam" message in the title bar
   var img1 = document.getElementById("commentBlock"+commentId);
   img1.className+=img1.className?' spammed':'spammed';
   img1.style.visibility = "hidden";
   img1.style.display = "none" ;
   var img1 = document.getElementById("spammedTitleMessage"+commentId);
   img1.style.visibility = "visible";
   img1.style.display = "inline" ;

//ce.innerHTML += " Before commentRatingSentMessage ";

// Send message to user
   commentClearTimers();
   var rt = document.getElementById(id);
   rt.innerHTML = 'Rating sent!';
   timerComments = window.setTimeout('clearCommentTitleMessage("'+id+'")', 7000); 
}

function handleNewCommentReturn(data) {

   if ((data == null) || (data == "")) {
	// Big problem
	if (comment2Update == 0)
		commentProblemMessage("newCommentMessageBox"); 
        else 
		commentProblemMessage("newReplyMessageBox"+comment2Update); 
   } else if (data.indexOf("You are not allowed to comment") != -1) {
	if (comment2Update == 0)
		commentProblemDisplayMessage(data, "newCommentMessageBox"); 
        else 
		commentProblemDisplayMessage(data, "newReplyMessageBox"+comment2Update); 
   } else {  // Success
	if (comment2Update == 0) {
// Gray out comment and submit button
		var cb = document.getElementById("commentButton");
     		cb.backgroundColor = '#333333';
   		cb.setAttribute("disabled", "true");
		commentSuccess("newCommentMessageBox"); 
        } else {
// Delete form
        	commentClearMessage("newReplyBox"+comment2Update);
		commentSuccess("newReplyMessageBox"+comment2Update); 
	}
   }
}


function sendNewComment(nickname, tID, ctID, tsID, reply2, box) {

   var messageInput;
   if (reply2 > 0) 
	messageInput = document.getElementById("newReply"+reply2);
   else
	messageInput = document.getElementById("newComment");

   var message = messageInput.value;

   if (message == null) {
	commentEmptyMessage(box);
	setfocus(messageInput);
	return(false);
   } 
   if (message.length < 1) {
	commentEmptyMessage(box);
	setfocus(messageInput);
	return(false);
   } 

   if (isAjaxSupportedComment()) {
	comment2Update = (reply2 > 0)  ? reply2 : 0;
	commentWaitMessage(box);
   	JGetCommentInfo.createComment(tID, ctID, tsID, "", message, reply2, nickname, false, handleNewCommentReturn);

	// Clear message box
	if (reply2 <= 0) {
   		messageInput.value = "";
        	charCounter("newComment","newCommentcount", 500);
	}

	timerAjaxComments = window.setTimeout('commentProblemMessage("'+box+'")', 30000); 
	return false;
   } else { 
	return true ; 
   } 

}

function reply2Comment(nickname, tID, ctID, tsID, commentID, box) {

   var formInfo = '<FORM  enctype="application/x-www-form-urlencoded" ACTION="./NewComment" METHOD=POST name="UploadNewCommentForm" id="UploadNewCommentForm" onSubmit="return sendNewComment(\''+nickname+'\', '+tID+', '+ctID+', '+tsID+', '+commentID+', \''+box+'\');" >'+
			'<textarea name="newReply'+commentID+'" id="newReply'+commentID+'" rows="5"  cols="20" style="width:80%;" tabindex="10" ></textarea> '+
         		'<INPUT TYPE=hidden NAME="reply2Comment" id="reply2Comment" VALUE="'+commentID+'"> '+
         		'<INPUT TYPE=hidden NAME="tidComment" id="tidComment" VALUE="'+tID+'" /> '+
         		'<INPUT TYPE=hidden NAME="ctidComment" id="ctidComment" VALUE="'+ctID+'" />'+
         		'<INPUT TYPE=hidden NAME="tsidComment" id="tsidComment" VALUE="'+tsID+'" />'+
         		'<INPUT TYPE=hidden NAME="cidComment" id="cidComment" VALUE="'+nickname+'" />'+  
 			'<INPUT TYPE="submit" VALUE="Post Comment" name="replyButton'+commentID+'" id="commentButton'+commentID+'" tabindex="20"  />'+
 			'<INPUT TYPE="reset" VALUE="Discard" name="discardButton" id="discardButton" tabindex="30" onClick="commentClearMessage(\'newReplyBox'+commentID+'\'); commentClearMessage(\'newReplyMessageBox'+commentID+'\');" /> '+
			'</FORM>';
   var box = document.getElementById('newReplyBox'+commentID);
   box.innerHTML = formInfo;
}
