var request;
var requestFinished = true;

/* Create a new XMLHttpRequest object to talk to the Web server */
function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = false;
      }
    }
  }

  if (!request)
    alert("Ajax Error");
}

function getElementsValues(elements){
  var tmpArray = new Array();
  var result = new Array();
  tmpArray = elements.split(';');
  for(var i = 0; i < tmpArray.length; i++){
    result[i] = tmpArray[i]+"="+document.getElementById(tmpArray[i]).value;
  }
  return result;
}

/**********************************************************
CallServer description :

  Parameters :
    -strutsAjaxAction : full path of the action to call
    -requestParameters : ids of field to be given to the action. If you want to use a static value, then define a hidden field.
      The name of an action attribute must match with the id of the field it's refering to.
      If several parameters have to be defined, then separate them with a ';' character.
      i.e: 'param1;param2;param2'

    -responseParameters : id of the field(s) to populate with response value(s).
      If several parameters have to be populated, then separate them with a ';' character.
      i.e: 'field1;field2;field3'

    -updateDiv : boolean that specify if the callServer should return value to populate field or a jsp to display in a <div>.<b>

  Examples :
    -For response parameters only :
      i.e targets :  <span id="field1"></span> | <textfield id="field2"/> | <label id="field3"/>
      callServer('/ajax/ajaxProcess.do', 'param1;param2;param3', 'field1;field2;field3', false)

    -For Div window update :
      i.e target :  <div id="div1"></div>
      callServer('/ajax/ajaxCall.do', 'param1;param2;param3', 'div1', true)

***********************************************************/
function callServer(strutsAjaxAction, requestParameters, responseParameters, updateDiv){
  if(requestFinished){
    requestFinished = false;
    createRequest();

    // Build the URL to connect to
    var url = strutsAjaxAction;

    var resTmp = new Array();

    //split parameter string and store it within an array.
    resTmp = responseParameters.split(';');

    if (requestParameters!='null'){
      url = strutsAjaxAction+"?";


      var reqTmp = getElementsValues(requestParameters);

      //add parameters to url
      for(var i = 0; i < reqTmp.length; i++){
        url += reqTmp[i]+"&";
      }
      //remove the last '&' character
      url = url.substring(0,url.length-1);
    }

    // Open a connection to the server
    request.open("GET", url, true);

    // Setup a function for the server to run when it's done
    request.onreadystatechange = function(){updatePage(resTmp, updateDiv)};

    // Send the request
    request.send(null);
    }
}

/**********************************************************
CallServerSyn description :

  Parameters :
    -strutsAjaxAction : full path of the action to call
    -requestParameters : ids of field to be given to the action. If you want to use a static value, then define a hidden field.
      The name of an action attribute must match with the id of the field it's refering to.
      If several parameters have to be defined, then separate them with a ';' character.
      i.e: 'param1;param2;param2'

    -responseParameters : id of the field(s) to populate with response value(s).
      If several parameters have to be populated, then separate them with a ';' character.
      i.e: 'field1;field2;field3'

    -updateDiv : boolean that specify if the callServer should return value to populate field or a jsp to display in a <div>.<b>

  Examples :
    -For response parameters only :
      i.e targets :  <span id="field1"></span> | <textfield id="field2"/> | <label id="field3"/>
      callServer('/ajax/ajaxProcess.do', 'param1;param2;param3', 'field1;field2;field3', false)

    -For Div window update :
      i.e target :  <div id="div1"></div>
      callServer('/ajax/ajaxCall.do', 'param1;param2;param3', 'div1', true)

  What differentiates this from an asynchronous call is that we pass false as the third parameter in the request.open method and
  we don't need to set up an onreadystatechange handler. The request will be opened, sent and then the browser will hang at
  request.send(null) until either the response has been received or the request has timed out (A process which may last more
  than two minutes and make it appear the browser has crashed).

***********************************************************/

function callServerSyn(strutsAjaxAction, requestParameters, responseParameters, updateDiv){

  // Build the URL to connect to
  var url = strutsAjaxAction;

  var resTmp = new Array();

  //split parameter string and store it within an array.
  resTmp = responseParameters.split(';');
  if (requestParameters!='null'){
    url = strutsAjaxAction+"?";
    var reqTmp = getElementsValues(requestParameters);
    //add parameters to url
    for(var i = 0; i < reqTmp.length; i++){
      url += reqTmp[i]+"&";
    }
    //remove the last '&' character
    url = url.substring(0,url.length-1);
  }

  createRequest();
  if(request) {
    // Open a connection to the server
    request.open("GET", url, false);

    // Send the request
    request.send(null);

    if(!request.getResponseHeader("Date")) {
	  var cached = request;
	  request = (typeof(XMLHttpRequest) != "undefined") ?
	      new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");
	  var ifModifiedSince = cached.getResponseHeader("Last-Modified");
	  ifModifiedSince = (ifModifiedSince) ?
	      ifModifiedSince : new Date(0);
	  request.open("GET", url, false);
	  request.setRequestHeader("If-Modified-Since", ifModifiedSince);
	  request.send("");
	  if(request.status == 304) {
	    request = cached;
	  }
	}

    updatePage(resTmp, updateDiv);
  } else {
    return false;
  }
}

/**********************************************************
callServerWithCallback description :

  Parameters :
    -strutsAjaxAction : full path of the action to call
    -requestParameters : ids of field to be given to the action. If you want to use a static value, then define a hidden field.
      The name of an action attribute must match with the id of the field it's refering to.
      If several parameters have to be defined, then separate them with a ';' character.
      i.e: 'param1;param2;param2'
    -callback : the function to execute once the response arrived

  Example:
    callServerWithCallback('/forms/groupProfile/getHotelsByDestinations.do', 'destinationsList', function(){populateSelects("hotels","hotel1","hotel2","hotel3");});

***********************************************************/
function callServerWithCallback(strutsAjaxAction, requestParameters, callback){
  if(requestFinished){
    requestFinished = false;
    createRequest();

    // Build the URL to connect to
    var url = strutsAjaxAction;

    if (requestParameters!='null'){
      url = strutsAjaxAction+"?";

      var reqTmp = getElementsValues(requestParameters);

      //add parameters to url
      for(var i = 0; i < reqTmp.length; i++){
        url += reqTmp[i]+"&";
      }
      //remove the last '&' character
      url = url.substring(0,url.length-1);
    }

    // Open a connection to the server
    request.open("GET", url, true);

    // Setup a function for the server to run when it's done
    request.onreadystatechange = function(){
      if (request.readyState == 4) {
        if(request.status == 200){
          callback();
          requestFinished = true;
        }else{
          //alert("error updating ajax");
        }
      }
    };

    // Send the request
    request.send(null);
    }
}

function updatePage(resTmp, updateDiv) {
  if (request.readyState == 4) {
    if(request.status == 200){
      if(updateDiv){
        document.getElementById(resTmp[0]).innerHTML = request.responseText;
      }else{

        for(var i = 0; i < resTmp.length; i++){
            var updatedElt = document.getElementById(resTmp[i]);
            updatedElt.innerHTML = request.getResponseHeader(resTmp[i]);
            if (updatedElt.disabled) {
              updatedElt.disabled = false;
            }
          }

        }
        requestFinished = true;
    }else{
      //alert("error updating ajax");
    }
  }
}

/**
 * populateSelects(headerName, selectId...)
 *
 * A function to use as callback to populate <select> elements with an ajax call returning JSON data.
 *
 * Example:
 * callServerWithCallback('/forms/groupProfile/getHotelsByDestinations.do', 'destinationsList', function(){populateSelects("hotels","hotel1","hotel2","hotel3");});
 *
 */
function populateSelects() {
  var args = populateSelects.arguments;
  if (args.length < 2) return;
  var response = request.getResponseHeader(args[0]);
  if (response) {
    var selects = new Array();
    for(var i=1 ; i<args.length ; i++) {
      selects[i-1] = document.getElementById(args[i]);
      selects[i-1].options.length = 0;
      selects[i-1].options[0] = new Option("","");
    }
    var items = eval("("+response+")");
    for(var item in items) {
      for(var i=0 ; i<selects.length ; i++) {
        selects[i].options[selects[i].options.length] = new Option(items[item],item);
      }
    }
    for(var i=0 ; i<selects.length ; i++) {
      selects[i].disabled = false;
    }
  }
}

/**
 * populateMultiSelects(headerName, selectId...)
 *
 * A function to use as callback to populate <select> elements with an ajax call returning JSON data.
 *
 * Example:
 * callServerWithCallback('/forms/groupProfile/getHotelsByDestinations.do', 'destinationsList', function(){populateSelects("hotels","resortCode","tours","tourCode");});
 *
 */
function populateMultiSelects() {
  var args = populateSelects.arguments;
  if (args.length < 2) return;
  for(var n=0;n<args.length;n=n+2){
    var response = request.getResponseHeader(args[n]);
    if (response) {
      var selects = new Array();
      for(var i=n+1 ; i<n+2 ; i++) {
        selects[i-n-1] = document.getElementById(args[i]);
        selects[i-n-1].options.length = 0;
        selects[i-n-1].options[0] = new Option("","");
      }
      var items = eval("("+response+")");
      for(var item in items) {
        for(var i=0 ; i<selects.length ; i++) {
          selects[i].options[selects[i].options.length] = new Option(items[item],item);
        }
      }
      for(var i=0 ; i<selects.length ; i++) {
        selects[i].disabled = false;
      }
    }

  }
}

numberOfRequests = 0;

function turnToAjaxForm(formElt) {
  formElt.submit = function() {
    var requestIndex = (++ numberOfRequests);
    sbmtNotComplete = true;
    jQuery.ajax({
      url: formElt.action,
      type: "POST",
      dataType: "html",
      data: jQuery.param($(formElt).serializeArray()),
      complete: function(res, status) {
        // process only the last request
        if (requestIndex == numberOfRequests) {
          sbmtNotComplete = false;
          // remove the loader div
          if(window.ajaxDiv){
           $(window.ajaxDiv).remove();
           window.ajaxDiv = undefined;
          }
          // If successful, inject the HTML into all the matched elements
          if ( status == "success" || status == "notmodified" ) {
              $('.estimateMessage').hide();
            var div = $("#searchResultsDiv");
	        var text = res.responseText;
            div.slideUp(function() {
              div.html(text);
              div.slideDown();
              smallImageBrowser.init();
            });
          }
        }
      }
    });
    // create the loader if it doesn't exist yet
    if(! window.ajaxDiv) {
      var ajaxLoader = document.createElement('img')
      $(ajaxLoader).attr({
        'id':'bigAjaxLoader',
        'src':'/media/images/common/web/placeholders/ajax-loader.gif'
      });
      window.ajaxDiv = document.createElement("div");
      var ie6 = (jQuery.browser.msie && jQuery.browser.version < 7);

      $(window.ajaxDiv).css({
        'position': (ie6 ? 'absolute' : 'fixed'),
        'top':'50%',
        'left':'50%',
        'opacity':0,
        'background':'#E6E6E6',
        'z-index':1000,
        'width':'100px',
        'height':'100px'
      });

      if (sbmtNotComplete) {
        $('body').append(window.ajaxDiv);
        $(window.ajaxDiv).show();
        $(window.ajaxDiv).append(ajaxLoader);
        $(window.ajaxDiv).animate({opacity: 0.9}, 300, "");
      }
    }
    return false;
  };
  formElt.reset = function() {
    clearForm(formElt);
    formElt.needReset.value = 'false';
  }
}

function turnToAjaxInterestForm(formElt) {
  formElt.submit = function() {
    var requestIndex = (++ numberOfRequests);
    sbmtNotComplete = true;
    jQuery.ajax({
      url: formElt.action,
      type: "POST",
      dataType: "html",
      data: jQuery.param($(formElt).serializeArray()),
      complete: function(res, status) {
        // process only the last request
        if (requestIndex == numberOfRequests) {
          sbmtNotComplete = false;
          // remove the loader div
          if(window.ajaxDiv){
           $(window.ajaxDiv).remove();
           window.ajaxDiv = undefined;
          }
          // If successful, inject the HTML into all the matched elements
          if ( status == "success" || status == "notmodified" ) {
            var hiddenDiv = $("#hiddenAjaxResponse");
            hiddenDiv.slideUp(function() {
              hiddenDiv.html(res.responseText);
            });
            var searchResultDiv = $("#searchResultsDiv");
            searchResultDiv.slideUp(function() {
              searchResultDiv.html(hiddenDiv.find("div:eq(0)").html());
              searchResultDiv.slideDown();
              smallImageBrowser.init();
            });

            var filterDiv = $("#interestFilterContainerDiv");
            var text2 = hiddenDiv.find("div:eq(0) + div").html();
            hiddenDiv.find("div:eq(0) + div").remove();
            filterDiv.html(text2);
            turnToAjaxInterestForm(document.interestFilter);

          }
        }
      }
    });
    // create the loader if it doesn't exist yet
    if(! window.ajaxDiv) {
      var ajaxLoader = document.createElement('img')
      $(ajaxLoader).attr({
        'id':'bigAjaxLoader',
        'src':'/media/images/common/web/placeholders/ajax-loader.gif'
      });
      window.ajaxDiv = document.createElement("div");
      var ie6 = (jQuery.browser.msie && jQuery.browser.version < 7);

      $(window.ajaxDiv).css({
        'position': (ie6 ? 'absolute' : 'fixed'),
        'top':'50%',
        'left':'50%',
        'opacity':0,
        'background':'#E6E6E6',
        'z-index':1000,
        'width':'100px',
        'height':'100px'
      });

      if (sbmtNotComplete) {
        $('body').append(window.ajaxDiv);
        $(window.ajaxDiv).show();
        $(window.ajaxDiv).append(ajaxLoader);
        $(window.ajaxDiv).animate({opacity: 0.9}, 300, "");
      }
    }
    return false;
  };

  formElt.reset = function() {
    clearForm(formElt);
    formElt.needReset.value = 'false';
  }
}



function getPurlUrl() {

     $('#purl').hide();
    
     jQuery.ajax({
           type: "POST",
           dataType: "html",
           url: '/purl/purlURL.do',
           complete: function(res, status) {

               var responseString =  res.responseText;
               if (responseString  == null || jQuery.trim(responseString).length==0) {
                      $('#purl').hide();
               }   else {
                      $('#purl').show()  ;
                       $('#purl').html(res.responseText);
           }
           }

     });
 }





      function clearForm(formElt) {

        // iterate over all of the inputs for the form

        // element that was passed in

        $(':input', formElt).each(function() {

          var type = this.type;

          var tag = this.tagName.toLowerCase(); // normalize case


          // it's ok to reset the value attr of text inputs,

          // password inputs, and textareas

          if (type == 'text' || type == 'password' || tag == 'textarea')

            this.value = "";



          // checkboxes and radios need to have their checked state cleared

          // but should *not* have their 'value' changed

          else if (type == 'checkbox' && this.checked == true){

            this.checked = false;
            this.label.className = 'checkboxOff';

			}



          // select elements need to have their 'selectedIndex' property set to -1

          // (this works for both single and multiple select elements)

          else if (tag == 'select')

            this.selectedIndex = 0;

        });

      };




