/*
	
	==========================================================================================================
	AjaxSubmit() - see IMPORTANT Notes below.
	==========================================================================================================
	
	Allows you to submit forms to an action page and place the returned results in the DOM Id of your choosing.
	
	This kind of replaces the process of filling in a form, pressing submit, and then having the next page load.
	In this case, you fill in a form, and whether you submit it or have it triggered by onchanges, the page does 
	not reload, it only has the DIV you've specified get its content rewritten.
	
	Example: 

	<form  action="ajax-request-handler.asp" id="frm" method="post" onsubmit="return false;">
	<!-- "onsubmit='return false;'" is important in this example because we want to make sure that the 
	user does not go somewhere else when they hit enter (which in most cases, will submit a form) -->
		<input type="hidden" name="operation"  value="update_inventory_qty"/>
		<input type="hidden" name="p_id" value="2"/>
		<input type="hidden" name="c_id" value="3"/>
		<input type="hidden" name="m_id" value="9"/>
		<input type="hidden" name="s_id" value="1"/>
		<input type="text" size="2" name="qty" value=""
			onchange="AjaxSubmit(this.form, 'ajax_feedback','ajax_status'); "
		/>
	</form>

	<div id="ajax_status">
		<!-- this spot gets updated while ajax is working -->
	</div> 

	<div id="ajax_feedback">
		<!-- the end result of whatever the ajax request did gets placed here -->
	</div>


	
	----------------------------------------------------------------------------------------------------------
	IMPORTANT NOTE #1: 
	THE SERVER PROCESS THAT HANDLES THE AJAX REQUESTS MUST RETURN THE RESULTS IN THE FOLLOWING FORMAT
	----------------------------------------------------------------------------------------------------------
	<?xml version="1.0" encoding="iso-8859-1"?>
	<results>
		<result  
		         success="True" 
		         ResultDivID="SimplyReturningWhatWasSubmitted"
		>
		Arbitrary HTML [that is escaped / html-encoded; this is inside XML after all], preformatted and returned by your server program, that you will want to be placed in the div of your choosing on the original page. 
		</result>
	</results>

	ResultDivID is where the message goes after the thing you originally wanted to do gets done (or if it fails).



	----------------------------------------------------------------------------------------------------------
	IMPORTANT NOTE #2:
	THIS SCRIPT DEPENDS ON THE "PROTOTYPE" JAVASCRIPT LIBRARY (v 1.6 at the time of this writing)
	----------------------------------------------------------------------------------------------------------




	----------------------------------------------------------------------------------------------------------
	IMPORTANT NOTE #3: 
	PROPER MIME TYPE HEADER RESPONSE.
	----------------------------------------------------------------------------------------------------------
	The script that returns the results must send them as "text/xml"  ("Content-Type: text/xml" header ). 
	





	That is all.

*/


	//---------------------------------------------	
	//---------------------------------------------	
	function ajax_returnXmlObject(sXmlBlob) {
		var xmlDoc;
		try {
			//Internet Explorer
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.loadXML(sXmlBlob);
			xmlDoc.async=false;
		}
		catch(e) {
			try {
				//Firefox, Mozilla, Opera, etc.
		    		var parser=new DOMParser();
    				xmlDoc=parser.parseFromString(sXmlBlob,"text/xml");
			}	
			catch(e) {
				// alert('cannot process request. ');// Dont send errors as alerts. that's rude. 
				return false;
			}
		}
		return xmlDoc;
	}

	//---------------------------------------------	
	//---------------------------------------------	
	function ajax_createRequestObject() {
		var ro;
		var browser = navigator.appName;
		if(browser == "Microsoft Internet Explorer"){
			ro = new ActiveXObject("Microsoft.XMLHTTP");
		}else{
			ro = new XMLHttpRequest();
		}
		return ro;
	}
	
	//---------------------------------------------	
	// Leverage the power of the DOM! Sneaky, eh?
	//---------------------------------------------	
	function htmlencode(str){
	   var div = document.createElement('div');
	   var text = document.createTextNode(str);
	   div.appendChild(text);
	   return div.innerHTML;
	}

	//---------------------------------------------	
	// Status Div ID gives a little bit of visual feedback during the communications process.
	//---------------------------------------------	
	function ajax_SendRequest(action, req, sResultDivID, sStatusDivID) {
		var http = ajax_createRequestObject();
		var READYSTATE_UNSENT = 0;
		var READYSTATE_OPENED = 1;
		var READYSTATE_HEADERS_RECEIVED = 2;
		var READYSTATE_LOADING = 3;
		var READYSTATE_DONE = 4;

		var feedbackdiv;
		//feedbackdiv = $(unescape(sResultDivID));
		feedbackdiv = sResultDivID;


		var statusdiv;
		if (!sStatusDivID) {
			//statusdiv = $(unescape(sResultDivID));
			statusdiv = sResultDivID; // $(unescape(sResultDivID));
		} else {
			//statusdiv = $(unescape(sStatusDivID));
			statusdiv = sStatusDivID;
		}
		

		$(statusdiv).innerHTML = "Working...";
		$(statusdiv).className = "ajax_working";

		http.open("POST", action);
					
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
		http.onreadystatechange = function () {
			//alert("http.readyState:" + http.readyState.toString());
			$(statusdiv).innerHTML = "Working (" + http.readyState.toString() + ")...";
			$(statusdiv).className = "ajax_working";
			
			if(http.readyState != READYSTATE_DONE){
				// Still busy.
				return;
			}
			if (http.status!=200){ 
				//if request was successful (versus "page not found" etc)
				$(statusdiv).className = "ajax_idle";
				$(statusdiv).innerHTML = "Idle. Last request failed.";
				$(feedbackdiv).innerHTML = "Unexpected HTTP status: " + http.status.toString() + ". Request aborted (126).<br /><a href=\"" + action + "?" + req + "\" target=\"_blank\">debug</a>";
				return;
			}
			var contentType=http.getResponseHeader("Content-Type")
			if (contentType!="text/xml"){
				$(statusdiv).className = "ajax_idle";
				$(statusdiv).innerHTML = "Idle. Last request failed.";
				$(feedbackdiv).innerHTML = "Unexpected content type was returned: " + contentType + ". Request aborted (132).<br /><a href=\"" + action + "?" + req + "\" target=\"_blank\">debug</a>";
				return;
			}
			var s = http.responseText;
			var xmlDoc = ajax_returnXmlObject(s);
			if (!xmlDoc) {
				$(statusdiv).className = "ajax_idle";
				$(statusdiv).innerHTML = "Idle. Last request failed.";
				$(feedbackdiv).innerHTML = "Unable to parse response: " + htmlencode(s) + ". (139).<br /><a href=\"" + action + "?" + req + "\" target=\"_blank\">debug</a>";
				return;
			}
			
			var oResults = xmlDoc.getElementsByTagName("result");
			if (!oResults) {
				$(statusdiv).className = "ajax_idle";
				$(statusdiv).innerHTML = "Idle. Last request failed.";
				$(feedbackdiv).innerHTML = "No 'result' tag was found in response: " + htmlencode(s) + ". (147).<br /><a href=\"" + action + "?" + req + "\" target=\"_blank\">debug</a>";
				return;
			}
			
			var oResultElement = oResults[0];
			if (!oResultElement) {
				$(statusdiv).className = "ajax_idle";
				$(statusdiv).innerHTML = "Idle. Last request failed.";
				$(feedbackdiv).innerHTML = "Could not get 'result' attribute from response: " + htmlencode(s) + ". (147).<br /><a href=\"" + action + "?" + req + "\" target=\"_blank\">debug</a>";
				return;
			}
			

			$(statusdiv).className = "ajax_complete";
			$(statusdiv).innerHTML = "Request Complete.";

			var success = oResultElement.getAttribute("success");
			//alert(success);
			var color;
			var cssClass;
			if ("true" == String(success).toLowerCase()) {
				color = "#ccffcc";
			} else {
				color = "#ffdddd";
			}
			
			//alert(ResultDivID);
			//alert(oResultElement.firstChild.nodeValue);
			$(feedbackdiv).innerHTML = s;
			$(feedbackdiv).innerHTML = oResultElement.firstChild.nodeValue;	
			try{
				var bgclOrig = $(feedbackdiv).style.backgroundColor;
				$(feedbackdiv).style.backgroundColor = color;
				Animation($(feedbackdiv)).duration(500).checkpoint().to("backgroundColor", bgclOrig).go(); 
			} catch (e) {
				$(feedbackdiv).style.backgroundColor = bgclOrig;
			}
			$(statusdiv).className = "ajax_idle";
			$(statusdiv).innerHTML = "Idle.";
		}
		http.send(req);
		return false;

	}

	
	//---------------------------------------------	
	// Some CaSE tOlEranCE 
	//---------------------------------------------	
	function ajaxSubmit(form, sResultDivID, sStatusDivID){
		return AjaxSubmit(form, sResultDivID, sStatusDivID);
	}
	
	
	//---------------------------------------------	
	// Optional: sStatusDivID
	//---------------------------------------------	
	function AjaxSubmit(form, sResultDivID, sStatusDivID){
		var action = form.action
		var req = "ResultDivID=" + sResultDivID;
		var oInput;
		var sType;
		var sName;
		var sID;
		var statusdiv;
		if (!sStatusDivID) {
			//statusdiv = $(unescape(sResultDivID));
			statusdiv = sResultDivID; // $(unescape(sResultDivID));
		} else {
			//statusdiv = $(unescape(sStatusDivID));
			statusdiv = sStatusDivID;
		}
		
		req += "&" + $(form).serialize()
		//alert(req);
		//$(sResultDivID).innerHTML = req;
		ajax_SendRequest(action, req, sResultDivID, sStatusDivID);
		//alert(req);
		return false;
	}








	

