/*******************************************************************************************
 * callBack
 * Written by Craig Francis
 * Take a form and submit it though "AJAX", and replace the forms contents with the response
 *******************************************************************************************/

	var callBack = new function() {

		//--------------------------------------------------
		// Do not allow older browsers to run this script

			if (!document.getElementById || !document.getElementsByTagName) {
				return;
			}

		//--------------------------------------------------
		// Initialisation function used for setup

			this.init = function() {

				//--------------------------------------------------
				// By default no forms are active

					callBack.curentReq = false;
					callBack.curentSubmitName = null;
					callBack.curentSubmitValue = null;

				//--------------------------------------------------
				// Find the forms

					var forms = document.getElementsByTagName('form');

					for (var k = (forms.length - 1); k >= 0; k--) {
						if (cssjs('check', forms[k], 'jsCallBack')) {

							console.log('jsCallBack: setup');

							callBack.setup(forms[k]);

						}
					}

			}

		//--------------------------------------------------
		// Setup a form

			this.setup = function(form) {

				//--------------------------------------------------
				// Add tracer for which submit button was used

					var inputs = form.getElementsByTagName('input');

					for (var k = (inputs.length - 1); k >= 0; k--) {
						if (inputs[k].value && inputs[k].name && inputs[k].name != '') {

							var type = inputs[k].type.toLowerCase();

							if (type == 'submit' || type == 'image') {

								inputs[k].onclick = function() {
									callBack.curentSubmitName = this.name;
									callBack.curentSubmitValue = this.value;
								};

								if (!callBack.curentSubmitName) {
									callBack.curentSubmitName = inputs[k].name;
									callBack.curentSubmitValue = inputs[k].value;
								}

							}

						}
					}

				//--------------------------------------------------
				// Master form handler

					form.onsubmit = callBack.formSubmit;

			}

		//--------------------------------------------------
		// Get fields within a form

			this.formValues = function(form) {

				//--------------------------------------------------
				// Initialise the variables

					var formValues = new Array();

				//--------------------------------------------------
				// Inputs

					var inputs = form.getElementsByTagName('input');

					for (var k = (inputs.length - 1); k >= 0; k--) {
						if (inputs[k].name && inputs[k].name != '') {

							var type = inputs[k].type.toLowerCase();

							if (type == 'checkbox') {

								if (inputs[k].checked) {
									formValues[formValues.length] = escape(inputs[k].name) + '=' + escape(inputs[k].value);
								}

							} else if (type == 'radio') {

								// To add

							} else if (type == 'submit' || type == 'image') {

								// Ignore

							} else {

								formValues[formValues.length] = escape(inputs[k].name) + '=' + escape(inputs[k].value);

							}

						}
					}

				//--------------------------------------------------
				// Selects

					var selects = form.getElementsByTagName('select');
					var value;

					for (var k = (selects.length - 1); k >= 0; k--) {
						if (selects[k].name && selects[k].name != '') {

							//--------------------------------------------------
							// Value

								if (selects[k].value) {

									value = selects[k].value;

								} else if (selects[k].selectedIndex > 0) {

									value = selects[k].options[selects[k].selectedIndex].text;

								} else {

									value = ''; // Multiple selection field, with none selected

								}

							//--------------------------------------------------
							// Store

								formValues[formValues.length] = escape(selects[k].name) + '=' + escape(value);

						}
					}

				//--------------------------------------------------
				// The submit button used

					if (callBack.curentSubmitName) {
						formValues[formValues.length] = escape(callBack.curentSubmitName) + '=' + escape(callBack.curentSubmitValue);
					}

				//--------------------------------------------------
				// Return the formValues

					return formValues;

			}

		//--------------------------------------------------
		// Function called when the form is submitted

			this.formSubmit = function() {

				//--------------------------------------------------
				// If the form has already been sent, and this
				// has been triggered again... assume that the
				// form submit failed, and that the user wants to
				// do it normally.

					if (callBack.curentReq) {
						return true;
					}

				//--------------------------------------------------
				// Get the field values

					var formValues = callBack.formValues(this);

				//--------------------------------------------------
				// Create the XMLHttpRequest

					var req = null;

					try {
						req = new ActiveXObject("Msxml2.XMLHTTP");
					} catch(e) {
						try {
							req = new ActiveXObject("Microsoft.XMLHTTP");
						} catch(oc) {
							req = null;
						}
					}

					if (req === null && typeof XMLHttpRequest != "undefined") {
						req = new XMLHttpRequest();
					}

					if (req === null) {
						return true; // Error, so use traditional form submission
					}

				//--------------------------------------------------
				// When the server responds

					callBack.curentForm = this;

					callBack.curentReq = req;
					callBack.curentReq.onreadystatechange = callBack.formResult;

				//--------------------------------------------------
				// Post the data back to the server.

					var query = 'js=true'
					for (var k = (formValues.length - 1); k >= 0; k--) {
						query += '&' + formValues[k];
					}

					console.log('jsCallBack: query = ' + query);
					console.log('jsCallBack: action = ' + this.action);

					req.open('POST', this.action, true);
					req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					req.send(query);

				//--------------------------------------------------
				// Show the loading graphic

					var inputs = this.getElementsByTagName('input');

					for (var k = (inputs.length - 1); k >= 0; k--) {
						if (inputs[k].type.toLowerCase() == 'image' && cssjs('check', inputs[k], 'jsShowLoading')) {

							var newSrc = inputs[k].src.replace(/(\.[a-z]+$)/, 'Loading$1');

							console.log('jsCallBack: request = ' + newSrc);

							inputs[k].src = newSrc;

						}
					}

				//--------------------------------------------------
				// Await response - false so the form is not
				// submitted.

					return false;

			}

		//--------------------------------------------------
		// Function called when the XMLHttpRequest has
		// returned;

			this.formResult = function() {
				if (callBack.curentReq.readyState == 4) {

					//--------------------------------------------------
					// Give up if the request was not successful

						if (callBack.curentReq.status != 200) {

							alert("Unfortunately an error has occurred, I will now try to use the traditional form submission method.\nERROR: " + callBack.curentReq.statusText);

							callBack.curentForm.onsubmit = null;
							callBack.curentForm.submit();

							return;

						}

					//--------------------------------------------------
					// Replace the form's contents - UGLY! should use
					// the DOM, but don't have time.

						callBack.curentForm.innerHTML = callBack.curentReq.responseText;

					//--------------------------------------------------
					// Update the form setup

						callBack.setup(callBack.curentForm);

					//--------------------------------------------------
					// Form request is no longer active

						callBack.curentReq = false;

				}
			}

		//--------------------------------------------------
		// When the page has loaded, run the init function

			addLoadEvent (function() {
				callBack.init();
			});

	}

