
// list of cached content
var ajaxRequestCache = new Array();

/*
 * Makes asynchronous Ajax request. Caches retrieved content using 
 * combination of request URL and parameter strings as a key.
 *
 *   - requestURL  URL used to make request
 *   - requestParameters  string of key/value pairs. Key/value are separated  
 *                        by '=' sign and between each pair is separated by '&' symbol
 *   - elementId  id of a DOM element whose content will be replaced with the ajax response
 *   - onCompletefunction  reference to function that is going to be executed
 *   - disableCaching   boolean indicating if retrieved content will be cached
 * 	 - options 			a hash that specifies additional configuration parameters
 *  					Valid options include:
 *							showWaitMessage - boolean (defaults to true) 					 
 */
function sendAjaxRequest(requestURL, requestParameters, elementId, onCompletefunction, disableCaching, options) {
  requestParameters = (requestParameters == null || requestParameters == '') ? '': requestParameters + '&';
  requestParameters += 'returnDataEncoding=ajaxEncoding&elementId=' + elementId;  
  requestURL = NCLUtils.createURL(requestURL);

  /* TODO: for now, hack to fix bug in shorexLanding.html when you click "Not yet a member of ncl.com? Click here to register."
     it goes to a secure URL and ajax calls get affected by it due to above NCLUtil.createURL function */          
  if(requestURL.indexOf('/secure/shorex.html') > -1)
  {
    requestURL = requestURL.replace(/https/, 'http');
  	requestURL = requestURL.replace(/secure\//, '');
  }
  
  if (getElement(elementId) != null) {
    if (ajaxRequestCache[requestURL + '?' + requestParameters] == null || disableCaching) {    	
    	if (!options || !!options.showWaitMessage) {
    		var target = (null == options || null == options.waitMessageContainer) ? elementId : options.waitMessageContainer;
    		displayWaitMessage(target);
    	}
		
      // Ajax response structure
      var callback = {
        success: handleSuccess,
        failure: handleFailure,
        argument: {finishCall: onCompletefunction, requestString: requestURL + '?' + requestParameters}
      };

      // create new cache entry
      ajaxRequestCache[requestURL + '?' + requestParameters] = {
        responseText: null,
        argument: {requestString: requestURL + '?' + requestParameters, finishCall: onCompletefunction}
      };

      YAHOO.util.Connect.asyncRequest('GET', requestURL + '?' + requestParameters, callback);
    } else if (ajaxRequestCache[requestURL + '?' + requestParameters].responseText != null) {
      handleSuccess(ajaxRequestCache[requestURL + '?' + requestParameters]);
    }
  }
}

/*
 * Copies content retruned from server into document DOM tree. Executes
 * function that was defined to be executed after Ajax request.
 *
 *   - response  Ajax response object with information on retrieved content
 */
function handleSuccess(response) {
  parseResponse(response.argument.requestString, response.responseText);
  ajaxRequestCache[response.argument.requestString].responseText = response.responseText;
  
  if (response.argument.finishCall != null) {
    response.argument.finishCall();
  }
}

/*
 * Copies text returned by Ajax lookup into DOM. Text is set as an
 * innerHTML of element identified by delimiter in response. Each 
 * delimeter is a string that contains id of element that will receive 
 * text that follows delimeter. 
 *
 *   - requestString  string used to make request. Combination of request URL and request parameters
 *   - responseText  returned text
 */
function parseResponse(requestString, responseText) {
  var delimeterPattern = /UPDATE ELEMENT WITH ID=".*" END OF ELEMENT DELIMETER/g;
  var idPattern = /UPDATE ELEMENT WITH ID="(.*)" END OF ELEMENT DELIMETER/;
  var responseContent = responseText.split(delimeterPattern);
  var delimeters = responseText.match(delimeterPattern);

  // first element in responseContent array is white space that comes before content
  for (var i = 1; i < responseContent.length; i++) {
    getElement(delimeters[i - 1].match(idPattern)[1]).innerHTML = responseContent[i];
  }
}

/*
 * In case of failures that have status code received from server loads error
 * page.
 *
 *   - response  Ajax response object with information on failure
 */
function handleFailure(response) {
	//do nothing
}
