PageSourceSearch

https://www.booksbygordon.com/dwr/engine.js

js booksbygordon.com collected 2026-10-07 15:19:03 UTC 47,704 bytes, 1,335 lines download raw bytes

1/*
2 * Copyright 2005 Joe Walker
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/**
18 * Declare an object to which we can add real functions.
19 */
20if (dwr == null) var dwr = {};
21if (dwr.engine == null) dwr.engine = {};
22if (DWREngine == null) var DWREngine = dwr.engine;
23
24/**
25 * Set an alternative error handler from the default alert box.
26 * @see getahead.org/dwr/browser/engine/errors
27 */
28dwr.engine.setErrorHandler = function(handler) {
29  dwr.engine._errorHandler = handler;
30};
31
32/**
33 * Set an alternative warning handler from the default alert box.
34 * @see getahead.org/dwr/browser/engine/errors
35 */
36dwr.engine.setWarningHandler = function(handler) {
37  dwr.engine._warningHandler = handler;
38};
39
40/**
41 * Setter for the text/html handler - what happens if a DWR request gets an HTML
42 * reply rather than the expected Javascript. Often due to login timeout
43 */
44dwr.engine.setTextHtmlHandler = function(handler) {
45  dwr.engine._textHtmlHandler = handler;
46};
47
48/**
49 * Set a default timeout value for all calls. 0 (the default) turns timeouts off.
50 * @see getahead.org/dwr/browser/engine/errors
51 */
52dwr.engine.setTimeout = function(timeout) {
53  dwr.engine._timeout = timeout;
54};
55
56/**
57 * The Pre-Hook is called before any DWR remoting is done.
58 * @see getahead.org/dwr/browser/engine/hooks
59 */
60dwr.engine.setPreHook = function(handler) {
61  dwr.engine._preHook = handler;
62};
63
64/**
65 * The Post-Hook is called after any DWR remoting is done.
66 * @see getahead.org/dwr/browser/engine/hooks
67 */
68dwr.engine.setPostHook = function(handler) {
69  dwr.engine._postHook = handler;
70};
71
72/**
73 * Custom headers for all DWR calls
74 * @see getahead.org/dwr/????
75 */
76dwr.engine.setHeaders = function(headers) {
77  dwr.engine._headers = headers;
78};
79
80/**
81 * Custom parameters for all DWR calls
82 * @see getahead.org/dwr/????
83 */
84dwr.engine.setParameters = function(parameters) {
85  dwr.engine._parameters = parameters;
86};
87
88/** XHR remoting type constant. See dwr.engine.set[Rpc|Poll]Type() */
89dwr.engine.XMLHttpRequest = 1;
90
91/** XHR remoting type constant. See dwr.engine.set[Rpc|Poll]Type() */
92dwr.engine.IFrame = 2;
93
94/** XHR remoting type constant. See dwr.engine.setRpcType() */
95dwr.engine.ScriptTag = 3;
96
97/**
98 * Set the preferred remoting type.
99 * @param newType One of dwr.engine.XMLHttpRequest or dwr.engine.IFrame or dwr.engine.ScriptTag
100 * @see getahead.org/dwr/browser/engine/options
101 */
102dwr.engine.setRpcType = function(newType) {
103  if (newType != dwr.engine.XMLHttpRequest && newType != dwr.engine.IFrame && newType != dwr.engine.ScriptTag) {
104    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" });
105    return;
106  }
107  dwr.engine._rpcType = newType;
108};
109
110/**
111 * Which HTTP method do we use to send results? Must be one of "GET" or "POST".
112 * @see getahead.org/dwr/browser/engine/options
113 */
114dwr.engine.setHttpMethod = function(httpMethod) {
115  if (httpMethod != "GET" && httpMethod != "POST") {
116    dwr.engine._handleError(null, { name:"dwr.engine.invalidHttpMethod", message:"Remoting method must be one of GET or POST" });
117    return;
118  }
119  dwr.engine._httpMethod = httpMethod;
120};
121
122/**
123 * Ensure that remote calls happen in the order in which they were sent? (Default: false)
124 * @see getahead.org/dwr/browser/engine/ordering
125 */
126dwr.engine.setOrdered = function(ordered) {
127  dwr.engine._ordered = ordered;
128};
129
130/**
131 * Do we ask the XHR object to be asynchronous? (Default: true)
132 * @see getahead.org/dwr/browser/engine/options
133 */
134dwr.engine.setAsync = function(async) {
135  dwr.engine._async = async;
136};
137
138/**
139 * Does DWR poll the server for updates? (Default: false)
140 * @see getahead.org/dwr/browser/engine/options
141 */
142dwr.engine.setActiveReverseAjax = function(activeReverseAjax) {
143  if (activeReverseAjax) {
144    // Bail if we are already started
145    if (dwr.engine._activeReverseAjax) return;
146    dwr.engine._activeReverseAjax = true;
147    dwr.engine._poll();
148  }
149  else {
150    // Can we cancel an existing request?
151    if (dwr.engine._activeReverseAjax && dwr.engine._pollReq) dwr.engine._pollReq.abort();
152    dwr.engine._activeReverseAjax = false;
153  }
154  // TODO: in iframe mode, if we start, stop, start then the second start may
155  // well kick off a second iframe while the first is still about to return
156  // we should cope with this but we don't
157};
158
159/**
160 * The default message handler.
161 * @see getahead.org/dwr/browser/engine/errors
162 */
163dwr.engine.defaultErrorHandler = function(message, ex) {
164  dwr.engine._debug("Error: " + ex.name + ", " + ex.message, true);
165  /*if (message == null || message == "") alert("A server error has occured.");
166  // Ignore NS_ERROR_NOT_AVAILABLE if Mozilla is being narky
167  else if (message.indexOf("0x80040111") != -1) dwr.engine._debug(message);
168  else if (message.indexOf("Failed to read input") == -1 && 
169    message.indexOf("Not Implemented") == -1 && 
170    message.indexOf("Service Unavailable") == -1 ) alert(message);
171    */
172    dwr.engine._debug(message);
173};
174
175/**
176 * The default warning handler.
177 * @see getahead.org/dwr/browser/engine/errors
178 */
179dwr.engine.defaultWarningHandler = function(message, ex) {
180  dwr.engine._debug(message);
181};
182
183/**
184 * For reduced latency you can group several remote calls together using a batch.
185 * @see getahead.org/dwr/browser/engine/batch
186 */
187dwr.engine.beginBatch = function() {
188  if (dwr.engine._batch) {
189    dwr.engine._handleError(null, { name:"dwr.engine.batchBegun", message:"Batch already begun" });
190    return;
191  }
192  dwr.engine._batch = dwr.engine._createBatch();
193};
194
195/**
196 * Finished grouping a set of remote calls together. Go and execute them all.
197 * @see getahead.org/dwr/browser/engine/batch
198 */
199dwr.engine.endBatch = function(options) {
200  var batch = dwr.engine._batch;
201  if (batch == null) {
202    dwr.engine._handleError(null, { name:"dwr.engine.batchNotBegun", message:"No batch in progress" });
203    return;
204  }
205  dwr.engine._batch = null;
206  if (batch.map.callCount == 0) return;
207
208  // The hooks need to be merged carefully to preserve ordering
209  if (options) dwr.engine._mergeBatch(batch, options);
210
211  // In ordered mode, we don't send unless the list of sent items is empty
212  if (dwr.engine._ordered && dwr.engine._batchesLength != 0) {
213    dwr.engine._batchQueue[dwr.engine._batchQueue.length] = batch;
214  }
215  else {
216    dwr.engine._sendData(batch);
217  }
218};
219
220/** @deprecated */
221dwr.engine.setPollMethod = function(type) { dwr.engine.setPollType(type); };
222dwr.engine.setMethod = function(type) { dwr.engine.setRpcType(type); };
223dwr.engine.setVerb = function(verb) { dwr.engine.setHttpMethod(verb); };
224dwr.engine.setPollType = function() { dwr.engine._debug("Manually setting the Poll Type is not supported"); };
225
226//==============================================================================
227// Only private stuff below here
228//==============================================================================
229
230/** The original page id sent from the server */
231dwr.engine._origScriptSessionId = "EAF334B623A0DF4ED1F9E4EB5DCF604C";
232
233/** The session cookie name */
234dwr.engine._sessionCookieName = "JSESSIONID"; // JSESSIONID
235
236/** Is GET enabled for the benefit of Safari? */
237dwr.engine._allowGetForSafariButMakeForgeryEasier = "false";
238
239/** The script prefix to strip in the case of scriptTagProtection. */
240dwr.engine._scriptTagProtection = "throw 'allowScriptTagRemoting is false.';";
241
242/** The default path to the DWR servlet */
243dwr.engine._defaultPath = "/system/dwr";
244
245/** Do we use XHR for reverse ajax because we are not streaming? */
246dwr.engine._pollWithXhr = "false";
247
248/** The read page id that we calculate */
249dwr.engine._scriptSessionId = null;
250
251/** The function that we use to fetch/calculate a session id */
252dwr.engine._getScriptSessionId = function() {
253  if (dwr.engine._scriptSessionId == null) {
254    dwr.engine._scriptSessionId = dwr.engine._origScriptSessionId + Math.floor(Math.random() * 1000);
255  }
256  return dwr.engine._scriptSessionId;
257};
258
259/** A function to call if something fails. */
260dwr.engine._errorHandler = dwr.engine.defaultErrorHandler;
261
262/** For debugging when something unexplained happens. */
263dwr.engine._warningHandler = dwr.engine.defaultWarningHandler;
264
265/** A function to be called before requests are marshalled. Can be null. */
266dwr.engine._preHook = null;
267
268/** A function to be called after replies are received. Can be null. */
269dwr.engine._postHook = null;
270
271/** An map of the batches that we have sent and are awaiting a reply on. */
272dwr.engine._batches = {};
273
274/** A count of the number of outstanding batches. Should be == to _batches.length unless prototype has messed things up */
275dwr.engine._batchesLength = 0;
276
277/** In ordered mode, the array of batches waiting to be sent */
278dwr.engine._batchQueue = [];
279
280/** What is the default rpc type */
281dwr.engine._rpcType = dwr.engine.XMLHttpRequest;
282
283/** What is the default remoting method (ie GET or POST) */
284dwr.engine._httpMethod = "POST";
285
286/** Do we attempt to ensure that calls happen in the order in which they were sent? */
287dwr.engine._ordered = false;
288
289/** Do we make the calls async? */
290dwr.engine._async = true;
291
292/** The current batch (if we are in batch mode) */
293dwr.engine._batch = null;
294
295/** The global timeout */
296dwr.engine._timeout = 0;
297
298/** ActiveX objects to use when we want to convert an xml string into a DOM object. */
299dwr.engine._DOMDocument = ["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];
300
301/** The ActiveX objects to use when we want to do an XMLHttpRequest call. */
302dwr.engine._XMLHTTP = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
303
304/** Are we doing comet or polling? */
305dwr.engine._activeReverseAjax = false;
306
307/** The iframe that we are using to poll */
308dwr.engine._outstandingIFrames = [];
309
310/** The xhr object that we are using to poll */
311dwr.engine._pollReq = null;
312
313/** How many milliseconds between internal comet polls */
314dwr.engine._pollCometInterval = 200;
315
316/** How many times have we re-tried to poll? */
317dwr.engine._pollRetries = 0;
318dwr.engine._maxPollRetries = 0;
319
320/** Do we do a document.reload if we get a text/html reply? */
321dwr.engine._textHtmlHandler = null;
322
323/** If you wish to send custom headers with every request */
324dwr.engine._headers = null;
325
326/** If you wish to send extra custom request parameters with each request */
327dwr.engine._parameters = null;
328
329/** Undocumented interceptors - do not use */
330dwr.engine._postSeperator = "&";
331dwr.engine._defaultInterceptor = function(data) { return data; };
332dwr.engine._urlRewriteHandler = dwr.engine._defaultInterceptor;
333dwr.engine._contentRewriteHandler = dwr.engine._defaultInterceptor;
334dwr.engine._replyRewriteHandler = dwr.engine._defaultInterceptor;
335
336/** Batch ids allow us to know which batch the server is answering */
337dwr.engine._nextBatchId = 0;
338
339/** A list of the properties that need merging from calls to a batch */
340dwr.engine._propnames = [ "rpcType", "httpMethod", "async", "timeout", "errorHandler", "warningHandler", "textHtmlHandler" ];
341
342/** Do we stream, or can be hacked to do so? */
343dwr.engine._partialResponseNo = 0;
344dwr.engine._partialResponseYes = 1;
345dwr.engine._partialResponseFlush = 2;
346
347/** Is this page in the process of unloading? */
348dwr.engine._unloading = false;
349
350/**
351 * @private Send a request. Called by the Javascript interface stub
352 * @param path part of URL after the host and before the exec bit without leading or trailing /s
353 * @param scriptName The class to execute
354 * @param methodName The method on said class to execute
355 * @param func The callback function to which any returned data should be passed
356 *       if this is null, any returned data will be ignored
357 * @param vararg_params The parameters to pass to the above class
358 */
359dwr.engine._execute = function(path, scriptName, methodName, vararg_params) {
360  var singleShot = false;
361  if (dwr.engine._batch == null) {
362    dwr.engine.beginBatch();
363    singleShot = true;
364  }
365  var batch = dwr.engine._batch;
366  // To make them easy to manipulate we copy the arguments into an args array
367  var args = [];
368  for (var i = 0; i < arguments.length - 3; i++) {
369    args[i] = arguments[i + 3];
370  }
371  // All the paths MUST be to the same servlet
372  if (batch.path == null) {
373    batch.path = path;
374  }
375  else {
376    if (batch.path != path) {
377      dwr.engine._handleError(batch, { name:"dwr.engine.multipleServlets", message:"Can't batch requests to multiple DWR Servlets." });
378      return;
379    }
380  }
381  // From the other params, work out which is the function (or object with
382  // call meta-data) and which is the call parameters
383  var callData;
384  var lastArg = args[args.length - 1];
385  if (typeof lastArg == "function" || lastArg == null) callData = { callback:args.pop() };
386  else callData = args.pop();
387
388  // Merge from the callData into the batch
389  dwr.engine._mergeBatch(batch, callData);
390  batch.handlers[batch.map.callCount] = {
391    exceptionHandler:callData.exceptionHandler,
392    callback:callData.callback
393  };
394
395  // Copy to the map the things that need serializing
396  var prefix = "c" + batch.map.callCount + "-";
397  batch.map[prefix + "scriptName"] = scriptName;
398  batch.map[prefix + "methodName"] = methodName;
399  batch.map[prefix + "id"] = batch.map.callCount;
400  var refctx = [];
401  for (i = 0; i < args.length; i++) {
402    dwr.engine._serializeAll(batch, refctx, args[i], prefix + "param" + i);
403  }
404
405  // Now we have finished remembering the call, we incr the call count
406  batch.map.callCount++;
407  if (singleShot) dwr.engine.endBatch();
408};
409
410/** @private Poll the server to see if there is any data waiting */
411dwr.engine._poll = function() {
412  if (!dwr.engine._activeReverseAjax) return;
413
414  var batch = dwr.engine._createBatch();
415  batch.map.id = 0; // TODO: Do we need this??
416  batch.map.callCount = 1;
417  batch.isPoll = true;
418  if (dwr.engine._pollWithXhr == "true") {
419    batch.rpcType = dwr.engine.XMLHttpRequest;
420    batch.map.partialResponse = dwr.engine._partialResponseNo;
421  }
422  else {
423    if (navigator.userAgent.indexOf("Gecko/") != -1) {
424      batch.rpcType = dwr.engine.XMLHttpRequest;
425      batch.map.partialResponse = dwr.engine._partialResponseYes;
426    }
427    else {
428      batch.rpcType = dwr.engine.XMLHttpRequest;
429      batch.map.partialResponse = dwr.engine._partialResponseNo;
430    }
431  }
432  batch.httpMethod = "POST";
433  batch.async = true;
434  batch.timeout = 0;
435  batch.path = dwr.engine._defaultPath;
436  batch.preHooks = [];
437  batch.postHooks = [];
438  batch.errorHandler = dwr.engine._pollErrorHandler;
439  batch.warningHandler = dwr.engine._pollErrorHandler;
440  batch.handlers[0] = {
441    callback:function(pause) {
442      dwr.engine._pollRetries = 0;
443      setTimeout(dwr.engine._poll, pause);
444    }
445  };
446
447  // Send the data
448  dwr.engine._sendData(batch);
449  if (batch.rpcType == dwr.engine.XMLHttpRequest && batch.map.partialResponse == dwr.engine._partialResponseYes) {
450    dwr.engine._checkCometPoll();
451  }
452};
453
454/** Try to recover from polling errors */
455dwr.engine._pollErrorHandler = function(msg, ex) {
456  // if anything goes wrong then just silently try again (up to 3x) after 10s
457  dwr.engine._pollRetries++;
458  dwr.engine._debug("Reverse Ajax poll failed (pollRetries=" + dwr.engine._pollRetries + "): " + ex.name + " : " + ex.message);
459  if (dwr.engine._pollRetries < dwr.engine._maxPollRetries) {
460    setTimeout(dwr.engine._poll, 10000);
461  }
462  else {
463    dwr.engine._activeReverseAjax = false;
464    dwr.engine._debug("Giving up.");
465  }
466};
467
468/** @private Generate a new standard batch */
469dwr.engine._createBatch = function() {
470  var batch = {
471    map:{
472      callCount:0,
473      page:window.location.pathname + window.location.search,
474      httpSessionId:dwr.engine._getJSessionId(),
475      scriptSessionId:dwr.engine._getScriptSessionId()
476    },
477    charsProcessed:0, paramCount:0,
478    parameters:{}, headers:{},
479    isPoll:false, handlers:{}, preHooks:[], postHooks:[],
480    rpcType:dwr.engine._rpcType,
481    httpMethod:dwr.engine._httpMethod,
482    async:dwr.engine._async,
483    timeout:dwr.engine._timeout,
484    errorHandler:dwr.engine._errorHandler,
485    warningHandler:dwr.engine._warningHandler,
486    textHtmlHandler:dwr.engine._textHtmlHandler
487  };
488  if (dwr.engine._preHook) batch.preHooks.push(dwr.engine._preHook);
489  if (dwr.engine._postHook) batch.postHooks.push(dwr.engine._postHook);
490  var propname, data;
491  if (dwr.engine._headers) {
492    for (propname in dwr.engine._headers) {
493      data = dwr.engine._headers[propname];
494      if (typeof data != "function") batch.headers[propname] = data;
495    }
496  }
497  if (dwr.engine._parameters) {
498    for (propname in dwr.engine._parameters) {
499      data = dwr.engine._parameters[propname];
500      if (typeof data != "function") batch.parameters[propname] = data;
501    }
502  }
503  return batch;
504};
505
506/** @private Take further options and merge them into */
507dwr.engine._mergeBatch = function(batch, overrides) {
508  var propname, data;
509  for (var i = 0; i < dwr.engine._propnames.length; i++) {
510    propname = dwr.engine._propnames[i];
511    if (overrides[propname] != null) batch[propname] = overrides[propname];
512  }
513  if (overrides.preHook != null) batch.preHooks.unshift(overrides.preHook);
514  if (overrides.postHook != null) batch.postHooks.push(overrides.postHook);
515  if (overrides.headers) {
516    for (propname in overrides.headers) {
517      data = overrides.headers[propname];
518      if (typeof data != "function") batch.headers[propname] = data;
519    }
520  }
521  if (overrides.parameters) {
522    for (propname in overrides.parameters) {
523      data = overrides.parameters[propname];
524      if (typeof data != "function") batch.map["p-" + propname] = "" + data;
525    }
526  }
527};
528
529/** @private What is our session id? */
530dwr.engine._getJSessionId =  function() {
531  var cookies = document.cookie.split(';');
532  for (var i = 0; i < cookies.length; i++) {
533    var cookie = cookies[i];
534    while (cookie.charAt(0) == ' ') cookie = cookie.substring(1, cookie.length);
535    if (cookie.indexOf(dwr.engine._sessionCookieName + "=") == 0) {
536      return cookie.substring(dwr.engine._sessionCookieName.length + 1, cookie.length);
537    }
538  }
539  return "";
540};
541
542/** @private Check for reverse Ajax activity */
543dwr.engine._checkCometPoll = function() {
544  for (var i = 0; i < dwr.engine._outstandingIFrames.length; i++) {
545    var text = "";
546    var iframe = dwr.engine._outstandingIFrames[i];
547    try {
548      text = dwr.engine._getTextFromCometIFrame(iframe);
549    }
550    catch (ex) {
551      dwr.engine._handleWarning(iframe.batch, ex);
552    }
553    if (text != "") dwr.engine._processCometResponse(text, iframe.batch);
554  }
555  if (dwr.engine._pollReq) {
556    var req = dwr.engine._pollReq;
557    var text = req.responseText;
558    if (text != null) dwr.engine._processCometResponse(text, req.batch);
559  }
560
561  // If the poll resources are still there, come back again
562  if (dwr.engine._outstandingIFrames.length > 0 || dwr.engine._pollReq) {
563    setTimeout(dwr.engine._checkCometPoll, dwr.engine._pollCometInterval);
564  }
565};
566
567/** @private Extract the whole (executed an all) text from the current iframe */
568dwr.engine._getTextFromCometIFrame = function(frameEle) {
569  var body = frameEle.contentWindow.document.body;
570  if (body == null) return "";
571  var text = body.innerHTML;
572  // We need to prevent IE from stripping line feeds
573  if (text.indexOf("<PRE>") == 0 || text.indexOf("<pre>") == 0) {
574    text = text.substring(5, text.length - 7);
575  }
576  return text;
577};
578
579/** @private Some more text might have come in, test and execute the new stuff */
580dwr.engine._processCometResponse = function(response, batch) {
581  if (batch.charsProcessed == response.length) return;
582  if (response.length == 0) {
583    batch.charsProcessed = 0;
584    return;
585  }
586
587  var firstStartTag = response.indexOf("//#DWR-START#", batch.charsProcessed);
588  if (firstStartTag == -1) {
589    // dwr.engine._debug("No start tag (search from " + batch.charsProcessed + "). skipping '" + response.substring(batch.charsProcessed) + "'");
590    batch.charsProcessed = response.length;
591    return;
592  }
593  // if (firstStartTag > 0) {
594  //   dwr.engine._debug("Start tag not at start (search from " + batch.charsProcessed + "). skipping '" + response.substring(batch.charsProcessed, firstStartTag) + "'");
595  // }
596
597  var lastEndTag = response.lastIndexOf("//#DWR-END#");
598  if (lastEndTag == -1) {
599    // dwr.engine._debug("No end tag. unchanged charsProcessed=" + batch.charsProcessed);
600    return;
601  }
602
603  // Skip the end tag too for next time, remembering CR and LF
604  if (response.charCodeAt(lastEndTag + 11) == 13 && response.charCodeAt(lastEndTag + 12) == 10) {
605    batch.charsProcessed = lastEndTag + 13;
606  }
607  else {
608    batch.charsProcessed = lastEndTag + 11;
609  }
610
611  var exec = response.substring(firstStartTag + 13, lastEndTag);
612
613  dwr.engine._receivedBatch = batch;
614  dwr.engine._eval(exec);
615  dwr.engine._receivedBatch = null;
616};
617
618/** @private Actually send the block of data in the batch object. */
619dwr.engine._sendData = function(batch) {
620  batch.map.batchId = dwr.engine._nextBatchId;
621  dwr.engine._nextBatchId++;
622  dwr.engine._batches[batch.map.batchId] = batch;
623  dwr.engine._batchesLength++;
624  batch.completed = false;
625
626  for (var i = 0; i < batch.preHooks.length; i++) {
627    batch.preHooks[i]();
628  }
629  batch.preHooks = null;
630  // Set a timeout
631  if (batch.timeout && batch.timeout != 0) {
632    batch.timeoutId = setTimeout(function() { dwr.engine._abortRequest(batch); }, batch.timeout);
633  }
634  // Get setup for XMLHttpRequest if possible
635  if (batch.rpcType == dwr.engine.XMLHttpRequest) {
636    if (window.XMLHttpRequest) {
637      batch.req = new XMLHttpRequest();
638    }
639    // IE5 for the mac claims to support window.ActiveXObject, but throws an error when it's used
640    else if (window.ActiveXObject && !(navigator.userAgent.indexOf("Mac") >= 0 && navigator.userAgent.indexOf("MSIE") >= 0)) {
641      batch.req = dwr.engine._newActiveXObject(dwr.engine._XMLHTTP);
642    }
643  }
644
645  var prop, request;
646  if (batch.req) {
647    // Proceed using XMLHttpRequest
648    if (batch.async) {
649      batch.req.onreadystatechange = function() {
650        if (typeof dwr != 'undefined') dwr.engine._stateChange(batch);
651      };
652    }
653    // If we're polling, record this for monitoring
654    if (batch.isPoll) {
655      dwr.engine._pollReq = batch.req;
656      // In IE XHR is an ActiveX control so you can't augment it like this
657      if (!(document.all && !window.opera)) batch.req.batch = batch;
658    }
659    // Workaround for Safari 1.x POST bug
660    var indexSafari = navigator.userAgent.indexOf("Safari/");
661    if (indexSafari >= 0) {
662      var version = navigator.userAgent.substring(indexSafari + 7);
663      if (parseInt(version, 10) < 400) {
664        if (dwr.engine._allowGetForSafariButMakeForgeryEasier == "true") batch.httpMethod = "GET";
665        else dwr.engine._handleWarning(batch, { name:"dwr.engine.oldSafari", message:"Safari GET support disabled. See getahead.org/dwr/server/servlet and allowGetForSafariButMakeForgeryEasier." });
666      }
667    }
668    batch.mode = batch.isPoll ? dwr.engine._ModePlainPoll : dwr.engine._ModePlainCall;
669    request = dwr.engine._constructRequest(batch);
670    try {
671      batch.req.open(batch.httpMethod, request.url, batch.async);
672      try {
673        for (prop in batch.headers) {
674          var value = batch.headers[prop];
675          if (typeof value == "string") batch.req.setRequestHeader(prop, value);
676        }
677        //if (!batch.headers["Content-Type"]) batch.req.setRequestHeader("Content-Type", "text/plain");
678        batch.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
679      }
680      catch (ex) {
681        dwr.engine._handleWarning(batch, ex);
682      }
683      batch.req.send(request.body);
684      if (!batch.async) dwr.engine._stateChange(batch);
685    }
686    catch (ex) {
687      dwr.engine._handleError(batch, ex);
688    }
689  }
690  else if (batch.rpcType != dwr.engine.ScriptTag) {
691    var idname = batch.isPoll ? "dwr-if-poll-" + batch.map.batchId : "dwr-if-" + batch.map.batchId;
692    // Removed htmlfile implementation. Don't expect it to return before v3
693    batch.div = document.createElement("div");
694    // Add the div to the document first, otherwise IE 6 will ignore onload handler.
695    document.body.appendChild(batch.div);
696    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>";
697    batch.document = document;
698    batch.iframe = batch.document.getElementById(idname);
699    batch.iframe.batch = batch;
700    batch.mode = batch.isPoll ? dwr.engine._ModeHtmlPoll : dwr.engine._ModeHtmlCall;
701    if (batch.isPoll) dwr.engine._outstandingIFrames.push(batch.iframe);
702    request = dwr.engine._constructRequest(batch);
703    if (batch.httpMethod == "GET") {
704      batch.iframe.setAttribute("src", request.url);
705    }
706    else {
707      batch.form = batch.document.createElement("form");
708      batch.form.setAttribute("id", "dwr-form");
709      batch.form.setAttribute("action", request.url);
710      batch.form.setAttribute("style", "display:none;");
711      batch.form.setAttribute("target", idname);
712      batch.form.target = idname;
713      batch.form.setAttribute("method", batch.httpMethod);
714      for (prop in batch.map) {
715        var value = batch.map[prop];
716        if (typeof value != "function") {
717          var formInput = batch.document.createElement("input");
718          formInput.setAttribute("type", "hidden");
719          formInput.setAttribute("name", prop);
720          formInput.setAttribute("value", value);
721          batch.form.appendChild(formInput);
722        }
723      }
724      batch.document.body.appendChild(batch.form);
725      batch.form.submit();
726    }
727  }
728  else {
729    batch.httpMethod = "GET"; // There's no such thing as ScriptTag using POST
730    batch.mode = batch.isPoll ? dwr.engine._ModePlainPoll : dwr.engine._ModePlainCall;
731    request = dwr.engine._constructRequest(batch);
732    batch.script = document.createElement("script");
733    batch.script.id = "dwr-st-" + batch.map["c0-id"];
734    batch.script.src = request.url;
735    document.body.appendChild(batch.script);
736  }
737};
738
739dwr.engine._ModePlainCall = "/call/plaincall/";
740dwr.engine._ModeHtmlCall = "/call/htmlcall/";
741dwr.engine._ModePlainPoll = "/call/plainpoll/";
742dwr.engine._ModeHtmlPoll = "/call/htmlpoll/";
743
744/** @private Work out what the URL should look like */
745dwr.engine._constructRequest = function(batch) {
746  // A quick string to help people that use web log analysers
747  var request = { url:batch.path + batch.mode, body:null };
748  if (batch.isPoll == true) {
749    request.url += "ReverseAjax.dwr";
750  }
751  else if (batch.map.callCount == 1) {
752    request.url += batch.map["c0-scriptName"] + "." + batch.map["c0-methodName"] + ".dwr";
753  }
754  else {
755    request.url += "Multiple." + batch.map.callCount + ".dwr";
756  }
757  // Play nice with url re-writing
758  var sessionMatch = location.href.match(/jsessionid=([^?]+)/);
759  if (sessionMatch != null) {
760    request.url += ";jsessionid=" + sessionMatch[1];
761  }
762
763  var prop;
764  if (batch.httpMethod == "GET") {
765    // Some browsers (Opera/Safari2) seem to fail to convert the callCount value
766    // to a string in the loop below so we do it manually here.
767    batch.map.callCount = "" + batch.map.callCount;
768    request.url += "?";
769    for (prop in batch.map) {
770      if (typeof batch.map[prop] != "function") {
771        request.url += encodeURIComponent(prop) + "=" + encodeURIComponent(batch.map[prop]) + "&";
772      }
773    }
774    request.url = request.url.substring(0, request.url.length - 1);
775  }
776  else {
777    // PERFORMANCE: for iframe mode this is thrown away.
778    request.body = "";
779    if (document.all && !window.opera) {
780      // Use array joining on IE (fastest)
781      var buf = [];
782      for (prop in batch.map) {
783        if (typeof batch.map[prop] != "function") {
784          buf.push(prop + "=" + encodeURIComponent(batch.map[prop]) + dwr.engine._postSeperator);
785        }
786      }
787      request.body = buf.join("");
788    }
789    else {
790      // Use string concat on other browsers (fastest)
791      for (prop in batch.map) {
792        if (typeof batch.map[prop] != "function") {
793          request.body += prop + "=" + encodeURIComponent(batch.map[prop]) + dwr.engine._postSeperator;
794        }
795      }
796    }
797    request.body = dwr.engine._contentRewriteHandler(request.body);
798  }
799  request.url = dwr.engine._urlRewriteHandler(request.url);
800  return request;
801};
802
803/** @private Called by XMLHttpRequest to indicate that something has happened */
804dwr.engine._stateChange = function(batch) {
805  var toEval;
806
807  if (batch.completed) {
808    dwr.engine._debug("Error: _stateChange() with batch.completed");
809    return;
810  }
811
812  var req = batch.req;
813  try {
814    if (req.readyState != 4) return;
815  }
816  catch (ex) {
817    dwr.engine._handleWarning(batch, ex);
818    // It's broken - clear up and forget this call
819    dwr.engine._clearUp(batch);
820    return;
821  }
822
823  if (dwr.engine._unloading) {
824    dwr.engine._debug("Ignoring reply from server as page is unloading.");
825    return;
826  }
827  
828  try {
829    var reply = req.responseText;
830    reply = dwr.engine._replyRewriteHandler(reply);
831    var status = req.status; // causes Mozilla to except on page moves
832
833    if (reply == null || reply == "") {
834      dwr.engine._handleWarning(batch, { name:"dwr.engine.missingData", message:"No data received from server" });
835    }
836    else if (status != 200) {
837      dwr.engine._handleError(batch, { name:"dwr.engine.http." + status, message:req.statusText });
838    }
839    else {
840      var contentType = req.getResponseHeader("Content-Type");
841      if (!contentType.match(/^text\/plain/) && !contentType.match(/^text\/javascript/)) {
842        if (contentType.match(/^text\/html/) && typeof batch.textHtmlHandler == "function") {
843          batch.textHtmlHandler({ status:status, responseText:reply, contentType:contentType });
844        }
845        else {
846          dwr.engine._handleWarning(batch, { name:"dwr.engine.invalidMimeType", message:"Invalid content type: '" + contentType + "'" });
847        }
848      }
849      else {
850        // Comet replies might have already partially executed
851        if (batch.isPoll && batch.map.partialResponse == dwr.engine._partialResponseYes) {
852          dwr.engine._processCometResponse(reply, batch);
853        }
854        else {
855          if (reply.search("//#DWR") == -1) {
856            dwr.engine._handleWarning(batch, { name:"dwr.engine.invalidReply", message:"Invalid reply from server" });
857          }
858          else {
859            toEval = reply;
860          }
861        }
862      }
863    }
864  }
865  catch (ex) {
866    dwr.engine._handleWarning(batch, ex);
867  }
868
869  dwr.engine._callPostHooks(batch);
870
871  // Outside of the try/catch so errors propogate normally:
872  dwr.engine._receivedBatch = batch;
873  if (toEval != null) toEval = toEval.replace(dwr.engine._scriptTagProtection, "");
874  dwr.engine._eval(toEval);
875  dwr.engine._receivedBatch = null;
876  dwr.engine._validateBatch(batch);
877  if (!batch.completed) dwr.engine._clearUp(batch);
878};
879
880/**
881 * @private This function is invoked when a batch reply is received.
882 * It checks that there is a response for every call in the batch. Otherwise,
883 * an error will be signaled (a call without a response indicates that the 
884 * server failed to send complete batch response). 
885 */
886dwr.engine._validateBatch = function(batch) {
887  // If some call left unreplied, report an error.
888  if (!batch.completed) {
889    for (var i = 0; i < batch.map.callCount; i++) {
890      if (batch.handlers[i] != null) {
891        dwr.engine._handleWarning(batch, { name:"dwr.engine.incompleteReply", message:"Incomplete reply from server" });
892        break;
893      }
894    }
895  }
896}
897
898/** @private Called from iframe onload, check batch using batch-id */
899dwr.engine._iframeLoadingComplete = function(batchId) {
900  // dwr.engine._checkCometPoll();
901  var batch = dwr.engine._batches[batchId];
902  if (batch) dwr.engine._validateBatch(batch);
903}
904
905/** @private Called by the server: Execute a callback */
906dwr.engine._remoteHandleCallback = function(batchId, callId, reply) {
907  var batch = dwr.engine._batches[batchId];
908  if (batch == null) {
909    dwr.engine._debug("Warning: batch == null in remoteHandleCallback for batchId=" + batchId, true);
910    return;
911  }
912  // Error handlers inside here indicate an error that is nothing to do
913  // with DWR so we handle them differently.
914  try {
915    var handlers = batch.handlers[callId];
916    batch.handlers[callId] = null;
917    if (!handlers) {
918      dwr.engine._debug("Warning: Missing handlers. callId=" + callId, true);
919    }
920    else if (typeof handlers.callback == "function") handlers.callback(reply);
921  }
922  catch (ex) {
923    dwr.engine._handleError(batch, ex);
924  }
925};
926
927/** @private Called by the server: Handle an exception for a call */
928dwr.engine._remoteHandleException = function(batchId, callId, ex) {
929  var batch = dwr.engine._batches[batchId];
930  if (batch == null) { dwr.engine._debug("Warning: null batch in remoteHandleException", true); return; }
931  var handlers = batch.handlers[callId];
932  batch.handlers[callId] = null;
933  if (handlers == null) { dwr.engine._debug("Warning: null handlers in remoteHandleException", true); return; }
934  if (ex.message == undefined) ex.message = "";
935  if (typeof handlers.exceptionHandler == "function") handlers.exceptionHandler(ex.message, ex);
936  else if (typeof batch.errorHandler == "function") batch.errorHandler(ex.message, ex);
937};
938
939/** @private Called by the server: The whole batch is broken */
940dwr.engine._remoteHandleBatchException = function(ex, batchId) {
941  var searchBatch = (dwr.engine._receivedBatch == null && batchId != null);
942  if (searchBatch) {
943    dwr.engine._receivedBatch = dwr.engine._batches[batchId];
944  }
945  if (ex.message == undefined) ex.message = "";
946  dwr.engine._handleError(dwr.engine._receivedBatch, ex);
947  if (searchBatch) {
948    dwr.engine._receivedBatch = null;
949    dwr.engine._clearUp(dwr.engine._batches[batchId]);
950  }
951};
952
953/** @private Called by the server: Reverse ajax should not be used */
954dwr.engine._remotePollCometDisabled = function(ex, batchId) {
955  dwr.engine.setActiveReverseAjax(false);
956  var searchBatch = (dwr.engine._receivedBatch == null && batchId != null);
957  if (searchBatch) {
958    dwr.engine._receivedBatch = dwr.engine._batches[batchId];
959  }
960  if (ex.message == undefined) ex.message = "";
961  dwr.engine._handleError(dwr.engine._receivedBatch, ex);
962  if (searchBatch) {
963    dwr.engine._receivedBatch = null;
964    dwr.engine._clearUp(dwr.engine._batches[batchId]);
965  }
966};
967
968/** @private Called by the server: An IFrame reply is about to start */
969dwr.engine._remoteBeginIFrameResponse = function(iframe, batchId) {
970  if (iframe != null) dwr.engine._receivedBatch = iframe.batch;
971  dwr.engine._callPostHooks(dwr.engine._receivedBatch);
972};
973
974/** @private Called by the server: An IFrame reply is just completing */
975dwr.engine._remoteEndIFrameResponse = function(batchId) {
976  dwr.engine._clearUp(dwr.engine._receivedBatch);
977  dwr.engine._receivedBatch = null;
978};
979
980/** @private This is a hack to make the context be this window */
981dwr.engine._eval = function(script) {
982  if (script == null) return null;
983  if (script == "") { dwr.engine._debug("Warning: blank script", true); return null; }
984  // dwr.engine._debug("Exec: [" + script + "]", true);
985  return eval(script);
986};
987
988/** @private Called as a result of a request timeout */
989dwr.engine._abortRequest = function(batch) {
990  if (batch && !batch.completed) {
991    dwr.engine._clearUp(batch);
992    if (batch.req) batch.req.abort();
993    dwr.engine._handleError(batch, { name:"dwr.engine.timeout", message:"Timeout" });
994  }
995};
996
997/** @private call all the post hooks for a batch */
998dwr.engine._callPostHooks = function(batch) {
999  if (batch.postHooks) {
1000    for (var i = 0; i < batch.postHooks.length; i++) {
1001      batch.postHooks[i]();
1002    }
1003    batch.postHooks = null;
1004  }
1005};
1006
1007/** @private A call has finished by whatever means and we need to shut it all down. */
1008dwr.engine._clearUp = function(batch) {
1009  if (!batch) { dwr.engine._debug("Warning: null batch in dwr.engine._clearUp()", true); return; }
1010  if (batch.completed) { dwr.engine._debug("Warning: Double complete", true); return; }
1011
1012  // IFrame tidyup
1013  if (batch.div) batch.div.parentNode.removeChild(batch.div);
1014  if (batch.iframe) {
1015    // If this is a poll frame then stop comet polling
1016    for (var i = 0; i < dwr.engine._outstandingIFrames.length; i++) {
1017      if (dwr.engine._outstandingIFrames[i] == batch.iframe) {
1018        dwr.engine._outstandingIFrames.splice(i, 1);
1019      }
1020    }
1021    batch.iframe.parentNode.removeChild(batch.iframe);
1022  }
1023  if (batch.form) batch.form.parentNode.removeChild(batch.form);
1024
1025  // XHR tidyup: avoid IE handles increase
1026  if (batch.req) {
1027    // If this is a poll frame then stop comet polling
1028    if (batch.req == dwr.engine._pollReq) dwr.engine._pollReq = null;
1029    delete batch.req;
1030  }
1031
1032  // Timeout tidyup
1033  if (batch.timeoutId != null) {
1034    clearTimeout(batch.timeoutId);
1035    delete batch.timeoutId;
1036  }
1037
1038  if (batch.map && (batch.map.batchId || batch.map.batchId == 0)
1038) {
1039    delete dwr.engine._batches[batch.map.batchId];
1040    dwr.engine._batchesLength--;
1041  }
1042
1043  batch.completed = true;
1044
1045  // If there is anything on the queue waiting to go out, then send it.
1046  // We don't need to check for ordered mode, here because when ordered mode
1047  // gets turned off, we still process *waiting* batches in an ordered way.
1048  if (dwr.engine._batchQueue.length != 0) {
1049    var sendbatch = dwr.engine._batchQueue.shift();
1050    dwr.engine._sendData(sendbatch);
1051  }
1052};
1053
1054/** @private Abort any XHRs in progress at page unload (solves zombie socket problems in IE). */
1055dwr.engine._unloader = function() {
1056  dwr.engine._unloading = true;
1057
1058  // Empty queue of waiting ordered requests
1059  dwr.engine._batchQueue.length = 0;
1060
1061  // Abort any ongoing XHRs and clear their batches
1062  for (var batchId in dwr.engine._batches) {
1063    var batch = dwr.engine._batches[batchId];
1064    // Only process objects that look like batches (avoid prototype additions!)
1065    if (batch && batch.map) {
1066      if (batch.req) {
1067        batch.req.abort();
1068      }
1069      dwr.engine._clearUp(batch);
1070    }
1071  }
1072};
1073// Now register the unload handler
1074if (window.addEventListener) window.addEventListener('unload', dwr.engine._unloader, false);
1075else if (window.attachEvent) window.attachEvent('onunload', dwr.engine._unloader);
1076
1077/** @private Generic error handling routing to save having null checks everywhere */
1078dwr.engine._handleError = function(batch, ex) {
1079  if (typeof ex == "string") ex = { name:"unknown", message:ex };
1080  if (ex.message == null) ex.message = "";
1081  if (ex.name == null) ex.name = "unknown";
1082  if (batch && typeof batch.errorHandler == "function") batch.errorHandler(ex.message, ex);
1083  else if (dwr.engine._errorHandler) dwr.engine._errorHandler(ex.message, ex);
1084  if (batch) dwr.engine._clearUp(batch);
1085};
1086
1087/** @private Generic error handling routing to save having null checks everywhere */
1088dwr.engine._handleWarning = function(batch, ex) {
1089  if (typeof ex == "string") ex = { name:"unknown", message:ex };
1090  if (ex.message == null) ex.message = "";
1091  if (ex.name == null) ex.name = "unknown";
1092  if (batch && typeof batch.warningHandler == "function") batch.warningHandler(ex.message, ex);
1093  else if (dwr.engine._warningHandler) dwr.engine._warningHandler(ex.message, ex);
1094  if (batch) dwr.engine._clearUp(batch);
1095};
1096
1097/**
1098 * @private Marshall a data item
1099 * @param batch A map of variables to how they have been marshalled
1100 * @param referto An array of already marshalled variables to prevent recurrsion
1101 * @param data The data to be marshalled
1102 * @param name The name of the data being marshalled
1103 */
1104dwr.engine._serializeAll = function(batch, referto, data, name) {
1105  if (data == null) {
1106    batch.map[name] = "null:null";
1107    return;
1108  }
1109
1110  switch (typeof data) {
1111  case "boolean":
1112    batch.map[name] = "boolean:" + data;
1113    break;
1114  case "number":
1115    batch.map[name] = "number:" + data;
1116    break;
1117  case "string":
1118    batch.map[name] = "string:" + encodeURIComponent(data);
1119    break;
1120  case "object":
1121    var objstr = Object.prototype.toString.call(data);
1122    if (objstr == "[object String]") batch.map[name] = "String:" + encodeURIComponent(data);
1123    else if (objstr == "[object Boolean]") batch.map[name] = "Boolean:" + data;
1124    else if (objstr == "[object Number]") batch.map[name] = "Number:" + data;
1125    else if (objstr == "[object Date]") batch.map[name] = "Date:" + data.getTime();
1126    else if (objstr == "[object Array]") batch.map[name] = dwr.engine._serializeArray(batch, referto, data, name);
1127    else batch.map[name] = dwr.engine._serializeObject(batch, referto, data, name);
1128    break;
1129  case "function":
1130    // We just ignore functions.
1131    break;
1132  default:
1133    dwr.engine._handleWarning(null, { name:"dwr.engine.unexpectedType", message:"Unexpected type: " + typeof data + ", attempting default converter." });
1134    batch.map[name] = "default:" + data;
1135    break;
1136  }
1137};
1138
1139/** @private Have we already converted this object? */
1140dwr.engine._lookup = function(referto, data, name) {
1141  var lookup;
1142  // Can't use a map: getahead.org/ajax/javascript-gotchas
1143  for (var i = 0; i < referto.length; i++) {
1144    if (referto[i].data == data) {
1145      lookup = referto[i];
1146      break;
1147    }
1148  }
1149  if (lookup) return "reference:" + lookup.name;
1150  referto.push({ data:data, name:name });
1151  return null;
1152};
1153
1154/** @private Marshall an object */
1155dwr.engine._serializeObject = function(batch, referto, data, name) {
1156  var ref = dwr.engine._lookup(referto, data, name);
1157  if (ref) return ref;
1158
1159  // This check for an HTML is not complete, but is there a better way?
1160  // Maybe we should add: data.hasChildNodes typeof "function" == true
1161  if (data.nodeName && data.nodeType) {
1162    return dwr.engine._serializeXml(batch, referto, data, name);
1163  }
1164
1165  // treat objects as an associative arrays
1166  var reply = "Object_" + dwr.engine._getObjectClassName(data) + ":{";
1167  var element;
1168  for (element in data) {
1169    if (typeof data[element] != "function") {
1170      batch.paramCount++;
1171      var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
1172      dwr.engine._serializeAll(batch, referto, data[element], childName);
1173
1174      reply += encodeURIComponent(element) + ":reference:" + childName + ", ";
1175    }
1176  }
1177
1178  if (reply.substring(reply.length - 2) == ", ") {
1179    reply = reply.substring(0, reply.length - 2);
1180  }
1181  reply += "}";
1182
1183  return reply;
1184};
1185
1186/** @private Returns the classname of supplied argument obj */
1187dwr.engine._errorClasses = { "Error":Error, "EvalError":EvalError, "RangeError":RangeError, "ReferenceError":ReferenceError, "SyntaxError":SyntaxError, "TypeError":TypeError, "URIError":URIError };
1188dwr.engine._getObjectClassName = function(obj) {
1189  // Try to find the classname by stringifying the object's constructor
1190  // and extract <class> from "function <class>".
1191  if (obj && obj.constructor && obj.constructor.toString)
1192  {
1193    var str = obj.constructor.toString();
1194    var regexpmatch = str.match(/function\s+(\w+)/);
1195    if (regexpmatch && regexpmatch.length == 2) {
1196      return regexpmatch[1];
1197    }
1198  }
1199
1200  // Now manually test against the core Error classes, as these in some 
1201  // browsers successfully match to the wrong class in the 
1202  // Object.toString() test we will do later
1203  if (obj && obj.constructor) {
1204    for (var errorname in dwr.engine._errorClasses) {
1205      if (obj.constructor == dwr.engine._errorClasses[errorname]) return errorname;
1206    }
1207  }
1208
1209  // Try to find the classname by calling Object.toString() on the object
1210  // and extracting <class> from "[object <class>]"
1211  if (obj) {
1212    var str = Object.prototype.toString.call(obj);
1213    var regexpmatch = str.match(/\[object\s+(\w+)/);
1214    if (regexpmatch && regexpmatch.length==2) {
1215      return regexpmatch[1];
1216    }
1217  }
1218
1219  // Supplied argument was probably not an object, but what is better?
1220  return "Object";
1221};
1222
1223/** @private Marshall an object */
1224dwr.engine._serializeXml = function(batch, referto, data, name) {
1225  var ref = dwr.engine._lookup(referto, data, name);
1226  if (ref) return ref;
1227
1228  var output;
1229  if (window.XMLSerializer) output = new XMLSerializer().serializeToString(data);
1230  else if (data.toXml) output = data.toXml;
1231  else output = data.innerHTML;
1232
1233  return "XML:" + encodeURIComponent(output);
1234};
1235
1236/** @private Marshall an array */
1237dwr.engine._serializeArray = function(batch, referto, data, name) {
1238  var ref = dwr.engine._lookup(referto, data, name);
1239  if (ref) return ref;
1240
1241  if (document.all && !window.opera) {
1242    // Use array joining on IE (fastest)
1243    var buf = ["Array:["];
1244    for (var i = 0; i < data.length; i++) {
1245      if (i != 0) buf.push(",");
1246      batch.paramCount++;
1247      var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
1248      dwr.engine._serializeAll(batch, referto, data[i], childName);
1249      buf.push("reference:");
1250      buf.push(childName);
1251    }
1252    buf.push("]");
1253    reply = buf.join("");
1254  }
1255  else {
1256    // Use string concat on other browsers (fastest)
1257    var reply = "Array:[";
1258    for (var i = 0; i < data.length; i++) {
1259      if (i != 0) reply += ",";
1260      batch.paramCount++;
1261      var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
1262      dwr.engine._serializeAll(batch, referto, data[i], childName);
1263      reply += "reference:";
1264      reply += childName;
1265    }
1266    reply += "]";
1267  }
1268
1269  return reply;
1270};
1271
1272/** @private Convert an XML string into a DOM object. */
1273dwr.engine._unserializeDocument = function(xml) {
1274  var dom;
1275  if (window.DOMParser) {
1276    var parser = new DOMParser();
1277    dom = parser.parseFromString(xml, "text/xml");
1278    if (!dom.documentElement || dom.documentElement.tagName == "parsererror") {
1279      var message = dom.documentElement.firstChild.data;
1280      message += "\n" + dom.documentElement.firstChild.nextSibling.firstChild.data;
1281      throw message;
1282    }
1283    return dom;
1284  }
1285  else if (window.ActiveXObject) {
1286    dom = dwr.engine._newActiveXObject(dwr.engine._DOMDocument);
1287    dom.loadXML(xml); // What happens on parse fail with IE?
1288    return dom;
1289  }
1290  else {
1291    var div = document.createElement("div");
1292    div.innerHTML = xml;
1293    return div;
1294  }
1295};
1296
1297/** @param axarray An array of strings to attempt to create ActiveX objects from */
1298dwr.engine._newActiveXObject = function(axarray) {
1299  var returnValue;  
1300  for (var i = 0; i < axarray.length; i++) {
1301    try {
1302      returnValue = new ActiveXObject(axarray[i]);
1303      break;
1304    }
1305    catch (ex) { /* ignore */ }
1306  }
1307  return returnValue;
1308};
1309
1310/** @private Used internally when some message needs to get to the programmer */
1311dwr.engine._debug = function(message, stacktrace) {
1312  var written = false;
1313  try {
1314    if (window.console) {
1315      if (stacktrace && window.console.trace) window.console.trace();
1316      window.console.log(message);
1317      written = true;
1318    }
1319    else if (window.opera && window.opera.postError) {
1320      window.opera.postError(message);
1321      written = true;
1322    }
1323  }
1324  catch (ex) { /* ignore */ }
1325
1326  if (!written) {
1327    var debug = document.getElementById("dwr-debug");
1328    if (debug) {
1329      var contents = message + "<br/>" + debug.innerHTML;
1330      if (contents.length > 2048) contents = contents.substring(0, 2048);
1331      debug.innerHTML = contents;
1332    }
1333  }
1334};
1335

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.