/*!
	@header
		This JavaScript script provides the message board
		functionality.

	@indexgroup JSBoard (JavaScript)
 */

/** The base path to the jsboard folder on the server
    relative to the server root. */
var mybasepath='/jsboard/';

/* No user-configurable parts from here down. */

/** Don't touch.  Used by replacecomment (which should really be rewritten to
    not use global variables).
 */
var box = null;

/** Returns the first element among the immediate children of an
    object whose name matches the specified name.
 */
function getFirstElementByName(object, name)
{
    for (var i=0; i<object.childNodes.length; i++) {
	var testobj = object.childNodes[i];
	var debug = 0;

	if (debug) { alert('test: '+testobj.tagName); }
	if (testobj.getAttribute) {
		var checkname = testobj.getAttribute('name');
		if (debug) { alert('compare: '+checkname+' ?= '+name+'\n'); }
		if (checkname == name) { return testobj; }
	}
    }
    return undefined;
}

/** Formats a number as a two-digit number. */
function zeroformat(num, digits)
{
    var newnum = num + "";

    while (newnum.length < digits) {
	newnum = "0" + newnum;
    }

    return newnum;
}

/** Formats a time stamp for display. */
function formattimestamp(timestamp)
{

	if (timestamp.substring(4, 5) == '-') {
		year = timestamp.substring(0, 4);
		month = timestamp.substring(5, 7);
		day = timestamp.substring(8, 10);
		hour = timestamp.substring(11, 13);
		minute = timestamp.substring(14, 16);
		second = timestamp.substring(17, 19);
	} else {
		year = timestamp.substring(0, 4);
		month = timestamp.substring(4, 6);
		day = timestamp.substring(6, 8);
		hour = timestamp.substring(8, 10);
		minute = timestamp.substring(10, 12);
		second = timestamp.substring(12, 14);
	}

	return zeroformat(year,4)+"-"+zeroformat(month, 2)+"-"+zeroformat(day,2)+" "+zeroformat(hour,2)+":"+zeroformat(minute,2)+":"+zeroformat(second,2);
}

/** Creates ta comment box at the specified nesting depth. */
function mkbox(id, title, username, timestamp, parentcolor, depth)
{
	var retval = '';
	var color = '';
	var deep = '';

	if (depth >= 3) { deep = 'deep'; }
	// alert('depth: '+depth);

	if (parentcolor === '') {
		color='commentdark';
	} else if (parentcolor == 'commentwhite') {
		color="commentlight";
	} else if (parentcolor == 'commentdark') {
		color="commentlight";
	} else {
		color="commentwhite";
	}
	// alert('parent is '+parentcolor+'; color is '+color+'\n');

	retval += "<div name='comment' nestdepth='"+(depth + 1)+"' class='"+color+"' dbid='"+id+"'><table width='100%' border=0 name='toptable'>\n";
	retval += "<tr name='namerow'><td></td><td>Posted by: "+username+"</td><td align='right'>"+formattimestamp(timestamp)+"</td></tr>\n";
	retval += "<tr name='titlerow'><td width='20'><img onClick='openclose(this);' isopen=0 src='"+mybasepath+"disc_closed.png' open='"+mybasepath+"disc_open.png' closed='"+mybasepath+"disc_closed.png' /></td><td>\n";
	retval += "<div class='title' name='title'>"+title+"</div>\n";
	retval += "</td><td name='controls' class='controls' align='right'><a class='jsboardlink' name='reply' href='"+mybasepath+"post.php?parent="+id+"'>Reply</a></td></tr></table>\n";
	retval += "<div name='commenttext' class='commenttext'></div><!-- comment text -->\n";
	retval += "<div name='commentchildren' class='commentchildren"+deep+"'></div>\n";
	retval += "</div><!-- comment -->\n";
	// alert('ret: '+retval);

	return retval;
}

/** Replaces the contents of a comment with text obtained from the
    database.
 */
function replacecomment(cbox)
{
    var ie_is_broken = 1;
    box = cbox;
    id = parseInt(box.getAttribute('dbid'), 10);

    // alert('box is '+box+'\n');
    
                /* This code block liberally lifted from the example code                   at http://jibbering.com/2002/4/httprequest.html */                var xmlhttp=false;                /*@cc_on @*/                /*@if (@_jscript_version >= 5)                // JScript gives us Conditional compilation, we can cope with old IE versions.
                // and security blocked creation of the objects.
                 try {
                  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                 } catch (e) {
                  try {
                   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                  } catch (E) {
                   xmlhttp = false;
                  }
                 }
                @end @*/
                if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
                  xmlhttp = new XMLHttpRequest();
		  ie_is_broken = 0; // real browsers work this way....
                }
                /* End lifted block */
                
                if (xmlhttp && !ie_is_broken) {
                        xmlhttp.cachecontrol = "no-cache";
                }
                
                if (!xmlhttp) {
			alert('This site requires xmlhttp support.  Please update your browser.');
                } else {
                        /* Let's give this a shot. */
                        // start = parseInt(form.alterLabEntryStart.value, 10);
			// setSpinner(eid, 1);
		}

		geturl = mybasepath+'data.php?gettitles=1&forparent='+id+'&referer='+escape(document.location.href);

                        // do XML HTTP call to change the data.
                        xmlhttp.open("GET", geturl, true);
                        xmlhttp.onreadystatechange = function() {
                                if (xmlhttp.readyState == 4) {
					// parse response here.
					var guts = '';
					var retval = xmlhttp.responseText;
					if (retval === null) { retval = ''; }
					var lines = retval.split('\n');
					// alert('responseText: '+retval);

					var ct = getFirstElementByName(box, 'commenttext');
					var depth = parseInt(box.getAttribute('nestdepth'), 10);
					var childbox = getFirstElementByName(box, 'commentchildren');
					var color = box.className;
					// alert('RAWCOLOR['+box+']: '+color);

					var mode = 0;
					var comment = '';
					for (var i=0; i<lines.length; i++) {
						var line = lines[i];
						var id = parseInt(line, 10);
						var pos = line.indexOf('\t') +1;
						var rem1 = line.substring(pos, line.length);
						var pos2 = rem1.indexOf('\t') +1;
						var username = line.substring(pos, pos + pos2 - 1);
						var rem2 = rem1.substring(pos2, rem1.length);
						// alert('rem2:'+rem2);
						var pos3 = rem2.indexOf('\t') +1;
						var timestamp = rem2.substring(0, pos3 - 1);
						// alert('ts:'+timestamp);
						var title = rem2.substring(pos3, rem2.length);
						if (!line.length) { continue; }
						// alert('line: '+line);
						// alert('id: '+id+', title: '+title);
						if (line == '@') {
							// alert('@');
							mode = 1;
						} else if (mode) {
							// alert('comment');
							comment += line+'\n';
						} else {
							// alert('box');
							guts += mkbox(id, title, username, timestamp, color, depth);
						}
					}

					// setSpinner(eid, 0, whichone);
					ct.innerHTML = comment + '<br>&nbsp;<br>\n'; // "Daffy Duck Rulz.\n";
					childbox.innerHTML = guts; // "Daffy Duck Rulz.\n";
				}
			};

			xmlhttp.send(null);

}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) { return null; }
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/** Fills in the contents of the comment box. */
function replacebox()
{
    var box = document.getElementById('commentbox');
    var ie_is_broken = 1;
    // alert('box is '+box+'\n');

    
                /* This code block liberally lifted from the example code                   at http://jibbering.com/2002/4/httprequest.html */                var xmlhttp=false;                /*@cc_on @*/                /*@if (@_jscript_version >= 5)                // JScript gives us Conditional compilation, we can cope with old IE versions.
                // and security blocked creation of the objects.
                 try {
                  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                 } catch (e) {
                  try {
                   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                  } catch (E) {
                   xmlhttp = false;
                  }
                 }
                @end @*/
                if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
                  xmlhttp = new XMLHttpRequest();
		  ie_is_broken = 0; // real browsers work this way....
                }
                /* End lifted block */

                if (xmlhttp && !ie_is_broken) {
                        xmlhttp.cachecontrol = "no-cache";
                }
                
                if (!xmlhttp) {
			alert('This site requires xmlhttp support.  Please update your browser.');
                } else {
                        /* Let's give this a shot. */
                        // start = parseInt(form.alterLabEntryStart.value, 10);
			// setSpinner(eid, 1);
		}

		geturl = mybasepath+'data.php?gettitles=1&forparent=0&referer='+escape(document.location.href);
		// alert('geturl is '+geturl);

                        // do XML HTTP call to change the data.
                        xmlhttp.open("GET", geturl, true);
                        xmlhttp.onreadystatechange = function() {
                                if (xmlhttp.readyState == 4) {
					// parse response here.
					var box = document.getElementById('commentbox');
					var logincookie = getCookie('login');
					var passcookie = getCookie('cryptpass');
					// alert('cookies are: '+document.cookie);
					var loginstring = "<a class='jsboardlink' href='"+mybasepath+"/dbcore.php?transferurl="+escape(document.location.href)+"'>Login</a>\n";
					// alert('LC: '+logincookie);
					if (logincookie && passcookie) {
						loginstring = "Logged in as "+logincookie+" (";
						loginstring += "<a class='jsboardlink' href='"+mybasepath+"/dbcore.php?setpass_page=1&transferurl="+escape(document.location.href)+"'>Change Password</a>";
						// if (passcookie != 'digest') {
							loginstring += "&nbsp;|&nbsp;";
							loginstring += "<a class='jsboardlink' href='"+mybasepath+"/dbcore.php?logout=1&transferurl="+escape(document.location.href)+"'>Logout</a>";
						// }
						loginstring += ")\n";
					}
					var guts = "<div hideForFull='true' class='commenthead'><table width='100%'><tr><td><a class='jsboardlink' href='"+mybasepath+"post.php'>Post Comment</a></td><td align='right' class='jsboardtext'>"+loginstring+"</td></tr></table><br></div>\n";
					var retval = xmlhttp.responseText;
					if (retval === null) { retval = ''; }
					// alert('retval: '+retval);
					var lines = retval.split('\n');

					var mode = 0;
					for (var i=0; i<lines.length; i++) {
						var line = lines[i];
						var id = parseInt(line, 10);

						// alert('line: '+line);
						// alert('id: '+id+', title: '+title);
						var pos = line.indexOf('\t') +1;
						var rem1 = line.substring(pos, line.length);
						var pos2 = rem1.indexOf('\t') +1;
						var username = line.substring(pos, pos + pos2 - 1);
						var rem2 = rem1.substring(pos2, rem1.length);
						// alert('rem2:'+rem2);
						var pos3 = rem2.indexOf('\t') +1;
						var timestamp = rem2.substring(0, pos3 - 1);
						// alert('ts:'+timestamp);
						var title = rem2.substring(pos3, rem2.length);
						if (!line.length) { continue; }
						if (line[0] == '@') {
							mode = 1;
						} else if (!mode) {
							guts += mkbox(id, title, username, timestamp, "", 0);
						}
					}

					// setSpinner(eid, 0, whichone);
					box.innerHTML = guts; // "Daffy Duck Rulz.\n";
				}
			};

			xmlhttp.send(null);

}

/** Sets and clears an activity spinner.  Currently unused and blank. */
function setSpinner(id, value)
{

}

/** Handles opening and closing a disclosure triangle and the
    comment associated with it.  This happens when a user clicks
    on a disclosure triangle.
 */
function openclose(disclosure)
{
    var logincookie = getCookie('login');
    var passcookie = getCookie('cryptpass');
    if (logincookie) {
	var expdate = new Date();
	var exptime = expdate.getTime() + 2 * 3600 * 1000; // 2 hours.
	expdate.setTime(exptime);
	document.cookie = "login="+escape(logincookie)+"; expires="+expdate.toGMTString();
	document.cookie = "login="+escape(logincookie)+"; expires="+expdate.toGMTString();
    }
    var div = disclosure.parentNode.parentNode.parentNode.parentNode.parentNode;
	// alert('div: '+div);
    var open = disclosure.getAttribute('isopen');
	// alert('open: '+open);
    var text = getFirstElementByName(div, 'commenttext');
    var children = getFirstElementByName(div, 'commentchildren');
    var toptable = getFirstElementByName(div, 'toptable');
	// alert('tt '+toptable);
    var tablebody = toptable.getElementsByTagName('TBODY')[0];
	// alert('tb '+tablebody);
    var titlerow = getFirstElementByName(tablebody, 'titlerow');
	// alert('tr '+titlerow);
    var controls = getFirstElementByName(titlerow, 'controls');
	// alert('ctrls '+controls);

    // alert('text is '+text);
    if (open == 1) {
	disclosure.src = disclosure.getAttribute('closed');
	disclosure.setAttribute('isopen', '0');
	text.style.display = "none";
	children.style.display = "none";
	controls.style.display = "none";
    } else {
	disclosure.src = disclosure.getAttribute('open');
	disclosure.setAttribute('isopen', '1');

	if (!text.innerHTML.length) {
		// fetch it here.
		// text.innerHTML="Daffy Duck Rulz.\n";
		replacecomment(div);
	}
	text.style.display = "block";
	children.style.display = "block";
	controls.style.display = "block";
    }
    

}

document.onload=replacebox();
