/***************
How to incorporate ajax requests into your page:

1. Wrap the data you would like to change on the page within a named <div>. Note the <div> id should be
prefixed with 'ajax' for maintainability.
2. Register the named <div> with ajax by pushing it into the 'ajaxElements' array 
3. Register the url with ajax using an identifier
4. Create a function that submits that submits the ajax request along with relevant parameters along with the
identifier from step 3. 
5. Make sure that the html content in the response is well-formed or it will not be processed properly.
See sample code below:

...
<script type="text/javascript">
	ajaxElements.push("myId");
	function registerAjaxEngine("myIdentifier","ajax.html");
	sendAjaxRequest("myIdentifier","dispatch=doStuff","parameter=param1:value1;param2:value2;param3:value3","myId");
</script>

<div id="myId">
	DATA TO REPLACE
</div>
...

The response below would replace the data in the 'myId' div with the data within the <rows> element.
Note that the element id value in the response is set to 'myId'. The jsp page that is used to build the response must
set this value. The params passed can be used by the struts action to obtain any additional information as required.

sample ajax response
<ajax-response>
<response type="element" id='myId'>
<rows update_ui='true' >
	DYNAMIC DATA GOES HERE
</rows>
</response>
</ajax-response>

ajax response tiles layout. Replace the body with the appropriate jsp page in the tiles-definition file. Note: the page
must use request attributes/jsp include params as opposed to having specific ActionForm references.
<%@ include file="/common/taglibs.jsp"%>
	<ajax-response>
		<response type="element" id='<c:out value="${ajaxForm.elementId}"/>'>
			<rows update_ui='true' >
 				<tiles:get name="body"/>
			</rows>
		</response>
	</ajax-response>
***************/


//Array that holds all elements to be registered with ajax
var ajaxElements = new Array();

/***************
* registerAjaxEngine
* This function will associate the passed identifier with the passed url in the ajax engine.
* identifier - the string identifier registered in ajax with the url.
* url - the url to to which the ajax request will be sent.
***************/
function registerAjaxEngine(identifier,url){
	ajaxEngine.registerRequest(identifier,url);
}

/***************
* registerElementsWithAjax
* This function is called as part of the bodyOnLoads by being pushed into the onLoads array.
****************/
function registerElementsWithAjax(){
	for ( var i = 0 ; i < ajaxElements.length ; i++ ){
		//alert(ajaxElements[i]);
		ajaxEngine.registerAjaxElement(ajaxElements[i]);
	}
}

/***************
*sendAjaxRequest
*This function sends an ajax request.
* identifier - the identifier string mapped to a url in the ajax engine. The associated url will
* target for the ajax request.
* dispatch - the struts dispatch that will handle the processing of the request
* params - a delimited string containing sets of key/value parameter pairs with the following structure:
* key1:value1;key2:value2;...;keyn:valuen
* elementId - the DOM element id whose content will be replaced with the ajax response.
*
* This function was updated to parse the context from the url.  It will no longer function
* correctly if we remove the web application context (i.e. change the context to /).
***************/

function sendAjaxRequest(identifier, dispatch, elementId) {
  displayWaitMessage(elementId);

  var params = new Array();
    
  // since arguments variable is not a true Array object and we have to 
  // add "returnDataEncoding" parameter, arguments is copied into real array.
  // dispatch and elementId arguments have to be updated to name/value pair
  for (var i = 0; i < arguments.length; i++) {
    if (i == 1 && arguments[i] != null && arguments[i] != '') {
      params.push("dispatch=" + arguments[i]);
    } else if (i == 2 && arguments[i] != null && arguments[i] != '') {
      params.push("elementId=" + arguments[i]);
    } else if (arguments[i] != null && arguments[i] != '') {
      params.push(arguments[i]);
    }
  }
  
  params.push("returnDataEncoding=ajaxEncoding");

  ajaxEngine.sendRequest.apply(ajaxEngine, params);
}

/*
 * Sends Ajax request. On request completion invokes specified function.
 *
 *   - identifier  identifies request URL registered with Ajax engine
 *   - onCompletefunction  reference to function that is going to be executed
 *   - elementId  identifier for DOM element where retrieved HTML will be copied
 *   - params  string with '&' seperated parameters in key=value pairs
 */
function sendAjaxRequestWithParamsAndOncomplete(identifier, onCompletefunction, elementId, params) {
  displayWaitMessage(elementId);
  
  if (params.length > 0) {
    params += "&";
  }

  params += "elementId=" + elementId + "&returnDataEncoding=ajaxEncoding";
  
  // data structure that holds onComplete function reference and parameters for request
  var options = {
    onComplete: onCompletefunction,
    parameters: params
  };
  
  ajaxEngine.sendRequest(identifier, options);
}

function changeElementIdWhileLoading(elementId) {
  // Change the id of the select - so the tests will not get an element back for this id until the ajax call returns.
  // The whole div will be replaced when the ajax returns, so this id rename is just temporary.
  var element = document.getElementById(elementId);
  if (element != null) {
    element.name = elementId + "IsWaitingToBePopulated";
  }
}

/*
 * Changes opacity of element that will be reloaded with Ajax and
 * displays loading message if there is enough space for it.
 *
 *   - elementId  identifier on page for element whose body will be 
 *                reloaded
 */
function displayWaitMessage(elementId) {
  var refElmnt = document.getElementById(elementId);
  var maxWidth = 270;
  var maxHeight = 75;
  var backgroundOpacity = 70;

  var elmnts = refElmnt.getElementsByTagName('DIV');
  var i = 0;
  
  for (; i < elmnts.length && elmnts[i].className != 'loading_image'; i++);

  // skip showing of wait loading graphics if they are already displayed
  if (i == elmnts.length) {
    disablePageFunctionality(backgroundOpacity, refElmnt);
  
    if (refElmnt.offsetWidth > maxWidth && refElmnt.offsetHeight > maxHeight) {
      displayLoadingElement(refElmnt);
    }
  }
}

/*
 * Creates element with loading message and adds it to element that
 * will be reloaded by Ajax.
 *
 *   - refElmnt  element that will contain loading message
 */
function displayLoadingElement(refElmnt) {
  var loadingContentDiv = document.createElement('div');
  loadingContentDiv.id = 'loading';
  
  refElmnt.appendChild(loadingContentDiv);

  loadingContentDiv.innerHTML = '<div>If for some reason you are unable to view this loading message, you\'ll need to upgrade to the latest version of <a href="http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">Adobe Flash</a>. It\' s quick, easy and safe.</div>'
    + '<div class="loading_image"></div>';

  var fo = new FlashObject("../flash/title.swf", "title", "270", "51", "7", "#000");
  fo.addParam("allowScriptAccess", "sameDomain");
  fo.addParam("quality", "high");
  fo.addParam("wmode", "transparent");
  fo.addVariable("title", "Loading: ");
  fo.addVariable("subtitle", "Please wait...");

  var title = loadingContentDiv.getElementsByTagName('div')[0];
  fo.write(title);
  
  // position loading message in middle of reference element and 10% from the top
  loadingContentDiv.style.top = (refElmnt.offsetHeight / 10 + offsetTop(refElmnt)) + 'px';
  
  var left = ((refElmnt.offsetWidth - 270) > 0) ? (refElmnt.offsetWidth - 270) / 2: 0;
  
  loadingContentDiv.style.left = (left + offsetLeft(refElmnt)) + 'px';
  
  loadingContentDiv.style.visibility = 'visible';
}