/// <Reference Path="/CustomSource/JavaScript/jquery-vsdoc.js"/>
// Attempt to store the comments that are submitted, just in case the process fails.
var SubmittedComments = "";

//Function to add an ajax logo that surrounds the discussion board contents
function addAjaxLogo() {
	ajaxContentElement = document.getElementById("ajaxContent");
	ajaxContentElement.innerHTML = "<div class='discussionsWrap1'><div class='discussionsWrap2'><div class='discussionsWrap3'><div class='discussionsWrap4'>" + ajaxContentElement.innerHTML + "</div></div></div></div>";
}

//Function that allows multiple calls to functions upon loading of the web page
function addOnloadEvent(fnc){
  if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", fnc, false );
  else if ( typeof window.attachEvent != "undefined" ) {
    window.attachEvent( "onload", fnc );
  }
  else {
    if ( window.onload != null ) {
      var oldOnload = window.onload;
      window.onload = function ( e ) {
        oldOnload( e );
		window[fnc]();		
      };
    }
    else 
      window.onload = fnc;
  }
}

$(function () {
	addAjaxLogo();
});


//Javascript function to trim empty spaces
function trim(str)
{
  return str.replace(/^\s*|\s*$/g,"");
}

//Javascript function to get the year
function takeYear(theDate)
{
  x = theDate.getYear();
  var y = x % 100;
  y += (y < 38) ? 2000 : 1900;
  return y;
}

// Function gives focus to the textarea, to reply to an existing comment.
function delayCommentFocus(commentID) {
	setTimeout("if (!(!(document.getElementById('" + commentID + "')))) document.getElementById('" + commentID + "').focus();",1500);
}

//Javascript validation to ensure text was entered into the comments field before adding the comments to the database
function validateForm(TheForm, TheAction) {
	if (trim(TheForm.Comments.value) == "") {
		alert("Please enter your comments.");
		TheForm.Comments.focus();
		return false;
	}

	if (TheForm.Comments.value.length > 1500) {
		alert("The maximum characters allowed for the comments field is 1500.");
		TheForm.Comments.focus();
		return false;
	}

  var TheRecordID = escape(trim(TheForm.RecordID.value));
  var TheContentID = escape(trim(TheForm.ContentID.value));
  var TheUserName = escape(trim(TheForm.UserName.value));
  var TheDate = new Date();
  var TheMonth = TheDate.getMonth()+1;
  var TheDay = TheDate.getDate();
  var TheYear = takeYear(TheDate);
  var TheMonthString = new String(TheMonth);
  var TheDayString = new String(TheDay);
  var TheYearString = new String(TheYear);		  
  //if (TheMonthString.length == 1) TheMonthString = "0" + TheMonthString;
  //if (TheDayString.length == 1) TheDayString = "0" + TheDayString;
  var TheDateFormatted = TheMonthString + "/" + TheDayString + "/" + TheYearString.substr(2,2); 
  var curr_hour = TheDate.getHours();
  if (curr_hour < 12) {
    a_p = "am";
  } else {
    a_p = "pm";
  }
  if (curr_hour == 0) {
    curr_hour = 12;
  }
  if (curr_hour > 12) {
    curr_hour = curr_hour - 12;
  }
  var TheCurrentHour = new String(curr_hour);
  //if (TheCurrentHour.length == 1) TheCurrentHour = "0" + TheCurrentHour;
  var curr_min = TheDate.getMinutes();
  var TheCurrentMinutes = new String(curr_min);
  if (TheCurrentMinutes.length == 1) TheCurrentMinutes = "0" + TheCurrentMinutes;
  var TheTime = TheCurrentHour + ":" + TheCurrentMinutes + a_p;
  TheDate = escape(trim(TheDateFormatted));
  TheTime = escape(trim(TheTime));
  var TheComments = TheForm.Comments.value;
  TheComments = TheComments.replace(new RegExp( "\\n", "g" ),"_____");  
  TheForm.Comments.value = "";
  TheComments = escape(trim(TheComments));
  if (TheAction == "AddComment")
  {
    addComments(TheRecordID,'AddComment',TheContentID,TheUserName,TheDate,TheTime,TheComments);		
  }
  else
  {
    addComments(TheRecordID,'ReplyComment',TheContentID,TheUserName,TheDate,TheTime,TheComments);		
  }
  if (document.getElementById('AddContainer').style.display == 'none')
  {
    document.getElementById('AddContainer').style.display = 'block';
  }
  return true;
}

//Declare the xml doc variable
var xmlDoc = "";

//Javascript function to add comments to the database by receiving the value of the record id
function addComments(RecordID,TheAction,ContentID,UserName,TheDate,TheTime,Comments) {
	/// <summary>
	/// Save comments to the database.
	/// </summary>
	/// <param name="RecordID">The id of the comment being replied to, or 0 if replying to the content itself.</param>
	/// <param name="TheAction">Either AddComment or ReplyComment.</param>
	/// <param name="ContentID">Unique id of the content to associate the comment to.</param>
	/// <param name="UserName">User name to store the comment as.</param>
	/// <param name="TheDate">Date of the comment.</param>
	/// <param name="TheTime">Time of the comment.</param>
	/// <param name="Comments">Comments to save.</param>
	SubmittedComments = Comments;
	document.getElementById("RecordDisplay").innerHTML = "<div align='center'><h2>Processing ...</h2><br /><img alt='Processing ...' src='/AM/Graphics/bigrotation.gif'/></div>";
	xmlDoc = "";

	$.ajax({
		url: "/AM/CustomSource/Treads/treadsprocess.cfm?RecordID=" + RecordID + "&TheAction=" + TheAction + "&ContentID=" + ContentID + "&UserName=" + UserName + "&TheDate=" + TheDate + "&TheTime=" + TheTime + "&Comments=" + Comments + "&theRequest=addComments",
		cache: false,
		success: function (data) {
			xmlDoc = data;
			displayComments();
		},
		error: function () {
			$('#RecordDisplay').html('<p class="error">There was an error saving your comments. Please try again momentarily.</p>');
		}
	});
}

function requestComments(contentId) {
	/// <summary>
	/// Get comments for a particular content record, based on the content id.
	/// </summary>
	/// <param name="contentId">Content id of the record.</param>
	$('#RecordDisplay').html('<div align="center"><h2>Processing ...</h2><br/><img alt="Processing ..." src="/AM/Graphics/bigrotation.gif"/></div>');

	$.ajax({
		url: '/AM/CustomSource/Treads/treadsprocess.cfm?ContentID=' + contentId + '&theRequest=requestComments',
		success: function (data) {
			xmlDoc = data;
			displayComments();
		},
		error: function () {
			$('#RecordDisplay').html('<p class="error">Unable to load comments. Please try again momentarily. If the problem continues, please try another browser.');
		}
	});
}

//Javascript function that displays the comments to the web browser
function displayComments()
{
	var TheXML = xmlDoc.getElementsByTagName('records');
	document.getElementById("RecordDisplay").innerHTML = "";
	TempText = "";
	writeVar = 0;
	if (TheXML.length && TheXML.length > 0) {
		traverse(TheXML[0]);
		document.getElementById("RecordDisplay").innerHTML = "<img src='/AM/CustomSource/Treads/images/comments-top.gif' style='width:428px;height:4px;'><div id='discussionInformation'>&nbsp;<span style=''>Comments (" + TheXML[0].getAttribute('ct') + ")</span></div><div style='margin:1px;'>&nbsp;</div>" + TempText;
	} else {
		if (document.getElementById("RecordDisplay")) {
			document.getElementById("RecordDisplay").innerHTML = '<p>Your comment was <em style="font-weight:bold;">not</em> saved.</p>';
			if (SubmittedComments && SubmittedComments != '') {
				document.getElementById('RecordDisplay').innerHTML += '<p>We have the following as your comment:</p>' + '<p>' + unescape(SubmittedComments) + '</p>';
			}
		}
	}
}

var TempText;
TempText = "";

var writeVar;
writeVar = 0;

var theContentIDString;

function traverse(tree)
{
  if (tree != null && tree.hasChildNodes())
  {
	switch (tree.tagName) {
	  case "record":
	    writeVar = 1;
		TempText += '<div class="discussionComment">';
		break;
	  case "contentid":
	    writeVar = 1;
		break;
	  case "end":
		writeVar = 1;
		TempText += '</div>';
		break;
	  case "username":
		writeVar = 1;
		TempText += '<div class="commentInfo"><div class="commentUser">';
		break;
	  case "date":
		writeVar = 1;
		TempText += '</div><div class="commentDate">';
		break;
	  case "time":
		writeVar = 1;
		break;
	  case "comments":
		writeVar = 1;
		TempText += '</div></div><div class="commentText">';
		TempText += "<div>";
		break;
	  default:
		writeVar = 0;
		break;
	}
	for(var i=0; i<tree.childNodes.length; i++)
	{
	  traverse(tree.childNodes[i]);
	}
  }
  else
  {
	if (writeVar)
	{
	  writeVar = 0;
	  switch (tree.parentNode.tagName)
	  {		
	    case "contentid":
		  if (tree.nodeValue != "unknown")
		  {
			theContentIDString = tree.nodeValue;			
		  }		  
		  break;
		case "username":
		  if (tree.nodeValue != "unknown")
		  {
		    TempText += "by <span>" +  tree.nodeValue + "</span>";
		  }
		  else
		  {
		    TempText += "<b>No Comments</b>";
		  }
		  break;
		case "date":
		  if (tree.nodeValue != "unknown")
		  {
		    TempText += "on <span>" + tree.nodeValue + "</span>";
		  }		  
		  break;
		case "time":
		  if (tree.nodeValue != "unknown")
		  {
		    TempText += " @ <span>" + tree.nodeValue + "</span>";
		  }
		  break;
		case "comments":
		  var TheComments = tree.nodeValue;		  
		  var theFieldValueLongText = TheComments;
		  var TheCommentsNew = "";
		  var TheLineBreak = "_____";
		  var TheCommentsLength = theFieldValueLongText.length;
		  if (TheComments.indexOf(TheLineBreak) != -1)
		  {
		    while (TheComments.indexOf(TheLineBreak) != -1)
		    {
		      var thePos = TheComments.indexOf(TheLineBreak);
			  TheCommentsNew = TheComments.substr(0, thePos);
			  TempText += TheCommentsNew;
			  TempText += "<br>";
			  TheComments = TheComments.substr(thePos + TheLineBreak.length, TheComments.length);
			  if (TheComments.indexOf(TheLineBreak) == -1)
			  {
				TempText += TheComments + "</div></div>";
			  }
		    }
		  }
		  else
		  {
		    TempText += TheComments + "</div></div>";
		  }
		  if (TheComments != "There are currently no comments posted for this content." && TheComments != "We were unable to process your comment posting.  Please try again.")
          {
		    TempText += "<div style='float:left'></div>";
	        var ClearReplyContainers = "";
	        for (y=0;y<tree.childNodes.length;y++)
            {
	          if (y != tree.parentNode.parentNode.getAttribute('id'))
	          {
	            //ClearReplyContainers = ClearReplyContainers + "javascript:new Effect.CloseDown('ReplyContainer"+y+"', arguments[1] || {});"
	          }
	        }
			//TempText += "<div style=\"float:right\"><a href=\"#\" class=\"morelink\" id=\"" + tree.parentNode.parentNode.getAttribute('id') + "\" onclick=\"" + ClearReplyContainers + "javascript:Effect.Combo('ReplyContainer"+tree.parentNode.parentNode.getAttribute('id')+"', arguments[1] || {});delayCommentFocus('Comments" + tree.parentNode.parentNode.getAttribute('id') + 1 + "');return false;\">Reply</a></div><div style='margin:5px;'>&nbsp;</div>";
			TempText += "<div style=\"float:right\"><a href=\"#\" class=\"morelink\" id=\"" + tree.parentNode.parentNode.getAttribute('id') + "\" onclick=\"" + ClearReplyContainers + "$('#ReplyContainer" + tree.parentNode.parentNode.getAttribute('id') + "').toggle('slow');return false;\">Reply</a></div><div style='margin:5px;'>&nbsp;</div>";
          }
		  TempText += "<div class='ReplyContainer' id='ReplyContainer" + tree.parentNode.parentNode.getAttribute('id') + "' style='display:none;'>";

		if (!document.form1 || !document.form1.UserName.value || document.form1.UserName.value == "unknown") {
			TempText += "<div>&nbsp;<h2>Reply To Comment</h2></div>";
			TempText += "<div class='commentInfo'>";
			TempText += "<div class='commentUser'><span>Access Denied</span></div>";
			TempText += "</div>";
			TempText += "<div style='background:url(/AM/CustomSource/Treads/images/commentsfill.jpg); background-repeat:repeat-x;'>";
			TempText += "<div style='height:125px; padding:10px'>I'm sorry but you are not logged in with an account that allows you to use this feature.  Please <a href='/AM/Template.cfm?Section=News&template=/security/Login.cfm' class='morelink' onclick='window.open(this.href);return false;'>log in</a> with your email or member number and password. If you have logged in, <a href='javascript:location.reload(true)' class='morelink'>refresh this page</a>.</div></div>";			
		} else if (document.form1.UserName.value == "banned") {
			TempText += "<div>&nbsp;<h2>Reply To Comment</h2></div>";
			TempText += "<div class='commentInfo'>";
			TempText += "<div class='commentUser'><span>Access Denied</span></div>";
			TempText += "</div>";
			TempText += "<div style='background:url(/AM/CustomSource/Treads/images/commentsfill.jpg); background-repeat:repeat-x;'>";
			TempText += "<div style='height:125px; padding:10px'>You are unable to comment on this content. If you believe this to be in error, please contact the <a href=\"mailto:webmaster@wisbar.org\">webmaster</a>.</div></div>";
		} else {						
		    TempText += "<form name='form" + tree.parentNode.parentNode.getAttribute('id') + 1 + "' id='form" + tree.parentNode.parentNode.getAttribute('id') + 1 + "' style='margin:0;'>";
			TempText += "<div>&nbsp;<h2>Reply To Comment</h2></div>";
			TempText += "<div class='commentInfo'>"
			TempText += "<div class='commentUser'>as <span>" + document.form1.UserName.value + "</span></div></div>";
		    TempText += "<div style='background:url(/AM/CustomSource/Treads/images/commentsfill.jpg); background-repeat:repeat-x;'>";
			TempText += "<div>"			
			var browser=navigator.appName;
            if (browser == "Microsoft Internet Explorer") {
			  TempText += "<textarea name='Comments' id='Comments" + tree.parentNode.parentNode.getAttribute('id') + 1 + "' style='width:396px;'></textarea>";
            } else {
              TempText += "<textarea name='Comments' id='Comments" + tree.parentNode.parentNode.getAttribute('id') + 1 + "' style='width:398px;'></textarea>";
            }
			TempText += "</div></div>"
			TempText += "<div align='center'>";			
		    TempText += "<input name='RecordID' id='RecordID' value='" + tree.parentNode.parentNode.getAttribute('id') + "' type='hidden'>";
		    TempText += "<input name='ContentID' id='ContentID' value='" + theContentIDString + "' type='hidden'>";
		    TempText += "<input name='UserName' id='UserName' value='" + document.form1.UserName.value + "' type='hidden'>";
		    TempText += "<input name='Submit' id='Submit' value='Submit'  style='width:175px' onclick=\"return validateForm(document.getElementById('form" + tree.parentNode.parentNode.getAttribute('id') + 1 + "'),'ReplyComment')\" type='button'>";
			TempText += "</div>";

			TempText += "<div class=\"discussionPolicy\">";
			TempText += "<div><a href=\"/am/template.cfm?section=faq&amp;template=/cm/contentdisplay.cfm&amp;contentid=60877\" onclick=\"window.open(this.href);return false;\">Guidelines/Policy</a></div>";
			TempText += "</div>";

			TempText += "</form>";
		  }
		  TempText += "</div>";
		  break;
	    default:
		  break;
	  }
    }
  }
}
