/* Rudy Rucker's javascript for www.monkeyview.net.  (c) 2007
 * adapted for monkeybrains.net,  Wed  Apr 09, 2008
 * - added DEBUG code... browse to #DEBUG and it will turn on...
 * - added subDoc
 * - added concurrent jax requests
 *
 * checkHash()
 * Periodically check the 'hash' in the Location
 * This will catch the forward and back button usage
 * and make Ajax work!
 * Written by Rudy Rucker.  To support this script,
 * colocate your server at MonkeyBrains.net!
*/
var DEBUG = false;
var lastHash = location.hash;
var didMenuSwap = false;
function checkHash()
{
	
	if (location.hash && location.hash == "#DEBUG") { DEBUG = true; }
	else if (location.hash && (location.hash != lastHash || ! lastHash))
	{
		lastHash = location.hash;
		var hashPage = location.hash.substring(1);
		if (location.hash.indexOf('_') > 1)
			hashPage = location.hash.substring(1,location.hash.indexOf('_'));
		//alert(hashPage);
		dotab(hashPage);
		// dotab(location.hash.substring(1));
	} else if (! location.hash && lastHash ) {
		lastHash = false;
		dotab('Welcome',false,true);  // back button to first page!
	} 

	setTimeout('checkHash()',1000);
}
setTimeout('checkHash()',1000);

// check for a Hash at page load time.... call this from the onLoad
function loadDefault (u)
{
        if (location.hash)
			dotab(location.hash.substring(1));
        else if (u)
			dotab(u);	
}

// subsets of tags call this function
function doSubtab(n) 
{ 
	if (document.getElementById("subtabArea"))
		dotab(n, document.getElementById("subtabArea"), true);
	else if (DEBUG) 
		alert("Need div for sub tabs...");
}

function dotab (n,area,skipMakeAndLocation) 
{
	if (DEBUG)
		alert(n+' --- '+area+' --- '+skipMakeAndLocation );
 	if (! area)
		area =  document.getElementById("tabArea");

	var tabID = "tab" + n;
	if (! area || ! area.hasChildNodes())
		return false;
	var children = area.childNodes;
	var foundTab = false;
	var lastContent;
	for (var i = 0; i < children.length; i++)
    {	
		var e = children[i];
		if (e.id && e.id.indexOf('tab') == 0)
		{
			makeNewContent(n);
			var content = document.getElementById("content" + e.id.substring(3));
			if (e.id == tabID)
			{
				if (DEBUG)
			    	alert("Setting " + tabID +".  Class for child " + i + " is " + e.className);
				e.className="tabOrange";
				if (content) {
					content.style.display = "block";
					if (content.innerHTML.indexOf("Loading") == 0)
						monkey_jax_url(n + ".html",content,false);
				}
				foundTab = true;
			} else {
				if (e.className != ("tabClear"))
					e.className="tab";
				if (content && content.style.display!="none")
				{
					content.style.display = "none";
					lastContent = content;
				}
			}
		}
	}
	
	if (! skipMakeAndLocation)
	{
		if (foundTab)
		{
			location.href="/#" + document.getElementById("tab"+n).innerHTML;
		} else {
			lastContent.style.display = "block";
			makeNewTab(n);
		}
	}
    return false;
}
	
function makeNewTab(n)
{
	var newTab = document.getElementById("tabWelcome").cloneNode(false);
	newTab.className="tabOrange";
	newTab.innerHTML=n;
	newTab.id="tab"+n;
	newTab.onclick=function () { dotab(n) };
	if (document.getElementById("tabWebmail"))
	{
		document.getElementById("tabArea").removeChild(document.getElementById("tabWebmail"));
		document.getElementById("contentWebmail").style.display="none";
	}
	if (document.getElementById("tabNews"))
	{
		document.getElementById("tabArea").removeChild(document.getElementById("tabNews"));
		document.getElementById("contentNews").style.display="none";
	}
	document.getElementById("tabArea").appendChild( newTab );
	makeNewContent(n);
	if (document.getElementById("tab"+n))
		dotab(n);
}
function makeNewContent(n)
{
	// add a content div if we need to.
	if (!  document.getElementById("content"+n))
	{
		var newContent = document.getElementById("contentWelcome").cloneNode(false);
		newContent.style.display="block";
		newContent.id="content"+n;
		document.getElementById("tabDoc").appendChild( newContent );
		newContent.innerHTML="Loading";
	}
}
function subDoc (u) 
{
	makeNewContent("Services");
	dotab("Services");

    monkey_jax_url(u,"theSubDoc",false);
	document.getElementById("theSubDocHeader").style.display="none";
    return false;
}


function changeMe(flipItImage)
{
	if (flipItImage.parentNode.lastChild.style.display=="none" ||
		(flipItImage.parentNode.lastChild.style.display=="" && flipItImage.alt=="[+]") )
	{
		flipItImage.parentNode.lastChild.style.display="block";
		flipItImage.alt="[-]";
		flipItImage.src="/images/minus.png";
	}
	else
	{
		flipItImage.parentNode.lastChild.style.display="none";
		flipItImage.alt="[+]";
		flipItImage.src="/images/plus.png";
	}
}

/* Monkey brains aJax routines */
var monkey_jax_in_action=false;
function monkey_jax_url(URLorForm, OutputId, LoadMessage, ErrMessage, callbackOverRide)
{
	/* ------------------   Process Arguments --------------------- */
	if (monkey_jax_in_action) 
	{	// oh my goodness, you cannot do conncurrent jax... try again in 2/3 second.
		setTimeout('monkey_jax_url("'+URLorForm+'","'+OutputId+'","'+LoadMessage+'")', 666);
		return;
	}
	monkey_jax_in_action=true;
	var TargetDiv;
	var ActionURL;
	var ActionMethod = 'GET';
	var ActionPost = '';
	var ActionCallback;
	var MonkeyForm;

	/* allow a variety of things as parameters;
	   determine the target HTML Element
	   */
	if (OutputId && typeof OutputId == 'string')
		TargetDiv =  document.getElementById(OutputId);
	else if (OutputId && typeof OutputId == 'object')
		TargetDiv =  OutputId;
	else if (! OutputId && typeof URLorForm == 'object')
		TargetDiv = URLorForm.parentNode;  // pick the parent!
	else
	{
		TargetDiv = document; // Should we do this?
		alert("I don't know where to output the request.  Bad.");
		return false; // this stops the action.
	}

	if (DEBUG)
		alert("Using "+URLorForm+" and putting output in "+TargetDiv.id);
	/* Determine if we have a URL or a FORM to deal with. */
	if (typeof URLorForm == 'string')
		ActionURL = make_uri(URLorForm);
	else if (typeof URLorForm == 'object' &&  URLorForm.constructor == '[HTMLInputElement]')
		 return monkey_jax_url(URLorForm.parentNode, OutputId, LoadMessage, ErrMessage); // Try the parent form!
	/* should be this:
		else if (typeof URLorForm == 'object' &&  URLorForm.constructor == '[HTMLFormElement]')
		but some browsers get don't get it.  */
	else if (typeof URLorForm == 'object')
	{
		// We have a form...
		MonkeyForm = URLorForm;
		ActionURL = MonkeyForm.action;
		if (MonkeyForm.method)
			ActionMethod = MonkeyForm.method; // see if a desired method has been specified.
		else
			ActionMethod = 'POST'; // Default to post.

		if (DEBUG) // set at top of file.
			alert("Posting Form... " + MonkeyForm.id);
	}
	else
	{
		alert("I don't know how to fetch and show a " + URLorForm);
		return false;
	}

	/* --------------------   Set up the callbacks ---------------- */

	 ActionCallback = {
		success: function(o)
		{
		/*
			var subMast =  document.getElementById('subMast');
			if (subMast)
				subMast.innerHTML = "<small>got"+ActionURL +"</small>";
				*/
			TargetDiv.innerHTML = o.responseText;
			window.status=ActionURL;
/*
			// figure out opacity...
				new Effect.Opacity(TargetDiv.id,
					{ duration: 1,
					transition: Effect.Transitions.linear,
					from: 0.4, to: 1 });
*/

		},
		failure: function(o)
		{
			TargetDiv.className = 'error';
			TargetDiv.innerHTML = "<big>Error</big><br>Fetching: "+ActionURL+" failed.<br>";
			if (ErrMessage)
				TargetDiv.innerHTML += ErrMessage;
/*
			new Effect.Opacity(TargetDiv.id,
				{ duration: 2,
				transition: Effect.Transitions.linear,
				from: 0.4, to: 1 });
*/
		}
	}
	if (callbackOverRide && callbackOverRide['success'])
		ActionCallback = callbackOverRide;


	/* -------------------  Prepare the TargetDiv ----------------- */

	// Set up the TargetDiv, unhide, show working gif, add any LoadMessage
	if (TargetDiv.style.display == 'none')
		TargetDiv.style.display = 'block';

	//new Effect.Opacity(TargetDiv.id, {  duration: 1, transition: Effect.Transitions.linear, from: 0.4, to: 1 });

	if (LoadMessage)
		TargetDiv.innerHTML = " " + LoadMessage ;
	if (DEBUG) // set at top of file.
		TargetDiv.innerHTML = "Query " + ActionURL + " with a " + ActionMethod + ".\nTarget element for HTML: " + TargetDiv.id;


	/* ----------------------  Do It ------------------------------ */
	// all the code above set everything up, now this one line!
	doHTTP(ActionMethod,  ActionURL, ActionCallback, MonkeyForm);
}


var request;
var requestCallback;
function doHTTP(M,URL,c,form)
{
	var post = null;
	if (!request)
		makeRequestObjct();
	if (form)
	{
		if (M == "POST" ||  M == "post" ||  M == "Post")
		{
			request.open(M, URL, true);
			request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			post = wwwEncodeForm(form);
		}
		else
		{
			URL += "?" + wwwEncodeForm(form);
			request.open(M, URL, true);
		}
	}
	else
		request.open(M, URL, true);

	requestCallback = c;
	request.onreadystatechange = HTTPresponse;
	request.send(post);

}

function makeRequestObjct()
{
	/* Thanks to: http://www-128.ibm.com/developerworks/java/library/wa-ajaxintro2/index.html */
	request = false;
	try
	{
		request = new XMLHttpRequest();
	}
	catch (microsoft)
	{
		try
		{
			request = new ActiveXObject("Msxml2.XMLHTTP");
	 	}
		catch (othermicrosoft)
		{
			try
			{
		 		request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (failed)
			{
		 		request = false;
			}
	 	}
	}

	if (!request)
		alert("Error initializing HttpRequest!");
}

function wwwEncodeForm(form)
{
	var pairs = new Array();
	var elements = form.elements;

	for (var i = 0; i < elements.length; i++) {
		if ((name = elements[i].name) && (value = elements[i].value))
			pairs.push(name + "=" + encodeURIComponent(value));
	}

	return pairs.join("&");
}

function HTTPresponse()
{
	 if (request.readyState == 4)
	 {
		monkey_jax_in_action=false; // got file
		if (request.status == 200)
		{
			if (requestCallback['success'])
				requestCallback['success'](request);
			else
		 		alert("Request complete.\nNo handler, howerver, so, click to continue!");
		}
		else if (request.status == 404)
		{
			if (requestCallback['failure'])
				requestCallback['failure'](request);
			else
		 		alert("Request URL does not exist");
		}
		else
		{
			alert("Error: status code is " + request.status);
			if (requestCallback['failure'])
				requestCallback['failure'](request);
		}
	}	
}


function make_uri (u)
{
	// generate absolute, offsite, or relative URIs (in order)
	if (u.charAt(0) == '/')
		return location.href.substring(0,location.href.indexOf('/',8)+1) + u;
	else if (u.indexOf("://") > 2 || u.indexOf("://") < 8 )
		return u;
	else
		return location.href.substring(0,location.href.lastIndexOf('/')+1) + u;
}


var lastClassName;
function classChange (e, newName)
{
	if (e.className && newName) 
	{
		lastClassName=e.className;
		e.className=newName;
	}
}
function classRevert (e)
{
	if (e.className && lastClassName)
		e.className=lastClassName;
	lastClassName=null;
}




