// 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 style=\"background-image: url(/AM/Graphics/Axaj_Side_1.jpg); background-repeat: repeat-y;background-position: right top;\"><div style=\"background-image: url(/AM/Graphics/Axaj_Corner_1.jpg); background-repeat: no-repeat;background-position: right top;\"><div style=\"background-image: url(/AM/Graphics/Axaj_Corner_3.jpg); background-repeat: no-repeat;background-position: left bottom;\"><div style=\"background-image: url(/AM/Graphics/Axaj_Corner_2.jpg); background-repeat: no-repeat;background-position: right bottom;padding-bottom: 25px;\">" + ajaxContentElement.innerHTML + "</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;
  }
}

//Calls the onload function to add the ajax logo upon loading of the web page
addOnloadEvent(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, the action (AddComment or ReplyComment), content id, user name, the date, the time and the comments field
function addComments(RecordID,TheAction,ContentID,UserName,TheDate,TheTime,Comments)
{
	SubmittedComments = Comments;
  document.getElementById("RecordDisplay").innerHTML = "<div align='center'><h2>Processing....</h2><br /><img src='/AM/Graphics/bigrotation.gif'></div>";
  xmlDoc = "";
  if (document.implementation && document.implementation.createDocument)
  {	
	xmlDoc = document.implementation.createDocument("", "", null);
	xmlDoc.onload = displayComments;
  }
  else if (window.ActiveXObject)
  {
	xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.onreadystatechange = function () {
		if (xmlDoc.readyState == 4) displayComments()
	};
  }
  else
  {
	alert('Your browser can\'t handle this script');
	return;
  }  
  xmlDoc.load("/AM/CustomSource/Treads/treadsprocess.cfm?RecordID=" + RecordID + "&TheAction=" + TheAction + "&ContentID=" + ContentID + "&UserName=" + UserName + "&TheDate=" + TheDate + "&TheTime=" + TheTime + "&Comments=" + Comments + "&theRequest=addComments");
}

//Javascript function to request comments from the database by receiving the value of the Content id
function requestComments(ContentID) {
	document.getElementById("RecordDisplay").innerHTML = "<div align='center'><h2>Processing....</h2><br><img src='/AM/Graphics/bigrotation.gif'></div>";
	if (document.implementation && document.implementation.createDocument) {
		xmlDoc = document.implementation.createDocument("", "records", null);
		xmlDoc.onload = displayComments;
	} else if (window.ActiveXObject) {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4) displayComments()
		};
	} else {
		alert('Your browser can\'t handle this script');
		return;
	}
	try {
		// xmlDoc.load is undefined on WebKit, but not on IE/FF ...
		xmlDoc.load("/AM/CustomSource/Treads/treadsprocess.cfm?ContentID=" + ContentID + "&theRequest=requestComments");
	} catch (ex) {
		if (document.getElementById("RecordDisplay")) {
			document.getElementById("RecordDisplay").innerHTML = '<p class="error">Unable to load comments. Please try again momentarily.<br />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>';
			}
		}
	}
  //alert(TempText);
}

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=\"#\" className=\"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=\"#\" className=\"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' className='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)' className='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;
	  }
    }  
  }
}