
/**
 * Ajax.js
 *
 * Collection of Scripts to allow in page communication from browser to (struts) server
 * ie can reload part instead of full page
 *
 * How to use
 * ==========
 * 1) Call retrieveURL from the relevant event on the HTML page (e.g. onclick)
 * 2) Pass the url to contact (e.g. Struts Action), the name of the HTML form to post
 *     and the action ("GET" or "POST")
 * 3) When the server responds ...
 *		 - the script loops through the response , looking for <span id="name">newContent</span>
 * 		 - each <span> tag in the *existing* document will be replaced with newContent
 *
 * NOTE: <span id="name"> is case sensitive. Name *must* follow the first quote mark and end in a quote
 *		 Everything after the first '>' mark until </span> is considered content.
 *		 Empty Sections should be in the format <span id="name"></span>
 */

//global variables
var req;
var which;
/**
 * Get the contents of the URL via an Ajax call
 * url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1) 
 * nodeToOverWrite - when callback is made
 * nameOfFormToPost - which form values will be posted up to the server as part 
 *					of the request (can be null)
 */
function retrieveURL(url, formName, action, allValues) {
	// Show "please wait" image before doing Ajax call
 	//showWaitImage();
	retrieveURLNoWait(url, formName, action, allValues);
}
/**
 * Get the contents of the URL via an Ajax call without displaying the wait image.
 * url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1) 
 * nodeToOverWrite - when callback is made
 * nameOfFormToPost - which form values will be posted up to the server as part 
 *					of the request (can be null)
 */
function retrieveURLNoWait(url, formName, action, allValues) {
	// Set up URL
	form = document.forms[formName];
	if (url.indexOf("?") > 0) {
		url = url + "&ask=COMMAND_NAME_1";
	} else {
		url = url + "?ask=COMMAND_NAME_1";
	}
	if (action == "GET") {
		url = url + getFormAsString(form);
	}
    // Do the Ajax call
	if (window.XMLHttpRequest) { // Non-IE browsers
		req = new XMLHttpRequest();
	} else {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP"); // New IE browsers
		}
		catch (e) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	if (req) {
		req.onreadystatechange = processStateChange;
		req.open(action, url, true);
		if (action == "POST") {
			req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			if (allValues) {
				formValues = setAttributes(form);
			} else {
				formValues = "";
			}
			req.send(formValues);
		} else {
			req.send(null);
		}
	} else {
		// Session has ended so return home
		document.location.href = "index.do";
	}
	return (false);
}
/*
   * Set as the callback method for when XmlHttpRequest State Changes 
   * used by retrieveUrl
  */
function processStateChange() {
	if (req.readyState < 5 && req.readyState > 0) {
		if (req.readyState == 4) { 
			// Complete
			if (req.status == 200) { // OK response
		        //Split the text response into Span elements
				spanElements = splitTextIntoSpan(req.responseText);
		        //Use these span elements to update the page
				replaceExistingWithNewHtml(spanElements);
				postAjaxProcessing();
			} else {
				// Session has ended so return home
				document.location.href = "index.do";
				return;
      			//alert("Problem with server response:n " + req.statusText);
			}
		}
	} else {
		// Session has ended so return home
		document.location.href = "index.do";
		return;
	}
}
/**
  * Gets the contents of the form as a URL encoded String
  * suitable for appending to a url
  * @param form to encode
  * @return string with encoded form values , beings with &
  */
function getFormAsString(form) {
	returnString = "";
	if (form == null) {
		return returnString;
	}
	formElements = form.elements;
 	
 	// Loop through the array , building up the url
 	// in the form /strutsaction.do&name=value
	for (var i = formElements.length - 1; i >= 0; --i) {
 		// We escape (encode) each value
		returnString = returnString + "&" + escape(formElements[i].name) + "=" + escape(formElements[i].value);
	}
	return returnString;
}
/**
  * Splits the text into <span> elements
  * @param the text to be parsed
  * @return array of <span> elements - this array can contain nulls
  */
function splitTextIntoSpan(textToSplit) {
 
  	//Split the document
	returnElements = textToSplit.split("</span>");

 	//Process each of the elements 	
	for (var i = returnElements.length - 1; i >= 0; --i) {
 		//Remove everything before the 1st span
		spanPos = returnElements[i].indexOf("<span");		
 		//if we find a match , take out everything before the span
		if (spanPos > 0) {
			subString = returnElements[i].substring(spanPos);
			returnElements[i] = subString;
		}
	}
	return returnElements;
}
/*
  * Replace html elements in the existing (ie viewable document)
  * with new elements (from the ajax requested document)
  * WHERE they have the same name AND are <span> elements
  * @param newTextElements (output of splitTextIntoSpan)
  *	in the format <span id=name>texttoupdate
  */
function replaceExistingWithNewHtml(newTextElements) {
 
 	//loop through newTextElements
	for (var i = newTextElements.length - 1; i >= 0; --i) {
  
 		//check that this begins with <span
		if (newTextElements[i].indexOf("<span") > -1) {
 			
 			//get the name - between the 1st and 2nd quote mark
			startNamePos = newTextElements[i].indexOf("\"") + 1;
			endNamePos = newTextElements[i].indexOf("\"", startNamePos);
			name = newTextElements[i].substring(startNamePos, endNamePos);
 			//get the content - everything after the first > mark
			startContentPos = newTextElements[i].indexOf(">") + 1;
			var newStuff = newTextElements[i].substring(startContentPos);
 			
 			//Now update the existing Document with this element
 			
	 			//check that this element exists in the document
			if (document.getElementById(name)) {
 				//update content in document
				document.getElementById(name).innerHTML = newStuff;
			}
		}
	}
}
function replaceAll(str, from, to) {
	var idx = str.indexOf(from);
	while (idx > -1) {
		str = str.replace(from, to);
		idx = str.indexOf(from);
	}
	return str;
}
function setAttributes(form) {
	formElements = form.elements;
	returnString = "";
 	
 	// Loop through the array, setting the values in the request
	for (var i = formElements.length - 1; i >= 0; --i) {
		var element = formElements[i].name;
		var value = formElements[i].value;
		returnString = returnString + "&" + escape(element) + "=" + escape(value);
	}
	return returnString;
}
function postAjaxProcessing() {
	// Re-initialize accommodation and attraction dropdowns
	// after an Ajax call
	if (window.InitAll) {
		if (selectedDiv == 4) { // Accommodation tab is selected
			InitAll(1);
		} else {
			if (selectedDiv == 0) { // Attractions tab is selected
				InitAll(2);
			}
		}
	}
	// Set scroll of maneuver table
	var maneuverTable = document.getElementById("maneuverTable");
	if (maneuverTable) {
		maneuverTable.scrollTop = maneuverTableScrollTop;
	}
	// Set scroll of accommodation div
	var accomDiv = document.getElementById("accomDiv");
	if (accomDiv) {
		accomDiv.scrollTop = accomDivScrollTop;
	}
	// Set scroll of attractions div
	var attDiv = document.getElementById("attDiv");
	if (attDiv) {
		attDiv.scrollTop = attDivScrollTop;
	}
	// Set scroll of addresses div
	var addDiv = document.getElementById("addressDiv");
	if (addDiv) {
		addDiv.scrollTop = addressDivScrollTop;
	}
	// Set scroll of trips div
	var tripDiv = document.getElementById("tripDiv");
	if (tripDiv) {
		tripDiv.scrollTop = tripDivScrollTop;
	}
	// Restore tab state in itinerary screen
	try {
		if (theTabIndices) {
			for (var i = 0; i < theTabIndices.length; i++) {
				var tabIndex = theTabIndices[i];
				var savedTab = document.getElementById("a_saved_w" + tabIndex);
				selectTab(savedTab, "w" + tabIndex);
			}
		}
	}
	catch (e) {
		// Do nothing
	}
	// Hide "please wait" image
	try {
		hideWaitImage();
	}
	catch (e) {
 		// Do nothing
	}
 	// Itinerary screen initialization
	try {
		itineraryInit();
	}
	catch (e) {
 		// Do nothing
	}
 	
 	// Traffic stuff
	//refreshMap();
}

