/*


	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'); "
		/>
	</form>
	<div id="ajax_feedback"></div>


	
	IMPORTANT NOTE #1 
	

	'#########################################################################################
	'THE SERVER PROCESS THAT HANDLES THE AJAX REQUESTS MUST RETURN THE RESULTS IN THE FOLLOWING FORMAT: 
	'#########################################################################################
	
	' ResultDivID is where the message goes after the thing you originally wanted to do gets done (or if it fails).
	
	<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>

	IMPORTANT NOTE #2
	
	This script depends on Prototype. 
	


*/


	//---------------------------------------------	
	//---------------------------------------------	
	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('Your browser does not support client-side XML processing. ');
			}
		}
		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;
	}
	
	//---------------------------------------------	
	//---------------------------------------------	
	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 = 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 = "#ddffdd";
			} else {
				color = "#ffdddd";
			}
			
			//alert(ResultDivID);
			//alert(oResultElement.firstChild.nodeValue);
			$(feedbackdiv).innerHTML = s;
			$(feedbackdiv).innerHTML = oResultElement.firstChild.nodeValue;	
			var bgclOrig = $(feedbackdiv).style.backgroundColor;
			//alert($(feedbackdiv));
			//alert($(feedbackdiv).style);
			//alert(bgclOrig);
			$(feedbackdiv).style.backgroundColor = color;
			if (Animation){
				Animation($(feedbackdiv)).duration(500).checkpoint().to("backgroundColor", bgclOrig).go(); 
				//Animation($(feedbackdiv)).duration(500).checkpoint().to("backgroundColor", bgclOrig).go(); 
			}
			$(statusdiv).className = "ajax_idle";
			$(statusdiv).innerHTML = "Idle.";
		}
		http.send(req);
		return false;

	}

	
	//---------------------------------------------	
	// Some CaSE tOlEranCE 
	//---------------------------------------------	
	function ajaxSubmit(form, sResultDivID){
		return AjaxSubmit(form, sResultDivID);
	}
	
	
	//---------------------------------------------	
	// Optional: sStatusDivID
	//---------------------------------------------	
	function AjaxSubmit(form, sResultDivID, sStatusDivID){
		var action = form.action
		var req = "ResultDivID=" + sResultDivID;
		var oInput;
		var sType;
		for (iElementsCount=0; iElementsCount < form.elements.length; iElementsCount++) {
			req += "&" + escape(form.elements[iElementsCount].name) + "=";
			oInput = form.elements[iElementsCount];
			sType = oInput.type;
			if (sType == "hidden" || sType == "text" || sType == "textarea" || sType == "file" || sType == "password") {
				req += escape(oInput.value);

			} else if (sType == "button" || sType == "submit" || sType == "reset"){
				//ignore these.

//			} else if (sType == "radio"){
//                              // still need to write something for this type.	

			} else if (sType == "select" || sType == "select-single" || sType == "select-multiple" ||  sType == "select-one" ){
				req +=escape(oInput.options[oInput.selectedIndex].value);
				//alert(req);

			} else if (sType == "checkbox"){
				if (oInput.checked){
					req += escape(oInput.value);
				}else{
					req +="";
				}


			} else {
				alert("Unhandled input type - '" + sType +"'. The site admin will need to fix this. [lib-ajax.js, AjaxSubmit(), line 158] ");
				return false;
			}

					
		
		}
		//$(sResultDivID).innerHTML = req;
		ajax_SendRequest(action, req, sResultDivID, sStatusDivID);
		//alert(req);
		return false;
	}








	
