/* Rudy Rucker's javascript for www.monkeyview.net
 */

var DEBUG_MODE = 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 */
function monkey_jax_url(URLorForm, OutputId, LoadMessage, ErrMessage, callbackOverRide)
{
	/* ------------------   Process Arguments --------------------- */
	var TargetDiv;
	var ActionURL;
	var ActionMethod = 'GET';
	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.
	}

	/* 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 =='[HTMLFormElement]' || URLorForm.constructor =='[object HTMLFormElement]'))
	{
		// We have a form... Feed it into the YAHOO.util.Connect object.
		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_MODE) // set at top of file.
			alert("Posting Form... " + MonkeyForm.id);
	}
	else if (typeof URLorForm == 'object' &&  (URLorForm.constructor == '[HTMLInputElement]' || URLorForm.constructor =='[object HTMLInputElement]'))
		 return monkey_jax_url(URLorForm.parentNode, OutputId, LoadMessage, ErrMessage); // Try the parent form!
	else
	{
		alert("I don't know how to Fetch and show a " + typeof URLorForm + " - " + URLorForm.constructor);
		return false;
	}

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

	 ActionCallback = {
		success: function(o)
		{
			TargetDiv.className = 'jax_success';
			TargetDiv.innerHTML = o.responseText;
/*
			// 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_MODE) // 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)
	 {
		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;
}




