/**
 * Ajax Interface
 *
 * The CMAjax class provides an abstraction layer for xmlhttprequests
 * and the resultant dynamic functionality.
 *
 * License:
 * Coalmarch Productions, LLC
 * All rights to source code and implementation files reserved.
 * http://www.coalmarch.com | info@coalmarch.com
 * (919) 481-2895
 *
 */
var debugAjax = false;
var submit_ajax_form_result;
CMAjax.prototype.success = function()
{
	var response = this.xmlhttp.responseXML.documentElement;
	if (typeof(this.control.finalizeRenderable) != "undefined")
	{
		var renderable = "";
		var script = "";
		try
		{
			renderable = response.getElementsByTagName('renderable')[0].firstChild.nodeValue;
		}catch(e){}
		try
		{
			script = response.getElementsByTagName('script')[0].firstChild.nodeValue;
		}
		catch(e){}
		if( renderable == "" )
		{
			try
			{
				renderable = response.getElementsByTagName('returnval')[0].firstChild.nodeValue;
				submit_ajax_form_result=renderable;
			}catch(e){}
		}
		if( renderable == "" )
		{
			renderable = this.xmlhttp.responseText;
		}
		if( debugAjax ){ window.prompt("script",script); }
		this.control.finalizeRenderable(renderable,script);
	}
}
CMAjax.prototype.failure = function()
{
	window.alert("failure "+this.control);
}

CMAjax.prototype.execute = function(initialize)
{
	//alert(typeof(initialize));
	//alert(initialize);
	/*@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 {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		try {
			this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			this.xmlhttp = false;
		}
	}
	@end @*/
	if (!this.xmlhttp && typeof(XMLHttpRequest) != 'undefined') {
		this.xmlhttp = new XMLHttpRequest();
	}

	//window.alert("using "+this.method+"\n on "+this.url+"\n using "+this.xmlhttp+",\n on "+this.control+"\n sending "+this.data);
	//alert(xmlhttp.onreadystatechange);
	if (typeof(this.control.initialize) != "undefined" && (typeof(initialize) != "boolean" || initialize == true))
	{
		this.control.initialize();
	}

	var me = this;
	this.xmlhttp.onreadystatechange = function()
	{
		try {
			if ( me.xmlhttp.readyState == 4  && me.xmlhttp.status == 200)
			{
				if( debugAjax ){ window.prompt("me.xmlhttp.responseText",me.xmlhttp.responseText); }
				/*
					We want to gracefully handle errors and as such the following cases
					are detailed.

					1. If the response contains the word "error" then likely a php
						error has occurred during processing, we want to display these
						directly to the user so that they can send us the output of the
						error.
					2. If the response does not contain "CError" then we'll send it
						this is because CErrors are handled gracefully in output
						already.
					3. If the response contains a $compile_dir message, this means
						that the script executed, but creating a renderable object
						failed. In this case we want to skip attempting to draw
						anything. Likely this is due to a redirect happening somewhere.
				*/
				if( typeof(me.xmlhttp) != "undefined" )
				{
					if( typeof(me.xmlhttp.responseText) == "string" )
					{
						if( me.xmlhttp.responseText.toLowerCase().indexOf("Parse error:") == 0 &&
							me.xmlhttp.responseText.toLowerCase().indexOf("cerror") < 0 &&
							me.xmlhttp.responseText.toLowerCase().indexOf("compile_dir") < 0 )
						{
							window.prompt("System Level Error Occurred: ",me.xmlhttp.responseText);
						}
						if( me.xmlhttp.responseText.toLowerCase().indexOf("$compile_dir") > -1 )
						{
							return;
						}
					}
				}
				if( debugAjax ){ window.prompt("me.xmlhttp.responseXML",me.xmlhttp.responseXML); }
				if( debugAjax ){ window.prompt("me.xmlhttp.responseXML.documentElement",me.xmlhttp.responseXML.documentElement); }
				var response = me.xmlhttp.responseXML.documentElement;
				try
				{
					var renderable = response.getElementsByTagName('renderable')[0].firstChild.nodeValue;
				}
				catch(e){if( debugAjax ){ window.alert("Exception in setting renderable to response.getElementByTagName('renderable')"); }}
				try
				{
					var r = response.getElementsByTagName('script')[0].firstChild.nodeValue;
				}
				catch(e){if( debugAjax ){ window.alert("Exception in setting r to response.getElementsByTagName('script')"); }}

				if (((me.xmlhttp.responseText) ||  (me.xmlhttp.responseXML))&& (me.xmlhttp.status == 200))
				{
					me.success();
				}
				else
				{
					me.failure();
				}
			}
		} catch(e){if( debugAjax ){ window.alert("Uncaught: "+e); }}
	}
	if( debugAjax ){ window.prompt(this.url,this.data); }
	this.xmlhttp.open(this.method, this.url, this.async);
	this.xmlhttp.setRequestHeader('Content-Type',  "application/x-www-form-urlencoded");
	this.xmlhttp.send(this.data);
}
function CMAjax( method, url, control )
{
	this.method = method;
	this.url = url;
	this.control = control;
	this.results = null;
	this.data = null;
	this.xmlhttp = null;
	this.renderable = null;
	this.result = null;
	this.async = true;
}

function buildPOST(theFormName, xmlHttp)
{
	var theForm = document.getElementById(theFormName);
	var qs = '';
	var radioString = '';
	//alert('theFormName='+theFormName+'  length='+theForm.length+'  tagname='+theForm.tagName.toLowerCase());
	for (e=0;e<theForm.length;e++)
	{
		//alert(theForm[e].name+'='+theForm[e].value);
		if (theForm[e].name!='')
		{
			if( theForm[e].tagName.toLowerCase() == "select" )
			{
				var name = theForm[e].name;
				if(!theForm[e].multiple == true)
				{
					qs+=(qs=='')?'':'&';
					qs+= name+'='+escape(theForm[e][theForm[e].selectedIndex].value);
				}
				else
				{
					for(x=0;x<theForm[e].length;x++)
					{
						if(theForm[e][x].selected)
						{
							qs+=(qs=='')?'':'&';
							qs+= name+'='+theForm[e][x].value
						}
					}
				}
			}
			else if( theForm[e].type.toLowerCase() == "checkbox" ||
					 theForm[e].type.toLowerCase() == "radio" )
			{
				if(theForm[e].type.toLowerCase() == "radio")
				{
					radioString += theForm[e].name+" "+theForm[e].checked+"\n";
				}
				if( theForm[e].checked )
				{
					var name = theForm[e].name;
					qs+=(qs=='')?'':'&';
					qs+= name+'='+escape(theForm[e].value);
				}
			}
			else if( theForm[e].type.toLowerCase() == "hidden" )
			{
				if (theForm[e].name.indexOf("jx_") > -1)
				{
					var fieldname = theForm[e].name.substring(3,theForm[e].name.length);
					var fieldvalue = theForm[e].value;
					if (typeof (fieldvalue) != "undefined" && fieldvalue.length > 0)
					{
						var errorStep = 1;
						try {
							var fieldobject = null;
							var fieldcommand = 'fieldobject=document.getElementById("'+fieldvalue+'");';
							errorStep = 2;

							var fieldresult = eval(fieldcommand);
							errorStep = 3;
							if (fieldobject != null)
							{
								if (typeof(fieldobject.getCTFile_id) == "function" || typeof(fieldobject.getCTFile_id) == "string")
								{
									errorStep = 4;
									fieldresult = fieldobject.getCTFile_id();
									errorStep = 5;
									qs+= (qs=='')?'':'&';
									qs+=fieldname+"="+fieldresult;
								}
								else
								{
									//firefox handles objects a little differently, so we try again for the embeded object
									//if this plan fails, give a good error message
									try {
										eval('fieldobject=document.getElementById("'+fieldvalue+'_embed");');
										fieldresult = fieldobject.getCTFile_id();
										qs+= (qs=='')?'':'&';
										qs+=fieldname+"="+fieldresult;
									} catch (mm) {
										alert("Could not pull CTFile_id from applet.  If the upload was successful, you will be able to find it in existing files.");
									}
								}
							}
						} catch (m) {
							alert(m+" in step "+errorStep);
						}
					}
				}
				else
				{
					var name = theForm[e].name;
					qs+=(qs=='')?'':'&';
					qs+= name+'='+escape(theForm[e].value);
					//qs+="\n";
				}
				//document.getElementById('{$submitInto}').value = document.uploadAppletInline_{$UID}.getCTFile_id();
				//document.getElementById('{$submitRadio}').checked = true"

			}
			else
			{
				var name = theForm[e].name;
				qs+=(qs=='')?'':'&';
				var temp = theForm[e].value.replace(/%/g,"%25").replace(/&/g,"%26amp;");
				qs+= name+'='+temp.replace(/\+/g,"%2B");//plus needs to be encoded, or php will interpret as a space
			}
			//alert('qs='+qs);
		}
		else
		{
			if( debugAjax ){ window.alert("The Form Control "+theForm[e].id+" has no name attribute!"); }
		}
	}
	//window.prompt('blah',radioString);
	//qs+="\n";
	return qs;
}

function submit_ajax_form(callingForm,target,funcvalue)
{
	submit_ajax_form_result="";
	if( callingForm.tagName.toLowerCase() != "form" )
	{
		window.alert("Expected a [FORM] but received a "+callingForm.tagName);
	}
	var ajax = new CMAjax("Post","/xml/ajax.php","");
	ajax.data = '';
	ajax.data += "func="+callingForm.CTForm_func.value;
	if( debugAjax ){ window.alert(ajax.data); }
	if( debugAjax ){ window.alert(callingForm.id); }
	ajax.data += "&"+buildPOST(callingForm.id);
	if( debugAjax ){ window.alert(ajax.data); }

	if(typeof(funcvalue) == "string" && funcvalue.length > 0)
	{
		ajax.async = true;
	}

	/* Move this to a sane location. */
	var tmpTargetId = target;
	var tmpTarget = document.getElementById(target);
	var tmpTargetPanel;
	try {
		eval("tmpTargetPanel = "+target);
	} catch (e) {}

	/* Snip */
	try{
		if(typeof(tmpTargetPanel) != "undefined" && typeof(tmpTargetPanel.initialize) != "undefined")
		{
				tmpTargetPanel.initialize();
		}
		else
		{
			tmpTarget.initialize = function()
			{
				//tmpTarget.hide();
				document.getElementById(tmpTargetId).innerHTML = "Loading...";
				//tmpTarget.show();
			}
		}
		tmpTarget.finalizeRenderable = function(result,script)
		{
			//tmpTarget.hide();
			if(result != "SUCCESS")
			{
				document.getElementById(tmpTargetId).innerHTML = result;
			}
			//tmpTarget.show();
			if( debugAjax ){ window.prompt("submit_ajax_form::tmpTarget.finalizeRenderable",funcvalue); }
			installScript(funcvalue);
			installScript(script);
		}
		ajax.control = tmpTarget;
		ajax.execute();
		//alert(ajax.xmlhttp.responseText);alert(ajax.xmlhttp.responseXML);
	}catch(e){ window.alert("There was an unknown error submitting this form via XMLHTTPRequest.\n"+e); }
	return false;
}
function replaceSelect(callingInput,target,func)
{
	var callingForm = callingInput.form;
	if( callingForm.tagName.toLowerCase() != "form" || callingInput.tagName.toLowerCase() != "select")
	{
		alert("Invalid Usage of replaceSelect");
		return;
	}

	var tmpTargetId = target;
	var tmpTarget = document.getElementById(target);
	if (typeof(tmpTarget) == "undefined")
	{
		alert("Target not defined");
		return;
	}

	var oldSelectedValue=tmpTarget.options[tmpTarget.selectedIndex].value;

	var ajax = new CMAjax("Post","/xml/ajax.php","");
	ajax.data = "func="+func+"&data="+callingInput.options[callingInput.selectedIndex].value;
	try{
		tmpTarget.initialize = function()
		{
			tmpTarget.selectedIndex=0;
			tmpTarget.options.length=1;
			tmpTarget.options[0].value="";
			tmpTarget.options[0].innerHTML="Loading...";
			tmpTarget.options[0].text="Loading...";
		}
		tmpTarget.finalizeRenderable = function(result,script)
		{
			var responseArray = result.split('\n');
			tmpTarget.length = responseArray.length;
			for (i = 0; i < responseArray.length; i++) {
				var temp = responseArray[i].split(',');
				tmpTarget.options[i].value = temp[0];
				tmpTarget.options[i].text = temp[1];
				if (oldSelectedValue == temp[0])
				{
					tmpTarget.selectedIndex=i;
				}
			}
		}
		ajax.control = tmpTarget;
		ajax.execute();
	}catch(e){ window.alert("There was an unknown error updating the select.\n"+e); }
}

function ajaxReplaceResult(callingForm)
{
	var params = buildPOST(callingForm.id);
	var ajax = new Ajax.Request('/xml/ajax.php?func='+callingForm.CTForm_func.value,
								{method:'post',
								 parameters:params,
								 onFailure:null,
								 asynchronous:false}
								);
	var strAjaxResult =
		ajax.transport.responseText;
	if( strAjaxResult.toLowerCase().indexOf("<renderable>") > -1 )
	{
		var renderable = "";
		var script = "";
		try
		{
			renderable = ajax.transport.responseXML.documentElement.getElementsByTagName('renderable')[0].firstChild.nodeValue;
			var tempDiv = document.createElement('div');
			tempDiv.innerHTML = renderable;
			for(i=0;i<tempDiv.childNodes.length;i++)
			{
				if (tempDiv.childNodes[i].nodeName.toUpperCase() == "DIV")
				{
					document.getElementById(tempDiv.childNodes[i].id).innerHTML=tempDiv.childNodes[i].innerHTML;
				}
			}
		}catch(e){ window.prompt("Error In Ajax Renderable Assignment",e); }
		try
		{
			if( strAjaxResult.indexOf("<script>") > -1 )
			{
				script = ajax.transport.responseXML.documentElement.getElementsByTagName('script')[0].firstChild.nodeValue;
				if( script.length > 0 )
				{
					installScript(script);
				}
			}
		}
		catch(e){ window.prompt("Error In Ajax Script Execution",e); }
	}
	else
	{
		alert("An error occured during the form sumission.  Please try again.");
	}
	return false;
}
function ajaxNotificationDisplay(callParams,confirmText)
{
	if (confirmText != null && confirmText != '')
	{
		confirmed = window.confirm(confirmText);
		if (!confirmed )
		{
			return;
		}
	}

	var ajax = new Ajax.Request('/xml/ajax.php?'+callParams,
								{method:'post',
								 parameters:'',
								 onFailure:null,
								 asynchronous:false}
								);

	try {
		displayNotificationBox(ajax.transport.responseXML.documentElement.getElementsByTagName('returnval')[0].firstChild.nodeValue);
	} catch (e) {
		alert("A problem occurred during processing: "+e);
	}
}

