/** > /scripts-v66/view/json/modules/jsonrpc_push.js **/
/**
 * Appel du coeur de JSON.
 */
 
/** Loading /scripts-v66/view/json/jsonrpc_ah.js **/
/* ATTENTION 1 : NE PAS FAIRE DE PROTOTYPE POUR L INSTANT DANS CE JS PAR MESURE DE COMPATIBILITE AVEC LES PAGE COMPORTANT TJS DU PSEUDOJS
   ATTENTION 2 : <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr"> est obligatoire sur la pages incluant ce js */

/** Loading /scripts-v66/dwr/interface/RemoteView.js **/
// Provide a default path to dwr.engine
if (dwr == null) var dwr = {};
if (dwr.engine == null) dwr.engine = {};
if (DWREngine == null) var DWREngine = dwr.engine;

if (RemoteView == null) var RemoteView = {};
RemoteView._path = '/dwr';
RemoteView.toString = function(callback) {
  dwr.engine._execute(RemoteView._path, 'RemoteView', 'toString', callback);
}

RemoteView.getViewBeans = function(p0, p1, p2, p3, callback, p4) {
  if (typeof p4 == "undefined") // Retrocompatibilite
    dwr.engine._execute(RemoteView._path, 'RemoteView', 'getViewBeans', p0, p1, p2, p3, callback);
  else 
    dwr.engine._execute(RemoteView._path, 'RemoteView', 'getViewBeans', p0, p1, p2, p3, p4, callback);
}

/** Done /scripts-v66/dwr/interface/RemoteView.js **/ 

/** Loading /scripts-v66/dwr/engine.js **/
/*
 * Copyright 2005 Joe Walker
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Declare an object to which we can add real functions.
 */
if (dwr == null) var dwr = {};
if (dwr.engine == null) dwr.engine = {};
if (DWREngine == null) var DWREngine = dwr.engine;

/**
 * Set an alternative error handler from the default alert box.
 * @see getahead.org/dwr/browser/engine/errors
 */
dwr.engine.setErrorHandler = function(handler) {
  dwr.engine._errorHandler = handler;
};

/**
 * Set an alternative warning handler from the default alert box.
 * @see getahead.org/dwr/browser/engine/errors
 */
dwr.engine.setWarningHandler = function(handler) {
  dwr.engine._warningHandler = handler;
};

/**
 * Setter for the text/html handler - what happens if a DWR request gets an HTML
 * reply rather than the expected Javascript. Often due to login timeout
 */
dwr.engine.setTextHtmlHandler = function(handler) {
  dwr.engine._textHtmlHandler = handler;
};

/**
 * Set a default timeout value for all calls. 0 (the default) turns timeouts off.
 * @see getahead.org/dwr/browser/engine/errors
 */
dwr.engine.setTimeout = function(timeout) {
  dwr.engine._timeout = timeout;
};

/**
 * The Pre-Hook is called before any DWR remoting is done.
 * @see getahead.org/dwr/browser/engine/hooks
 */
dwr.engine.setPreHook = function(handler) {
  dwr.engine._preHook = handler;
};

/**
 * The Post-Hook is called after any DWR remoting is done.
 * @see getahead.org/dwr/browser/engine/hooks
 */
dwr.engine.setPostHook = function(handler) {
  dwr.engine._postHook = handler;
};

/**
 * Custom headers for all DWR calls
 * @see getahead.org/dwr/????
 */
dwr.engine.setHeaders = function(headers) {
  dwr.engine._headers = headers;
};

/**
 * Custom parameters for all DWR calls
 * @see getahead.org/dwr/????
 */
dwr.engine.setParameters = function(parameters) {
  dwr.engine._parameters = parameters;
};

/** XHR remoting type constant. See dwr.engine.set[Rpc|Poll]Type() */
dwr.engine.XMLHttpRequest = 1;

/** XHR remoting type constant. See dwr.engine.set[Rpc|Poll]Type() */
dwr.engine.IFrame = 2;

/** XHR remoting type constant. See dwr.engine.setRpcType() */
dwr.engine.ScriptTag = 3;

/**
 * Set the preferred remoting type.
 * @param newType One of dwr.engine.XMLHttpRequest or dwr.engine.IFrame or dwr.engine.ScriptTag
 * @see getahead.org/dwr/browser/engine/options
 */
dwr.engine.setRpcType = function(newType) {
  if (newType != dwr.engine.XMLHttpRequest && newType != dwr.engine.IFrame && newType != dwr.engine.ScriptTag) {
    dwr.engine._handleError(null, { name:"dwr.engine.invalidRpcType", message:"RpcType must be one of dwr.engine.XMLHttpRequest or dwr.engine.IFrame or dwr.engine.ScriptTag" });
    return;
  }
  dwr.engine._rpcType = newType;
};

/**
 * Which HTTP method do we use to send results? Must be one of "GET" or "POST".
 * @see getahead.org/dwr/browser/engine/options
 */
dwr.engine.setHttpMethod = function(httpMethod) {
  if (httpMethod != "GET" && httpMethod != "POST") {
    dwr.engine._handleError(null, { name:"dwr.engine.invalidHttpMethod", message:"Remoting method must be one of GET or POST" });
    return;
  }
  dwr.engine._httpMethod = httpMethod;
};

/**
 * Ensure that remote calls happen in the order in which they were sent? (Default: false)
 * @see getahead.org/dwr/browser/engine/ordering
 */
dwr.engine.setOrdered = function(ordered) {
  dwr.engine._ordered = ordered;
};

/**
 * Do we ask the XHR object to be asynchronous? (Default: true)
 * @see getahead.org/dwr/browser/engine/options
 */
dwr.engine.setAsync = function(async) {
  dwr.engine._async = async;
};

/**
 * Does DWR poll the server for updates? (Default: false)
 * @see getahead.org/dwr/browser/engine/options
 */
dwr.engine.setActiveReverseAjax = function(activeReverseAjax) {
  if (activeReverseAjax) {
    // Bail if we are already started
    if (dwr.engine._activeReverseAjax) return;
    dwr.engine._activeReverseAjax = true;
    dwr.engine._poll();
  }
  else {
    // Can we cancel an existing request?
    if (dwr.engine._activeReverseAjax && dwr.engine._pollReq) dwr.engine._pollReq.abort();
    dwr.engine._activeReverseAjax = false;
  }
  // TODO: in iframe mode, if we start, stop, start then the second start may
  // well kick off a second iframe while the first is still about to return
  // we should cope with this but we don't
};

/**
 * The default message handler.
 * @see getahead.org/dwr/browser/engine/errors
 */
dwr.engine.defaultErrorHandler = function(message, ex) {
  dwr.engine._debug("Error: " + ex.name + ", " + ex.message, true);
  if (message == null || message == "") alert("A server error has occured.");
  // Ignore NS_ERROR_NOT_AVAILABLE if Mozilla is being narky
  else if (message.indexOf("0x80040111") != -1) dwr.engine._debug(message);
  else alert(message);
};

/**
 * The default warning handler.
 * @see getahead.org/dwr/browser/engine/errors
 */
dwr.engine.defaultWarningHandler = function(message, ex) {
  dwr.engine._debug(message);
};

/**
 * For reduced latency you can group several remote calls together using a batch.
 * @see getahead.org/dwr/browser/engine/batch
 */
dwr.engine.beginBatch = function() {
  if (dwr.engine._batch) {
    dwr.engine._handleError(null, { name:"dwr.engine.batchBegun", message:"Batch already begun" });
    return;
  }
  dwr.engine._batch = dwr.engine._createBatch();
};

/**
 * Finished grouping a set of remote calls together. Go and execute them all.
 * @see getahead.org/dwr/browser/engine/batch
 */
dwr.engine.endBatch = function(options) {
  var batch = dwr.engine._batch;
  if (batch == null) {
    dwr.engine._handleError(null, { name:"dwr.engine.batchNotBegun", message:"No batch in progress" });
    return;
  }
  dwr.engine._batch = null;
  if (batch.map.callCount == 0) return;

  // The hooks need to be merged carefully to preserve ordering
  if (options) dwr.engine._mergeBatch(batch, options);

  // In ordered mode, we don't send unless the list of sent items is empty
  if (dwr.engine._ordered && dwr.engine._batchesLength != 0) {
    dwr.engine._batchQueue[dwr.engine._batchQueue.length] = batch;
  }
  else {
    dwr.engine._sendData(batch);
  }
};

/** @deprecated */
dwr.engine.setPollMethod = function(type) { dwr.engine.setPollType(type); };
dwr.engine.setMethod = function(type) { dwr.engine.setRpcType(type); };
dwr.engine.setVerb = function(verb) { dwr.engine.setHttpMethod(verb); };
dwr.engine.setPollType = function() { dwr.engine._debug("Manually setting the Poll Type is not supported"); };

//==============================================================================
// Only private stuff below here
//==============================================================================

/** The original page id sent from the server */
dwr.engine._origScriptSessionId = "2858DC313E6A37485D9FFDE0491583D3";

/** The session cookie name */
dwr.engine._sessionCookieName = "JSESSIONID"; // JSESSIONID

/** Is GET enabled for the benefit of Safari? */
dwr.engine._allowGetForSafariButMakeForgeryEasier = "false";

/** The script prefix to strip in the case of scriptTagProtection. */
dwr.engine._scriptTagProtection = "throw 'allowScriptTagRemoting is false.';";

/** The default path to the DWR servlet */
dwr.engine._defaultPath = "/accorhotels/dwr";

/** Do we use XHR for reverse ajax because we are not streaming? */
dwr.engine._pollWithXhr = "false";

/** The read page id that we calculate */
dwr.engine._scriptSessionId = null;

/** The function that we use to fetch/calculate a session id */
dwr.engine._getScriptSessionId = function() {
  if (dwr.engine._scriptSessionId == null) {
    dwr.engine._scriptSessionId = dwr.engine._origScriptSessionId + Math.floor(Math.random() * 1000);
  }
  return dwr.engine._scriptSessionId;
};

/** A function to call if something fails. */
dwr.engine._errorHandler = dwr.engine.defaultErrorHandler;

/** For debugging when something unexplained happens. */
dwr.engine._warningHandler = dwr.engine.defaultWarningHandler;

/** A function to be called before requests are marshalled. Can be null. */
dwr.engine._preHook = null;

/** A function to be called after replies are received. Can be null. */
dwr.engine._postHook = null;

/** An map of the batches that we have sent and are awaiting a reply on. */
dwr.engine._batches = {};

/** A count of the number of outstanding batches. Should be == to _batches.length unless prototype has messed things up */
dwr.engine._batchesLength = 0;

/** In ordered mode, the array of batches waiting to be sent */
dwr.engine._batchQueue = [];

/** What is the default rpc type */
dwr.engine._rpcType = dwr.engine.XMLHttpRequest;

/** What is the default remoting method (ie GET or POST) */
dwr.engine._httpMethod = "POST";

/** Do we attempt to ensure that calls happen in the order in which they were sent? */
dwr.engine._ordered = false;

/** Do we make the calls async? */
dwr.engine._async = true;

/** The current batch (if we are in batch mode) */
dwr.engine._batch = null;

/** The global timeout */
dwr.engine._timeout = 0;

/** ActiveX objects to use when we want to convert an xml string into a DOM object. */
dwr.engine._DOMDocument = ["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];

/** The ActiveX objects to use when we want to do an XMLHttpRequest call. */
dwr.engine._XMLHTTP = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];

/** Are we doing comet or polling? */
dwr.engine._activeReverseAjax = false;

/** The iframe that we are using to poll */
dwr.engine._outstandingIFrames = [];

/** The xhr object that we are using to poll */
dwr.engine._pollReq = null;

/** How many milliseconds between internal comet polls */
dwr.engine._pollCometInterval = 200;

/** How many times have we re-tried to poll? */
dwr.engine._pollRetries = 0;
dwr.engine._maxPollRetries = 0;

/** Do we do a document.reload if we get a text/html reply? */
dwr.engine._textHtmlHandler = null;

/** If you wish to send custom headers with every request */
dwr.engine._headers = null;

/** If you wish to send extra custom request parameters with each request */
dwr.engine._parameters = null;

/** Undocumented interceptors - do not use */
dwr.engine._postSeperator = "\n";
dwr.engine._defaultInterceptor = function(data) { return data; };
dwr.engine._urlRewriteHandler = dwr.engine._defaultInterceptor;
dwr.engine._contentRewriteHandler = dwr.engine._defaultInterceptor;
dwr.engine._replyRewriteHandler = dwr.engine._defaultInterceptor;

/** Batch ids allow us to know which batch the server is answering */
dwr.engine._nextBatchId = 0;

/** A list of the properties that need merging from calls to a batch */
dwr.engine._propnames = [ "rpcType", "httpMethod", "async", "timeout", "errorHandler", "warningHandler", "textHtmlHandler" ];

/** Do we stream, or can be hacked to do so? */
dwr.engine._partialResponseNo = 0;
dwr.engine._partialResponseYes = 1;
dwr.engine._partialResponseFlush = 2;

/** Is this page in the process of unloading? */
dwr.engine._unloading = false;

/**
 * @private Send a request. Called by the Javascript interface stub
 * @param path part of URL after the host and before the exec bit without leading or trailing /s
 * @param scriptName The class to execute
 * @param methodName The method on said class to execute
 * @param func The callback function to which any returned data should be passed
 *       if this is null, any returned data will be ignored
 * @param vararg_params The parameters to pass to the above class
 */
dwr.engine._execute = function(path, scriptName, methodName, vararg_params) {
  var singleShot = false;
  if (dwr.engine._batch == null) {
    dwr.engine.beginBatch();
    singleShot = true;
  }
  var batch = dwr.engine._batch;
  // To make them easy to manipulate we copy the arguments into an args array
  var args = [];
  for (var i = 0; i < arguments.length - 3; i++) {
    args[i] = arguments[i + 3];
  }
  // All the paths MUST be to the same servlet
  if (batch.path == null) {
    batch.path = path;
  }
  else {
    if (batch.path != path) {
      dwr.engine._handleError(batch, { name:"dwr.engine.multipleServlets", message:"Can't batch requests to multiple DWR Servlets." });
      return;
    }
  }
  // From the other params, work out which is the function (or object with
  // call meta-data) and which is the call parameters
  var callData;
  var lastArg = args[args.length - 1];
  if (typeof lastArg == "function" || lastArg == null) callData = { callback:args.pop() };
  else callData = args.pop();

  // Merge from the callData into the batch
  dwr.engine._mergeBatch(batch, callData);
  batch.handlers[batch.map.callCount] = {
    exceptionHandler:callData.exceptionHandler,
    callback:callData.callback
  };

  // Copy to the map the things that need serializing
  var prefix = "c" + batch.map.callCount + "-";
  batch.map[prefix + "scriptName"] = scriptName;
  batch.map[prefix + "methodName"] = methodName;
  batch.map[prefix + "id"] = batch.map.callCount;
  for (i = 0; i < args.length; i++) {
    dwr.engine._serializeAll(batch, [], args[i], prefix + "param" + i);
  }

  // Now we have finished remembering the call, we incr the call count
  batch.map.callCount++;
  if (singleShot) dwr.engine.endBatch();
};

/** @private Poll the server to see if there is any data waiting */
dwr.engine._poll = function() {
  if (!dwr.engine._activeReverseAjax) return;

  var batch = dwr.engine._createBatch();
  batch.map.id = 0; // TODO: Do we need this??
  batch.map.callCount = 1;
  batch.isPoll = true;
  if (dwr.engine._pollWithXhr == "true") {
    batch.rpcType = dwr.engine.XMLHttpRequest;
    batch.map.partialResponse = dwr.engine._partialResponseNo;
  }
  else {
    if (navigator.userAgent.indexOf("Gecko/") != -1) {
      batch.rpcType = dwr.engine.XMLHttpRequest;
      batch.map.partialResponse = dwr.engine._partialResponseYes;
    }
    else {
      batch.rpcType = dwr.engine.XMLHttpRequest;
      batch.map.partialResponse = dwr.engine._partialResponseNo;
    }
  }
  batch.httpMethod = "POST";
  batch.async = true;
  batch.timeout = 0;
  batch.path = dwr.engine._defaultPath;
  batch.preHooks = [];
  batch.postHooks = [];
  batch.errorHandler = dwr.engine._pollErrorHandler;
  batch.warningHandler = dwr.engine._pollErrorHandler;
  batch.handlers[0] = {
    callback:function(pause) {
      dwr.engine._pollRetries = 0;
      setTimeout(dwr.engine._poll, pause);
    }
  };

  // Send the data
  dwr.engine._sendData(batch);
  if (batch.rpcType == dwr.engine.XMLHttpRequest && batch.map.partialResponse == dwr.engine._partialResponseYes) {
    dwr.engine._checkCometPoll();
  }
};

/** Try to recover from polling errors */
dwr.engine._pollErrorHandler = function(msg, ex) {
  // if anything goes wrong then just silently try again (up to 3x) after 10s
  dwr.engine._pollRetries++;
  dwr.engine._debug("Reverse Ajax poll failed (pollRetries=" + dwr.engine._pollRetries + "): " + ex.name + " : " + ex.message);
  if (dwr.engine._pollRetries < dwr.engine._maxPollRetries) {
    setTimeout(dwr.engine._poll, 10000);
  }
  else {
    dwr.engine._activeReverseAjax = false;
    dwr.engine._debug("Giving up.");
  }
};

/** @private Generate a new standard batch */
dwr.engine._createBatch = function() {
  var batch = {
    map:{
      callCount:0,
      page:window.location.pathname + window.location.search,
      httpSessionId:dwr.engine._getJSessionId(),
      scriptSessionId:dwr.engine._getScriptSessionId()
    },
    charsProcessed:0, paramCount:0,
    parameters:{}, headers:{},
    isPoll:false, handlers:{}, preHooks:[], postHooks:[],
    rpcType:dwr.engine._rpcType,
    httpMethod:dwr.engine._httpMethod,
    async:dwr.engine._async,
    timeout:dwr.engine._timeout,
    errorHandler:dwr.engine._errorHandler,
    warningHandler:dwr.engine._warningHandler,
    textHtmlHandler:dwr.engine._textHtmlHandler
  };
  if (dwr.engine._preHook) batch.preHooks.push(dwr.engine._preHook);
  if (dwr.engine._postHook) batch.postHooks.push(dwr.engine._postHook);
  var propname, data;
  if (dwr.engine._headers) {
    for (propname in dwr.engine._headers) {
      data = dwr.engine._headers[propname];
      if (typeof data != "function") batch.headers[propname] = data;
    }
  }
  if (dwr.engine._parameters) {
    for (propname in dwr.engine._parameters) {
      data = dwr.engine._parameters[propname];
      if (typeof data != "function") batch.parameters[propname] = data;
    }
  }
  return batch;
};

/** @private Take further options and merge them into */
dwr.engine._mergeBatch = function(batch, overrides) {
  var propname, data;
  for (var i = 0; i < dwr.engine._propnames.length; i++) {
    propname = dwr.engine._propnames[i];
    if (overrides[propname] != null) batch[propname] = overrides[propname];
  }
  if (overrides.preHook != null) batch.preHooks.unshift(overrides.preHook);
  if (overrides.postHook != null) batch.postHooks.push(overrides.postHook);
  if (overrides.headers) {
    for (propname in overrides.headers) {
      data = overrides.headers[propname];
      if (typeof data != "function") batch.headers[propname] = data;
    }
  }
  if (overrides.parameters) {
    for (propname in overrides.parameters) {
      data = overrides.parameters[propname];
      if (typeof data != "function") batch.map["p-" + propname] = "" + data;
    }
  }
};

/** @private What is our session id? */
dwr.engine._getJSessionId =  function() {
  var cookies = document.cookie.split(';');
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    while (cookie.charAt(0) == ' ') cookie = cookie.substring(1, cookie.length);
    if (cookie.indexOf(dwr.engine._sessionCookieName + "=") == 0) {
      return cookie.substring(dwr.engine._sessionCookieName.length + 1, cookie.length);
    }
  }
  return "";
};

/** @private Check for reverse Ajax activity */
dwr.engine._checkCometPoll = function() {
  for (var i = 0; i < dwr.engine._outstandingIFrames.length; i++) {
    var text = "";
    var iframe = dwr.engine._outstandingIFrames[i];
    try {
      text = dwr.engine._getTextFromCometIFrame(iframe);
    }
    catch (ex) {
      dwr.engine._handleWarning(iframe.batch, ex);
    }
    if (text != "") dwr.engine._processCometResponse(text, iframe.batch);
  }
  if (dwr.engine._pollReq) {
    var req = dwr.engine._pollReq;
    var text = req.responseText;
    if (text != null) dwr.engine._processCometResponse(text, req.batch);
  }

  // If the poll resources are still there, come back again
  if (dwr.engine._outstandingIFrames.length > 0 || dwr.engine._pollReq) {
    setTimeout(dwr.engine._checkCometPoll, dwr.engine._pollCometInterval);
  }
};

/** @private Extract the whole (executed an all) text from the current iframe */
dwr.engine._getTextFromCometIFrame = function(frameEle) {
  var body = frameEle.contentWindow.document.body;
  if (body == null) return "";
  var text = body.innerHTML;
  // We need to prevent IE from stripping line feeds
  if (text.indexOf("<PRE>") == 0 || text.indexOf("<pre>") == 0) {
    text = text.substring(5, text.length - 7);
  }
  return text;
};

/** @private Some more text might have come in, test and execute the new stuff */
dwr.engine._processCometResponse = function(response, batch) {
  if (batch.charsProcessed == response.length) return;
  if (response.length == 0) {
    batch.charsProcessed = 0;
    return;
  }

  var firstStartTag = response.indexOf("//#DWR-START#", batch.charsProcessed);
  if (firstStartTag == -1) {
    // dwr.engine._debug("No start tag (search from " + batch.charsProcessed + "). skipping '" + response.substring(batch.charsProcessed) + "'");
    batch.charsProcessed = response.length;
    return;
  }
  // if (firstStartTag > 0) {
  //   dwr.engine._debug("Start tag not at start (search from " + batch.charsProcessed + "). skipping '" + response.substring(batch.charsProcessed, firstStartTag) + "'");
  // }

  var lastEndTag = response.lastIndexOf("//#DWR-END#");
  if (lastEndTag == -1) {
    // dwr.engine._debug("No end tag. unchanged charsProcessed=" + batch.charsProcessed);
    return;
  }

  // Skip the end tag too for next time, remembering CR and LF
  if (response.charCodeAt(lastEndTag + 11) == 13 && response.charCodeAt(lastEndTag + 12) == 10) {
    batch.charsProcessed = lastEndTag + 13;
  }
  else {
    batch.charsProcessed = lastEndTag + 11;
  }

  var exec = response.substring(firstStartTag + 13, lastEndTag);

  dwr.engine._receivedBatch = batch;
  dwr.engine._eval(exec);
  dwr.engine._receivedBatch = null;
};

/** @private Actually send the block of data in the batch object. */
dwr.engine._sendData = function(batch) {
  batch.map.batchId = dwr.engine._nextBatchId;
  dwr.engine._nextBatchId++;
  dwr.engine._batches[batch.map.batchId] = batch;
  dwr.engine._batchesLength++;
  batch.completed = false;

  for (var i = 0; i < batch.preHooks.length; i++) {
    batch.preHooks[i]();
  }
  batch.preHooks = null;
  // Set a timeout
  if (batch.timeout && batch.timeout != 0) {
    batch.timeoutId = setTimeout(function() { dwr.engine._abortRequest(batch); }, batch.timeout);
  }
  // Get setup for XMLHttpRequest if possible
  if (batch.rpcType == dwr.engine.XMLHttpRequest) {
    if (window.XMLHttpRequest) {
      batch.req = new XMLHttpRequest();
    }
    // IE5 for the mac claims to support window.ActiveXObject, but throws an error when it's used
    else if (window.ActiveXObject && !(navigator.userAgent.indexOf("Mac") >= 0 && navigator.userAgent.indexOf("MSIE") >= 0)) {
      batch.req = dwr.engine._newActiveXObject(dwr.engine._XMLHTTP);
    }
  }

  var prop, request;
  if (batch.req) {
    // Proceed using XMLHttpRequest
    if (batch.async) {
      batch.req.onreadystatechange = function() {
        if (typeof dwr != 'undefined') dwr.engine._stateChange(batch);
      };
    }
    // If we're polling, record this for monitoring
    if (batch.isPoll) {
      dwr.engine._pollReq = batch.req;
      // In IE XHR is an ActiveX control so you can't augment it like this
      if (!(document.all && !window.opera)) batch.req.batch = batch;
    }
    // Workaround for Safari 1.x POST bug
    var indexSafari = navigator.userAgent.indexOf("Safari/");
    if (indexSafari >= 0) {
      var version = navigator.userAgent.substring(indexSafari + 7);
      if (parseInt(version, 10) < 400) {
        if (dwr.engine._allowGetForSafariButMakeForgeryEasier == "true") batch.httpMethod = "GET";
        else dwr.engine._handleWarning(batch, { name:"dwr.engine.oldSafari", message:"Safari GET support disabled. See getahead.org/dwr/server/servlet and allowGetForSafariButMakeForgeryEasier." });
      }
    }
    batch.mode = batch.isPoll ? dwr.engine._ModePlainPoll : dwr.engine._ModePlainCall;
    request = dwr.engine._constructRequest(batch);
    try {
      batch.req.open(batch.httpMethod, request.url, batch.async);
      try {
        for (prop in batch.headers) {
          var value = batch.headers[prop];
          if (typeof value == "string") batch.req.setRequestHeader(prop, value);
        }
        if (!batch.headers["Content-Type"]) batch.req.setRequestHeader("Content-Type", "text/plain");
      }
      catch (ex) {
        dwr.engine._handleWarning(batch, ex);
      }
      batch.req.send(request.body);
      if (!batch.async) dwr.engine._stateChange(batch);
    }
    catch (ex) {
      dwr.engine._handleError(batch, ex);
    }
  }
  else if (batch.rpcType != dwr.engine.ScriptTag) {
    var idname = batch.isPoll ? "dwr-if-poll-" + batch.map.batchId : "dwr-if-" + batch.map.batchId;
    // Removed htmlfile implementation. Don't expect it to return before v3
    batch.div = document.createElement("div");
    // Add the div to the document first, otherwise IE 6 will ignore onload handler.
    document.body.appendChild(batch.div);
    batch.div.innerHTML = "<iframe src='javascript:void(0)' frameborder='0' style='width:0px;height:0px;border:0;' id='" + idname + "' name='" + idname + "' onload='dwr.engine._iframeLoadingComplete (" + batch.map.batchId + ");'></iframe>";
    batch.document = document;
    batch.iframe = batch.document.getElementById(idname);
    batch.iframe.batch = batch;
    batch.mode = batch.isPoll ? dwr.engine._ModeHtmlPoll : dwr.engine._ModeHtmlCall;
    if (batch.isPoll) dwr.engine._outstandingIFrames.push(batch.iframe);
    request = dwr.engine._constructRequest(batch);
    if (batch.httpMethod == "GET") {
      batch.iframe.setAttribute("src", request.url);
    }
    else {
      batch.form = batch.document.createElement("form");
      batch.form.setAttribute("id", "dwr-form");
      batch.form.setAttribute("action", request.url);
      batch.form.setAttribute("style", "display:none;");
      batch.form.setAttribute("target", idname);
      batch.form.target = idname;
      batch.form.setAttribute("method", batch.httpMethod);
      for (prop in batch.map) {
        var value = batch.map[prop];
        if (typeof value != "function") {
          var formInput = batch.document.createElement("input");
          formInput.setAttribute("type", "hidden");
          formInput.setAttribute("name", prop);
          formInput.setAttribute("value", value);
          batch.form.appendChild(formInput);
        }
      }
      batch.document.body.appendChild(batch.form);
      batch.form.submit();
    }
  }
  else {
    batch.httpMethod = "GET"; // There's no such thing as ScriptTag using POST
    batch.mode = batch.isPoll ? dwr.engine._ModePlainPoll : dwr.engine._ModePlainCall;
    request = dwr.engine._constructRequest(batch);
    batch.script = document.createElement("script");
    batch.script.id = "dwr-st-" + batch.map["c0-id"];
    batch.script.src = request.url;
    document.body.appendChild(batch.script);
  }
};

dwr.engine._ModePlainCall = "/call/plaincall/";
dwr.engine._ModeHtmlCall = "/call/htmlcall/";
dwr.engine._ModePlainPoll = "/call/plainpoll/";
dwr.engine._ModeHtmlPoll = "/call/htmlpoll/";

/** @private Work out what the URL should look like */
dwr.engine._constructRequest = function(batch) {
  // A quick string to help people that use web log analysers
  var request = { url:batch.path + batch.mode, body:null };
  if (batch.isPoll == true) {
    request.url += "ReverseAjax.dwr";
  }
  else if (batch.map.callCount == 1) {
    request.url += batch.map["c0-scriptName"] + "." + batch.map["c0-methodName"] + ".dwr";
  }
  else {
    request.url += "Multiple." + batch.map.callCount + ".dwr";
  }
  // Play nice with url re-writing
  var sessionMatch = location.href.match(/jsessionid=([^?]+)/);
  if (sessionMatch != null) {
    request.url += ";jsessionid=" + sessionMatch[1];
  }

  var prop;
  if (batch.httpMethod == "GET") {
    // Some browsers (Opera/Safari2) seem to fail to convert the callCount value
    // to a string in the loop below so we do it manually here.
    batch.map.callCount = "" + batch.map.callCount;
    request.url += "?";
    for (prop in batch.map) {
      if (typeof batch.map[prop] != "function") {
        request.url += encodeURIComponent(prop) + "=" + encodeURIComponent(batch.map[prop]) + "&";
      }
    }
    request.url = request.url.substring(0, request.url.length - 1);
  }
  else {
    // PERFORMANCE: for iframe mode this is thrown away.
    request.body = "";
    if (document.all && !window.opera) {
      // Use array joining on IE (fastest)
      var buf = [];
      for (prop in batch.map) {
        if (typeof batch.map[prop] != "function") {
          buf.push(prop + "=" + batch.map[prop] + dwr.engine._postSeperator);
        }
      }
      request.body = buf.join("");
    }
    else {
      // Use string concat on other browsers (fastest)
      for (prop in batch.map) {
        if (typeof batch.map[prop] != "function") {
          request.body += prop + "=" + batch.map[prop] + dwr.engine._postSeperator;
        }
      }
    }
    request.body = dwr.engine._contentRewriteHandler(request.body);
  }
  request.url = dwr.engine._urlRewriteHandler(request.url);
  return request;
};

/** @private Called by XMLHttpRequest to indicate that something has happened */
dwr.engine._stateChange = function(batch) {
  var toEval;

  if (batch.completed) {
    dwr.engine._debug("Error: _stateChange() with batch.completed");
    return;
  }

  var req = batch.req;
  try {
    if (req.readyState != 4) return;
  }
  catch (ex) {
    dwr.engine._handleWarning(batch, ex);
    // It's broken - clear up and forget this call
    dwr.engine._clearUp(batch);
    return;
  }

  if (dwr.engine._unloading) {
    dwr.engine._debug("Ignoring reply from server as page is unloading.");
    return;
  }
  
  try {
    var reply = req.responseText;
    reply = dwr.engine._replyRewriteHandler(reply);
    var status = req.status; // causes Mozilla to except on page moves

    if (reply == null || reply == "") {
      dwr.engine._handleWarning(batch, { name:"dwr.engine.missingData", message:"No data received from server" });
    }
    else if (status != 200) {
      dwr.engine._handleError(batch, { name:"dwr.engine.http." + status, message:req.statusText });
    }
    else {
      var contentType = req.getResponseHeader("Content-Type");
      if (!contentType.match(/^text\/plain/) && !contentType.match(/^text\/javascript/)) {
        if (contentType.match(/^text\/html/) && typeof batch.textHtmlHandler == "function") {
          batch.textHtmlHandler({ status:status, responseText:reply, contentType:contentType });
        }
        else {
          dwr.engine._handleWarning(batch, { name:"dwr.engine.invalidMimeType", message:"Invalid content type: '" + contentType + "'" });
        }
      }
      else {
        // Comet replies might have already partially executed
        if (batch.isPoll && batch.map.partialResponse == dwr.engine._partialResponseYes) {
          dwr.engine._processCometResponse(reply, batch);
        }
        else {
          if (reply.search("//#DWR") == -1) {
            dwr.engine._handleWarning(batch, { name:"dwr.engine.invalidReply", message:"Invalid reply from server" });
          }
          else {
            toEval = reply;
          }
        }
      }
    }
  }
  catch (ex) {
    dwr.engine._handleWarning(batch, ex);
  }

  dwr.engine._callPostHooks(batch);

  // Outside of the try/catch so errors propogate normally:
  dwr.engine._receivedBatch = batch;
  if (toEval != null) toEval = toEval.replace(dwr.engine._scriptTagProtection, "");
  dwr.engine._eval(toEval);
  dwr.engine._receivedBatch = null;
  dwr.engine._validateBatch(batch);
  if (!batch.completed) dwr.engine._clearUp(batch);
};

/**
 * @private This function is invoked when a batch reply is received.
 * It checks that there is a response for every call in the batch. Otherwise,
 * an error will be signaled (a call without a response indicates that the 
 * server failed to send complete batch response). 
 */
dwr.engine._validateBatch = function(batch) {
  // If some call left unreplied, report an error.
  if (!batch.completed) {
    for (var i = 0; i < batch.map.callCount; i++) {
      if (batch.handlers[i] != null) {
        dwr.engine._handleWarning(batch, { name:"dwr.engine.incompleteReply", message:"Incomplete reply from server" });
        break;
      }
    }
  }
}

/** @private Called from iframe onload, check batch using batch-id */
dwr.engine._iframeLoadingComplete = function(batchId) {
  // dwr.engine._checkCometPoll();
  var batch = dwr.engine._batches[batchId];
  if (batch) dwr.engine._validateBatch(batch);
}

/** @private Called by the server: Execute a callback */
dwr.engine._remoteHandleCallback = function(batchId, callId, reply) {
  var batch = dwr.engine._batches[batchId];
  if (batch == null) {
    dwr.engine._debug("Warning: batch == null in remoteHandleCallback for batchId=" + batchId, true);
    return;
  }
  // Error handlers inside here indicate an error that is nothing to do
  // with DWR so we handle them differently.
  try {
    var handlers = batch.handlers[callId];
    batch.handlers[callId] = null;
    if (!handlers) {
      dwr.engine._debug("Warning: Missing handlers. callId=" + callId, true);
    }
    else if (typeof handlers.callback == "function") handlers.callback(reply);
  }
  catch (ex) {
    dwr.engine._handleError(batch, ex);
  }
};

/** @private Called by the server: Handle an exception for a call */
dwr.engine._remoteHandleException = function(batchId, callId, ex) {
  var batch = dwr.engine._batches[batchId];
  if (batch == null) { dwr.engine._debug("Warning: null batch in remoteHandleException", true); return; }
  var handlers = batch.handlers[callId];
  batch.handlers[callId] = null;
  if (handlers == null) { dwr.engine._debug("Warning: null handlers in remoteHandleException", true); return; }
  if (ex.message == undefined) ex.message = "";
  if (typeof handlers.exceptionHandler == "function") handlers.exceptionHandler(ex.message, ex);
  else if (typeof batch.errorHandler == "function") batch.errorHandler(ex.message, ex);
};

/** @private Called by the server: The whole batch is broken */
dwr.engine._remoteHandleBatchException = function(ex, batchId) {
  var searchBatch = (dwr.engine._receivedBatch == null && batchId != null);
  if (searchBatch) {
    dwr.engine._receivedBatch = dwr.engine._batches[batchId];
  }
  if (ex.message == undefined) ex.message = "";
  dwr.engine._handleError(dwr.engine._receivedBatch, ex);
  if (searchBatch) {
    dwr.engine._receivedBatch = null;
    dwr.engine._clearUp(dwr.engine._batches[batchId]);
  }
};

/** @private Called by the server: Reverse ajax should not be used */
dwr.engine._remotePollCometDisabled = function(ex, batchId) {
  dwr.engine.setActiveReverseAjax(false);
  var searchBatch = (dwr.engine._receivedBatch == null && batchId != null);
  if (searchBatch) {
    dwr.engine._receivedBatch = dwr.engine._batches[batchId];
  }
  if (ex.message == undefined) ex.message = "";
  dwr.engine._handleError(dwr.engine._receivedBatch, ex);
  if (searchBatch) {
    dwr.engine._receivedBatch = null;
    dwr.engine._clearUp(dwr.engine._batches[batchId]);
  }
};

/** @private Called by the server: An IFrame reply is about to start */
dwr.engine._remoteBeginIFrameResponse = function(iframe, batchId) {
  if (iframe != null) dwr.engine._receivedBatch = iframe.batch;
  dwr.engine._callPostHooks(dwr.engine._receivedBatch);
};

/** @private Called by the server: An IFrame reply is just completing */
dwr.engine._remoteEndIFrameResponse = function(batchId) {
  dwr.engine._clearUp(dwr.engine._receivedBatch);
  dwr.engine._receivedBatch = null;
};

/** @private This is a hack to make the context be this window */
dwr.engine._eval = function(script) {
  if (script == null) return null;
  if (script == "") { dwr.engine._debug("Warning: blank script", true); return null; }
  // dwr.engine._debug("Exec: [" + script + "]", true);
  return eval(script);
};

/** @private Called as a result of a request timeout */
dwr.engine._abortRequest = function(batch) {
  if (batch && !batch.completed) {
    dwr.engine._clearUp(batch);
    if (batch.req) batch.req.abort();
    dwr.engine._handleError(batch, { name:"dwr.engine.timeout", message:"Timeout" });
  }
};

/** @private call all the post hooks for a batch */
dwr.engine._callPostHooks = function(batch) {
  if (batch.postHooks) {
    for (var i = 0; i < batch.postHooks.length; i++) {
      batch.postHooks[i]();
    }
    batch.postHooks = null;
  }
};

/** @private A call has finished by whatever means and we need to shut it all down. */
dwr.engine._clearUp = function(batch) {
  if (!batch) { dwr.engine._debug("Warning: null batch in dwr.engine._clearUp()", true); return; }
  if (batch.completed) { dwr.engine._debug("Warning: Double complete", true); return; }

  // IFrame tidyup
  if (batch.div) batch.div.parentNode.removeChild(batch.div);
  if (batch.iframe) {
    // If this is a poll frame then stop comet polling
    for (var i = 0; i < dwr.engine._outstandingIFrames.length; i++) {
      if (dwr.engine._outstandingIFrames[i] == batch.iframe) {
        dwr.engine._outstandingIFrames.splice(i, 1);
      }
    }
    batch.iframe.parentNode.removeChild(batch.iframe);
  }
  if (batch.form) batch.form.parentNode.removeChild(batch.form);

  // XHR tidyup: avoid IE handles increase
  if (batch.req) {
    // If this is a poll frame then stop comet polling
    if (batch.req == dwr.engine._pollReq) dwr.engine._pollReq = null;
    delete batch.req;
  }

  // Timeout tidyup
  if (batch.timeoutId) {
    clearTimeout(batch.timeoutId);
    delete batch.timeoutId;
  }

  if (batch.map && (batch.map.batchId || batch.map.batchId == 0)) {
    delete dwr.engine._batches[batch.map.batchId];
    dwr.engine._batchesLength--;
  }

  batch.completed = true;

  // If there is anything on the queue waiting to go out, then send it.
  // We don't need to check for ordered mode, here because when ordered mode
  // gets turned off, we still process *waiting* batches in an ordered way.
  if (dwr.engine._batchQueue.length != 0) {
    var sendbatch = dwr.engine._batchQueue.shift();
    dwr.engine._sendData(sendbatch);
  }
};

/** @private Abort any XHRs in progress at page unload (solves zombie socket problems in IE). */
dwr.engine._unloader = function() {
  dwr.engine._unloading = true;

  // Empty queue of waiting ordered requests
  dwr.engine._batchQueue.length = 0;

  // Abort any ongoing XHRs and clear their batches
  for (var batchId in dwr.engine._batches) {
    var batch = dwr.engine._batches[batchId];
    // Only process objects that look like batches (avoid prototype additions!)
    if (batch && batch.map) {
      if (batch.req) {
        batch.req.abort();
      }
      dwr.engine._clearUp(batch);
    }
  }
};
// Now register the unload handler
if (window.addEventListener) window.addEventListener('unload', dwr.engine._unloader, false);
else if (window.attachEvent) window.attachEvent('onunload', dwr.engine._unloader);

/** @private Generic error handling routing to save having null checks everywhere */
dwr.engine._handleError = function(batch, ex) {
  if (typeof ex == "string") ex = { name:"unknown", message:ex };
  if (ex.message == null) ex.message = "";
  if (ex.name == null) ex.name = "unknown";
  if (batch && typeof batch.errorHandler == "function") batch.errorHandler(ex.message, ex);
  else if (dwr.engine._errorHandler) dwr.engine._errorHandler(ex.message, ex);
  if (batch) dwr.engine._clearUp(batch);
};

/** @private Generic error handling routing to save having null checks everywhere */
dwr.engine._handleWarning = function(batch, ex) {
  if (typeof ex == "string") ex = { name:"unknown", message:ex };
  if (ex.message == null) ex.message = "";
  if (ex.name == null) ex.name = "unknown";
  if (batch && typeof batch.warningHandler == "function") batch.warningHandler(ex.message, ex);
  else if (dwr.engine._warningHandler) dwr.engine._warningHandler(ex.message, ex);
  if (batch) dwr.engine._clearUp(batch);
};

/**
 * @private Marshall a data item
 * @param batch A map of variables to how they have been marshalled
 * @param referto An array of already marshalled variables to prevent recurrsion
 * @param data The data to be marshalled
 * @param name The name of the data being marshalled
 */
dwr.engine._serializeAll = function(batch, referto, data, name) {
  if (data == null) {
    batch.map[name] = "null:null";
    return;
  }

  switch (typeof data) {
  case "boolean":
    batch.map[name] = "boolean:" + data;
    break;
  case "number":
    batch.map[name] = "number:" + data;
    break;
  case "string":
    batch.map[name] = "string:" + encodeURIComponent(data);
    break;
  case "object":
    if (data instanceof String) batch.map[name] = "String:" + encodeURIComponent(data);
    else if (data instanceof Boolean) batch.map[name] = "Boolean:" + data;
    else if (data instanceof Number) batch.map[name] = "Number:" + data;
    else if (data instanceof Date) batch.map[name] = "Date:" + data.getTime();
    else if (data && data.join) batch.map[name] = dwr.engine._serializeArray(batch, referto, data, name);
    else batch.map[name] = dwr.engine._serializeObject(batch, referto, data, name);
    break;
  case "function":
    // We just ignore functions.
    break;
  default:
    dwr.engine._handleWarning(null, { name:"dwr.engine.unexpectedType", message:"Unexpected type: " + typeof data + ", attempting default converter." });
    batch.map[name] = "default:" + data;
    break;
  }
};

/** @private Have we already converted this object? */
dwr.engine._lookup = function(referto, data, name) {
  var lookup;
  // Can't use a map: getahead.org/ajax/javascript-gotchas
  for (var i = 0; i < referto.length; i++) {
    if (referto[i].data == data) {
      lookup = referto[i];
      break;
    }
  }
  if (lookup) return "reference:" + lookup.name;
  referto.push({ data:data, name:name });
  return null;
};

/** @private Marshall an object */
dwr.engine._serializeObject = function(batch, referto, data, name) {
  var ref = dwr.engine._lookup(referto, data, name);
  if (ref) return ref;

  // This check for an HTML is not complete, but is there a better way?
  // Maybe we should add: data.hasChildNodes typeof "function" == true
  if (data.nodeName && data.nodeType) {
    return dwr.engine._serializeXml(batch, referto, data, name);
  }

  // treat objects as an associative arrays
  var reply = "Object_" + dwr.engine._getObjectClassName(data) + ":{";
  var element;
  for (element in data) {
    if (typeof data[element] != "function") {
      batch.paramCount++;
      var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
      dwr.engine._serializeAll(batch, referto, data[element], childName);

      reply += encodeURIComponent(element) + ":reference:" + childName + ", ";
    }
  }

  if (reply.substring(reply.length - 2) == ", ") {
    reply = reply.substring(0, reply.length - 2);
  }
  reply += "}";

  return reply;
};

/** @private Returns the classname of supplied argument obj */
dwr.engine._errorClasses = { "Error":Error, "EvalError":EvalError, "RangeError":RangeError, "ReferenceError":ReferenceError, "SyntaxError":SyntaxError, "TypeError":TypeError, "URIError":URIError };
dwr.engine._getObjectClassName = function(obj) {
  // Try to find the classname by stringifying the object's constructor
  // and extract <class> from "function <class>".
  if (obj && obj.constructor && obj.constructor.toString)
  {
    var str = obj.constructor.toString();
    var regexpmatch = str.match(/function\s+(\w+)/);
    if (regexpmatch && regexpmatch.length == 2) {
      return regexpmatch[1];
    }
  }

  // Now manually test against the core Error classes, as these in some 
  // browsers successfully match to the wrong class in the 
  // Object.toString() test we will do later
  if (obj && obj.constructor) {
	for (var errorname in dwr.engine._errorClasses) {
      if (obj.constructor == dwr.engine._errorClasses[errorname]) return errorname;
    }
  }

  // Try to find the classname by calling Object.toString() on the object
  // and extracting <class> from "[object <class>]"
  if (obj) {
    var str = Object.prototype.toString.call(obj);
    var regexpmatch = str.match(/\[object\s+(\w+)/);
    if (regexpmatch && regexpmatch.length==2) {
      return regexpmatch[1];
    }
  }

  // Supplied argument was probably not an object, but what is better?
  return "Object";
};

/** @private Marshall an object */
dwr.engine._serializeXml = function(batch, referto, data, name) {
  var ref = dwr.engine._lookup(referto, data, name);
  if (ref) return ref;

  var output;
  if (window.XMLSerializer) output = new XMLSerializer().serializeToString(data);
  else if (data.toXml) output = data.toXml;
  else output = data.innerHTML;

  return "XML:" + encodeURIComponent(output);
};

/** @private Marshall an array */
dwr.engine._serializeArray = function(batch, referto, data, name) {
  var ref = dwr.engine._lookup(referto, data, name);
  if (ref) return ref;

  if (document.all && !window.opera) {
    // Use array joining on IE (fastest)
    var buf = ["Array:["];
    for (var i = 0; i < data.length; i++) {
      if (i != 0) buf.push(",");
      batch.paramCount++;
      var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
      dwr.engine._serializeAll(batch, referto, data[i], childName);
      buf.push("reference:");
      buf.push(childName);
    }
    buf.push("]");
    reply = buf.join("");
  }
  else {
    // Use string concat on other browsers (fastest)
    var reply = "Array:[";
    for (var i = 0; i < data.length; i++) {
      if (i != 0) reply += ",";
      batch.paramCount++;
      var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
      dwr.engine._serializeAll(batch, referto, data[i], childName);
      reply += "reference:";
      reply += childName;
    }
    reply += "]";
  }

  return reply;
};

/** @private Convert an XML string into a DOM object. */
dwr.engine._unserializeDocument = function(xml) {
  var dom;
  if (window.DOMParser) {
    var parser = new DOMParser();
    dom = parser.parseFromString(xml, "text/xml");
    if (!dom.documentElement || dom.documentElement.tagName == "parsererror") {
      var message = dom.documentElement.firstChild.data;
      message += "\n" + dom.documentElement.firstChild.nextSibling.firstChild.data;
      throw message;
    }
    return dom;
  }
  else if (window.ActiveXObject) {
    dom = dwr.engine._newActiveXObject(dwr.engine._DOMDocument);
    dom.loadXML(xml); // What happens on parse fail with IE?
    return dom;
  }
  else {
    var div = document.createElement("div");
    div.innerHTML = xml;
    return div;
  }
};

/** @param axarray An array of strings to attempt to create ActiveX objects from */
dwr.engine._newActiveXObject = function(axarray) {
  var returnValue;  
  for (var i = 0; i < axarray.length; i++) {
    try {
      returnValue = new ActiveXObject(axarray[i]);
      break;
    }
    catch (ex) { /* ignore */ }
  }
  return returnValue;
};

/** @private Used internally when some message needs to get to the programmer */
dwr.engine._debug = function(message, stacktrace) {
  var written = false;
  try {
    if (window.console) {
      if (stacktrace && window.console.trace) window.console.trace();
      window.console.log(message);
      written = true;
    }
    else if (window.opera && window.opera.postError) {
      window.opera.postError(message);
      written = true;
    }
  }
  catch (ex) { /* ignore */ }

  if (!written) {
    var debug = document.getElementById("dwr-debug");
    if (debug) {
      var contents = message + "<br/>" + debug.innerHTML;
      if (contents.length > 2048) contents = contents.substring(0, 2048);
      debug.innerHTML = contents;
    }
  }
};

/** Done /scripts-v66/dwr/engine.js **/ 

var jsonrpc;
var preventCall=false;
var beans;
var beanToLoad;
var dummyElement;
var codeLang;
var viewBeans;

/*Initialisation des beans par leurs noms declares*/
function initBeanList(beanNames){
	if (beanNames){
		beanToLoad="beans="+beanNames;
		var tabBean = beanNames.split(";");
		beans = new Array;

		for(var num=0;num<tabBean.length;num++)
			beans.unshift(new Bean(tabBean[num]));
	} else
		 alert("Attention: Pas de beans declares!");
}

/*Decalaration de l objet bean*/
function Bean(nomBean){
	this.nom = nomBean;
	this.bean= null;
}

/*Initialisation de la vue*/
function initView(viewBeans) {
	for( var num=0;num<beans.length; num++)
		beans[num].bean = viewBeans[beans[num].nom];
}

function updateView(actionName, viewName, parameters){
	try {
		if (preventCall==false) {
			preventCall=true;

			if (!codeLang)
				codeLang = getDirLangFromHtmlAttrib();			
			
      RemoteView.getViewBeans(actionName, viewName, parameters, codeLang, { callback:function(data) {
          viewBeans = data;           
          initView(viewBeans); 
        }, async:false
        , errorHandler:function(errorString, exception) {
                 
            if (errorString && errorString.startsWith("Erreur de session")){
              document.location='/'+ codeLang + '/session/expired.html';
            }
                
            throw exception;            
          }
        }, document.referrer      
      );			
			rewriteView();
		}
	} catch(e) {
		if (e.name == "JSONRpcClientException" ) {
			/* Redirection vers page err tech
			if (!codeLang || codeLang=="")
				var errPage = "/gb/error/error.shtml";
			else
				var errPage = "/" + codeLang + "/error/error.shtml";

			if (parent.location.href == self.location.href)
				 document.location.href = errPage;
			else
				 parent.location.href = errPage;
			alert("UpdateView failed: " + e);
			*/
		} else
			throw e;

	} finally {
		preventCall=false;
	}
}

/* Permet de recuperer la langue de la page. Meta OBLIGATOIRE sur les pages incluant ce js !
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
 */
function getDirLangFromHtmlAttrib() {
	var htmlTag = document.getElementsByTagName("html")[0];
	var langue = "";
	if(htmlTag.attributes["xml:lang"] && htmlTag.attributes["xml:lang"].value)
		langue = htmlTag.attributes["xml:lang"].value;
	else if(htmlTag.attributes["lang"] && htmlTag.attributes["lang"].value)
		langue = htmlTag.attributes["lang"].value;
	return convertEn2Gb(langue);
}

function convertEn2Gb(langue) {
	if (langue && langue.toUpperCase()=="EN")
		langue = "gb";
  return langue;
}

function fillSelect(selectId, values, selectedValue, blankValue){
	// si l element n est pas present, on sort
	if (!document.getElementById(selectId)) return;
	var selectElement = document.getElementById(selectId);
	//On force le nettoyage du select
	selectElement.options.length=0;
	selectElement.innerHTML="";

	var index = 0;
	var selectIndex = -1;
	if(blankValue!=null)
		selectElement[index++]=new Option(blankValue, "");

	for(var mapKey in values){
		//On regarde si c est une option ou un groupe d ptions
		//Cas groupe d options
		if(values[mapKey]!=null && typeof(values[mapKey]) == 'object'){
			var oGroup = document.createElement('optgroup');
			oGroup.label = mapKey;
			selectElement.appendChild(oGroup);
			var options = values[mapKey];
			for(var optionKey in options){
				var oOption = document.createElement('option');
				oOption.value = optionKey;
				oOption.innerHTML = options[optionKey];
				oGroup.appendChild(oOption);
			}
		}
		//Cas option seule
		else {
			//BUG IE : bug sur innerHTML dans un select et pb constrinction select en DOM + selection valeur pas defaut
			selectElement.options[index] = new Option(values[mapKey],mapKey);
		}
		if(selectedValue!= null && mapKey==selectedValue){

			selectIndex=index;
		}
		index++;
	}

	if(selectIndex!=-1){
	 //alert(selectIndex);
		selectElement.selectedIndex=selectIndex;
	}else
		selectElement.selectedIndex=0;
}

function fillSelectWithKeys(selectId, values, selectedValue, blankValue){
	// si l element n est pas present, on sort
	if (!document.getElementById(selectId)) return;
	var selectElement = document.getElementById(selectId);
	selectElement.options.length=0;
	var index = 0;
	var selectIndex = -1;
	if(blankValue && blankValue!=null)
		selectElement[index++]=new Option(blankValue, "");
	for(var mapKey in values){
		selectElement[index]=new Option(mapKey, mapKey);
		if(selectedValue!= null && mapKey==selectedValue){
			selectIndex=index;
		}
		index++;

		if(selectIndex!=-1)
			selectElement.selectedIndex=selectIndex;
		else
			selectElement.selectedIndex=0;
	}
}

function updateCheckBoxStatus(checkBoxId){
	// si l element n est pas present, on sort
	if (!document.getElementById(checkBoxId)) return;

	var checkBoxElement = document.getElementById(checkBoxId);
	if(checkBoxElement.checked)
		checkBoxElement.value="ON";
	else
		checkBoxElement.value="";
}

function selectOption(selectid, selectedValue){
	// si l element n est pas present, on sort
	if (!document.getElementById(selectid)) return;

	var selectElement = document.getElementById(selectid);
	if(selectElement && selectElement.options){
		for(var i=0; i<selectElement.options.length; i++){
			if(selectElement.options[i].value==selectedValue)
				selectElement.selectedIndex=i;
		}
	}
}

function checkRadio(radioElement, selectedValue){
	// si l element n est pas present, on sort
	if (!radioElement) return;

	for(var i=0; i<radioElement.length; i++){
		if(radioElement[i].value==selectedValue)
			radioElement[i].checked=true;
	}
}

// fonction qui retourne un element s il existe, sinon retourne un element dummy qui n est jamais ecrit dans la page
// mais qui permet de faire fonctionner le js meme si l element cherche n existe pas
function getElementByIdIfExists(id){
	if (document.getElementById(id)){
		return document.getElementById(id);
	} else {
		// creation d un element dummy s il n existe pas
		if (!dummyElement)
			dummyElement = document.createElement('dummy_json_rpc');
		return dummyElement;
	}
}

/** Done /scripts-v66/view/json/jsonrpc_ah.js **/ 


var core = Array();
//********************************************************************************
// Cette fonctionnalite permet de charger des objets javascripts, declares dans
// des fichiers annexes, et qui s'ajoutent au tableau core.
// Sur le onload le tableau est parcouru, et les methode getBeans, initJSON, 
// Et rewrite sont appelee.
// Les objets ajoutes dans le core doivent avoir le prototype suivant:
// var MyJsonObject = {
//     variable: null,
//     
//     getBeans: function() {
//         return "MyViewBeanObject;";
//     },
//     
//     initJSON: function() {
//         var num;
//     	try {
//         	for( num in beans){
//                 if("MyViewBeanObject" == beans[num].nom) {
//                     variable = beans[num].bean;
//             	}
//             }
//         } catch(e) {
//     		alert(e);
//     	}
//     }, 
//     
//     //
//     // Dear agencies, Write your code here.
//     //
//     rewrite: function() {
//         // Your code here ...
//     }
// }
// 
// core.push(MyJsonObject);
//********************************************************************************

      Event.observe(window, 'load', function () {pushOnLoad();});      
      Event.observe(document, 'rewrite:load', function () {pushOnLoad();});

function pushOnLoad() {    
    if(core.length>0) {
        var beanNames = "";
        for(var i=0;i<core.length;i++) {
            beanNames=beanNames+core[i].getBeans()+";";
        }        
        initBeanList(beanNames);
        updateView(null, "", beanToLoad);
    }
}

//********************************************************************************
// Cette methode est appelee lors de la mise a jour du JSON par la methode
// updateView().
//********************************************************************************
function rewriteView() {
    for(var i=0;i<core.length;i++) {
        core[i].initJSON();
        core[i].rewrite();  
    }
}

function Bean(nom, bean) {
    this.nom = nom;
    this.bean = bean;
}

/** < /scripts-v66/view/json/modules/jsonrpc_push.js **/

/** > /scripts-v66/view/spec/profile.js **/

var Profile = {
  
  initialized: false,
  
  elm_ident: null,
  elm_not_ident: null,
  elm_name: null,
  
  init: function() {
    if (!this.initialized) {
      this.elm_ident = document.getElementById("bloc_ident");
      this.elm_notIdent = document.getElementById("bloc_not_ident");
      this.elm_template = $("profile-template");
      this.initialized = !!this.elm_ident && !!this.elm_notIdent && !!this.elm_template;
    }
  },
  
  getBeans: function() {
    return "ProfileViewBean";
  },
  
  initJSON: function() {
  },
  
  rewrite: function() {
    
    this.init();
    var bean = viewBeans["ProfileViewBean"];

    if(bean && this.initialized){
    
      // creation et replissage du template
      var data = {name: (bean.firstName.toLowerCase().capitalize())};
      var template = new Template(unescape(this.elm_template.innerHTML));
      Element.update(this.elm_template, template.evaluate(data));

      this.elm_ident.style.display = "block";
      this.elm_notIdent.style.display = "none";
    }
  }

}

core.push(Profile);




/** < /scripts-v66/view/spec/profile.js **/

/** > /scripts-v66/profil/utils.js **/
/*
 * $Id: utils.js,v 1.3 2009/02/23 19:17:14 blo Exp $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var StrutsUtils = {};

// gets an object with validation errors from string returned by 
// the ajaxValidation interceptor
StrutsUtils.getValidationErrors = function(data) {
  if(data.indexOf("{}&& {") == 0) {
    return eval("( " + data.substring(4, data.length) + " )");
  } else {
    return null;
  }  
};

StrutsUtils.clearValidationErrors = function(form) {
    clearErrors(form);
};

StrutsUtils.clearActionErrors = function(errorMsgDiv) {
    clearActionErrors(errorMsgDiv);
};   

// shows validation errors using functions from xhtml/validation.js
// or css_xhtml/validation.js
StrutsUtils.showValidationErrors = function(form, errors) {
  
  StrutsUtils.clearValidationErrors(form, errors);      
  StrutsUtils.clearActionErrors(); 
  
  if(errors.fieldErrors) {
    for(var fieldName in errors.fieldErrors) {              
      for(var i = 0; i < errors.fieldErrors[fieldName].length; i++) {                  
            //var el = form.elements[fieldName];
            
            //alert( form.elements[fieldName] );
            
            //if (form.elements[fieldName][0] && form.elements[fieldName][0].type == 'radio')
            //if (el instanceof NodeList)
            //  addError(el[0], errors.fieldErrors[fieldName][i]);
            //else              
              addError(fieldName, errors.fieldErrors[fieldName][i]);                           
      }
    }
  }
  
   if(errors.actionErrors) {
         for(var i = 0; i < errors.actionErrors.length; i++) {                                 
          addActionError(errors.actionErrors[i]);                           
    }
  }
};

StrutsUtils.firstElement  = function(parentNode, tagName) {
  var node = parentNode.firstChild;
  while(node && node.nodeType != 1){
    node = node.nextSibling;
  }
  if(tagName && node && node.tagName && node.tagName.toLowerCase() != tagName.toLowerCase()) {
    node = StrutsUtils.nextElement(node, tagName);
  }
  return node;  
};

StrutsUtils.nextElement = function(node, tagName) {
  if(!node) { return null; }
  do {
    node = node.nextSibling;
  } while(node && node.nodeType != 1);

  if(node && tagName && tagName.toLowerCase() != node.tagName.toLowerCase()) {
    return StrutsUtils.nextElement(node, tagName);
  }
  return node;  
};

StrutsUtils.previousElement = function(node, tagName) {
  if(!node) { return null; }
  if(tagName) { tagName = tagName.toLowerCase(); }
  do {
    node = node.previousSibling;
  } while(node && node.nodeType != 1);
  
  if(node && tagName && tagName.toLowerCase() != node.tagName.toLowerCase()) {
    return StrutsUtils.previousElement(node, tagName);
  }
  return node;  
};

StrutsUtils.addOnLoad = function(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
};

StrutsUtils.addEventListener = function(element, name, observer, capture) {
  if (element.addEventListener) {
    element.addEventListener(name, observer, false);
  } else if (element.attachEvent) {
    element.attachEvent('on' + name, observer);
  }
};

/** < /scripts-v66/profil/utils.js **/


/** > /scripts-v66/profil/validation.js **/
/*
 * $Id: validation.js,v 1.4 2011/03/08 13:34:42 hcu Exp $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */


function addClassName(ele, className)
{
	if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1))
		return;
	ele.className += (ele.className ? " " : "") + className;
}

function removeClassName(ele, className)
{
	if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1))
		return;
	ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
}

function clearErrors(form) {
    // set all labels back to the normal class
    
    var elements = form.elements;
    for (var i = 0; i < elements.length; i++) {
      var e = elements[i];
      
      var container = $(e.id + "-container");
      var label = $(e.id + "-label");
        
    	if(container)	   	
    		removeClassName(container, 'validatorInvalidState');
    		
    	if(label)	   	
    		removeClassName(label, 'validatorInvalidState');
    		
    	if(e)	   	
    		removeClassName(e, 'validatorInvalidState');
    }
}

function clearActionErrors(errorMsgDiv) {
  $(errorMsgDiv).innerHTML = "";
  $(errorMsgDiv).style.display = "none";
  /*$(errorMsgDiv).setAttribute("style", "display:none;");*/
}

function addActionError(message, errorMsgDiv) {
  $(errorMsgDiv).innerHTML = $(errorMsgDiv).innerHTML + message + "<br/>";
}

/*
function addError(e, errorText) {
             
    try {
                  	
    	var container = $(e + ".container");    

   	  $(e + '.errorMessage').innerHTML = errorText; 
  	  addClassName(container, 'validatorInvalidState');    	
    	
    } catch (error) {
        alert(e + "  " + errorText + " " + error);
    }
}*/

function hightlightErrorFields(errors){
	if(errors.fieldErrors) {
    var containerId = new String();
    for(var fieldName in errors.fieldErrors) {              
      for(var i = 0; i < errors.fieldErrors[fieldName].length; i++) {                   
    		containerId = fieldName.replace(".", "-")+"-container";
    		containerId = containerId.replace(".", "-");
      	if($(containerId)){
      		$(containerId).addClassName("validatorInvalidState");
      	}
      	labelId = fieldName.replace(".", "-")+"-label";
    		labelId = labelId.replace(".", "-");
      	if($(labelId)){
      		$(labelId).addClassName("validatorInvalidState");
      	}
      	
      	fieldId = fieldName.replace(".", "-");
    		fieldId = fieldId.replace(".", "-");
      	if($(fieldId)){
      		$(fieldId).addClassName("validatorInvalidState");
      	}
      }
    }
  }
}

/** < /scripts-v66/profil/validation.js **/


/** > /scripts-v66/formBean.js **/
document.write('<script type="text/javascript" src="/scripts-v66/lib/Url.js"></script>');
document.write('<script type="text/javascript" src="/scripts-v66/anti_doubleclick.js"></script>');

// Timestamp of formBean that page was last updated with
var req;
var _classNameOk='';
var _classNameError='';
var _form='';

var _submitUrl="";
var _functionOnSuccess="";
var _functionOnError="";
var _labelsFor;
var _formTarget;

function submitFormBean(classOk, classError, submitUrl, formulaire, functionOnSuccess, functionOnError, labelsFor, formTarget) {
 _classNameOk=classOk;
 _classNameError=classError;
 _form = formulaire;
 _submitUrl= submitUrl;
 _functionOnSuccess= functionOnSuccess;
 _functionOnError= functionOnError;
 _labelsFor = labelsFor || {};
 _formTarget= formTarget;
 var parameters = parseForm(formulaire);
 req = newXMLHttpRequest();
 req.open("POST","/validate.svlt", true);
 req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 parameters=parameters+"&formName="+formulaire.name;

 req.send(parameters);

 req.onreadystatechange = callback;
}

function parseForm(formulaire){

 var formElements = formulaire.elements;
 var param="";
 for(var i=0;i<formElements.length;i++){
 	var el = formElements[i];
 	var value = parseElement(el);
 	if (param!="undefined" && value && value!=undefined){
 		param = param +"&"+ value;
 	} 	
 }
 var codeLang = getDirLangFromHtmlAttrib();
 	if(codeLang)
 		param = param +"&lang="+codeLang;
 return param;
}

function parseElement(el){
	if(((el.type!='radio' && el.type!='checkbox') || el.checked) && el.value!=undefined)
		//Url.encode n'encode pas le '+' et le '/'
		return el.name+'='+Url.encode(el.value).replace('+','%2B').replace('/','%2F');
}

/* Permet de recuperer la langue de la page. Meta OBLIGATOIRE sur les pages incluant ce js !
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
 */
function getDirLangFromHtmlAttrib() {
	var htmlTag = document.getElementsByTagName("html")[0];
	var langue = "";
	if(htmlTag.attributes["xml:lang"] && htmlTag.attributes["xml:lang"].value)
		langue = htmlTag.attributes["xml:lang"].value;
	else if(htmlTag.attributes["lang"] && htmlTag.attributes["lang"].value)
		langue = htmlTag.attributes["lang"].value;
	return convertEn2Gb(langue);
}

function convertEn2Gb(langue) {
	if (langue && langue.toUpperCase()=="EN")
		langue = "gb";
  return langue;
}

function callback() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            // update the HTML DOM based on whether or not message is valid
            parseMessage();
        }
    }
}

function parseMessage() {
    var foundLabel = {};
    var formBean = req.responseXML.getElementsByTagName("formBean")[0];
	    var formOk = formBean.getElementsByTagName("formOk")[0].firstChild.nodeValue;
	    var fields = formBean.getElementsByTagName("fields")[0].getElementsByTagName("field");
	    for (var i=0; i<fields.length;i++){
				var field = fields[i];
					var fieldName ="";
					var fieldValue ="";
					var fieldOk ="";
					var feildId="";

		    		if(field.getElementsByTagName("id")[0].firstChild!=null)
		    			fieldName = field.getElementsByTagName("id")[0].firstChild.nodeValue;

		    		if(field.getElementsByTagName("value")[0].firstChild!=null)
		    			fieldValue = field.getElementsByTagName("value")[0].firstChild.nodeValue;

		    		if(field.getElementsByTagName("fieldOk")[0].firstChild!=null)
		    			fieldOk = field.getElementsByTagName("fieldOk")[0].firstChild.nodeValue;
		    		
		    		if(_form[fieldName])	
		    	  	feildId = _form[fieldName].id;


				if((feildId!="" && document.getElementById(feildId)!=null && document.getElementById(feildId).className!=null) ||
							(document.getElementById(fieldName+'_label')!=null && document.getElementById(fieldName+'_label').className!=null)){
					var fieldLabel;


					//On recherche les elements avec un id de type fieldName+'_label'
					if(document.getElementById(fieldName+'_label')!=null){
						fieldLabel=document.getElementById(fieldName+'_label');
						if(fieldOk=='false')
							fieldLabel.className=_classNameError;
						else
							fieldLabel.className=_classNameOk;
					} else {
						//On recherche les elements label d'un champ
						
						var labels = _form.getElementsByTagName('label');
						for(var j=0; j<labels.length; j++){
						  if( labels[j].attributes['for']!=null ){
						    var attrFor = labels[j].attributes['for'].value;						    
							  if(!foundLabel[attrFor] && (feildId==attrFor || (_labelsFor[attrFor] && _labelsFor[attrFor].indexOf(feildId) != -1))){
								  var className = labels[j].className.replace(' '+_classNameError,'').replace(_classNameError,'').replace(' '+_classNameOk,'').replace(_classNameOk,'');
								  if(fieldOk=='false' ){
									if((document.getElementById('form_aob'))||(document.getElementById('form_afgb'))) {
										$(fieldName).className=' '+_classNameError;
									}
									 labels[j].className=className+' '+_classNameError;
									 foundLabel[attrFor] = true;
								  }
								  else {
									  labels[j].className=className+' '+_classNameOk;
							    }
						    }
						  }
					  }
				 }
	     }
	    }
		if(formOk=='false'){
			
			var errorMessage = formBean.getElementsByTagName("errorMessage")[0].firstChild.nodeValue;
			if(document.getElementById('errorMessage'+"_"+_form.name)){
        document.getElementById('errorMessage'+"_"+_form.name).innerHTML=errorMessage+"<br>";
	   		document.getElementById('errorMessage'+"_"+_form.name).style.display="block";
      }
      else{
        document.getElementById('errorMessage').innerHTML=errorMessage+"<br>";
	   		document.getElementById('errorMessage').style.display="block";      
      }	   		
   		if (_functionOnError) {eval(_functionOnError);}
   		// reset de l'anti doubleclick si present dans la form
   		if (typeof submit != 'undefined') {
   			submit = true;
   		}  
		}else{
			if(document.getElementById('errorMessage'+"_"+_form.name)){
        document.getElementById('errorMessage'+"_"+_form.name).innerHTML="";
	   		document.getElementById('errorMessage'+"_"+_form.name).style.display="none";	
      }
      else{
        document.getElementById('errorMessage').innerHTML="";
			  document.getElementById('errorMessage').style.display="none";    
      }			
      if (_functionOnSuccess) {eval(_functionOnSuccess);}
			if (_submitUrl){
					if(_submitUrl.indexOf("?")!=-1)
						_form.setAttribute ('action',_submitUrl+'&formName='+_form.name);	
					else
						_form.setAttribute('action',_submitUrl+'?formName='+_form.name);
						
					if(_formTarget)	
						_form.target=_formTarget;
					
          if(submitThisForm())							
			      _form.submit();
		  }
		}
}
/** < /scripts-v66/formBean.js **/

/** > /scripts-v66/siteZones.js **/
var siteZones = {
	"" : 
	{   
				"France" : {"lang" : "fr", "country" : "fr", "zone" :"france"},	
				"Belgique" : {"lang" : "fr", "country" : "be", "zone" :"belgium"},
				"Suisse" : {"lang" : "fr", "country" : "ch", "zone" :"switzerland"},
				//"Schweiz" : {"lang" : "de", "country" : "ch", "zone" :"switzerland"},	
				"Deutschland" : {"lang" : "de", "country" : "de", "zone" :"deutschland"},
				"Oesterreich" : {"lang" : "de", "country" : "at", "zone" :"oesterreich"},
				"España": {"lang" : "es", "country" : "es", "zone" :"espana"},	 	
				"América Latina" : {"lang" : "es", "country" : "ar", "zone" :"sudamerica"},
				"United Kingdom" : {"lang" : "gb", "country" : "gb", "zone" :"united-kingdom"},
				"Other countries" : {"lang" : "gb", "country" : "", "zone" :"home"},
				"Autres pays" : {"lang" : "fr", "country" : "", "zone" :"home"},
				"Sonstige Länder" : {"lang" : "de", "country" : "", "zone" :"home"},				
				"Otros países" : {"lang" : "es", "country" : "", "zone" :"home"}
	}
};

 function getCookieCountry(){
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
	  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	  x=x.replace(/^\s+|\s+$/g,"");
	  if (x=='userBrowsingZoneLocalization')
		{
		return unescape(y);
		}
	  }
}

function at_show_aux(parent, child)
{
  var p = document.getElementById(parent);
  var c = document.getElementById(child );

  var top  = (c["at_position"] == "y") ? p.offsetHeight : 0;
  var left = (c["at_position"] == "x") ? p.offsetWidth +2 : 0;

  for (; p; p = p.offsetParent)
  {
    top  += 0 ;
    left += p.offsetLeft;
  }

  c.style.position   = "absolute";
  c.style.top        = top +'px';
  //c.style.left       = left+'px';
  c.style.visibility = "visible";
}

// ***** at_show *****

function at_show()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  at_show_aux(p.id, c.id);
  clearTimeout(c["at_timeout"]);
}

// ***** at_hide *****

function at_hide()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  c["at_timeout"] = setTimeout("document.getElementById('"+c.id+"').style.visibility = 'hidden'", 333);
}

// ***** at_click *****

function at_click()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  if (c.style.visibility != "visible") at_show_aux(p.id, c.id); else c.style.visibility = "hidden";
  return false;
}

// ***** at_attach *****

function at_attach(parent, child, showtype, position, cursor)
{
  var p = document.getElementById(parent);
  var c = document.getElementById(child);

  p["at_parent"]     = p.id;
  c["at_parent"]     = p.id;
  p["at_child"]      = c.id;
  c["at_child"]      = c.id;
  p["at_position"]   = position;
  c["at_position"]   = position;

  c.style.position   = "absolute";
  c.style.visibility = "hidden";

  if (cursor != undefined) p.style.cursor = cursor;

  switch (showtype)
  {
    case "click":
      p.onclick     = at_click;
      p.onmouseout  = at_hide;
      c.onmouseover = at_show;
      c.onmouseout  = at_hide;
      break;
    case "hover":

      p.onmouseover = at_show;
      p.onmouseout  = at_hide;
      c.onmouseover = at_show;
      c.onmouseout  = at_hide;
      break;
  }
}

function getCookie(sName) {
	var cookContent = document.cookie, cookEnd, i, j;
	var sName = sName + "=";

	for (i=0, c=cookContent.length; i<c; i++) {
			j = i + sName.length;
			if (cookContent.substring(i, j) == sName) {
					cookEnd = cookContent.indexOf(";", j);
					if (cookEnd == -1) {
							cookEnd = cookContent.length;
					}
					return decodeURIComponent(cookContent.substring(j, cookEnd));
			}
	}       
	return null;
}

 
function createSiteZonesOptions(selectId){
 if(document.getElementById(selectId) && siteZones){
	var zone ='';
	var currentLang ='';
	var langContent = document.getElementById('itemLang');
   
   /* case home tplHome */
	if (document.getElementById('tplHome')) {
	var langZoneExp = /\/([a-z]{2}(?:-[a-z]{2})?)\/([a-z\-]+)\/index\.shtml/;
	langZoneExp.exec(document.location);
	var zone = RegExp.$2;
	var currentLang = RegExp.$1;

	}
	 /* other case */
	else { 
	var countrySelected = getCookieCountry();
	if (countrySelected != undefined) { var zone = countrySelected; }
	var url = window.location.pathname;
	var currentLang = url.substring(1,url.indexOf("/",1));
	}

	for(var zones in siteZones){
		
   	if(siteZones[zones]){

		
   		for(var countryName in siteZones[zones]){
			
	   		if(siteZones[zones][countryName]){
				var oOption = document.createElement('li'); 
		 
				oOption.setAttribute("class", siteZones[zones][countryName].lang);
				oOption.setAttribute("className", siteZones[zones][countryName].lang);//ie
				
				var link = document.createElement('a'); 						
				link.setAttribute("href","/geo/setZone.jsp?lang="+siteZones[zones][countryName].lang+"&country="+siteZones[zones][countryName].country);	
				
				if (siteZones[zones][countryName].country != '')	{	
				
					link.setAttribute("class", siteZones[zones][countryName].zone+' '+siteZones[zones][countryName].lang);
					
					link.setAttribute("className", siteZones[zones][countryName].zone+' '+siteZones[zones][countryName].lang);//ie		
					
				}else{
					link.setAttribute("class", 'otherCountries');
					link.setAttribute("className", 'otherCountries');//ie	
					
				}				
				
				link.innerHTML = countryName.toString();
				oOption.appendChild(link);
				
				var userZoneSaved = getCookie('userBrowsingZoneLocalization');
				var userLocalSaved = getCookie('userLocalization');
				
				if(userZoneSaved && userLocalSaved ){
				
					if(userZoneSaved != "home" && siteZones[zones][countryName].country == userLocalSaved &&  siteZones[zones][countryName].zone ==  userZoneSaved && siteZones[zones][countryName].lang == currentLang){
						document.getElementById('currentLanguage').innerHTML =  countryName.toString();
					}else if(userZoneSaved == "home" && siteZones[zones][countryName].country == userLocalSaved && siteZones[zones][countryName].lang == currentLang){
						document.getElementById('currentLanguage').innerHTML =  countryName.toString();
					}
					
				}				
				else if(siteZones[zones][countryName].country =="" && siteZones[zones][countryName].lang == currentLang ){
				
					document.getElementById('currentLanguage').innerHTML =  countryName.toString();
				} 
				
				document.getElementById('listLang').setAttribute("class", siteZones[zones][countryName].lang);					
				document.getElementById('currentLanguage').setAttribute("selected","selected");
	     
			   langContent.appendChild(oOption);
		   }
		   
		   	
	 	}		  
   	}
	langContent.setAttribute("class", zone);
	langContent.setAttribute("className", zone); //ie
	
	if(navigator.userAgent.toLowerCase().indexOf('msie 6') != -1){//ie	
		at_attach("listLang", "itemLang", "hover", "y", "pointer");
	}
  }
 }
}   
/** < /scripts-v66/siteZones.js **/

/** > /scripts-v66/utils.js **/
// scrolling
var scrolling = {
    speed:1000,
	
	goTo : function(ancre){
    		jQuery('html,body').animate({scrollTop:$(ancre).offset().top},scrolling.speed,'swing',function(){
         
            jQuery(ancre).attr('tabindex','-1');
            jQuery(ancre).focus();
            jQuery(ancre).removeAttr('tabindex');
        });
    }
};

if(!util) { var util = {}; }
// Function change Langues
util.changeSelectUrl  = {
	init: function(el){
		util.changeSelectUrl.changeSelect(el);
	},
	changeSelect:function (el){
		el.change(function(){  
			 top.parent.location.href = el.val()
    	});
	}
	
};

		
// Function Language
util.getLang = {
	init: function(elt){
		util.getLang.en2gb(elt);
	},
	en2gb:function(elt){return (elt=='en')?'gb':elt}
};
// Function Accordion
util.displayAccordion  = {
	init: function(elt){
		util.displayAccordion.accordionAction(elt);
	},
	accordionAction:function (elt){
			if(jQuery(".toggleBloc").size() != 0){
				jQuery(".toggleBloc").attr("href","javascript:;");
				elt.next("div").find(".toggleBloc").click(function(){
					elt.next("div:visible").slideUp();
					elt.next("div:eq("+jQuery(this).attr("name")+")").slideToggle("slow");	
					scrolling.goTo(elt.next("div:eq("+jQuery(this).attr("name")+")").prev());
				})
		}
		elt.click(function(){
			if(jQuery(this).next("div").is(':visible')){ 
				jQuery(this).next("div").slideUp("slow"); 
				jQuery(this).toggleClass("open");
			}else{
				 elt.next("div:visible").slideUp();
				 elt.removeClass("open");
				 jQuery(this).next("div").slideToggle("slow"); 
				 jQuery(this).toggleClass("open"); 
			}   
		});
	}

};

// Function liens Noheto, Bandeau, footer et sitemap
var links_noheto = {

init: function (){
	links_noheto._get_noh_links_bandeau_footer_sitemap();

},

_get_noh_links_bandeau_footer_sitemap: function(){

	jQuery('#linkMenuOffers ul')	
	.load('http://www.adagio-city.com/hotel-cms/'+util.getLang.en2gb(jQuery("html").attr('lang'))+'/hotel-deals/menu.htm ul li', function(){
	
	// Toutes nos offres
	jQuery('li#linkMenuOffers ul li:first').before('<li class="first"><a href="'+jQuery('li#linkMenuOffers a:first').attr("href")+'">'+jQuery('li#linkMenuOffers a:first span').text()+'</a></li>');
	jQuery('li#linkMenuOffers ul li:last').attr("class",'last');
		
	jQuery("#linkMenuOffers ul li a").each(function(i, url) {
		
		// Footer
		jQuery('.mainContainer .footerContainer .footerContent .sitemap ul:eq(3)').append('<li><a href="'+url+'">'+jQuery(url).text()+'</a></li>');
		
		// Sitemap
		jQuery('.contentContainer .sitemap ul li ul:eq(3)').append('<li><a href="'+url+'">'+jQuery(url).text()+'</a></li>');

			});
		});

	}

}

var display_ie6 = {

_displayMenu : function(){
			jQuery("ul.menu > li, #login ul > li, #changeLang > li").hover(function(){
				jQuery(this).addClass("over");	
				jQuery(this).find("ul").show();							
			},function(){
				jQuery(this).removeClass("over");
				jQuery(this).find("ul").hide();		
			})
	}
}

jQuery.noConflict();

jQuery(document).ready(function(){
	links_noheto.init();				
	if(jQuery("#changeLang").size() != 0)	util.changeSelectUrl.init(jQuery("#changeLang"));
	if(jQuery(".accordion").size() != 0)	util.displayAccordion.init(jQuery(".accordion h2")); 
	if(jQuery(".mobile-faq").size() != 0)	util.displayAccordion.init(jQuery(".mobile-faq h3"));
	
	/* initialization sous menu IE6 */
	if (jQuery.browser.msie && jQuery.browser.version.substr(0,1)<7) display_ie6._displayMenu();
	
	// initialization popup & popin  
	if(jQuery(".popup").size() != 0) popups();
	if(jQuery(".popin").size() != 0) popins.init();
	if (jQuery('#minBookingEngine').length) { new minBooking('minBookingEngine',30,405);}
})

 
/** < /scripts-v66/utils.js **/

/** > /scripts-v66/banner-home-noh.js **/
/*  jJSON Object  */
var jJSON_page = {};
var jJSON_push = {};
 
var displayCarrousel = {
	linkJson: "",
	lang: (jQuery("html").attr("lang")=="en") ? "gb" : jQuery("html").attr("lang"),
	carrouselTplUrl: '/templates-v66/home/slideshow.tpl?day=' + new Date().getDay(),
	listData: {
		
			carousselCountElt: 0,
			numberLimit: 3,
			rest: 0,
			numberBegin: 0,
			lang: "",
			generated: "",			
			from: "",			
			inversion_currency: "",
			randombanner: "",		
			nbOffres: "",			
			megaBanner: {}
			
	},
		getMeta: function(n,d){
					 var _m = document.getElementsByTagName("meta");
					 for (i = 0;i<_m.length;i++) 
									 try {if (_m[i].name == n) return _m[i].content;}catch(ee){};
					 return d;
			},
	init : function(){
		
		this.linkJson = "/hotel-cms/"+this.lang+"/home/json/diapo-banners-"+displayCarrousel.getMeta("X-Accor-userBrowsingZone","home")+".js?day=" + new Date().getDay();
		this.getJson();		
	},


	getJson : function(){
		
		jQuery.getJSON(displayCarrousel.linkJson, function(jsonpush) { 
			
			jJSON_push['banners'] = (function() {
				response = {
							mainbanner: [],
							thumbnail: [],
							price: [],
							currency: [],
							bannerUnit: [],
							title:[],
							description:[],
							linkOffer:[],
							url_link:[],
							newwindow:[]
						};
				
				jQuery.each(jsonpush["banners"],function(i,itemsP) {	
						response.mainbanner[i] = itemsP['mainbanner']?itemsP['mainbanner']:'';
						response.thumbnail[i] = itemsP['thumbnail']?itemsP['thumbnail']:'';
						response.price[i] = itemsP['price']?itemsP['price']:'';
						response.currency[i] = itemsP['currency']?itemsP['currency']:'';
						response.bannerUnit[i] = itemsP['bannerUnit']?itemsP['bannerUnit']:'';
						response.title[i] = itemsP['title']?itemsP['title']:'';
						response.description[i] = itemsP['description']?itemsP['description']:'';
						response.linkOffer[i] = itemsP['linkOffer']?itemsP['linkOffer']:'';
						response.url_link[i] = itemsP['url_link']?itemsP['url_link']:'';
						response.newwindow[i] = itemsP['newwindow']?itemsP['newwindow']:'';
				});
				return response;
			})();
			
					displayCarrousel.listData.megaBanner				= jJSON_push["banners"];
					displayCarrousel.listData.lang						= jsonpush.meta.lang;
					displayCarrousel.listData.generated					= jsonpush.meta.generated;	
					displayCarrousel.listData.from						= jsonpush.param.from;	
					displayCarrousel.listData.inversion_currency 		= jsonpush.param.inversion_currency;		
					displayCarrousel.listData.randombanner 				= jsonpush.param.randombanner;			
					displayCarrousel.listData.carousselCountElt 		= jJSON_push["banners"].mainbanner.length;
					displayCarrousel.listData.numberLimit 				= displayCarrousel.listData.carousselCountElt-1;
					
					jQuery('#carrousel').setTemplateURL(displayCarrousel.carrouselTplUrl);
					jQuery('#carrousel').processTemplate(displayCarrousel);
					
					 // Display init Carroussel
					if(displayCarrousel.listData.carousselCountElt > 1)  ADG.displayHome.displayCarrousel();
					else jQuery(".adgMegabanner li:eq(0)").fadeIn(800);		
					
		})
	}
}
jQuery(document).ready(function(){
 displayCarrousel.init(); 
});
/** < /scripts-v66/banner-home-noh.js **/

/** > /scripts-v66/home.js **/
if(!ADG) {var ADG = {};};

ADG.displayHome = (function(){
		
	function _bookingEvent(){
		jQuery("#engine-criteres a span").click(function(){
			var elt = jQuery(this);
			jQuery(".roomOptions").slideToggle("",function(){
				elt.addClass("off").siblings("span").removeClass("off");
			})				 								 
		})
		jQuery(".checkbox").click(function(){			 
				if(jQuery(this).is(":checked") == true) jQuery(this).parent().next().slideDown();
				else jQuery(this).parent().next().hide();				
			})
		jQuery(".inputNumber").each(function(index){
			var index = jQuery(this).val();
			jQuery(this).focus(function(){
				$val = jQuery(this).val();
				if($val == index) jQuery(this).val("").css("color","#000");
			})						 
		})
		jQuery(".inputNumber").each(function(index){
			var index = jQuery(this).val();
			jQuery(this).blur(function(){
				$val = jQuery(this).val();
				if($val == "") jQuery(this).val(index).removeAttr("style");
			})
		})
	};
	
	function _goToNextVisuel(indexVis){
		if(indexVis != undefined){
			stopAutoSlideShow();
					var elt = jQuery(".adgMegabanner li:eq("+indexVis+")");
						jQuery(".adgMegabanner li").not(elt).fadeOut(700,function(){
						});
					jQuery(".adgMegabanner li:eq("+indexVis+")").fadeIn(800,function(){
						jQuery(".adgMegabanner li:eq("+indexVis+")").addClass("current")	
					});
				
			return;
		}
		var next = 0;
		jQuery(".adgMegabanner li").each(function(index){
			if(jQuery(this).hasClass("current")  && parseInt(index) == parseInt(jQuery(".adgMegabanner li").size()-1)){
					next =  0;
						jQuery(".adgMegabanner li:eq("+next+")").fadeIn(800,function(){
							jQuery(this).addClass("current");
							jQuery(".adgMegabanner li:last").fadeOut(800,function(){
							jQuery(this).removeClass("current");
							});
						});
			}
			else if(jQuery(this).hasClass("current")  && index != jQuery(".adgMegabanner li").size()){
				next =   parseInt(index+1);
				var elt =jQuery(this);
					jQuery(".adgMegabanner li:eq("+next+")").fadeIn(800,function(){
						jQuery(this).addClass("current");
						 elt.fadeOut(900,function(){
							jQuery(this).removeClass("current");
						});
					});
				
			}
		});
	jQuery("#pt_vignettes li").removeClass("current");
	};
	
	function _autoSlideShow(){
		isRun = setInterval(function() { _goToNextVisuel()},4000);
	};
	function stopAutoSlideShow(){ 
		if (this.isRun == null) return;
		clearInterval(this.isRun);
		this.isRun = null; 
	};

	function _displaySlideShow(){
		jQuery("#pt_vignettes li:first").addClass("current");
		jQuery(".adgMegabanner li:first").addClass("current");
		_autoSlideShow();
		jQuery("#pt_vignettes li").hover(function(e){
			leftVal = jQuery("#pt_vignettes ul").css("left");
			jQuery(this).addClass("over");
			
		},function(){
			jQuery(this).removeClass("over");	
		})
		jQuery("#pt_vignettes li").each(function(index){
		 jQuery(this).click(function(){
			if(jQuery(this).hasClass("current")) return;
			jQuery("#pt_vignettes li").removeClass("current");
			jQuery(this).addClass("current");
			_goToNextVisuel(index);
			
			return false;
		})			 
		})
		
	};
	
		function _displayMenuIe6(){
			jQuery("ul.menu > li, #login ul > li, #changeLang > li").hover(function(){
				jQuery(this).addClass("over");	
				jQuery(this).find("ul").show();							
			},function(){
				jQuery(this).removeClass("over");
				jQuery(this).find("ul").hide();		
			})
		};
			
	return { 
			init : function(){
				
				/* initialization popin */
				if(jQuery(".popin").length != 0) popins.init();
				
				/* initialization sous menu IE6 */
				if (jQuery.browser.msie && jQuery.browser.version.substr(0,1)<7)  _displayMenuIe6();
				
				/* initialization booking  */
				_bookingEvent();
				
				/* initialization tooltip */
				utils.tooltips.init();
				 homeBookingEngine = new BookingEngine("bookingEngine", "homeBookingEngine", true);				
				 ajaxRequest._executeByUrl("/bean/getViewBeans.action?beans=SearchCriteriaViewBean|OriginViewBean","validatorInvalidState","homeBookingEngine.success(errors, response);");  
			},
			
			displayCarrousel : function(){
				_displaySlideShow();	
			}
			
	} 
})
();

jQuery(document).ready(function(){
	ADG.displayHome.init(ADG) 
});
 /** < /scripts-v66/home.js **/

