Debian Codegraph @

terps/tads/tads3/lib/webuires/util.js

raw symbols SCIP
1 /* Copyright (c) 2010 by Michael J. Roberts. All Rights Reserved. */
2 /*
3 * Utility package for TADS 3 Web UI. This is a javascript file that's
4 * designed to be included from the main UI page of a Web-UI game. This
5 * provides a set of useful functions for implementing an IF-style user
6 * interface in HTML/Javascript.
7 */
8
9
10 /* ------------------------------------------------------------------------ */
11 /*
12 * Miscellaneous globals
13 */
14
15 // my page name, as I'm known to the server
16 var pageName = "";
17
18 // the generic noun we use to refer to this program in error messages
19 // (game, story, program, ...)
20 var selfNoun = "story";
21
22 // default action suggestion
23 var errorRecoveryAction =
24 " If the " + selfNoun + " otherwise seems to be running "
25 + "properly, you can ignore this error. If the " + selfNoun
26 + " isn't responding or is acting strangely, it might help to "
27 + "<a href=\"#\" onclick=\"javascript:$win().location.reload();"
28 + "return false;\">reload this page</a>.";
29
30 /* ------------------------------------------------------------------------ */
31 /*
32 * Define a property on an object. If the browser supports the
33 * defineProperty method, we'll use that; otherwise we'll just set the
34 * property directly.
35 *
36 * This differs from direct property setting in that we mark the property
37 * as non-enumerable. This is particularly useful for our Object.prototype
38 * extensions when jQuery is also being used. jQuery uses Object property
39 * enumerations internally and incorrectly assumes that all results are
40 * browser-defined properties, so our custom extensions can create problems
41 * if jQuery is also used. Explicitly hiding those from enumerations lets
42 * us define our own custom Object.prototype extensions without confusing
43 * jQuery. (The webui library itself doesn't use jQuery, so this isn't an
44 * issue out of the box, but it is an issue for individual game authors who
45 * want to use jQuery with the webui code.)
46 */
47 function defineProperty(target, name, method)
48 {
49 if (Object.defineProperty && Object.defineProperties)
50 Object.defineProperty(target, name,
51 {
52 'value': method,
53 'configurable': true,
54 'enumerable': false,
55 'writable': true
56 });
57 else
58 target[name] = method;
59 }
60
61 /* ------------------------------------------------------------------------ */
62 /*
63 * Initialize. Call this once at page load to set up this package.
64 */
65 function utilInit()
66 {
67 // if we have a parent, ask the parent for my name
68 if (window.parent && window.parent != window)
69 pageName = window.parent.pathFromWindow(window);
70
71 // detect the browser version
72 BrowserInfo.init();
73
74 // copy an object
75 defineProperty(Object.prototype, "copy", function(deep) {
76
77 // create a blank object with the same prototype as me
78 var newObj = CopyProto.create(this);
79
80 // copy each property
81 for (var prop in this)
82 {
83 // include only directly defined properties
84 if (this.hasOwnProperty(prop))
85 {
86 // get this value
87 var val = this[prop];
88
89 // recursively copy objects if this is a "deep" copy
90 if (deep && typeof(val) == "object")
91 val = val.copy(true);
92
93 // save this value
94 newObj[prop] = val;
95 }
96 }
97
98 // return the new object
99 return newObj;
100 });
101
102 // get the number of enumerable keys
103 defineProperty(Object.prototype, "propCount", function() {
104 var cnt = 0;
105 for (var prop in this)
106 {
107 if (this.hasOwnProperty(prop))
108 ++cnt;
109 }
110 return cnt;
111 });
112
113 // enumerate keys set in an object, excluding prototype keys
114 defineProperty(Object.prototype, "forEach", function(func) {
115 for (var prop in this)
116 {
117 // call the callback only for props directly defined in 'this'
118 if (this.hasOwnProperty(prop))
119 func(this[prop], prop);
120 }
121 });
122
123 // find the property for which a callback returns true
124 defineProperty(Object.prototype, "propWhich", function(func) {
125 for (var prop in this)
126 {
127 if (this.hasOwnProperty(prop) && func(this[prop], prop))
128 return prop;
129 }
130 return null;
131 });
132
133 // find the property value for which a callback returns true
134 defineProperty(Object.prototype, "valWhich", function(func) {
135 for (var prop in this)
136 {
137 var val;
138 if (this.hasOwnProperty(prop) && func(val = this[prop], prop))
139 return val;
140 }
141 return null;
142 });
143
144 // htmlify a string - convert markup-significant characters to & entities
145 String.prototype.htmlify = function() {
146 return this.replace(/[<>&"']/g, function(m) {
147 return { '<': "&lt;", '>': "&gt;", '&': "&amp;",
148 '"': "&#34;", '\'': "&#39;" }[m];
149 });
150 };
151
152 // remove html quoting from a string
153 String.prototype.unhtmlify = function() {
154 return this.replace(/&(gt|lt|amp|quot|nbsp|#[0-9]+);/ig,
155 function(m, i) {
156 var r = { 'gt': '>', 'lt': '<', 'amp': '&', 'quot': '"',
157 'nbsp': ' ' }[i.toLowerCase()];
158 if (r)
159 return r;
160 else
161 return String.fromCharCode(parseInt(i));
162 });
163 }
164
165 // trim leading and trailing spaces from a string
166 String.prototype.trim = function() {
167 return this.replace(/^\s+|\s+$/g, "");
168 };
169
170 // convenience method: find an item in an array
171 if (!Array.prototype.indexOf) {
172 Array.prototype.indexOf = function(val) {
173 for (var i = 0 ; i < this.length ; ++i)
174 {
175 if (val == this[i])
176 return i;
177 }
178 return -1;
179 };
180 }
181
182 // convenience method: find the index for a value matching a callback
183 if (!Array.prototype.indexWhich) {
184 Array.prototype.indexWhich = function(test) {
185 for (var i = 0 ; i < this.length ; ++i)
186 {
187 if (test(this[i], i))
188 return i;
189 }
190 return -1;
191 };
192 }
193
194 // convenience method: find a value matching a callback
195 if (!Array.prototype.valWhich) {
196 Array.prototype.valWhich = function(test) {
197 for (var i = 0 ; i < this.length ; ++i)
198 {
199 var v = this[i];
200 if (test(v, i))
201 return v;
202 }
203 return -1;
204 };
205 }
206
207 // convenience method: map items in an array
208 if (!Array.prototype.map) {
209 Array.prototype.map = function(mapping) {
210 var ret = [];
211 for (var i = 0 ; i < this.length ; ++i)
212 ret.push(mapping(this[i], i));
213 return ret;
214 };
215 }
216
217 // convenience method: filter an array
218 if (!Array.prototype.filter) {
219 Array.prototype.filter = function(filterFunc) {
220 var ret = [];
221 for (var i = 0 ; i < this.length ; ++i)
222 {
223 var ele = this[i];
224 if (filterFunc(ele, i))
225 ret.push(ele);
226 }
227 return ret;
228 };
229 }
230
231 // convenience method: get the top element of a stack-like array
232 Array.prototype.top = function() {
233 if (this.length)
234 return this[this.length - 1];
235 else
236 return null;
237 };
238
239 // override our copy method for arrays
240 Array.prototype.copy = function(deep) {
241
242 // create the new array
243 var newArray = [];
244
245 // copy each element
246 for (var i = 0 ; i < this.length ; ++i)
247 {
248 // get this value
249 var val = this[i];
250
251 // make a deep copy of object values, if desired
252 if (deep && typeof(val) == "object")
253 val = val.copy(true);
254
255 // set the new value
256 newArray[i] = val;
257 }
258
259 // return the new array
260 return newArray;
261 };
262
263 // override the for-each enumerator for arrays - just step through
264 // the index values from 0 to length
265 Array.prototype.forEach = function(func) {
266 for (var i = 0, len = this.length ; i < len ; ++i)
267 func(this[i], i);
268 };
269
270 // add a listener for mouse down events on the main document,
271 // for closing spring-loaded pop-up objects
272 addEventHandler(document, "mousedown", popupCloser);
273
274 // set our custom javascript error handler
275 window.onerror = function(msg, url, lineNum) {
276
277 // generate a stack trace
278 var s = getStackTrace();
279
280 // the top element is the onerror handler we're currently in,
281 // which isn't part of the error, so clip it out of the list
282 s.shift();
283
284 // create a human-readable trace listing
285 s = s.map(function(ele) {
286 return ele.desc.htmlify(); }).join("<br>");
287
288 // log the error
289 logError("An error occurred in the " + selfNoun
290 + "'s user interface programming. This is probably a "
291 + "bug that should be reported to the "
292 + selfNoun + "'s author."
293 + errorRecoveryAction,
294 "Javascript error: " + msg.htmlify()
295 + "<br>Window: " + pageName
296 + " (" + url.htmlify() + ")"
297 + "<br>Line: " + lineNum
298 + (s ? "<br>Call stack:<div class=\"errorSubDetail\">"
299 + s + "</div>": ""),
300 { failed: true, succeeded: false });
301
302 return true;
303 };
304
305 // set up an unload handler
306 addEventHandler(window, "beforeunload", unloadCleanup);
307 }
308
309 // window unload handler
310 function unloadCleanup()
311 {
312 // cancel outstanding ajax requests
313 cancelServerRequests();
314 }
315
316 /*
317 * Create an object with the same prototype as an existing object. To
318 * invoke, call SameProto.create(obj).
319 */
320 function CopyProto() { }
321 CopyProto.create = function(obj)
322 {
323 /*
324 * This is a bit tricky, but here's how this works. The ECMA spec says
325 * that a new object's prototype is set to its constructor's prototype
326 * *at the moment of creation*. So step 1 is to prepare the
327 * constructor's prototype so that it matches the source object's; then
328 * step 2 is to instantiate the object with 'new'.
329 */
330 CopyProto.prototype = obj.constructor.prototype;
331 return new CopyProto();
332 }
333
334
335 /*
336 * Get a stack trace. This returns a list of function call descriptors.
337 */
338 function getStackTrace()
339 {
340 // start with an empty list
341 var s = [];
342
343 // walk up the call stack starting with our caller
344 for (var c = arguments.callee.caller ; c ; c = c.caller)
345 {
346 // Make sure we haven't encountered this caller before.
347 // Javascript uses the function object to represent a call
348 // level, which makes it impossible to walk a recursive
349 // stack because each recursive call overwrites the caller
350 // information in the function object. JS of course has
351 // the actual caller information internally, but it's
352 // not exposed through the standard APIs.
353 for (var i = 0 ; i < s.length ; ++i)
354 {
355 if (s[i].fn == c)
356 {
357 s.push({ desc: "(recursive)" });
358 return s;
359 }
360 }
361
362 // set up the level descriptor
363 var ele = { fn: c, args: c.arguments };
364
365 // get a formatted version of the argument list
366 var a = [];
367 if (c.arguments)
368 {
369 for (var i = 0 ; i < c.arguments.length ; ++i)
370 a.push(valToDesc(c.arguments[i]));
371 }
372
373 // build the human-readable function call description
374 ele.desc = funcToDesc(c) + "(" + a.join(", ") + ")";
375
376 // add it to the list
377 s.push(ele);
378 }
379
380 // return the trace
381 return s;
382 }
383
384 function valToDesc(v)
385 {
386 // convert to string
387 switch (typeof(v))
388 {
389 case "function":
390 return funcToDesc(v);
391 break;
392
393 case "string":
394 // shorten it if it's long
395 if (v.length > 60)
396 v = v.substr(0, 30) + "..." + v.substr(v.length - 20);
397
398 // escape special characters
399 return "\""
400 + v.replace(/["\\\n\r\v\f\t]/g, function(m) {
401 return { '"': '\\"', '\n': '\\n',
402 '\r': '\\r', '\\': '\\\\',
403 '\v': '\\v', '\f': '\\f', '\t': '\\t'
404 }[m]; })
405 + "\"";
406
407 case null:
408 return "null";
409
410 case "undefined":
411 return "undefined";
412
413 default:
414 if (v == null)
415 {
416 return "null";
417 }
418 else if (v instanceof Array)
419 {
420 var a = [], amax = (v.length > 8 ? 5 : 8);
421 for (var i = 0 ; i < v.length && i < amax ; ++i)
422 a.push(valToDesc(v[i]));
423
424 if (v.length > amax)
425 a.push("... (" + (v.length - amax) + " more)");
426
427 return "[" + a.join(", ") + "]";
428 }
429 else
430 {
431 try { v = v.toString(); } catch (e) { v = typeof(v); }
432 if (v.match(/\[object\s+([a-z0-9_$]+)\]/i))
433 v = "object<" + RegExp.$1 + ">";
434 return v;
435 }
436 return typeof(v);
437 }
438 }
439
440 // format a function reference to a human-readable form (primarily for
441 // stack trace generation)
442 function funcToDesc(f)
443 {
444 // get the function in string form, and convert all whitespace
445 // (including newlines) to ordinary spaces
446 fn = f.toString().replace(/[ \n\r\v\f\t]+/g, " ");
447
448 // For a named function, the usual toString form is like this:
449 // function name(args) { body }
450 // Some browsers return this same form for anonymous functions,
451 // supplying 'anonymous' as the name.
452 if (fn.match(
453 /^function\s+([a-z0-9_$]+)\s*\([a-z0-9_$,\s]*\)\s*(\{.*)$/i))
454 {
455 // we have the basic syntax - if the name is 'anonymous', show
456 // using our anonymous function formatter; otherwise just use
457 // the function name
458 if (RegExp.$1 == "anonymous")
459 {
460 // The browser is using literally "anonymous" as the name.
461 // Pull out the body to show for context. Use a clipped
462 // version to keep the size reasonable.
463 var body = anonFuncToDesc(RegExp.$2);
464
465 // add the event handler name, if applicable
466 return funcToEventDesc(f) + body;
467 }
468 else
469 {
470 // Named function.
471 var body = RegExp.$2;
472 fn = RegExp.$1;
473
474 // Some browsers return a synthesized name based on the event
475 // attribute for an in-line event handler. If we have an
476 // event name, and the function has the same name, assume
477 // this is the situation, so include the function body for
478 // context as though it were an anonymous function.
479 var ev = funcToEventDesc(f);
480 if (ev && ev.substr(ev.indexOf(".") + 1) == fn)
481 return ev + anonFuncToDesc(body);
482
483 // it's just a regular named function
484 return fn;
485 }
486 }
487 else
488 {
489 // it's not in the standard format, so it's probably some other
490 // anonymous function formatting
491 return funcToEventDesc(f) + anonFuncToDesc(fn);
492 }
493 }
494
495 // Get the event object for a function call, if applicable
496 function eventFromFunc(f)
497 {
498 // Check for an event object in the function arguments. If we have
499 // at least one argument, and it's an object, and it has a "type"
500 // property, and the type property looks like "onxxx", assume it's
501 // an event object.
502 if (f.toString().match(/^function\s+[a-z]+\s*\(event\)/)
503 && f.arguments
504 && f.arguments.length >= 1
505 && f.arguments[0] != null
506 && typeof(f.arguments[0]) == "object"
507 && typeof(f.arguments[0].type) == "string"
508 && f.arguments[0].type.match(/^[a-z]+/))
509 return f.arguments[0];
510
511 // if this is IE, use the window.event object
512 if (window.event)
513 return window.event;
514
515 // no event object
516 return null;
517 }
518
519 // Check for an event handler. If this is a top-level function,
520 // and the target of the event has an attribute for the event
521 // method, and the attribute points to this function, we must be
522 // the handler for the event. In this case we can supply the
523 // name of the event and the ID or node type of the target object
524 // as additional context.
525 function funcToEventDesc(f)
526 {
527 // only top-level functions can be event handlers
528 if (f.caller != null)
529 return "";
530
531 // we obviously need to have an event for this to be an event handler
532 var ev = eventFromFunc(f);
533 if (!ev)
534 return "";
535
536 // figure the event attribute, based on the event type name
537 var attr = "on" + ev.type;
538
539 // The event handler could be on the target, or on a parent object
540 // by event bubbling. Scan up the parent tree for an object with
541 // a handler pointing to our function.
542 for (var targ = getEventTarget(ev) ; targ ; targ = targ.parentNode)
543 {
544 // check for a handler in this object pointing to our function
545 if (targ[attr] == f)
546 {
547 // Found it - this must be the handler we're running. Return
548 // the ID of the element (or just the tag name if there's no ID)
549 // and the event attribute name as the event description.
550 return (targ.id ? targ.id : targ.nodeName)
551 + "." + attr;
552 }
553 }
554
555 // didn't find a handler
556 return "";
557 }
558
559 // Format an anonymous function body to human-readable form. We'll
560 // show a fragment of the source code body of the function, if available.
561 function anonFuncToDesc(f)
562 {
563 // some browsers give us the format "{ javascript:source }" for
564 // in-line event handlers (onclick, etc) - remove the "javascript:".
565 if (f.match(/^\{\s*javascript:\s*(.*)$/i))
566 f = "{ " + RegExp.$1;
567
568 // If the body is short, return it unchanged. If it's long, clip
569 // out the middle to keep the display reasonably concise - keep
570 // the head and tail for context, and keep a little more of the
571 // head than the tail, since that's usually the most easily
572 // recognizable portion (for the human reader).
573 if (f.length > 60)
574 f = f.substr(0, 30) + "..." + f.substr(f.length - 20);
575
576 // return what we found
577 return f;
578 }
579
580 // request our initial state
581 function getInitState()
582 {
583 // send the initial status request for this window
584 serverRequest("/webui/getState?window=" + pageName,
585 ServerRequest.Command,
586 function(req, resp) { window.onGameState(req, resp); });
587 }
588
589
590 /* ------------------------------------------------------------------------ */
591 /*
592 * Generic document-level key handler, with focus setting. This does all
593 * the work of genericDocKey(), plus we set the default focus control if
594 * focus isn't already in a key-handling control.
595 *
596 * Any document objects that don't have their own special handling for
597 * keystrokes at the document level can install this default handler at
598 * load time. This handler looks for a default focus destination, and
599 * establishes focus there. The default location is normally the main
600 * command line in the main command transcript window. This handler makes
601 * the standard terminal-style UI a little smoother by always sending focus
602 * back to the command line when the user types something with the focus
603 * set somewhere that doesn't accept input.
604 *
605 * Some windows (such as the top-level window) have their own focus
606 * management rules that differ a little from ours, so they shouldn't use
607 * this. Instead, they should do their focus management, then call
608 * genericDocKey(), which does the rest of the generic key handling besides
609 * the focus setting.
610 */
611 function genericDocKeyFocus(desc)
612 {
613 // if it's a text editing key, try setting the default focus
614 if (isFieldKey(desc))
615 setDefaultFocus(desc, window);
616
617 // handle a generic document key
618 genericDocKey(desc);
619
620 // bubble the event
621 return true;
622 }
623
624 /*
625 * Handle a generic document-level keystroke. This should be called from
626 * each window's document key handler.
627 *
628 * First, we check to see if the key is going to an input control that has
629 * focus. If so, we let the key pass through without further attention, so
630 * that the control gets the key.
631 *
632 * If there's no input control with focus:
633 *
634 * - We try sending the key to the main window for server event handling.
635 * If the server has asked for an input event, we send the key as the
636 * requested event.
637 *
638 * - For certain keys, we suppress the default browser handling. Since our
639 * UI is primarily oriented around the command line, we want certain keys
640 * to keep their command-line meanings even between inputs. This is in
641 * case the the user is typing faster than we can keep up with; we don't
642 * want the the key to suddenly change meaning when the user thinks it's an
643 * editing key. In particular, the Backspace and Escape keys are common
644 * editing keys that would be disruptive to the UI if the browser applied
645 * their usual accelerator meanings of "go to the previous page" and "stop
646 * downloading stuff on this page".
647 */
648 function genericDocKey(desc)
649 {
650 // if the current focus processes the key, allow the default handling
651 var ae = document.activeElement;
652 if (eleKeepsFocus(ae, desc))
653 return;
654
655 // check to see if the server wants keystroke events
656 $win().keyToServer(desc);
657
658 // this key will be processed at the document level, so filter it
659 switch (desc.keyName)
660 {
661 case "U+0008":
662 case "U+001B":
663 // block the default handling for these keys
664 preventDefault(desc.event);
665 break;
666 }
667 }
668
669 /*
670 * Determine if the given keyboard event is a "field" key. Returns true if
671 * this is a key that's meaningful to an input field: a regular printable
672 * character, or a cursor movement key (arrow, Home, End, etc).
673 */
674 function isFieldKey(desc)
675 {
676 // get the key
677 var k = desc.keyName;
678
679 switch (k)
680 {
681 case "Shift":
682 case "Control":
683 case "Alt":
684 case "CapsLock":
685 case "PageUp":
686 case "PageDown":
687 case "NumLock":
688 case "ScrollLock":
689 case "Win": // Windows/Start shift keys
690 case "Pause":
691 case "F1":
692 case "F2":
693 case "F3":
694 case "F4":
695 case "F5":
696 case "F6":
697 case "F7":
698 case "F8":
699 case "F9":
700 case "F10":
701 case "F11":
702 case "F12":
703 case "U+0009": // tab
704 // none of these keys directly affect the field, so ignore them
705 return false;
706
707 case "U+0008":
708 case "U+001B":
709 // these are explicitly field keys
710 return true;
711
712 default:
713 // if the Ctrl or Alt keys are down, don't consider this a field
714 // key, since it's probably an accelerator or shortcut instead
715 if (desc.ctrlKey || desc.altKey || desc.metaKey)
716 return false;
717
718 // looks like a regular field key
719 return true;
720 }
721 }
722
723 /*
724 * Set the default focus. If the focus isn't currently in a control that
725 * accepts keyboard input, we'll move the focus to the default command
726 * input line, if there is one.
727 */
728 function setDefaultFocus(desc, fromWin)
729 {
730 // check for retained focus
731 if (evtKeepsFocus(desc))
732 return;
733
734 // if we have a parent window, ask it to look for a default
735 var par = window.parent;
736 if (par && par != window)
737 {
738 // there's a parent window - pass the request up to it
739 par.setDefaultFocus(desc, fromWin);
740 }
741 else
742 {
743 // there's no parent; try setting the default focus to a child window
744 setDefaultFocusChild(desc, fromWin);
745 }
746 }
747
748 /*
749 * Determine if focus should say put for the current keyboard event.
750 */
751 function evtKeepsFocus(desc)
752 {
753 // if there's no keyboard event, focus can move
754 if (!desc || !desc.event)
755 return false;
756
757 // There's a weird bug in IE where a control has focus for event
758 // purposes but doesn't actually have keyboard focus. When this
759 // happens, the actual Windows event goes to the actual focus control,
760 // which isn't part of the JS event bubble.
761 var ae = getEventTarget(desc.event);
762
763 // if the event is directed to an input control, leave it where it is
764 for ( ; ae ; ae = ae.parentNode)
765 {
766 // if focus is already in an input object of some kind, leave it there
767 if (eleKeepsFocus(ae, desc))
768 return true;
769 }
770
771 // didn't find a focus keeper
772 return false;
773 }
774
775 /*
776 * Determine if the given element should retain focus for the given
777 * keyboard event. We'll return true if the element is a focusable input
778 * control (an INPUT, TEXTAREA, or SELECT), or it's an <A HREF> and the
779 * event is the Return key (a return key in a hyperlink selects the
780 * hyperlink).
781 */
782 function eleKeepsFocus(ele, desc)
783 {
784 // if there's no element, it doesn't keep focus
785 if (!ele)
786 return false;
787
788 // Keep focus for all events if this is an input control of some
789 // kind (INPUT, TEXTAREA, or SELECT).
790 if (ele.nodeName == "INPUT"
791 || ele.nodeName == "TEXTAREA"
792 || ele.nodeName == "SELECT")
793 return true;
794
795 // For IE, also treat any element with contentEditable=true as an
796 // input control.
797 if (BrowserInfo.ie && ele.isContentEditable)
798 return true;
799
800 // If this is an <A HREF> element, and the event is the Return key,
801 // keep focus in the hyperlink. Pressing Return while a hyperlink
802 // has focus is usually equivalent to a click in the hyperlink, so
803 // this event is meaningful with focus left as it is.
804 if (ele.nodeName == "A" && ele.href && desc && desc.keyName == "Enter")
805 return true;
806
807 // the event isn't a meaningful input keystroke for this control
808 return false;
809 }
810
811 /*
812 * Move focus to a suitable child window. When we reach the top-level
813 * container window, it will call this to start working back down the
814 * window tree to find a suitable child to set focus in.
815 */
816 function setDefaultFocusChild(desc, fromWin)
817 {
818 // by default, do nothing; other window types can override it (notably
819 // the layout window)
820 }
821
822 /* ------------------------------------------------------------------------ */
823 /*
824 * Default document mouse-click handler: close any spring-loaded popups
825 * that are currently open.
826 */
827 function popupCloser(ev)
828 {
829 // get the event
830 var ev = getEvent(ev);
831
832 // if there's a spring-loaded popup active, and the event isn't within
833 // the top popup, close the top popup
834 if (springPopups.length > 0
835 && !isEventInObject(ev, springPopups.top().ele)
836 && !isEventInObject(ev, springPopups.top().openerEle))
837 closePopup();
838
839 // if we have a parent window, propagate the click
840 if (window.parent && window.parent != window)
841 window.parent.popupCloser(ev);
842 }
843
844 /*
845 * Close the topmost active popup
846 */
847 function closePopup(ele)
848 {
849 // if there's nothing to close, don't go on
850 if (springPopups.length == 0)
851 return;
852
853 // if they want to close a specific popup, and it's not the top
854 // one, ignore the request - this could be a queued event related
855 // to the event that already closed the indicated popup
856 if (ele && springPopups.top().ele != ele)
857 return;
858
859 // remove the top popup from the list
860 var s = springPopups.pop();
861
862 // hide the popup
863 s.ele.style.display = "none";
864
865 // call its 'close' method, if it has one
866 if (s.close)
867 s.close();
868
869 // if there's a default focus element, restore focus there
870 if (s.focusEle)
871 {
872 var fe = $(s.focusEle);
873 fe.focus();
874 if (fe.nodeName == "INPUT" && fe.type == "text")
875 setSelRangeInEle(fe);
876 }
877 }
878
879 /*
880 * Open a popup. 'ele' is the outermost html element of the popup, and
881 * 'close' is an optional function to call to close the popup. If
882 * 'closeFocusEle' is specified, it's the element where we'll set focus
883 * when the popup closes.
884 */
885 function openPopup(ev, ele, close, closeFocusEle, openerEle)
886 {
887 // first make sure we don't have another popup to close
888 popupCloser(ev);
889
890 // add it to the popup list
891 springPopups.push({
892 ele: ele,
893 close: close,
894 focusEle: closeFocusEle,
895 openerEle: openerEle
896 });
897
898 // move the focus to the popup object
899 if (ele.focus)
900 ele.focus();
901
902 // if we haven't added our keyboard handlers, do so now
903 if (!ele.popupKeyHandlers)
904 {
905 // add a key handler to catch return and escape while we have focus
906 var k = function(desc) {
907 if (desc.keyName == "Enter" || desc.keyName == "U+001B")
908 {
909 closePopup(ele);
910 cancelBubble(desc.event);
911 return false;
912 }
913 return true;
914 };
915
916 // Also set up a focus-loss handler: if focus leaves the popup
917 // (and its children), and focus isn't going to the opener element,
918 // close the popup. Not all elements can acquire focus in the
919 // first place on all browsers, so it's basically a no-op on some
920 // browsers, but it addresses some edge cases on IE in particular.
921 var f = function(ev) {
922 var ae = document.activeElement;
923 if (!(ae && (isChildElement(ele, ae) || ae == openerEle)))
924 closePopup(ele);
925 };
926
927 addEventHandler(ele, "keydown", function(ev) { return $kd(ev, k); });
928 addEventHandler(ele, "keypress", function(ev) { return $kp(ev, k); });
929 addEventHandler(ele, "blur", f);
930 ele.popupKeyHandlers = true;
931 }
932
933 // don't propagate this event any further
934 cancelBubble(ev);
935 }
936
937 // active popup list
938 var springPopups = [];
939
940
941 /* ------------------------------------------------------------------------ */
942 /*
943 * Shorthand to retrieve an object by name. Call like this:
944 *
945 *. $(obj, [sub [, sub2 [...]]])
946 *
947 * If 'obj' is a string, we treat it as a path of elements separated by
948 * periods. Each element can be:
949 *
950 * - an object ID
951 *. - a class name, given in square brackets
952 *. - a node name (tag), given in angle brackets
953 *
954 * For example, "mainDiv.[details]" returns the first child with
955 * class="details" of the element with ID "mainDiv". "form3.<INPUT>"
956 * returns the first INPUT element of form3.
957 *
958 * If 'obj' is any other type, we return it as-is. This allows passing in
959 * an element reference without first checking its type, since it will
960 * simply be returned unchanged. This makes it easy to write routines that
961 * accept path names or references as arguments: if the argument is a path
962 * name, it will be translated to an element; if it's already an element,
963 * it will be returned as given.
964 *
965 * If any 'sub' arguments are given, they must be strings giving the same
966 * path notation above. We'll search for each string in turn as a child
967 * path of the resulting object for the previous argument. This allows
968 * efficient searching within a part of the DOM tree for which you already
969 * have the root object.
970 */
971 function $()
972 {
973 // scan each argument
974 for (var obj = document.body, ac = 0 ; ac < arguments.length ; ++ac)
975 {
976 // get this argument
977 var arg = arguments[ac];
978
979 // if it's a string, look it up by name
980 if (typeof(arg) == "string")
981 {
982 // break it up into dot-delimited path elements
983 var path = arg.split(".");
984
985 // find each item in the path
986 for (var i = 0 ; i < path.length ; ++i)
987 {
988 // check the syntax for this element
989 var e = path[i];
990 if (e.match(/^\[.*\]$/))
991 {
992 // search by class name
993 e = e.substr(1, e.length - 2);
994 obj = breadthSearch(
995 obj, function(x) { return x.className == e; });
996 }
997 else if (e.match(/^\<.*\>$/))
998 {
999 // search by tag name
1000 e = e.substr(1, e.length - 2);
1001 obj = breadthSearch(
1002 obj, function(x) { return x.nodeName == e; });
1003 }
1004 else
1005 {
1006 // search by ID
1007 if (obj == document.body)
1008 obj = document.getElementById(e);
1009 else
1010 obj = breadthSearch(
1011 obj, function(x) { return x.id == e; });
1012 }
1013
1014 // if we didn't find a match at this point, give up
1015 if (!obj)
1016 return null;
1017 }
1018 }
1019 else if (typeof(arg) == "object")
1020 {
1021 // the argument is the pre-resolved object
1022 obj = arg;
1023 }
1024 else
1025 {
1026 // invalid type
1027 return null;
1028 }
1029 }
1030
1031 // return what we ended with
1032 return obj;
1033 }
1034
1035 /*
1036 * Do a breadth-first search for a child matching the given condition
1037 */
1038 function breadthSearch(obj, cond)
1039 {
1040 // first, search all direct children of 'obj'
1041 var chi;
1042 for (chi = obj.firstChild ; chi ; chi = chi.nextSibling)
1043 {
1044 if (cond(chi))
1045 return chi;
1046 }
1047
1048 // didn't find it among direct children, so search grandchildren
1049 for (chi = obj.firstChild ; chi ; chi = chi.nextSibling)
1050 {
1051 // skip certain types
1052 if (chi.nodeName == "SELECT")
1053 continue;
1054
1055 // search this child's children
1056 var gc = breadthSearch(chi, cond);
1057 if (gc)
1058 return gc;
1059 }
1060
1061 // didn't find it
1062 return null;
1063 }
1064
1065 /* ------------------------------------------------------------------------ */
1066 /*
1067 * Event handler manipulation. These routines let you attach and remove
1068 * event handler functions. An element can have any number of attached
1069 * handlers; these coexist with one another and with any in-line "onxxx"
1070 * handler defined in the element's HTML description.
1071 */
1072 function addEventHandler(obj, eventName, func)
1073 {
1074 obj = $(obj);
1075 if (obj.addEventListener)
1076 obj.addEventListener(eventName, func, false);
1077 else if (obj.attachEvent)
1078 {
1079 obj.attachEvent("on" + eventName, func);
1080
1081 // save it in our private list as well
1082 if (!obj.$eventList)
1083 obj.$eventList = [];
1084 obj.$eventList.push([eventName, func]);
1085 }
1086 }
1087
1088 function removeEventHandler(obj, eventName, func)
1089 {
1090 obj = $(obj);
1091 if (obj.removeEventListener)
1092 obj.removeEventListener(eventName, func, false);
1093 else if (obj.detachEvent)
1094 {
1095 obj.detachEvent("on" + eventName, func);
1096
1097 // remove it from our private list
1098 var l = obj.$eventList;
1099 if (l)
1100 {
1101 for (var i = 0 ; i < l.length ; ++i)
1102 {
1103 if (l[i][0] == eventName && l[i][1] == func)
1104 {
1105 l.splice(i, 1);
1106 break;
1107 }
1108 }
1109 }
1110 }
1111 }
1112
1113 /* ------------------------------------------------------------------------ */
1114 /*
1115 * Synthetic events. To fire an event, first create the event object with
1116 * createEvent(), then send it with sendEvent().
1117 */
1118
1119 /*
1120 * Create an event. 'type' is the class of the event object, taken from
1121 * the list below. 'name' is the name of the event, which is the root name
1122 * without the "on" prefix.
1123 *
1124 * 'params' is an object giving extra parameters for the event creation.
1125 * These vary by event class:
1126 *
1127 * - bubble: event bubbles up the hierarchy (default=true)
1128 *. - cancel: event can be canceled (default=true)
1129 *. - view: the window in which the event occurs (default=window)
1130 *. - detail: mouse click count, wheel count, etc (default=1)
1131 *. - screenX: screen x coordinate (default=0)
1132 *. - screenY: screen y coordinate (default=0)
1133 *. - clientX: client x coordinate (default=0)
1134 *. - clientY: client y coordinate (default=0)
1135 *. - ctrlKey: control key setting (default=false)
1136 *. - altKey: alt key setting (default=false)
1137 *. - shiftKey: shift key setting (default=false)
1138 *. - metaKey: meta key setting (default=false)
1139 *. - button: mouse button number (default=1)
1140 *. - relatedTarget: DOM element related to the mouse event (default=null)
1141 *
1142 * The event name can be one of the standard browser events, or can be a
1143 * custom invented name. For reference, we list the most common standard
1144 * names for the supported event classes below.
1145 *
1146 * The event types (classes) that we handle are:
1147 *
1148 * "Event": base event (blur, change, copy, cut, error, focus, input, load,
1149 * paste, reset, resize, scroll, select, submit, onload)
1150 *
1151 * "MouseEvent": mouse event (click, contextmenu, dblclick, drag, drop,
1152 * mousedown, mousemove, mouseout, mouseover, mouseup, mousewheel)
1153 *
1154 * For the above event types, we'll call the class-specific initializer for
1155 * the event, using the parameters specified in 'params'. These event
1156 * types are sufficiently cross-browser that we can support them uniformly.
1157 * Other classes are not universally supported, so we don't provide
1158 * specific handling for them. We'll return the event object that the
1159 * browser gave us, but we won't initialize it.
1160 */
1161 function createEvent(type, name, params)
1162 {
1163 // get a parameter with a default
1164 var p = function(prop, dflt) {
1165 return params && (prop in params) ? params[prop] : dflt;
1166 };
1167
1168 // create the event
1169 var e;
1170 if (document.createEvent)
1171 {
1172 // firefox, opera, safari... basically everyone but IE
1173 e = document.createEvent(type);
1174 switch (type)
1175 {
1176 case "Event":
1177 e.initEvent(name,
1178 p("bubble", true),
1179 p("cancel", true));
1180 break;
1181
1182 case "MouseEvent":
1183 e.initMouseEvent(name,
1184 p("bubble", true),
1185 p("cancel", true),
1186 p("view", window),
1187 p("detail", 1),
1188 p("screenX", 0),
1189 p("screenY", 0),
1190 p("clientX", 0),
1191 p("clientY", 0),
1192 p("ctrlKey", false),
1193 p("altKey", false),
1194 p("shiftKey", false),
1195 p("metaKey", false),
1196 p("button", 1),
1197 p("relatedTarget", null));
1198 break;
1199
1200 default:
1201 break;
1202 }
1203 }
1204 else if (document.createEventObject)
1205 {
1206 // IE has to do everything its own way, of course...
1207 e = document.createEventObject();
1208 e.type = name;
1209 switch (type)
1210 {
1211 case "MouseEvent":
1212 e.altKey = p("altKey", false);
1213 e.ctrlKey = p("ctrlKey", false);
1214 e.shiftKey = p("shiftKey", false);
1215 e.metaKey = p("metaKey", false);
1216 e.button = p("button", 1);
1217 e.clientX = p("clientX", 0);
1218 e.clientY = p("clientY", 0);
1219 e.fromElement = p("relatedTarget", null);
1220 e.toElement = p("relatedTarget", null);
1221 e.offsetX = 0; // $$$
1222 e.offsetY = 0; // $$$
1223 break;
1224 }
1225 }
1226 else
1227 {
1228 // no event creation function availble
1229 e = null;
1230 }
1231
1232 return e;
1233 }
1234
1235 /*
1236 * Send an event
1237 */
1238 function sendEvent(ele, ev)
1239 {
1240 if (ele.fireEvent)
1241 {
1242 // the IE way - set the target
1243 ev.srcElement = ele;
1244
1245 // for mouseover and mouseout, set the to/from element properly
1246 if (ev.type == "mouseover")
1247 ev.toElement = ele;
1248 else if (ev.type == "mouseout")
1249 ev.fromElement = ele;
1250
1251 // fire the event
1252 try
1253 {
1254 return ele.fireEvent("on" + ev.type, ev);
1255 }
1256 catch (e)
1257 {
1258 // IE doesn't allow synthesized events; it throws an "invalid
1259 // argument" error if we attempt it. Fall back on manually
1260 // calling the event handlers.
1261 for (ev.cancelBubble = false ; ele && !ev.cancelBubble ;
1262 ele = ele.parentNode)
1263 {
1264 // dispatch to our custom handlers in this element
1265 var l = ele.$eventList;
1266 if (l)
1267 {
1268 l.forEach(function(item) {
1269 if (item[0] == ev.type)
1270 item[1](ev);
1271 });
1272 }
1273
1274 // dispatch to the in-line handler for this element
1275 if (("on" + ev.type) in ele)
1276 ele["on" + ev.type](ev);
1277 }
1278 }
1279 }
1280 else if (ele.dispatchEvent)
1281 {
1282 // firefox, safari, opera... IE-bar
1283 return ele.dispatchEvent(ev);
1284 }
1285 else
1286 {
1287 return false;
1288 }
1289 }
1290
1291
1292 /* ------------------------------------------------------------------------ */
1293 /*
1294 * Add a keyboard event handler to an object. This sets up an event
1295 * handler based on our cross-browser keyboard package, so you only need to
1296 * write a single event handler for the combined keypress and keydown
1297 * events.
1298 */
1299 function addKeyHandler(obj, func, ctx)
1300 {
1301 // look up the element, if given by name
1302 obj = $(obj);
1303
1304 // set up the keydown and keypress delegation functions
1305 var kd = function(ev) { return $kd(ev, func, ctx); };
1306 var kp = function(ev) { return $kp(ev, func, ctx); };
1307
1308 // set up a record of the function, for later removal if desired
1309 if (!obj.keyHandlers)
1310 obj.keyHandlers = [];
1311 obj.keyHandlers.push({ func: func, kd: kd, kp: kp });
1312
1313 // add the delegation handlers
1314 addEventHandler(obj, "keydown", kd);
1315 addEventHandler(obj, "keypress", kp);
1316 }
1317
1318 /*
1319 * Remove a keyboard event handler
1320 */
1321 function removeKeyHandler(obj, func, ctx)
1322 {
1323 // look up the element, if given by name
1324 obj = $(obj);
1325
1326 // find the list of handlers we've defined for this element
1327 var kh = obj.keyHandlers;
1328 if (kh)
1329 {
1330 // search for the user function
1331 for (var i = 0 ; i < kh ; ++i)
1332 {
1333 // check for a match to the user function
1334 if (kh[i].func == func && kh[i].ctx == ctx)
1335 {
1336 // found it - remove the delegation handlers
1337 removeEventHandler(obj, "keydown", kh[i].kd);
1338 removeEventHandler(obj, "keypress", kh[i].kp);
1339
1340 // remove this element from the handler list
1341 kh.splice(i, 1);
1342
1343 // no need to keep looking
1344 break;
1345 }
1346 }
1347 }
1348 }
1349
1350
1351 /* ------------------------------------------------------------------------ */
1352 /*
1353 * Abstract event handler object. This simplifies handling for code that's
1354 * conditional on some external event or process completing. Use the
1355 * whenDone() method to invoke a callback if and when the event has
1356 * occurred: if the event has already occurred, we'll invoke the callback
1357 * immediately, otherwise we'll queue it up to be invoked when the event
1358 * occurs.
1359 *
1360 * The 'ele' and 'eventName' arguments are optional. If you provide them,
1361 * we'll automatically link the AbsEvent to the given native browser event
1362 * on the given element. To do this, we'll set up an event listener for
1363 * the given event on the given element that invokes the AbsEvent's fire()
1364 * method when the native event occurs.
1365 *
1366 * If you don't provide 'ele' and 'eventName', you must manually call
1367 * fire() to trigger the AbsEvent when appropriate.
1368 *
1369 * There are two main uses for AbsEvent:
1370 *
1371 * - External events, such as browser events or Flash movie events. For
1372 * this type of use, you can supply the 'ele' and 'eventName' arguments to
1373 * set up a handler automatically, OR you can write your own event handler,
1374 * which calls the AbsEvent object's fire() method when the native event
1375 * occurs. (It might seem redundant to have AbsEvent at all for native
1376 * events. The value of AbsEvent is that it easily lets you attach
1377 * multiple handlers to the event, and you don't have to worry about
1378 * whether or not the event has happened yet when you install a handler: if
1379 * the event has already happened, the handler will be invoked
1380 * immediately.)
1381 *
1382 * - Pseudo-threads. This is a long-running task that you break up into a
1383 * series of steps, and then carry out the steps gradually using timeouts.
1384 * The idea is to allow the UI to remain responsive while the long task is
1385 * being executed. For this, use the startThread() method to initiate the
1386 * task.
1387 */
1388 function AbsEvent(ele, eventName)
1389 {
1390 // we're not done yet, and we have no callbacks queued yet
1391 this.isDone = false;
1392 this.cb = [];
1393
1394 // set up our event listener, if applicable
1395 if (ele && eventName)
1396 {
1397 var ae = this;
1398 addEventHandler(ele, eventName, function() { ae.fire(); });
1399 }
1400
1401 // return the new object
1402 return this;
1403 }
1404
1405 /*
1406 * Invoke a callback if and when the event has occurred. If the event has
1407 * already occurred, we'll invoke the callback immediately; otherwise we'll
1408 * enqueue it to be invoked when the event fires.
1409 *
1410 * If 'hurry' is true, and this is a pseudo-thread, we'll set the thread's
1411 * step interval to zero so the thread runs to completion as soon as
1412 * possible. This won't affect external events for obvious reasons.
1413 */
1414 AbsEvent.prototype.whenDone = function(cb, hurry)
1415 {
1416 // check to see if the event has already fired
1417 if (this.isDone)
1418 {
1419 // the event has fired already - invoke the callback immediately
1420 cb();
1421 }
1422 else
1423 {
1424 // the event hasn't fired yet - queue the callback for later
1425 this.cb.push(cb);
1426
1427 // if the caller wants the thread to finish as soon as possible,
1428 // set the step delay interval to zero
1429 if (hurry)
1430 this.interval = 0;
1431 }
1432 };
1433
1434 /*
1435 * Completion event. The caller must invoke this when our external event
1436 * occurs.
1437 */
1438 AbsEvent.prototype.fire = function()
1439 {
1440 // note that the event has fired
1441 this.isDone = true;
1442
1443 // invoke each queued callback
1444 for (var i = 0 ; i < this.cb.length ; ++i)
1445 this.cb[i]();
1446
1447 // clear the callback list
1448 this.cb = [];
1449 };
1450
1451 /*
1452 * Start a pseudo-thread. This sets up a long-running task to be performed
1453 * in little chunks that run intermittently while the browser UI runs. We
1454 * accomplish this by executing the chunks with timeouts.
1455 *
1456 * thread(step) is the thread function to call. We will invoke this
1457 * periodically on a timer. 'step' starts at 0 and is incremented on each
1458 * call. The function should perform one chunk of work and then return
1459 * true if we should continue calling it, false if the whole task is
1460 * finished.
1461 *
1462 * interval is the optional timer interval in milliseconds. If not
1463 * supplied, we'll use a default of 25 sms.
1464 */
1465 AbsEvent.prototype.startThread = function(thread, interval)
1466 {
1467 // reset the event
1468 this.isDone = false;
1469
1470 // set the time-slice interval
1471 this.interval = (interval ? interval : 25);
1472
1473 // for statistics, note the starting time
1474 this.startTime = (new Date()).getTime();
1475
1476 // make the first call
1477 this.stepThread(thread, 0);
1478 }
1479
1480 AbsEvent.prototype.stepThread = function(thread, step)
1481 {
1482 // If the interval is zero, run the thread to completion without delay.
1483 // Otherwise do just one step, then schedule the next step after the
1484 // delay interval.
1485 if (this.interval == 0)
1486 {
1487 // no scheduling delay - run the thread to completion
1488 while (thread(step++)) ;
1489
1490 // signal the completion event
1491 this.fire();
1492 }
1493 else if (thread(step++))
1494 {
1495 // the thread wants to continue running - schedule the next step
1496 var e = this;
1497 setTimeout(function() { e.stepThread(thread, step); },
1498 this.interval);
1499 }
1500 else
1501 {
1502 // the thread is done - signal the completion event
1503 this.fire();
1504 }
1505 }
1506
1507
1508 /* ------------------------------------------------------------------------ */
1509 /*
1510 * Utility functions
1511 */
1512
1513 /*
1514 * Get the current text selection on the page. This returns a string
1515 * containing the text of the highlighted selection range, if any.
1516 */
1517 function getSelText()
1518 {
1519 // try it the Netscape way
1520 var sel = window.getSelection && window.getSelection();
1521 if (sel)
1522 return sel.toString();
1523
1524 var sel = document.getSelection && document.getSelection();
1525 if (sel)
1526 return sel;
1527
1528 // try it the IE way
1529 sel = document.selection;
1530 sel = sel && sel.createRange();
1531 sel = sel && sel.text;
1532
1533 // return whatever we found
1534 return sel;
1535 }
1536
1537 /*
1538 * Get the current selection range in a given element.
1539 */
1540 function getSelRangeInEle(ele)
1541 {
1542 // if they gave us the element name, look it up
1543 ele = $(ele);
1544 if (!ele)
1545 return null;
1546
1547 // for IE, use the selection range object for the document
1548 if (document.selection)
1549 {
1550 // IE - use a TextRange object, adjusted to be element-relative
1551 var r, r2, r3;
1552 try
1553 {
1554 if (ele.nodeName == "INPUT" && ele.type.toLowerCase() == "text"
1555 || ele.nodeName == "TEXTAREA")
1556 {
1557 ele.focus();
1558 r = document.selection.createRange();
1559 r2 = ele.createTextRange();
1560 r3 = ele.createTextRange();
1561 }
1562 else
1563 {
1564 r = document.selection.createRange();
1565 r2 = r.duplicate();
1566 r3 = r.duplicate();
1567 try { r2.moveToElementText(ele); } catch (exc) { }
1568 }
1569 r2.setEndPoint('EndToEnd', r);
1570 try { r3.moveToElementText(ele); } catch (exc) { }
1571
1572 // make sure it actually overlaps 'ele'
1573 if (r.compareEndPoints('StartToEnd', r3) <= 0
1574 && r.compareEndPoints('EndToStart', r3) >= 0)
1575 {
1576 // figure the relative start and end points
1577 var s = r2.text.length - r.text.length;
1578 var e = s + r.text.length;
1579
1580 // return the range, limiting to the ele's range
1581 return {
1582 start: Math.max(s, 0),
1583 end: Math.min(e, r3.text.length)
1584 };
1585 }
1586 else
1587 return null;
1588 }
1589 catch (exc)
1590 {
1591 }
1592 }
1593
1594 // for other browsers, INPUT and TEXTAREA elements have a special
1595 // way of handling this
1596 if (ele.selectionStart || ele.selectionStart == '0')
1597 return { start: ele.selectionStart, end: ele.selectionEnd };
1598
1599 // for other browsers, try the window selection range
1600 var r = window.getSelection();
1601 if (r)
1602 {
1603 // scan the subranges
1604 for (var i = 0 ; i < r.rangeCount ; ++i)
1605 {
1606 // check this subrange
1607 var sr = r.getRangeAt(i);
1608 if (rangeIntersectsEle(sr, ele))
1609 {
1610 var start, end;
1611
1612 // set up a range encompassing the target element
1613 var sr2 = sr.cloneRange();
1614 sr2.setStart(ele, 0);
1615 sr2.setEndAfter(ele);
1616
1617 // figure the starting point
1618 if (sr.compareBoundaryPoints(Range.START_TO_START, sr2) <= 0)
1619 start = 0;
1620 else
1621 start = sr.startOffset;
1622
1623 // figure the ending point
1624 if (sr.compareBoundaryPoints(Range.END_TO_END, sr2) >= 0)
1625 end = sr2.toString().length;
1626 else
1627 end = sr.endOffset;
1628
1629 // return the result
1630 return { start: start, end: end };
1631 }
1632 }
1633 }
1634
1635 // we didn't find a selection
1636 return null;
1637 }
1638
1639 function rangeIntersectsEle(range, ele)
1640 {
1641 // if they gave us the element name, look it up
1642 ele = $(ele);
1643
1644 var r = ele.ownerDocument.createRange();
1645 try {
1646 r.selectNode(ele);
1647 } catch (e) {
1648 r.selectNodeContents(ele);
1649 }
1650
1651 return range.compareBoundaryPoints(Range.END_TO_START, r) < 0
1652 && range.compareBoundaryPoints(Range.START_TO_END, r) > 0;
1653 }
1654
1655 // Set the selection range in a given element. If the range is omitted,
1656 // we'll select the whole contents of the element, if we can figure
1657 // the range.
1658 function setSelRangeInEle(ele, range)
1659 {
1660 // if they gave us the element name, look it up
1661 ele = $(ele);
1662
1663 // if the range isn't supplied, synthesize the range to cover
1664 // the whole element
1665 if (!range)
1666 {
1667 // if it's an INPUT or TEXTAREA, use its value
1668 if ((ele.nodeName == "INPUT" && ele.type == "text")
1669 || ele.nodeName == "TEXTAREA")
1670 {
1671 // it's a text control - use its value string as the range
1672 range = { start: 0, end: ele.value.length };
1673 }
1674 else if (typeof(ele.innerText) == "string")
1675 {
1676 // for anything else, use its inner text length
1677 range = { start: 0, end: ele.innerText.length };
1678 }
1679 else
1680 {
1681 // can't figure a range
1682 range = { start: 0, end: 0 };
1683 }
1684 }
1685
1686 // check for browser variations
1687 if (ele.createTextRange || document.body.createTextRange)
1688 {
1689 // IE - we have to do this indirectly through a TextRange object
1690 var r;
1691 if (ele.createTextRange)
1692 r = ele.createTextRange();
1693 else
1694 {
1695 r = document.body.createTextRange();
1696 r.moveToElementText(ele);
1697 }
1698 r.collapse(true);
1699 r.moveEnd('character', range.end);
1700 r.moveStart('character', range.start);
1701 r.select();
1702 }
1703 else if (ele.setSelectionRange)
1704 {
1705 // non-IE - there's a method that does exactly what we want
1706 ele.setSelectionRange(range.start, range.end);
1707 }
1708 }
1709
1710 // Replace the selection in the given control with the given text
1711 function replaceSelRange(ele, txt, selectNewText)
1712 {
1713 // if they gave us the element name, look it up
1714 ele = $(ele);
1715
1716 // get the current selection range
1717 var r = getSelRangeInEle(ele);
1718 if (r)
1719 {
1720 // make sure we're replacing ONLY the text in this element, by
1721 // explicitly selecting this range (the range within 'ele' might
1722 // only have been a subset of a larger selection)
1723 setSelRangeInEle(ele, r);
1724
1725 // replace the selection range with the new text
1726 if (ele.nodeName == "INPUT" || ele.nodeName == "TEXTAREA")
1727 {
1728 // replace the text in the element value
1729 ele.value = ele.value.substr(0, r.start)
1730 + txt
1731 + ele.value.substr(r.end);
1732 }
1733 else
1734 {
1735 // get the selection range object
1736 if (window.getSelection)
1737 {
1738 // non-IE - get the selectionRange for the selection
1739 var rr = window.getSelection();
1740 if (rr)
1741 {
1742 // create the selectionRange
1743 rr = rr.createRange();
1744
1745 // delete its contents
1746 rr.deleteFromDocument();
1747
1748 // make sure that actually happened (Opera is buggy)
1749 if (!window.getSelection().isCollapsed)
1750 document.execCommand("Delete");
1751
1752 // insert the new text
1753 if (rr.rangeCount > 0)
1754 rr.getRangeAt(0).insertNode(
1755 document.createTextNode(txt));
1756 }
1757 }
1758 else if (document.selection)
1759 {
1760 // IE - replace the selection text selection
1761 var rr = document.selection.createRange();
1762 rr.text = txt;
1763 }
1764 else
1765 return;
1766 }
1767
1768 // select the new text if desired, or move the selection to the
1769 // end of the new text if not
1770 var range = {
1771 start: selectNewText ? r.start : r.start + txt.length,
1772 end: r.start + txt.length
1773 };
1774 setSelRangeInEle(ele, range);
1775 }
1776 }
1777
1778 /* ------------------------------------------------------------------------ */
1779 /*
1780 * Add a new <select> option. 'before' is the index of the item to insert
1781 * the new item before; null inserts at the end of the list.
1782 */
1783 function addSelectOption(sel, label, val, before)
1784 {
1785 // create the option
1786 var opt = new Option(label, val);
1787
1788 // add it at the selected location
1789 if (before != null)
1790 {
1791 // insert before the given index
1792 try
1793 {
1794 // try it the IE way first: use an option reference for 'before'
1795 sel.add(opt, sel.options[before]);
1796 }
1797 catch (e)
1798 {
1799 // that didn't work - try it the standard (non-IE) way, with
1800 // the numeric index
1801 sel.add(opt, before);
1802 }
1803 }
1804 else
1805 {
1806 // insert at the end of the list
1807 try
1808 {
1809 // try it the IE way, with no extra argument
1810 sel.add(opt);
1811 }
1812 catch (e)
1813 {
1814 // that didn't work, so do it the standard way, with a null index
1815 sel.add(opt, null);
1816 }
1817 }
1818 }
1819
1820 /*
1821 * Add a new <select> option, sorting it alphabetically into the existing
1822 * list.
1823 */
1824 function addSelectOptionSort(sel, label, val)
1825 {
1826 // search the existing <option> list to find the insertion position
1827 for (var i = 0 ; i < sel.length ; ++i)
1828 {
1829 // if the new item sorts before this item, insert here
1830 var cur = sel.options[i].text;
1831 if (label.toLowerCase().localeCompare(cur.toLowerCase()) < 0)
1832 break;
1833 }
1834
1835 // add the new option at the position we figured
1836 addSelectOption(sel, label, val, i < sel.length ? i : null);
1837 }
1838
1839 /*
1840 * Set a <select>'s current selection by value. This looks for an <option>
1841 * child of the <select> with the given value, and sets the <select>'s
1842 * current selection index to that of the first matching <option>. Returns
1843 * the newly selected index if we find a match, null if not.
1844 */
1845 function setSelectByValue(sel, val)
1846 {
1847 // find the value in the option list
1848 var i = findSelectOptionByValue(sel, val);
1849
1850 // if we found it, select it
1851 if (i != null)
1852 sel.selectedIndex = i;
1853
1854 // return what we found
1855 return i;
1856 }
1857
1858 /*
1859 * Find the select option with the given value
1860 */
1861 function findSelectOptionByValue(sel, val)
1862 {
1863 // scan all <option> children
1864 for (var i = 0 ; i < sel.length ; ++i)
1865 {
1866 // check this option
1867 if (sel.options[i].value == val)
1868 return i;
1869 }
1870
1871 // didn't find it
1872 return null;
1873 }
1874
1875 /* ------------------------------------------------------------------------ */
1876 /*
1877 * Get the event, given the event parameter - if we actually have an event
1878 * parameter we'll just return it, otherwise we'll use the window event
1879 * object. (This weirdness is necessary because of browser variations.)
1880 */
1881 function getEvent(e)
1882 {
1883 return e || window.event;
1884 }
1885
1886 function getEventCopy(e)
1887 {
1888 return getEvent(e).copy(false);
1889 }
1890
1891 /*
1892 * cancel the "bubble" for an event
1893 */
1894 function cancelBubble(ev)
1895 {
1896 ev = getEvent(ev);
1897 if (ev.stopPropagation)
1898 ev.stopPropagation();
1899 else
1900 ev.cancelBubble = true;
1901 }
1902
1903 /*
1904 * cancel the default browser processing for an event
1905 */
1906 function preventDefault(ev)
1907 {
1908 ev = getEvent(ev);
1909 if (ev.preventDefault)
1910 ev.preventDefault();
1911 else
1912 ev.returnValue = false;
1913 }
1914
1915 /*
1916 * Get the event target: this is the DOM element where the event occurred.
1917 * For example, for a mouse click event, this is the DOM element at the
1918 * mouse position at the time of the click. This routine is needed to
1919 * account for browser variations.
1920 */
1921 function getEventTarget(e)
1922 {
1923 // get the actual event
1924 e = getEvent(e);
1925
1926 // get the target from the event object - this can be either the 'target'
1927 // or 'srcElement' property, depending on the browser
1928 var t = e.target || e.srcElement;
1929
1930 // this weirdness is a work-around for a bug in some Safari versions
1931 if (t && t.nodeType == 3)
1932 t = t.parentNode;
1933
1934 // got it
1935 return t;
1936 }
1937
1938 /*
1939 * Get the key code from a keyboard event. Note that this returns the key
1940 * code, not the character. The key code is useful for handling special
1941 * keys (cursor arrows, etc). This routine is needed to smooth out browser
1942 * variations.
1943 *
1944 * (Note that this function isn't needed if you're using the $kd/$kp
1945 * functions, which is what we recommend due to their greater portability.
1946 * This function is only useful if you're doing keypress/keydown handling
1947 * directly.)
1948 */
1949 function getEventKey(e)
1950 {
1951 // get the actual event
1952 e = getEvent(e);
1953
1954 // get the event - this varies by browser, naturally
1955 if (window.event)
1956 return e.keyCode;
1957 else
1958 return e.which;
1959 }
1960
1961 /*
1962 * Get the mouse coordinates of an event, expressed in document-relative
1963 * coordinates. Accounts for browser variations.
1964 */
1965 function getEventCoords(e)
1966 {
1967 // get the actual event
1968 e = getEvent(e);
1969
1970 // Some browsers use pageX/pageY, while others user clientX/clientY.
1971 var x, y;
1972 if (typeof(e.pageX) == 'number')
1973 {
1974 // We've got pageX and pageY, so this is easy - all browsers that
1975 // provide pageX and pageY use them consistently to mean
1976 // document-relative coordinates, so they tell us exactly what
1977 // we want to know.
1978 x = e.pageX;
1979 y = e.pageY;
1980 }
1981 else
1982 {
1983 // We don't have pageX/pageY, so we'll have to fall back on clientX
1984 // and clientY...
1985 x = e.clientX;
1986 y = e.clientY;
1987
1988 // ...which is trickier than it looks. The problem is that some
1989 // browsers provide document-relative coordinates in these properties,
1990 // while others provide coordinates relative to the client window.
1991 // For the latter, we need to adjust for scrolling to get our
1992 // desired document coordinates.
1993 if (!(BrowserInfo.opera
1994 || window.ScriptEngine && ScriptEngine().indexOf('InScript') != -1
1995 || BrowserInfo.konqueror))
1996 {
1997 // Okay, it's a browser that gives us client-window-relative
1998 // coordinates, so we have to adjust for scrolling.
1999 var scrollPos = getScrollPos();
2000 x += scrollPos.x;
2001 y += scrollPos.y;
2002 }
2003 }
2004
2005 // return the x,y coordinates
2006 return { x: x, y: y };
2007 }
2008
2009 /* ------------------------------------------------------------------------ */
2010 /*
2011 * Get the target-relative rectangle of the event. This returns a
2012 * rectangle structure consisting of 'x' and 'y' set to the offset WITHIN
2013 * THE TARGET OBJECT of the mouse position in the event, and 'width' and
2014 * 'height' set to the dimensions of the target object.
2015 */
2016 function getTargetRelativeRect(e)
2017 {
2018 // get the event coordinates relative to the target object *
2019 return getObjectRelativeRect(e, getEventTarget(e));
2020 }
2021
2022 /*
2023 * Get the object-relative rectangle of an event. This returns a rectangle
2024 * structure consisting of 'x' and 'y' set to the offset within 'obj' of
2025 * the mouse position of the event, and 'width' and 'height' set to the
2026 * dimensions of 'obj'.
2027 */
2028 function getObjectRelativeRect(e, obj)
2029 {
2030 // get the real event
2031 e = getEvent(e);
2032
2033 // get the event coordinates, in document coordinates
2034 var evtpos = getEventCoords(e);
2035
2036 // get the object rectangle
2037 var objpos = getObjectRect(obj);
2038
2039 // We have the event and target element positions now, both in the
2040 // same coordinate system (document-relative): so calculating the
2041 // event location relative to the target element is just a matter
2042 // of calculating the difference. Return the target-relative x
2043 // position, the target-relative y position, the target width,
2044 // the target height, and the target object.
2045 return { x: evtpos.x - objpos.x, y: evtpos.y - objpos.y,
2046 width: objpos.width, height: objpos.height,
2047 obj: obj };
2048 }
2049
2050 /*
2051 * Is the mouse position of the event within the given object's bounds?
2052 * This determines if the event occurred within the given object, directly
2053 * or indirectly. ("Indirectly" within the object means that the event is
2054 * within the object's bounds, but also within the bounds of a child of the
2055 * object. In this case, the event target will be the innermost child
2056 * containing the event mouse point. It's often useful to know if an event
2057 * occurs within an object or any of its children, which merely looking at
2058 * the target object won't tell you.)
2059 */
2060 function isEventInObject(e, obj)
2061 {
2062 // get the object-relative event coordinates
2063 var r = getObjectRelativeRect(e, obj);
2064
2065 // if x is between 0 and the width of the object, and y is
2066 // between 0 and the height of the object, we're within the object
2067 return (r.x >= 0
2068 && r.x <= r.width
2069 && r.y >= 0
2070 && r.y <= r.height);
2071 }
2072
2073 /*
2074 * Determine if 'chi' is a child of 'par'
2075 */
2076 function isChildElement(par, chi)
2077 {
2078 for (var e = chi ; e ; e = e.parentNode)
2079 {
2080 if (e == par)
2081 return true;
2082 }
2083 return false;
2084 }
2085
2086 /* ------------------------------------------------------------------------ */
2087 /*
2088 * Track mouse movement to simulate a button with a custom object. The
2089 * custom object uses styles to display normal, hover, and active button
2090 * states. You can use either text colors/effects (like hyperlinks do) or
2091 * different background images (for graphical buttons).
2092 *
2093 * To use this, set the element's onmousedown and onmouseover events to
2094 * point to this method, passing 'this' for 'ele'.
2095 *
2096 * The element must have a custom class definition for its style, plus two
2097 * extra classes. If the base class is called 'myclass', you should also
2098 * define 'myclassH' for the hovering version, and 'myclassA' for the
2099 * active (clicked) version. We'll automatically add the 'myclassH' or
2100 * 'myclassA' class to the element's class list: so the full class while
2101 * hovering is 'myclass myclassH', and while active 'myclass myclassA'.
2102 */
2103 var trackButtonDown = null, trackButtonHover = null;
2104 function trackButton(ev, ele)
2105 {
2106 // ignore it if we're tracking another element
2107 if (trackButtonDown && trackButtonDown != ele)
2108 return true;
2109
2110 // get the real event object
2111 ev = getEvent(ev);
2112
2113 // get the object's base class
2114 var baseClass = ele.className.split(" ")[0];
2115
2116 // check the event type
2117 if (ev.type == "mousedown" && trackButtonDown == null)
2118 {
2119 // enter the Active state
2120 ele.className = baseClass + " " + baseClass + "A";
2121
2122 // watch for mouse-up events on the document (we have to track the
2123 // whole document, since we won't get the event in the button itself
2124 // if the mouse is outside the element when the button is released)
2125 trackButtonDown = ele;
2126 addEventHandler(document, "mouseup", trackButtonUp);
2127
2128 // suppress text selection in IE during this tracking
2129 addEventHandler(document, "selectstart", trackButtonSelect);
2130
2131 // don't let this go up to any parent controls
2132 cancelBubble(ev);
2133 preventDefault(ev);
2134 return false;
2135 }
2136 else if (ev.type == "mouseover")
2137 {
2138 // enter the Hovering state, or the Active state if the
2139 // button is down
2140 ele.className = baseClass + " " + baseClass +
2141 (trackButtonDown == ele ? "A" : "H");
2142
2143 // watch for mouse-out, if we're not already
2144 if (!trackButtonHover || !isEventInObject(ev, trackButtonHover))
2145 {
2146 addEventHandler(ele, "mouseout", trackButtonOut);
2147 trackButtonHover = ele;
2148 }
2149
2150 // don't handle it further
2151 return false;
2152 }
2153
2154 // use default handling
2155 return true;
2156 }
2157 function trackButtonUp(ev)
2158 {
2159 ev = getEvent(ev);
2160 var ele = trackButtonDown;
2161
2162 // switch to the base class or Hover class, as appropriate
2163 var baseClass = ele.className.split(" ")[0];
2164 ele.className = baseClass +
2165 (trackButtonHover ? " " + baseClass + "H" : "");
2166
2167 // we're finished with the tracking
2168 removeEventHandler(document, "mouseup", trackButtonUp);
2169 removeEventHandler(document, "selectstart", trackButtonSelect);
2170 trackButtonDown = null;
2171 }
2172 function trackButtonSelect(ev)
2173 {
2174 return false;
2175 }
2176 function trackButtonOut(ev)
2177 {
2178 ev = getEvent(ev);
2179 var ele = trackButtonHover;
2180
2181 // switch to the base class
2182 ele.className = ele.className.split(" ")[0];
2183
2184 // we're finished with hovering for this control
2185 removeEventHandler(ele, "mouseout", trackButtonOut);
2186 trackButtonHover = null;
2187 }
2188
2189 /* ------------------------------------------------------------------------ */
2190 /*
2191 * Get the current scroll position in this document (the way of getting
2192 * this information varies by browser).
2193 */
2194 function getScrollPos()
2195 {
2196 // try the BODY element first
2197 var base;
2198 if ((base = document.body) != null
2199 && (base.scrollLeft || base.scrollTop))
2200 return { x: base.scrollLeft, y: base.scrollTop };
2201
2202 // no good; try the document element
2203 if ((base = document.documentElement) != null
2204 && (base.scrollLeft || base.scrollTop))
2205 return { x: base.scrollLeft, y: base.scrollTop };
2206
2207 // still couldn't find the position - use zeroes
2208 return { x: 0, y: 0 };
2209 }
2210
2211 /*
2212 * Get the window rectangle. This returns a rectangle giving the bounds of
2213 * the window, relative to itself. This means that the 'x' and 'y' offsets
2214 * are always zero; the actual information returned is thus the dimensions
2215 * of the window, as the width and height of the rectangle.
2216 */
2217 function getWindowRect()
2218 {
2219 var wid = 1000000, ht = 1000000;
2220
2221 // This is one of those things that varies a lot by browser.
2222 // Most browsers support window.innerWidth/Height, but of course
2223 // IE has its own weird way. What's more, IE has two different
2224 // ways, depending on version. And to make matters even worse,
2225 // the innerWidth/Height properties aren't even consistent across
2226 // the browsers that support them - some include the scrollbar
2227 // width in the size, some don't. We don't want the scrollbars
2228 // to count because they're not part of the area we can use
2229 // for drawing. The solution seems to be to try all of the
2230 // different methods, and use the smallest non-zero, non-null,
2231 // non-undefined result. Each browser seems to have at least
2232 // one way getting the area sans scrollers, which is the smallest
2233 // of the various values we'd get.
2234
2235 // try innerHeight on the window (this is the most common approach,
2236 // used by almost everyone except IE, but often includes the area
2237 // covered by scrollbars)
2238 var x = window.innerWidth, y = window.innerHeight;
2239 if (typeof(x) == "number" && x > 0)
2240 {
2241 wid = x;
2242 ht = y;
2243 }
2244
2245 // try clientHeight on the document (this works on most versions of
2246 // IE for Windows, and also gets us the sans-scrollbar sizes on some
2247 // others)
2248 x = document.documentElement.clientWidth;
2249 y = document.documentElement.clientHeight;
2250 if (typeof(x) == "number" && x > 0)
2251 {
2252 // keep the smallest so far
2253 wid = Math.min(wid, x);
2254 ht = Math.min(ht, y);
2255 }
2256
2257 // For the width, also try the clientWidth on the body (this works on
2258 // IE for Mac and some IE for Win, and gives us sans-scrollbar sizes
2259 // for many others). However, DON'T use this for the height unless
2260 // we don't have any height at all so far, since it might only tell
2261 // us the content height, not the window height.
2262 x = document.body.clientWidth;
2263 y = document.body.clientHeight;
2264 if (typeof(x) == "number" && x > 0)
2265 {
2266 wid = Math.min(wid, x);
2267 if (ht == 1000000)
2268 ht = y;
2269 }
2270
2271 // return the result
2272 return { x: 0, y: 0, width: wid, height: ht };
2273 }
2274
2275 /*
2276 * Get the size of the contents of the given window
2277 */
2278 function getContentRect(win)
2279 {
2280 // we don't know the height or width yet
2281 var ht = 0, wid = 0;
2282
2283 // get the document body element
2284 var doc = win.document;
2285 var body = win.document.body || win.document.documentElement;
2286 if (!body)
2287 return { x: 0, y: 0, width: 0, height: 0 };
2288
2289 // Add a probe division to find the bottom of the existing normal
2290 // flow elements. This is necessary in cases where the document only
2291 // has text elements (without any divisions or other block-level
2292 // elements wrapping them), because text elements don't make position
2293 // information available to javascript. The probe will be inserted
2294 // just below all of the existing normal-flow content, so its top
2295 // position gives us the height of the current normal-flow content.
2296 var probe = doc.createElement("DIV");
2297 body.appendChild(probe);
2298 if (probe.offsetTop > ht)
2299 ht = probe.offsetTop;
2300
2301 // done with the probe for now
2302 body.removeChild(probe);
2303
2304 // Now scan the direct children of the BODY node, and note the maximum
2305 // right and bottom coordinates. This will pick up normal-flow items
2306 // that are actual elements (not #text), as well as floating items and
2307 // position:absolute items that won't figure into our probe positioning.
2308 var chi = body.childNodes;
2309 for (var i = 0 ; i < chi.length ; ++i)
2310 {
2311 // get the child and check the type
2312 var c = chi[i];
2313 if (c.nodeType == 3)
2314 {
2315 // It's a #text node, which means we can't measure its bounding
2316 // box directly. Instead, wrap the same text in a SPAN and
2317 // measure the SPAN's width.
2318 probe = doc.createElement("SPAN");
2319 body.insertBefore(probe, body.firstChild);
2320 probe.innerHTML = c.nodeValue.replace('&', '&amp;')
2321 .replace('<', '&gt;');
2322
2323 // note the width
2324 if (probe.offsetLeft + probe.offsetWidth > wid)
2325 wid = probe.offsetLeft + probe.offsetWidth;
2326
2327 // done with the probe
2328 body.removeChild(probe);
2329 }
2330 else
2331 {
2332 // Normal element - measure its bounding box and check to see
2333 // if it sets a new high-water mark in width or height.
2334 var rc = getObjectRect(chi[i]);
2335 if (rc.x + rc.width > wid)
2336 wid = rc.x + rc.width;
2337 if (rc.y + rc.height > ht)
2338 ht = rc.y + rc.height;
2339 }
2340 }
2341
2342 // return the outer boundary rectangle
2343 return { x: 0, y: 0, width: wid, height: ht };
2344 }
2345
2346 /*
2347 * Get the bounds of an object, in document coordinates.
2348 */
2349 function getObjectRect(obj)
2350 {
2351 // return nothing if there's no object
2352 obj = $(obj);
2353 if (!obj)
2354 return null;
2355
2356 // IE has a special way of doing this
2357 if (obj.getBoundingClientRect)
2358 {
2359 // we need to do this in a try-catch due to a somewhat mysterious
2360 // problem that occurs with long-running Ajax requests; see
2361 // http://bugdb.tads.org/view.php?id=134
2362 var r = null;
2363 try
2364 {
2365 r = obj.getBoundingClientRect();
2366 }
2367 catch (e)
2368 {
2369 r = { top: 0, left: 0,
2370 right: obj.offsetWidth, bottom: obj.offsetHeight };
2371 }
2372 var de = document.documentElement;
2373 var dx = de.scrollLeft, dy = de.scrollTop;
2374 if (dx == 0 && dy == 0)
2375 {
2376 de = document.body;
2377 dx = de.scrollLeft;
2378 dy = de.scrollTop;
2379 }
2380 return { x: r.left + dx, y: r.top + dy,
2381 width: r.right - r.left, height: r.bottom - r.top };
2382 }
2383
2384 // get the size of the target element (in pixels)
2385 var twid = obj.offsetWidth;
2386 var tht = obj.offsetHeight;
2387
2388 // Calculate the document-relative coordinates of the (upper left corner
2389 // of the) target element. The only information we can get at directly
2390 // is the container-relative position, so start with that...
2391 var tx = obj.offsetLeft;
2392 var ty = obj.offsetTop;
2393
2394 // ...and now work our way up the parent chain, adding in the
2395 // container-relative offset of each container. Keep going until
2396 // we reach the outermost container (the Body element).
2397 for (var par = obj.offsetParent ; par != null && par != document.body ;
2398 par = par.offsetParent)
2399 {
2400 tx += par.offsetLeft;
2401 ty += par.offsetTop;
2402 }
2403
2404 // return an object representing the rectangle
2405 return { x: tx, y: ty, width: twid, height: tht };
2406 }
2407
2408 /*
2409 * move an element to a given document-relative location
2410 */
2411 function moveObject(obj, x, y)
2412 {
2413 // Find the containing box element (i.e., the parent element with
2414 // position absolute, relative, or fixed. Note that IE, as always,
2415 // has a different way of getting the computed style than the rest
2416 // of the browsers.
2417 var parent;
2418 for (parent = obj.parentNode ; parent != null && parent != document ;
2419 parent = parent.parentNode)
2420 {
2421 var s = parent.currentStyle
2422 || (document.defaultView
2423 && document.defaultView.getComputedStyle
2424 && document.defaultView.getComputedStyle(parent, ""));
2425 if (s)
2426 s = s.position;
2427 if (s == "absolute" || s == "relative" || s == "fixed")
2428 break;
2429 }
2430 if (parent == document)
2431 parent = null;
2432
2433 // get the parent adjustments
2434 var dx = 0, dy = 0;
2435 if (parent)
2436 {
2437 var prc = getObjectRect(parent);
2438 dx = prc.x;
2439 dy = prc.y;
2440 }
2441
2442 // move the object
2443 if (x != null)
2444 obj.style.left = (x - dx) + "px";
2445 if (y != null)
2446 obj.style.top = (y - dy) + "px";
2447 }
2448
2449 /*
2450 * Get the value for a given style of a given element. This returns the
2451 * actual computed style, even if the element doesn't have an explicit
2452 * setting for the style. For example, this can be used to identify the
2453 * current font of a given element.
2454 *
2455 * The property name is given in CSS format: font-name, border-top, etc.
2456 */
2457 function getStyle(ele, prop)
2458 {
2459 // if the element is given by name, get the object
2460 ele = $(ele);
2461
2462 // if we're asking for 'font' on IE, we need to build the overall
2463 // string manually
2464 if (prop == "font")
2465 {
2466 return getStyle(ele, "font-style")
2467 + " " + getStyle(ele, "font-variant")
2468 + " " + getStyle(ele, "font-weight")
2469 + " " + getStyle(ele, "font-size")
2470 + "/" + getStyle(ele, "line-height")
2471 + " " + getStyle(ele, "font-family");
2472 }
2473
2474 // check for the various ways the computed style is represented in
2475 // different browsers
2476 if (ele.currentStyle)
2477 {
2478 // try it with the name as given
2479 var v = ele.currentStyle[prop];
2480
2481 // if that didn't work, we might be on IE, which requires the
2482 // javascript-style font naming convention instead of CSS: so
2483 // font-name becomes fontName, etc
2484 var ieProp = prop.replace(/-([a-z])/g, function(m, lc) {
2485 return lc.toUpperCase(); });
2486 return ele.currentStyle[ieProp];
2487 }
2488 else if (window.getComputedStyle)
2489 return document.defaultView.getComputedStyle(ele, null)
2490 .getPropertyValue(prop);
2491
2492 // no style information is available in this browser, apparently
2493 return null;
2494 }
2495
2496
2497 /* ------------------------------------------------------------------------ */
2498 /*
2499 * Initialize the XmlFrame. This is a hack to work around the (apparently
2500 * well-known) Safari perma-throbber bug. The bug is that Safari animates
2501 * its spinning wheel throbber continuously as long as there's an
2502 * outstanding XMLHttpRequest. This is undesirable for a page that uses a
2503 * publish/subscribe scheme for contra-flow events and requests (from the
2504 * server to the client), because this scheme basically always has an
2505 * outstanding request, which makes Safari throb its throbber all the time.
2506 * At best it's visually distracting; at worst it's confusing, by making it
2507 * look like the browser is stuck loading some last bit of content that
2508 * never arrives.
2509 *
2510 * I've seen a few mentions of this bug on the Web, and some oblique
2511 * references to a known fix, but I haven't been able to track down any
2512 * actual details on what the fix would be. My intuition was that Safari
2513 * probably only spins for requests in the top-level window, and
2514 * empirically this seems to be the case. If the request comes from an
2515 * iframe, Safari doesn't seem to spin its throbber.
2516 *
2517 * But how exactly do you create a request in an iframe? The key seems to
2518 * be the location of the script where the "new XMLHttpRequest()" happens.
2519 * In particular, if a script in an iframe creates the request object, it
2520 * doesn't matter who uses it after that - presumably the browser is
2521 * tagging the object with the frame where it was created, and runs the
2522 * throbber or not accordingly.
2523 *
2524 * So the hack is to create an invisible iframe, and define the script that
2525 * creates our XMLHttpRequests objects in the iframe. The iframe has the
2526 * same domain as the main document, so we can freely call between scripts
2527 * in the main doc and the iframe. The iframe's contents aren't even a
2528 * separate http resource - we define them in-line by writing to the iframe
2529 * document directly from out script here.
2530 */
2531 function initXmlFrame()
2532 {
2533 // create an invisible iframe
2534 var f = document.createElement("iframe");
2535 f.id = "XmlFrame";
2536 f.style.display = "none";
2537 document.body.appendChild(f);
2538
2539 // get its document object
2540 var d = getIFrameDoc(f);
2541
2542 // give it a script that sets up a window function to create a request
2543 d.open();
2544 d.write("<html><body><script type='text/javascript'>\r\n<!--\r\n"
2545 + "window.createXmlRequest = function()"
2546 + "{ return new XMLHttpRequest(); }"
2547 + "\r\n-->\r\n</" + "script></body></html>");
2548 d.close();
2549 }
2550
2551 /*
2552 * Get the document object for a given IFRAME element
2553 */
2554 function getIFrameDoc(fr)
2555 {
2556 // IE and Mozilla have a contentWindow; Safari only has a contentDocument.
2557 // Opera 7 has contentDOcument, but actually returns a window!
2558 var doc = fr.contentWindow || fr.contentDocument;
2559
2560 // if the object is a window, it'll have a document property pointing
2561 // to the doc object; if not, it must already be the doc object
2562 return doc.document || doc;
2563
2564 // old way - might not be compatible with Opera 7
2565 // var w = fr.contentWindow;
2566 // return w.contentDocument || w.document
2567 }
2568
2569 /*
2570 * Create an XMLHttpRequest object, adjusting for the various browsers
2571 */
2572 function createXmlReq()
2573 {
2574 // try creating the request
2575 var req = null;
2576 try
2577 {
2578 // try the Safari sub-frame hack first
2579 req = $("XmlFrame").contentWindow.createXmlRequest();
2580 }
2581 catch (e)
2582 {
2583 try
2584 {
2585 // no good on the Safari hack - try again with the base window
2586 req = new XMLHttpRequest();
2587 }
2588 catch(e)
2589 {
2590 // no good on XMLHttpRequest - use IE's unique approach
2591 try
2592 {
2593 req = new ActiveXObject("Msxml2.XMLHTTP");
2594 }
2595 catch(e)
2596 {
2597 req = new ActiveXObject("Microsoft.XMLHTTP");
2598 }
2599 }
2600 }
2601
2602 // return the request object
2603 return req;
2604 }
2605
2606 // Send an AJAX request to the server.
2607 //
2608 // 'resource' is the URL to the object on the server that you're
2609 // sending the request to. Browser security restrictions generally
2610 // require this to be in the same domain as the current page, so you
2611 // should usually only use the resource portion of the URL, without
2612 // an "http://domain/" prefix. The TADS Web UI convention is to
2613 // start all command paths with the prefix "/webui/".
2614 //
2615 // 'typ' is the server request type. Use ServerRequest.Command for
2616 // a user-initiated action where we have to wait for a reply from
2617 // the server to complete the UI response; we display our little
2618 // "throbber" animation whenever a Command request is in progress,
2619 // to give the user a visual indication that we know we owe them
2620 // a response and that we're just taking our time thinking about it.
2621 // Use Server.Subscription for a request for a notification. We
2622 // do NOT show any visual indication of this type of request, since
2623 // a subscription request is specifically not expected to return
2624 // immediately; the whole point is to get notified when the subject
2625 // event occurs, which could take an indefinite amount of time, and
2626 // it might not even be a foregone conclusion that the event will
2627 // occur at all.
2628 //
2629 // 'cbfunc' is a function to call when the event completes. This
2630 // function is called as 'cbfunc(req, xmlDoc)', where 'req' is the
2631 // Javascript XMLHttpRequest object representing the request, and
2632 // 'xmlDoc' is the document element of the XML reply from the server.
2633 // The callback is only invoked if the request succeeds. We require
2634 // all requests to return XML replies, so it's an error if we get
2635 // a reply without an XML body, meaning the callback is never invoked
2636 // without an xmlDoc value. 'cbfunc' can be omitted or null, in
2637 // which case we simply ignore any successful reply from the request.
2638 //
2639 // 'postData' is an optional string containing the contents to send
2640 // with a POST request. If this is null, we'll execute a GET request
2641 // with no body; if this is provided, we'll execute a POST instead
2642 // and send the given data as the content body.
2643 //
2644 // 'postDataType' is an optional string with the content-type value
2645 // for the posted data. If this is omitted, x-www-form-urlencoded
2646 // is used by default.
2647 //
2648 function serverRequest(resource, typ, cbfunc, postData, postDataType)
2649 {
2650 // create a new request object, and send the request
2651 (new ServerRequest(resource, typ, cbfunc, postData, postDataType)).send();
2652 }
2653
2654 // our server request tracker object constructor
2655 function ServerRequest(resource, typ, cbfunc, postData, postDataType)
2656 {
2657 // save the parameters
2658 this.resource = resource;
2659 this.reqType = typ || ServerRequest.Command;
2660 this.cbFunc = cbfunc;
2661 this.postData = (postData ? postData : null);
2662 this.postDataType = postDataType;
2663 this.reqID = ServerRequest.nextID++;
2664 this.aborted = false;
2665
2666 // it hasn't succeeded or failed yet
2667 this.succeeded = this.failed = false;
2668
2669 // we haven't tried the request yet
2670 this.tries = 0;
2671 }
2672
2673 // Server request types
2674 ServerRequest.Command = 1; // command sent from the UI to the server
2675 ServerRequest.Subscription = 2; // subscription to event or other update
2676
2677 // Request ID. For debugging purposes, give each request a sequential
2678 // ID. This is different from the "sequence number" in that the sequence
2679 // number is incremented per XMLHttpRequest, whereas the request ID is
2680 // tied to a ServerRequest object.
2681 ServerRequest.nextID = 1;
2682
2683 // Sequence number. This is a parameter we add to all request URLs to
2684 // ensure that each request is unique, to prevent the browser from using
2685 // a cached reply to a past request as the answer to a new request. This
2686 // really shouldn't be necessary, because the server *should* set the
2687 // reply headers to indicate that the reply is not to be cached, and the
2688 // browser *should* obey those headers. But some browsers are buggy.
2689 // We work around this by making each URL unique, using a sequence number
2690 // parameter added to the other URL parameters. The browser uses the URL
2691 // as the cache key, so adding a different sequence number to each request's
2692 // URL effectively eliminates caching by ensuring that no two requests ever
2693 // have the exact same URL.
2694 ServerRequest.sequenceNum = (new Date()).getTime();
2695
2696 // Number of outstanding Command requests. While command requests are
2697 // pending, we show a visible "waiting" indicator so that the user knows
2698 // why the UI is unresponsive.
2699 ServerRequest.pendingCommandCnt = 0;
2700
2701 // list of open ServerRequest objects
2702 var openServerRequests = [];
2703
2704 // Send the request.
2705 ServerRequest.prototype.send = function()
2706 {
2707 // create a request
2708 var req = this.req = createXmlReq();
2709
2710 // if we got a request, send it
2711 if (req)
2712 {
2713 // set up the response callback
2714 var sr = this;
2715 req.onreadystatechange = function() { sr.xmlEvent(req); }
2716
2717 // Add a sequence number parameter to the URL. We presume the
2718 // server will ignore this, as it's just an extra parameter that
2719 // it's not looking for; this is simply to make certain the URL
2720 // is distinct from any past URLs we've ever sent, so that the
2721 // browser will actually send the request to the server rather
2722 // than using a cached reply from a past request.
2723 var resource = this.resource;
2724 resource += (resource.indexOf("?") < 0 ? "?" : "&")
2725 + "TADSWseqno=" + ServerRequest.sequenceNum++;
2726
2727 // open the request
2728 req.open(this.postData ? "POST" : "GET", resource, true);
2729
2730 // if this is a command request, start up the waiting indicator
2731 var w;
2732 if (this.reqType == ServerRequest.Command
2733 && (w = $win("main.statusline")) && w.NetThrobber)
2734 w.NetThrobber.onStartRequest();
2735
2736 // if we're posting data, set the content type to form data
2737 if (this.postData)
2738 req.setRequestHeader(
2739 "Content-type",
2740 this.postDataType || "application/x-www-form-urlencoded");
2741
2742 // Send it. If this is the first try, send it immediately.
2743 // If this is a retry, send it after a delay. Use longer delays
2744 // for repeated retries; if it's some kind of temporary network
2745 // or server glitch as we're assuming, but we keep failing, we
2746 // might just need more time for whatever it is to clear up.
2747 var postData = this.postData;
2748 var f = function()
2749 {
2750 // send the request
2751 req.send(postData);
2752
2753 // add it to our open request list
2754 openServerRequests.push(sr);
2755 }
2756 if (this.tries == 0)
2757 {
2758 // first try - send immediately
2759 f();
2760 }
2761 else
2762 {
2763 // retry - send with a delay according to the number of retries,
2764 // plus a small random component (just in case the problem is
2765 // server contention with another client; the random component
2766 // helps prevent us from retrying in lockstep with the other guy)
2767 var delays = [0, 500, 1000, 2000, 5000, 5000];
2768 var r = Math.floor(Math.random()*201) - 100;
2769 setTimeout(f, (this.tries < delays.length
2770 ? delays[this.tries] : 10000) + r);
2771 }
2772 }
2773 else
2774 {
2775 alert("This " + selfNoun
2776 + " requires support for XML Requests (sometimes "
2777 + "called \"Ajax\" requests). It appears that your "
2778 + "browser doesn't support this feature, or that "
2779 + "you've disabled it. To continue, you'll need to "
2780 + "upgrade your browser (or simply re-enable this feature, "
2781 + "if you've disabled it in the browser settings).");
2782 }
2783 }
2784
2785 // Abort a request
2786 ServerRequest.prototype.abort = function()
2787 {
2788 // flag the request as aborted
2789 this.aborted = true;
2790
2791 // abort the XMLHttpRequest
2792 if (this.req)
2793 this.req.abort();
2794 }
2795
2796 // XML event callback. The browser invokes this when the status of a
2797 // request changes.
2798 ServerRequest.prototype.xmlEvent = function(req)
2799 {
2800 // check the request status
2801 if (req.readyState == 4)
2802 {
2803 // if this is a command request, turn off the waiting indicator
2804 var w;
2805 if (this.reqType == ServerRequest.Command
2806 && (w = $win("main.statusline"))
2807 && w.NetThrobber)
2808 w.NetThrobber.onEndRequest();
2809
2810 // remove the request from our open request list
2811 var idx = openServerRequests.indexOf(this);
2812 if (idx >= 0)
2813 openServerRequests.splice(idx, 1);
2814
2815 // the request has completed - retrieve the XML document
2816 var xmlr = req.responseXML;
2817 if (xmlr)
2818 xmlr = xmlr.documentElement;
2819
2820 // if we got the XML document, we've completed successfully
2821 if (xmlr && req.status == 200)
2822 {
2823 // Successful completion - flag it as such
2824 this.succeeded = true;
2825
2826 // If this was a retry, an earlier try failed, so we logged
2827 // errors for the request. Mark those errors as now
2828 // automatically resolved.
2829 if (this.tries > 0)
2830 $win().unlogError(this);
2831
2832 // invoke the user callback
2833 if (this.cbFunc)
2834 this.cbFunc(req, xmlr);
2835 }
2836 else if (this.aborted)
2837 {
2838 // the request was aborted
2839 }
2840 else
2841 {
2842 // get the status text, if available
2843 try { var statusText = req.statusText; }
2844 catch (e) { statusText = ""; }
2845
2846 // We got an error from the server. Build a human-readable
2847 // list of details for the error.
2848 var detail = "Request ID: " + this.reqID
2849 + "<br>Resource: " + this.resource.htmlify()
2850 + "<br>HTTP Status: " + req.status
2851 + " " + statusText.htmlify()
2852 + (req.responseText
2853 ? "<br>Response:<br><div class=\"errorSubDetail\">"
2854 + req.responseText.htmlify()
2855 .replace(/\n/g, "<br>")
2856 + "</div>"
2857 : "");
2858
2859 // set up a default error message
2860 var msg = "An error occurred communicating with the server."
2861 + errorRecoveryAction;
2862
2863 // assume we won't retry this request
2864 var retry = false;
2865
2866 // Check for server disconnection in standalone mode on
2867 // Windows. On Windows, the standalone interpreter uses
2868 // the IE window.external interface to provide access to
2869 // this information. The disconnect flag tells us when the
2870 // user terminates the server program explicitly, such as
2871 // via the Workbench debugger. If we're not running on the
2872 // Windows interpreter in standalone mode, this interface
2873 // won't be available, so we'll harmlessly skip this test
2874 // on other platforms.
2875 //
2876 // Otherwise, check the HTTP status and the reply body to
2877 // determine what went wrong.
2878 //
2879 if (window.external
2880 && window.external.IsConnected
2881 && !window.external.IsConnected())
2882 {
2883 // The server program has been explicitly terminated,
2884 // such as with a Terminate Game command in the Workbench
2885 // debugger.
2886 this.failed = true;
2887 msg = "The program has been terminated.";
2888 }
2889 else if (req.status == 503
2890 && req.statusText.match(/\(Shutting Down\)/))
2891 {
2892 // Normally, the server won't shut down until all clients
2893 // disconnect. However, there are ways to force it to shut
2894 // down externally, such as via a Terminate Game command
2895 // in the debugger. When the server shuts down while
2896 // requests are still pending, it bounces the pending
2897 // requests with a 503 error with "(Shutting Down)" in
2898 // the status text.
2899 this.failed = true;
2900 msg = "The program has been terminated.";
2901 }
2902 else if (req.status != 408
2903 && req.status >= 400 && req.status <= 499)
2904 {
2905 // Most 400 status codes indicate that the request was
2906 // transmitted properly but is not acceptable to the
2907 // server. There's no reason to retry these requests.
2908 this.failed = true;
2909 msg = "The server rejected a network request from the "
2910 + "client. This could be due to a programming "
2911 + "error in the " + selfNoun + "'s display logic."
2912 + errorRecoveryAction;
2913 }
2914 else if (req.status == 500 || req.status == 501)
2915 {
2916 // 500 (internal server error) and 501 (not implemented)
2917 // indicate server-side errors that are most likely
2918 // permanent.
2919 this.failed = true;
2920 msg = "An error occurred on the server. This could be "
2921 + "due to a programming error in the "
2922 + selfNoun + "."
2923 + errorRecoveryAction;
2924 }
2925 else if (req.status != 200 || !req.responseText)
2926 {
2927 // No response text, so it could be a network or server
2928 // glitch, which could be temporary. Try resending the
2929 // request, unless we've already tried it several times,
2930 // in which case it's probably not going to clear up by
2931 // itself.
2932 if (this.tries++ < 5)
2933 {
2934 msg = "A (possibly temporary) network error occurred "
2935 + "communicating with the server. "
2936 + ["", "", "(Second attempt)", "(Third attempt)",
2937 "(Fourth attempt)", "(Fifth attempt)"]
2938 [this.tries];
2939 retry = true;
2940 }
2941 else
2942 {
2943 // we don't need to retry this request
2944 this.failed = true;
2945 }
2946 }
2947 else
2948 {
2949 // ill-formed reply - probably a server problem
2950 this.failed = true;
2951 msg = "The server sent an incorrectly formatted response. "
2952 + "This can be caused by a garbled network "
2953 + "transmission, or by a bug in the " + selfNoun + "."
2954 + errorRecoveryAction;
2955 }
2956
2957 // log the error
2958 $win().logError(msg, detail, this);
2959
2960 // if desired, retry the request
2961 if (retry)
2962 this.send();
2963 }
2964 }
2965 }
2966
2967 // Cancel all outstanding requests. We call this when the window is
2968 // about to be unloaded. This is particularly important for refresh,
2969 // because request objects from the previous incarnation of the document
2970 // can linger after the new document is loaded, and this can cause
2971 // various kinds of confusion.
2972 function cancelServerRequests()
2973 {
2974 openServerRequests.forEach(function(sr) { sr.abort(); });
2975 }
2976
2977
2978 /* ------------------------------------------------------------------------ */
2979 /*
2980 * Find a window by path. This traverses the window (iframe) tree starting
2981 * at the top-level window. Path name elements are separated by periods.
2982 * For example, "main.statusline" is the standard statusline window. If no
2983 * path is given, simply retrieves the top-level window.
2984 */
2985 function $win(path)
2986 {
2987 // find the top-level window
2988 var w;
2989 for (w = window ; w.parent && w.parent != w ; w = w.parent) ;
2990
2991 // if there's no path, get the top-level window
2992 if (!path)
2993 return w;
2994
2995 // ask the top-level window to resolve the path
2996 return w.windowFromAbsPath(path);
2997 }
2998
2999
3000 /* ------------------------------------------------------------------------ */
3001 /*
3002 * XML helpers
3003 */
3004
3005 // Get the list of children of an XML node with the given name
3006 function xmlChild(parent, name)
3007 {
3008 return parent.getElementsByTagName(name);
3009 }
3010
3011 // Get the text value of a child of an XML node
3012 function xmlChildText(parent, name)
3013 {
3014 // return the text contents of the child node of interest
3015 return xmlNodeText(xmlChild(parent, name));
3016 }
3017
3018 // Get the text value of a given node
3019 function xmlNodeText(node)
3020 {
3021 // if it's an array, get the first element
3022 if (node && node.length)
3023 node = node[0];
3024
3025 // if we found the node, return its text
3026 if (node && node.firstChild)
3027 {
3028 // Some browsers (e.g., Firefox) break up text nodes into 4k chunks,
3029 // so we need to check for multiple text children and paste
3030 // everything back together. Make a list of the child nodes.
3031 for (var s = [], c = node.firstChild ; c ; c = c.nextSibling)
3032 s.push(c.data);
3033
3034 // append them together and return the result
3035 return s.join("");
3036 }
3037 else
3038 {
3039 // no child node or no text - return an empty string
3040 return "";
3041 }
3042 }
3043
3044 // Does the given parent have the given child?
3045 function xmlHasChild(parent, name)
3046 {
3047 var child = parent.getElementsByTagName(name);
3048 return child && child.length;
3049 }
3050
3051 /*
3052 * General xml path parser. This takes an XML node and a path string, and
3053 * returns the value of the child or attribute specified by the path. The
3054 * path has these forms:
3055 *
3056 *. ele - a single child element description, as defined below
3057 *. ele/path - evaluate xpath(ele, path)
3058 *
3059 * 'ele' descriptions:
3060 *
3061 *. tag - first child node with tag name 'tag'
3062 *. tag[n] - nth child node with tag name 'tag'
3063 *. tag[*] - list of all children with tag name 'tag'
3064 *
3065 * The final path element can have a modifier:
3066 *
3067 *. .attr - get the value of attribute 'attr'
3068 *. #text - get the text contents of the node
3069 */
3070 function xpath(node, path)
3071 {
3072 // if the path isn't already an array, split it by '/' element
3073 if (typeof(path) == "string")
3074 path = path.split("/");
3075
3076 // pull the first element out of the list
3077 var ele = path.shift();
3078
3079 // if this is the last element, check for modifiers
3080 var mod = null, idx;
3081 if (path.length == 0 && (idx = ele.search(/\..+$|#text$/)) >= 0)
3082 {
3083 // separate the modifier and the element name
3084 mod = ele.substr(idx);
3085 ele = ele.substr(0, idx);
3086 }
3087
3088 // check for a [*] or [n] index; if it's not there, the default is zero
3089 var nodeIdx = 0;
3090 if ((idx = ele.search(/\[\*\]/)) >= 0)
3091 {
3092 // they want an array of all of the matching nodes
3093 nodeIdx = -1;
3094 ele = ele.substr(0, idx);
3095 }
3096 else if ((idx = ele.search(/\[\d+\]$/)) >= 0)
3097 {
3098 // get the index value, and remove it from the element name
3099 nodeIdx = parseInt(ele.substr(idx+1));
3100 ele = ele.substr(0, idx);
3101 }
3102
3103 // find the given child
3104 node = xmlChild(node, ele);
3105
3106 // if we didn't find it, return failure
3107 if (!node)
3108 return null;
3109
3110 // if the index is out of bounds, return failure
3111 if (nodeIdx >= node.length)
3112 return null;
3113
3114 // if they want the node array, return the array
3115 if (nodeIdx == -1)
3116 {
3117 // build a true array (rather than an XML node list object)
3118 for (var arr = [], i = 0 ; i < node.length ; ++i)
3119 arr.push(node[i]);
3120
3121 // use the array
3122 node = arr;
3123 }
3124 else
3125 {
3126 // pull out the indexed node
3127 node = node[nodeIdx];
3128 }
3129
3130 // if there's anything left, evaluate the rest of the path
3131 if (path.length)
3132 return xpath(node, path);
3133
3134 // That's the end of the path. If we have a modifier, apply the
3135 // modifier.
3136 if (mod)
3137 {
3138 if (mod == "#text")
3139 {
3140 // they want the text value of the node
3141 if (nodeIdx == -1)
3142 return node.map(function(ele) { return xmlNodeText(ele); });
3143 else
3144 return xmlNodeText(node);
3145 }
3146 else if (mod.substr(0, 1) == '.')
3147 {
3148 // they want an attribute - get the attribute object
3149 var attrName = mod.substr(1);
3150 if (nodeIdx == -1)
3151 {
3152 return node.map(function(ele) {
3153 var attr = ele.attributes.getNamedItem(attrName);
3154 return attr ? attr.value : null;
3155 });
3156 }
3157 else
3158 {
3159 var attr = node.attributes.getNamedItem(attrName);
3160 return attr ? attr.value : null;
3161 }
3162 }
3163 }
3164
3165 // no modifier - just return the node itself
3166 return node;
3167 }
3168
3169
3170 /* ------------------------------------------------------------------------ */
3171 /*
3172 * Handle a command hyperlink.
3173 */
3174 function gamehref(ev, href, win, ele)
3175 {
3176 // send this to the target window, if found
3177 if (win = $win(win))
3178 return win.gamehref(ev, href, null, ele);
3179
3180 // otherwise, we can't handle it - just ignore it
3181 return false;
3182 }
3183
3184 /* ------------------------------------------------------------------------ */
3185 /*
3186 * Log a debugging message
3187 */
3188 function debugLog(msg)
3189 {
3190 // send this to our parent window, if we have one
3191 if (window.parent && window.parent != window)
3192 window.parent.debugLog(msg);
3193 }
3194
3195 function debugLogLn(msg)
3196 {
3197 debugLog(msg + "<br><hr>");
3198 }
3199
3200 /*
3201 * It's sometimes helpful during development to see a stack trace in the
3202 * debug log, especially This is pretty user-unfriendly information, though, so we
3203 * omit it by default. If you do want to enable it during your development
3204 * and testing process, add this code to the functions above, or simply add
3205 * it directly wherever you'd like to see a stack trace.
3206 *
3207 *. debugLog(
3208 *. getStackTrace().map(
3209 *. function(ele) {return ele.desc.htmlify();}).join("<br>")
3210 *. + "<br><br>");
3211 */
3212
3213
3214 /* ------------------------------------------------------------------------ */
3215 /*
3216 * Show a custom dialog. See main.js for details on the parameters object.
3217 */
3218 function showDialog(params)
3219 {
3220 // send this to the top window
3221 $win().showDialog(params);
3222 }
3223
3224 /*
3225 * Show an alert dialog using the in-line dialog manager.
3226 */
3227 function $alert(message, title)
3228 {
3229 showDialog({
3230 title: title ? title : "Message",
3231 contents: message.htmlify()
3232 });
3233 }
3234
3235 /*
3236 * Show a yes/no confirmation dialog using the in-line dialog manager. On
3237 * closing the dialog, we'll call func(true) if they clicked Yes,
3238 * func(false) if No.
3239 */
3240 function $confirm(message, func, title)
3241 {
3242 showDialog({
3243 title: title ? title : "Confirm",
3244 contents: message.htmlify(),
3245 buttons: [
3246 { name: "Yes", val: true, key: "Y" },
3247 { name: "No", val: false, isCancel: true, key: "N" }
3248 ],
3249 dismiss: function(dlg, btn) {
3250 func(btn && btn.val);
3251 return true;
3252 }
3253 });
3254 }
3255
3256 /* ------------------------------------------------------------------------ */
3257 /*
3258 * Alpha (transparency) control. 'pct' is a percentage opacity value from
3259 * 0 to 100.
3260 */
3261 function setAlpha(ele, pct)
3262 {
3263 ele = $(ele);
3264 if (ele.filters)
3265 {
3266 // IE's typically overwrought approach
3267 pct = Math.floor(pct);
3268 if (ele.filters.alpha)
3269 {
3270 // already have an alpha filter - set it directly
3271 ele.filters.alpha.opacity = pct;
3272 }
3273 else
3274 {
3275 // No alpha yet - add it via the style. In IE8+, the filter
3276 // name requires the full "progid:DXImageTransform..." notation;
3277 // otherwise that notation isn't allowed, and we have to use
3278 // the simple "alpha" name.
3279 var fn = (BrowserInfo.ie && BrowserInfo.ie >= 8
3280 ? "progid:DXImageTransform.Microsoft.Alpha" : "alpha");
3281 var f = fn + "(opacity=" + pct + ")";
3282
3283 // if we have any filters, append this to the existing filter
3284 // style string, otherwise just set the initial filter style
3285 if (ele.filters.length > 0)
3286 ele.style.filter += " " + f;
3287 else
3288 ele.style.filter = f;
3289 }
3290 }
3291
3292 // everyone else (including IE9+) uses standard CSS 'opacity'
3293 try { ele.style.opacity = "" + pct/100; } catch(exc) { }
3294 }
3295
3296 // active fader threads
3297 var faderThreads = [];
3298
3299 /*
3300 * Fade an object in or out over a given time interval. 'dir' is 1 for
3301 * fading in, -1 for fading out. 't' is the time interval in milliseconds
3302 * for the overall fade. 'doneFunc' is an optional function to call when
3303 * the fade is completed.
3304 */
3305 function startFade(ele, dir, t, doneFunc)
3306 {
3307 // get the actual element
3308 ele = $(ele);
3309
3310 // kill any existing fader thread for this element
3311 var oldThread = killFaderThread(ele);
3312
3313 // figure the interval length based on the total fade time
3314 var interval = (t < 50 ? 5 : t < 250 ? 10 : 25);
3315
3316 // calculate how many of our intervals fit into t
3317 var intervals = t/interval;
3318
3319 // if we have no more than one interval, simply finish the fade now
3320 if (intervals < 2)
3321 {
3322 setAlpha(ele, dir > 0 ? 100 : 0);
3323 if (doneFunc)
3324 doneFunc();
3325 return;
3326 }
3327
3328 // start at full on or off
3329 var start = dir > 0 ? 0 : 100;
3330
3331 // ...unless a fade was in progress, in which case start at the
3332 // actual current alpha
3333 if (oldThread)
3334 start = oldThread.alpha;
3335
3336 // get the amount of fade per interval
3337 var step = dir * (100 / intervals);
3338
3339 // create a tracker object for this element and add it to our list
3340 var t = {ele: ele, doneFunc: doneFunc, alpha: start,
3341 interval: interval, step: step};
3342 faderThreads.push(t);
3343
3344 // start the fade timer running
3345 t.timer = setTimeout(function() { fadeFunc(t); }, 0);;
3346 }
3347
3348 function fadeFunc(t)
3349 {
3350 // calculate the next value
3351 t.alpha += t.step;
3352
3353 // limit the result to 0..100
3354 t.alpha = (t.alpha < 0 ? 0 : t.alpha > 100 ? 100 : t.alpha);
3355
3356 // set the new alpha
3357 setAlpha(t.ele, t.alpha);
3358
3359 // check to see if we're still going
3360 if (t.step > 0 ? t.alpha < 100 : t.alpha > 0)
3361 {
3362 // more to do - set the timer for the next step
3363 setTimeout(function() { fadeFunc(t); }, t.interval);
3364 }
3365 else
3366 {
3367 // done - remove our thread from the list
3368 for (var i = 0 ; i < faderThreads.length ; ++i)
3369 {
3370 if (faderThreads[i] == t)
3371 {
3372 faderThreads.splice(i, 1);
3373 break;
3374 }
3375 }
3376
3377 // call the 'done' callback, if there is one
3378 if (t.doneFunc)
3379 t.doneFunc();
3380 }
3381 }
3382
3383 function killFaderThread(ele)
3384 {
3385 // look for an existing fader for this element
3386 for (var i = 0 ; i < faderThreads.length ; ++i)
3387 {
3388 // if this is the one, kill this thread
3389 var t = faderThreads[i];
3390 if (t.ele == ele)
3391 {
3392 // cancel the timer
3393 clearTimeout(t.timer);
3394
3395 // remove the thread from the list
3396 faderThreads.splice(i, 1);
3397
3398 // if there's a finisher callback, invoke it now
3399 if (t.doneFunc)
3400 t.doneFunc();
3401
3402 // return the thread object
3403 return t;
3404 }
3405 }
3406
3407 // didn't find a fader for this element
3408 return null;
3409 }
3410
3411
3412 /* ------------------------------------------------------------------------ */
3413 /*
3414 * Image cache. We use this to pre-load images that we might need if the
3415 * network connection is lost (e.g., error dialog background images), and
3416 * for images that are needed in UI responses and thus must be immediately
3417 * ready to display without a network delay to load them.
3418 */
3419 var imageCache = [];
3420 function cacheImage(name)
3421 {
3422 // create an Image object for the image
3423 var i = new Image();
3424
3425 // load it
3426 i.src = name;
3427
3428 // save it in our cache list
3429 imageCache.push(i);
3430 }
3431
3432 /* ------------------------------------------------------------------------ */
3433 /*
3434 * Get the installed font list.
3435 *
3436 * On systems with Flash, this uses our custom Flash object to retrieve the
3437 * actual list of installed fonts. Where Flash isn't available, we'll use
3438 * a canned list of common fonts, but we'll filter it (using some CSS
3439 * kludgery) to include only the fonts actually present, so we'll return a
3440 * subset of installed fonts.
3441 */
3442 function getFontList()
3443 {
3444 // forward the request to the top-level winodw, which has the flash
3445 // object and supporting code
3446 return $win().getFontList();
3447 }
3448
3449 /*
3450 * Rebuild the font list. This starts the build process and returns
3451 * immediately. The build process runs in the background; when complete,
3452 * we call the callback.
3453 */
3454 function buildFontList(doneFunc)
3455 {
3456 $win().TADS_swf.buildFontList(doneFunc);
3457 }
3458
3459
3460 /* ------------------------------------------------------------------------ */
3461 /*
3462 * Parse an HTML tag attribute list. Returns an object giving the
3463 * attribute values keyed by attribute ID.
3464 */
3465 function parseTagAttrs(str)
3466 {
3467 // create an empty object to hold the attributes
3468 var attrs = { };
3469
3470 // parse the string
3471 while (str)
3472 {
3473 // match the next attribute
3474 var m = str.match(/^\s+([a-z0-9]+)(=([^\s]+|"[^"]+"|'[^']+'))?/i);
3475 if (!m)
3476 break;
3477
3478 // get the attribute value
3479 var val = RegExp.$3;
3480
3481 // if it's quoted, remove the quotes
3482 if (val.charAt(0) == '"' || val.charAt(0) == '\'')
3483 val = val.substr(1, val.length - 2);
3484
3485 // store the attribute
3486 attrs[RegExp.$1] = val;
3487
3488 // remove the bit we just parsed
3489 str = str.substr(m[0].length);
3490 }
3491
3492 // return the attribute list
3493 return attrs;
3494 }
3495
3496 /* ------------------------------------------------------------------------ */
3497 /*
3498 * CSS color parsing
3499 */
3500
3501 // parse a color in CSS format, either "#rrggbb" or "rgb(r,g,b)", returning
3502 // the integer rrggbb value
3503 function parseColor(val)
3504 {
3505 // remove spaces
3506 val = val.replace(/\s/g, "");
3507
3508 // check the various formats - #rgb, #rrggbb, rgb(r,g,b)
3509 var r, g, b;
3510 if (val.match(/^rgb\((\d+),(\d+),(\d+)\)/i))
3511 {
3512 // rgb(r,g,b) decimal format
3513 r = parseInt(RegExp.$1);
3514 g = parseInt(RegExp.$2);
3515 b = parseInt(RegExp.$3);
3516 }
3517 else if (val.match(/^#[0-9a-f]{3}$/i))
3518 {
3519 // #rgb format - expand into #rrggbb
3520 r = parseInt(val.substr(1) + val.substr(1), 16);
3521 g = parseInt(val.substr(2) + val.substr(2), 16);
3522 b = parseInt(val.substr(3) + val.substr(3), 16);
3523 }
3524 else if (val.match(/^#[0-9a-f]{4,6}/i))
3525 {
3526 // #rrggbb format
3527 return parseInt(val.substr(1, 6), 16);
3528 }
3529 else if (val.match(/^[0-9a-f]+/))
3530 {
3531 // rrggbb format (without the #)
3532 return parseInt(val.substr(1, 6), 16);
3533 }
3534 else
3535 {
3536 // unknown format
3537 return 0;
3538 }
3539
3540 // combine the components into the result value
3541 return ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
3542 }
3543
3544 // unparse a color in combined integer format
3545 function unparseColor(color)
3546 {
3547 return unparseCColor((color >> 16) & 0xff,
3548 (color >> 8) & 0xff,
3549 color & 0xff);
3550 }
3551
3552 // unparse a color in component format into a CSS #rrggbb string
3553 function unparseCColor(r, g, b)
3554 {
3555 // combine the RGB values into an integer
3556 var color = ((r << 16) | (g << 8) | b);
3557
3558 // convert it to a hex string
3559 color = color.toString(16);
3560
3561 // add the "#" and leading zeros to pad to 6 digits
3562 return "#000000".substr(0, 7 - color.length) + color;
3563 }
3564
3565 // generate the canonical #rrggbb format for a color in any CSS format
3566 function canonicalizeColor(color)
3567 {
3568 return unparseColor(parseColor(color));
3569 }
3570
3571
3572
3573 /* ------------------------------------------------------------------------ */
3574 /*
3575 * Flash player plug-in version detection. Returns the version string if
3576 * the flash player plug-in is installed, null otherwise.
3577 */
3578 function getFlashPlayerVersion()
3579 {
3580 // First, try the plugin list, which everyone except IE uses. If
3581 // that fails, and we're not on a Mac, try the IE ActiveX loader.
3582 if (navigator.plugins && navigator.plugins.length > 0)
3583 {
3584 var p;
3585 if (navigator.mimeTypes
3586 && (p = navigator.mimeTypes['application/x-shockwave-flash'])
3587 && (p = p.enabledPlugin)
3588 && p.description)
3589 return p.description;
3590 }
3591 else if (navigator.appVersion.indexOf("Mac") == -1 && window.execScript)
3592 {
3593 // possible class IDs
3594 var clid = ["ShockwaveFlash.ShockwaveFlash.7",
3595 "ShockwaveFlash.ShockwaveFlash.6",
3596 "ShockwaveFlash.ShockwaveFlash"];
3597
3598 // try each class ID
3599 for (var i = 0 ; i < clid.length ; ++i)
3600 {
3601 var obj;
3602 try
3603 {
3604 // try loading this class ID
3605 obj = new ActiveXObject(clid[i]);
3606
3607 // got it - return its version
3608 obj.AllowScriptAccess = "always";
3609 return obj.GetVariable("$version");
3610 }
3611 catch (exc)
3612 {
3613 // failed to load the current class ID
3614 obj = null;
3615 }
3616 }
3617 }
3618
3619 // if we get here, it means that we've exhausted our detection
3620 // alternatives without finding anything, so return failure
3621 return null;
3622 }
3623
3624
3625 /* ------------------------------------------------------------------------ */
3626 /*
3627 * Cross-browser keyboard event handling. This package smooths out most of
3628 * the differences between browsers for keyboard events, by providing a
3629 * uniform event model and key naming scheme across browsers, while still
3630 * retaining full information on special keys, modifiers, and so on.
3631 *
3632 * To set up a keyboard event handler with this package, DON'T write
3633 * keypress and keydown handlers. Instead, for each element where you want
3634 * to handle keyboard events, write a single key handler function with this
3635 * interface:
3636 *
3637 *. function myOnKey(desc, ctx)
3638 *
3639 * This function will be called once per keystroke with details on the key
3640 * pressed and the character generated, if any. 'desc' is a descriptor
3641 * object with information on the key event, as describe below, and 'ctx'
3642 * is the context argument you specify in the onkeydown and onkeypress
3643 * specifiers.
3644 *
3645 * To install your custom event handler function, add onkeydown and
3646 * onkeypress attributes to the HTML element where you want to intercept
3647 * the key events, as follows:
3648 *
3649 *. <input onkeydown="javascript:return $kd(event, myOnKey, myCtx);"
3650 *. onkeypress="javascript:return $kp(event, myOnKey, myCtx);">
3651 *
3652 * 'myOnKey' is the name of your custom key event handler function. The
3653 * rest is boilerplate that you should copy as shown. 'myCtx' is an
3654 * optional context argument for your function; if included, it's simply
3655 * passed as the second argument to myOnKey().
3656 *
3657 * The descriptor object 'desc' has the following properties:
3658 *
3659 *. keyName: a string giving the DOM 3 key identifier for the
3660 *. keyboard key pressed
3661 *. keyLoc: 0 for a regular key, 1 for the left key of a paired
3662 *. modifier key (e.g., Left Ctrl), 2 for the right key
3663 *. of a paired modifier key, 3 for a numeric keypad key
3664 *. ch: a string giving the character generated by the key, or
3665 *. null for a special key
3666 *. modifier: 0 for ordinary keys; 1 if the key is a temporpary
3667 *. modifier key that applies while held down (Shift, Ctrl,
3668 *. Alt, Meta, Option, Windows), 2 if the key is a modifier
3669 *. lock key that toggles a keyboard mode (Caps Lock,
3670 *. Num Lock, Scroll Lock)
3671 *. shiftKey: true if the Shift key was pressed, false if not
3672 *. ctrlKey: true if the Ctrl key was pressed, false if not
3673 *. altKey: true if the Alt key was pressed, false if not
3674 *. metaKey: true if the Meta key was pressed, false if not (on
3675 *. Macs, the Command key is the Meta key)
3676 *. keyCode: the raw key code generated by the browser
3677 *. event: the original javascript event object for the event
3678 *
3679 * Your function should return true or false: true means that the browser
3680 * should continue to the default processing, false means that the browser
3681 * should not perform its default processing. For example, for an <INPUT>
3682 * control, returning false blocks the browser from inserting the character
3683 * for the keystroke into the field.
3684 *
3685 * You can find the full set of DOM key codes at
3686 * http://www.w3.org/TR/DOM-Level-3-Events/#keyset-keyidentifiers. Here's
3687 * a brief list of the most common keys:
3688 *
3689 *. Up, Down, Left, Right - cursor arrows
3690 *. Home, End, Insert, PageUp, PageDown - cursor navigation
3691 *. U+007F - Delete (Unicode value for Delete)
3692 *. U+0008 - Backspace
3693 *. U+0009 - Tab
3694 *. U+001B - Escape
3695 *. Enter - Return/Enter
3696 *. U+0041 - "A" (Unicode value for capital A; likewise for other letters)
3697 *. U+0033 - 3/# key (Unicode for the unshifted symbol on the key)
3698 *. F1 - function key F1 (likewise F2, F3, ...)
3699 *
3700 * Note that the keyLoc value will sometimes return 0 for both versions of
3701 * a modifier key. This means that the current browser doesn't distinguish
3702 * the left/right versions. keyLoc will also return 0 for the numeric
3703 * keypad on Opera, which doesn't provide enough information to distinguish
3704 * the numeric keypad from the regular top row digit keys. You should
3705 * therefore avoid using the keypad digit keys for special commands, unless
3706 * you provide equivalents somewhere else on the keyboard for Opera users.
3707 *
3708 * The 'keyCode' value is browser-specific - it's simply the code passed in
3709 * from the browser in the original event object. You shouldn't need to
3710 * look at this in most cases, and indeed you shouldn't *want* to look at
3711 * it - it's incredibly hard to interpret properly because each browser has
3712 * its own numbering scheme, and some browsers have even changed schemes in
3713 * new versions. This is a big part of why you'd want to use this package
3714 * to start with. We include the raw key code really just for edge cases
3715 * that exceed the capabilities of this package, where we might have
3716 * discarded some information that we couldn't represent portably.
3717 *
3718 * The 'event' object also varies considerably by browser. For the most
3719 * part, you shouldn't need or want to look at this, since a major part of
3720 * this package's point is to provide you with the same information in a
3721 * somewhat more sane cross-browser format. However, as with the 'keyCode'
3722 * value, there might be occasional situations where you'll need some
3723 * original event information that we discarded. Use the event object as a
3724 * last resort when you can't get what you need from 'desc'.
3725 *
3726 * Another complication using 'keyCode' and/or 'event' is that your event
3727 * handler can be invoked on either the keydown or the keypress phase, so
3728 * you'll have to be careful to interpret 'keyCode' and 'event' using the
3729 * right context. 'keyCode' in particular often has different meanings in
3730 * the two phases. You can get the current phase from desc.event.type.
3731 *
3732 * Credits:
3733 *
3734 * Much of the functionality implemented here is based on the browser data
3735 * collected by Jan Wolter and documented in "JavaScript Madness: Keyboard
3736 * Events": http://unixpapa.com/js/key.html.
3737 */
3738
3739 // Key Code to key name mapping for the most common assignments. Some
3740 // browsers differ in some places, which we'll handle with exception
3741 // tables. Each entry consists of:
3742 //
3743 // [keyID, isSpecial, location, ctlChar, isMod]
3744 //
3745 // keyID - the key identifier per the DOM 3 specification.
3746 //
3747 // isSpecial - 0 if this is a "regular" key, which generates a character
3748 // code. 1 if this is a "special" key OTHER THAN a modifier key. A
3749 // special key is a key that doesn't generate a character code. These
3750 // include the cursor arrows, other cursor keys (Home, End, etc), paging
3751 // keys (Page Up, Page Down), function keys, etc. The traditional ASCII
3752 // control keys (Enter, Backspace, Tab, Escape, Delete) are NOT special,
3753 // because they do generate character codes, even though those characters
3754 // aren't printable. isSpecial is 2 for "modifier" keys. Modifiers are
3755 // non-character keys that combine with other keys to change their
3756 // meanings: Shift, Ctrl, Alt, Option, Meta, Windows, Apple/Command.
3757 // Like other specials, these don't generate character codes. We
3758 // distinguish them in the table because they have slightly different
3759 // behavior from other special keys in some browsers.
3760 //
3761 // location - the key location, per the DOM 3 specification: 0 for ordinary
3762 // keys on the main keyboard, 1 for the left version of a key mirrored on
3763 // both sides of the keyboard (such as Shift or Ctrl), 2 for the right
3764 // version of a mirrored key, and 3 for a key on the numeric keypad. The
3765 // key location can only be reliably determined from the DOM 2 event data
3766 // in a handful of cases, but we'll use this to pass along the information
3767 // when we can infer it. For cases where it's not possible to distinguish
3768 // the various possible versions of a key, we'll just use '0'.
3769 //
3770 // ctlChar - a few browsers (e.g., Mozilla 5) treat the ASCII control
3771 // characters (Enter, Tab, Backspace, Escape) as special characters, and
3772 // don't generate character codes for them. This element gives the ASCII
3773 // control character for these cases, so that we can plug them in manually
3774 // when needed.
3775 //
3776 // isMod - 0 for ordinary keys, 1 for temporary modifiers keys (Shift,
3777 // Ctrl, Alt, Meta, Option, Windows), 2 for shift lock keys that toggle
3778 // keyboard modes (Caps Lock, Num Lock, Scroll Lock).
3779 //
3780
3781 var KeyMapper = {
3782 commonKeyCodeMap: {
3783 65: ["U+0041", 0, 0, 0, 0], // A
3784 66: ["U+0042", 0, 0, 0, 0], // B
3785 67: ["U+0043", 0, 0, 0, 0], // C
3786 68: ["U+0044", 0, 0, 0, 0], // D
3787 69: ["U+0045", 0, 0, 0, 0], // E
3788 70: ["U+0046", 0, 0, 0, 0], // F
3789 71: ["U+0047", 0, 0, 0, 0], // G
3790 72: ["U+0048", 0, 0, 0, 0], // H
3791 73: ["U+0049", 0, 0, 0, 0], // I
3792 74: ["U+004A", 0, 0, 0, 0], // J
3793 75: ["U+004B", 0, 0, 0, 0], // K
3794 76: ["U+004C", 0, 0, 0, 0], // L
3795 77: ["U+004D", 0, 0, 0, 0], // M
3796 78: ["U+004E", 0, 0, 0, 0], // N
3797 79: ["U+004F", 0, 0, 0, 0], // O
3798 80: ["U+0050", 0, 0, 0, 0], // P
3799 81: ["U+0051", 0, 0, 0, 0], // Q
3800 82: ["U+0052", 0, 0, 0, 0], // R
3801 83: ["U+0053", 0, 0, 0, 0], // S
3802 84: ["U+0054", 0, 0, 0, 0], // T
3803 85: ["U+0055", 0, 0, 0, 0], // U
3804 86: ["U+0056", 0, 0, 0, 0], // V
3805 87: ["U+0057", 0, 0, 0, 0], // W
3806 88: ["U+0058", 0, 0, 0, 0], // X
3807 89: ["U+0059", 0, 0, 0, 0], // Y
3808 90: ["U+005A", 0, 0, 0, 0], // Z
3809 49: ["U+0031", 0, 0, 0, 0], // 1
3810 50: ["U+0032", 0, 0, 0, 0], // 2
3811 51: ["U+0033", 0, 0, 0, 0], // 3
3812 52: ["U+0034", 0, 0, 0, 0], // 4
3813 53: ["U+0035", 0, 0, 0, 0], // 5
3814 54: ["U+0036", 0, 0, 0, 0], // 6
3815 55: ["U+0037", 0, 0, 0, 0], // 7
3816 56: ["U+0038", 0, 0, 0, 0], // 8
3817 57: ["U+0039", 0, 0, 0, 0], // 9
3818 48: ["U+0030", 0, 0, 0, 0], // 0
3819 32: ["U+0020", 0, 0, 0, 0], // space
3820 13: ["Enter", 0, 0, "\015", 0], // Enter/Return
3821 9: ["U+0009", 1, 0, "\011", 0], // Tab
3822 27: ["U+001B", 0, 0, "\033", 0], // Escape
3823 8: ["U+0008", 1, 0, "\010", 0], // Backspace
3824 16: ["Shift", 2, 0, 0, 1], // Shift
3825 17: ["Control", 2, 0, 0, 1], //Control (Ctrl)
3826 18: ["Alt", 2, 0, 0, 1], // Alt
3827 19: ["Pause", 1, 0, 0, 0], // Pause/Break
3828 20: ["CapsLock", 2, 0, 0, 2], // Caps Lock
3829 144: ["NumLock", 2, 0, 0, 2], // Num Lock
3830 145: ["ScrollLock", 2, 0, 0, 2], // Scroll Lock
3831 37: ["Left", 1, 0, 0, 0], // Left cursor arrow
3832 38: ["Up", 1, 0, 0, 0], // Up cursor arrow
3833 39: ["Right", 1, 0, 0, 0], // Right cursor arrow
3834 40: ["Down", 1, 0, 0, 0], // Down cursor arrow
3835 45: ["Insert", 1, 0, 0, 0], // Insert
3836 46: ["U+007F", 1, 0, "\177", 0], // Delete
3837 36: ["Home", 1, 0, 0, 0], // Home
3838 35: ["End", 1, 0, 0, 0], // End
3839 33: ["PageUp", 1, 0, 0, 0], // Page Up (PgUp)
3840 34: ["PageDown", 1, 0, 0, 0], // Page Down (PgDn)
3841 112: ["F1", 1, 0, 0, 0], // F1
3842 113: ["F2", 1, 0, 0, 0], // F2
3843 114: ["F3", 1, 0, 0, 0], // F3
3844 115: ["F4", 1, 0, 0, 0], // F4
3845 116: ["F5", 1, 0, 0, 0], // F5
3846 117: ["F6", 1, 0, 0, 0], // F6
3847 118: ["F7", 1, 0, 0, 0], // F7
3848 119: ["F8", 1, 0, 0, 0], // F8
3849 120: ["F9", 1, 0, 0, 0], // F9
3850 121: ["F10", 1, 0, 0, 0], // F10
3851 122: ["F11", 1, 0, 0, 0], // F11
3852 123: ["F12", 1, 0, 0, 0], // F12
3853 188: ["U+002C", 0, 0, 0, 0], // "," (comma)
3854 190: ["U+002E", 0, 0, 0, 0], // "." (period)
3855 191: ["U+002F", 0, 0, 0, 0], // "/" (slash)
3856 192: ["U+0060", 0, 0, 0, 0], // "`" (back quote/grave accent)
3857 219: ["U+005B", 0, 0, 0, 0], // "[" (left square bracket)
3858 220: ["U+005C", 0, 0, 0, 0], // "\" (backslash)
3859 221: ["U+005D", 0, 0, 0, 0], // "]" (right square bracket)
3860 222: ["U+0027", 0, 0, 0, 0], // "'" (apostrophe)
3861 110: ["U+002E", 0, 3, 0, 0], // Keypad "."
3862 96: ["U+0030", 0, 3, 0, 0], // Keypad "0"
3863 97: ["U+0031", 0, 3, 0, 0], // Keypad "1"
3864 98: ["U+0032", 0, 3, 0, 0], // Keypad "2"
3865 99: ["U+0033", 0, 3, 0, 0], // Keypad "3"
3866 100: ["U+0034", 0, 3, 0, 0], // Keypad "4"
3867 101: ["U+0035", 0, 3, 0, 0], // Keypad "5"
3868 102: ["U+0036", 0, 3, 0, 0], // Keypad "6"
3869 103: ["U+0037", 0, 3, 0, 0], // Keypad "7"
3870 104: ["U+0038", 0, 3, 0, 0], // Keypad "8"
3871 105: ["U+0039", 0, 3, 0, 0], // Keypad "9"
3872 107: ["U+002B", 0, 3, 0, 0], // Keypad "+"
3873 109: ["U+002D", 0, 3, 0, 0], // Keypad "-"
3874 106: ["U+002A", 0, 3, 0, 0], // Keypad "*"
3875 111: ["U+002F", 0, 3, 0, 0], // Keypad "/"
3876 12: ["U+0035", 1, 3, 0, 0], // Keypad "5" with NumLock off
3877 91: ["Win", 1, 1, 0, 1], // Left "Windows" key (Windows)
3878 92: ["Win", 1, 2, 0, 1], // Right "Windows" key (Windows)
3879 93: ["Props", 1, 0, 0, 0] // "Properties" key (Windows)
3880 },
3881
3882 // Mozilla key mappings - these are used by Gecko-based browsers
3883 mozKeyMap: {
3884 59: ["U+003B", 0, 0, 0, 0], // ";" (semicolon)
3885 61: ["U+003D", 0, 0, 0, 0], // "=" (equals sign)
3886 109: ["U+002D", 0, 0, 0, 0], // "-" (hyphen)
3887 224: ["Meta", 1, 0, 0, 1] // Apple/Command key (Mac OS)
3888 },
3889
3890 // Key code mappings special to Gecko 1.09-based browsers
3891 moz109KeyMap: {
3892 107: ["U+003D", 0, 0, 0, 0] // "=" (equals sign) - in older
3893 // versions, this was the code for the
3894 // keypad +, but in 1.09 it seems to be
3895 // overloaded as the ordinary [=+] key
3896 },
3897
3898 // Key code mappings special to IE
3899 ieKeyMap: {
3900 186: ["U+003B", 0, 0, 0, 0], // ";" (semicolon)
3901 187: ["U+003D", 0, 0, 0, 0], // "=" (equals sign)
3902 189: ["U+002D", 0, 0, 0, 0] // "-" (hyphen)
3903 },
3904
3905 // Key mappings special to Opera 8.0-9.27 Win, Opera <9.5 Linux/Mac
3906 operaKeyMap: {
3907 59: ["U+003B", 0, 0, 0, 0], // ";" (semicolon)
3908 61: ["U+003D", 0, 0, 0, 0], // "=" (equals sign)
3909 44: ["U+002C", 0, 0, 0, 0], // "," (comma)
3910 46: ["U+002E", 0, 0, 0, 0], // "." (period)
3911 47: ["U+002F", 0, 0, 0, 0], // "/" (slash)
3912 96: ["U+0060", 0, 0, 0, 0], // "`" (backquote/grave accent)
3913 91: ["U+005B", 0, 0, 0, 0], // "[" (left square bracket)
3914 92: ["U+005C", 0, 0, 0, 0], // "\" (backslash)
3915 93: ["U+005D", 0, 0, 0, 0], // "]" (right square bracket)
3916 39: ["U+0027", 0, 0, 0, 0], // "'" (apostrophe)
3917 17: ["Control", 2, 0, 0, 1], // Control/Ctrl ; Apple/Command key on Mac
3918 219: ["Win", 2, 1, 0, 1], // Left "Windows" key (Windows)
3919 220: ["Win", 2, 2, 0, 1], // Right "Windows" key (Windows)
3920 144: ["NumLock", 1, 0, 0, 2], // Num Lock
3921 8: ["U+0008", 0, 0, "\010", 0], // Backspace isn't special on Opera
3922 9: ["U+0009", 0, 0, "\011", 0] // Tab
3923 },
3924
3925 // Key mappings special to Opera >=9.5 and Opera 7 win. These Opera
3926 // versions use the Gecko map (mozKeyMap), with the exceptions listed here.
3927 opera95KeyMap: {
3928 43: ["U+002B", 0, 3, 0, 0], // Keypad "+"
3929 42: ["U+002A", 0, 3, 0, 0], // Keypad "*"
3930 47: ["U+002F", 0, 3, 0, 0], // Keypad "/"
3931 17: ["Control", 2, 0, 0, 1], // Control/Ctrl ; Apple/Command key on Mac
3932 219: ["Win", 2, 1, 0, 1], // Left "Windows" key (Windows)
3933 220: ["Win", 2, 2, 0, 1], // Right "Windows" key (Windows)
3934 144: ["NumLock", 1, 0, 0, 2], // Num Lock
3935 8: ["U+0008", 0, 0, "\010", 0], // Backspace isn't special on Opera
3936 9: ["U+0009", 0, 0, "\011", 0] // Tab
3937 },
3938
3939 // WebKit key map. WebKit uses the same codes as IE, with one slight
3940 // exception: Tab, Escape, and Backspace are treated as special keys,
3941 // in that they don't generate keypress events.
3942 webKitKeyMap: {
3943 9: ["U+0009", 1, 0, "\011", 0], // Tab
3944 27: ["U+001B", 1, 0, "\033", 0], // Escape
3945 8: ["U+0008", 1, 0, "\010", 0] // Backspace
3946 },
3947
3948 // "Pseudo-ASCII" mappings special to Opera < 9.5 Linux & Mac,
3949 // and Konqueror
3950 pseudoAsciiKeyMap: {
3951
3952 },
3953
3954 // browser keyCode for the last keydown event
3955 kdCode: null,
3956
3957 // our key map entry for the last keydown event
3958 kdInfo: null,
3959
3960 // Should we suppress the next keydown event? For certain keys, we
3961 // need to call the user event handler in keydown in order to get in
3962 // at the right point to cancel browser default handling, if the user
3963 // handler should want to do so. In many cases, the browsers in
3964 // question don't send keypress events at all for the keys in question.
3965 // However, there are a few cases where the browser will send both
3966 // events, but since we do the handling in keydown, we need this flag
3967 // to tell our keypress handler not to repeat the user handler call.
3968 suppressKeypress: false,
3969
3970 // Opera timeout for processing potential Win keys (codes 219, 220)
3971 operaWinKeyTimeout: null,
3972
3973 // deferred keypress info, for workaround for Opera double keypad events
3974 deferredKeyPressInfo: null
3975 };
3976
3977 // General onkeydown processor.
3978 function $kd(ev, func, ctx)
3979 {
3980 // get the actual event object
3981 ev = ev || window.event;
3982
3983 // get the key code, which is always in event.keyCode
3984 var keyCode = KeyMapper.kdCode = ev.keyCode;
3985
3986 // browser info
3987 var brID = BrowserInfo.browser;
3988 var brVer = BrowserInfo.version;
3989 var brOS = BrowserInfo.OS;
3990
3991 // The *location* of the key code is the same in all browsers, but
3992 // that's a deceptive bit of uniformity, because the *meaning* of
3993 // the value stored there varies from one browser to the next, and
3994 // even from one version to the next of the same browser. To map
3995 // the key code to our portable key names, we need to run a bunch
3996 // of special-case tests for the various browsers.
3997 //
3998 // Start with the base mappings that most browsers agree on.
3999 keyInfo = KeyMapper.commonKeyCodeMap[keyCode];
4000
4001 // Now check for browser-specific exceptions
4002 var xkey = null;
4003 if (brID == "IE")
4004 {
4005 // use the IE key codes
4006 xkey = KeyMapper.ieKeyMap[keyCode];
4007 }
4008 else if (BrowserInfo.webKit)
4009 {
4010 // use the IE key codes, with the webkit exceptions
4011 xkey = KeyMapper.webKitKeyMap[keyCode];
4012 if (!xkey)
4013 xkey = KeyMapper.ieKeyMap[keyCode];
4014 }
4015 else if (BrowserInfo.gecko)
4016 {
4017 // if it's 1.09, use the 1.09 exceptions first
4018 if (BrowserInfo.gecko == 1.09)
4019 xkey = KeyMapper.moz109KeyMap[keyCode];
4020
4021 // use the standard Mozilla key codes if there wasn't an override
4022 if (!xkey)
4023 xkey = KeyMapper.mozKeyMap[keyCode];
4024 }
4025 else if ((brID == "Opera" && brVer >= 9.05)
4026 || (brID == "Opera" && brVer >= 7 && brVer < 8
4027 && brOS == "Windows"))
4028 {
4029 // these Opera versions *mostly* use mozKeyMap entries, except for
4030 // the exceptions in the opera95KeyMap (keypad and branded keys)
4031 xkey = KeyMapper.opera95KeyMap[keyCode];
4032 if (!xkey)
4033 xkey = KeyMapper.mozKeyMap[keyCode];
4034 }
4035 else if ((brID == "Opera" && brVer < 9.05)
4036 || brID == "Konqueror")
4037 {
4038 // these versions use the "pseudo-ASCII" key map
4039 xkey = pseudoAsciiKeyMap[keyCode];
4040 }
4041
4042 // Opera on Mac gives us "Control" for the Command/Apple key, when
4043 // it should really give us "Meta"
4044 if (brID == "Opera" && brOS == "Mac" && keyCode == 17)
4045 xkey = ["Meta", 1, 0, 0, 1];
4046
4047 // if we found an exception entry, it overrides the base mapping
4048 if (xkey)
4049 keyInfo = xkey;
4050
4051 // save the canonical key code information so that it's accessible in
4052 // onkeypress, and presume that we'll process the keypress if it comes
4053 KeyMapper.kdInfo = keyInfo;
4054 KeyMapper.suppressKeypress = false;
4055
4056 // If we're on Opera, and this looks like a Windows key, we have a
4057 // bit of a problem. Opera overloads the same codes for Win left,right
4058 // with the ordinary "[", "\" keys. There's a difference, though:
4059 // the Win keys don't generate keypress events, while the [ \ keys do.
4060 // So if we get to keypress for this key, we'll know it's a regular
4061 // key rather than a Win key. The snag is that we can only tell that
4062 // we have a Win key when we *don't* get a keypress event. This might
4063 // seem like it falls into the "it's impossible to prove a negative"
4064 // category, but we can deal with this via a timeout, because Opera
4065 // will queue the keypress immediately on our return. Now, once the
4066 // timeout expires without the keypress arriving, we have another
4067 // problem, which is that it's too late to cancel the keydown event
4068 // if the user callback wishes to do so. We'll accept that as a
4069 // limitation; this isn't too terrible, since the Win keys are
4070 // basically OS-level hotkeys, so it's not unreasonable to expect
4071 // that they're uncancellable anyway.
4072 if (brID == "Opera" && (keyCode == 219 || keyCode == 220))
4073 {
4074 // Set a timeout to call the callback if a keypress doesn't arrive
4075 // first, which would indicate that it's not a Win key after all
4076 var t = setTimeout(function() {
4077 callKeyFunc(func, keyInfo, null, ev, keyCode, ctx);
4078 }, 0);
4079
4080 // remember the key info and callback ID, in case the keypress occurs
4081 KeyMapper.operaWinKeyTimeout = { keyCode: keyCode, timeout: t }
4082
4083 // done with this event
4084 return false;
4085 }
4086 else
4087 {
4088 // clear the timeout record
4089 KeyMapper.operaWinKeyTimeout = null;
4090 }
4091
4092 // if we don't have any key information, proceed to keypress; no
4093 // use calling the callback now, as we have nothing to tell it
4094 if (!keyInfo)
4095 return true;
4096
4097 // Most browsers call both onkeydown and onkeypress for every key,
4098 // regular and special. Because we won't have the character code
4099 // (if any) until the onkeypress call, the simplest approach for
4100 // browsers that call both events for all keys is to return now,
4101 // and let our onkeypress handler call the user callback.
4102 //
4103 // There's a wrinkle, though: some browsers don't call onkeypress
4104 // for special keys. For these browsers, then, we have to call the
4105 // callback now, rather than waiting for onkeypress. Fortunately
4106 // there's no lost information doing this, since special keys don't
4107 // have character codes anyway. (The specific browsers are IE,
4108 // WebKit >= 525, and Konqueror 3.2.)
4109 //
4110 // You might wonder why we don't just call the callback for special
4111 // keys here, regardless of browser. The reason is that a bunch of
4112 // the other browsers (those that do call onkeypress for special
4113 // keys) have a different quirk: they don't call onkeydown for
4114 // auto-repeated special keys. So in order to generate our events
4115 // for auto-repeated specials, we need to wait until keypress for
4116 // the affected browsers. (The specific browsers are Opera,
4117 // Konqueror, WebKit < 525, Mac Gecko, and some Linux Gecko
4118 // versions.)
4119 //
4120 // Note that there's an overlapping group that calls both onkeypress
4121 // and onkeydown for special keys, including auto-repeated special
4122 // keys. For those browsers, we can call our callback for special
4123 // keys either here or in onkeypress. We'll choose to make the call
4124 // here only for browsers where we know we're not going to get
4125 // onkeypress calls at all, so that we don't have to make an extra
4126 // test to suppress onkeypress calls that we've already handled.
4127 //
4128 // If this is a shift key, we also won't get keypress events for Gecko,
4129 // WebKit >= 525, or Opera >= 10.10.
4130 //
4131 // On Windows, also call the callback immediately for Ctrl or Alt
4132 // used with regular keys. Some of the Windows browsers don't send
4133 // keypress events for these.
4134 var specialsNow = (brID == "IE"
4135 || (BrowserInfo.webKit && BrowserInfo.webKit >= 525)
4136 || (brID == "Konqueror" && brVer == 3.02));
4137 var shiftsNow = (BrowserInfo.gecko
4138 || (BrowserInfo.webKit && BrowserInfo.webKit >= 525)
4139 || (brID == "Opera" && brVer > 9.50));
4140 var ctlsNow = (brOS == "Windows"
4141 && (brID == "IE"
4142 || BrowserInfo.gecko
4143 || BrowserInfo.webKit));
4144 var altsNow = (brOS == "Windows"
4145 && (brID == "IE"
4146 || BrowserInfo.webKit));
4147
4148 if ((specialsNow && keyInfo[1])
4149 || (shiftsNow && keyInfo[1] == 2)
4150 || (ctlsNow && ev.ctrlKey && keyInfo[1] == 0)
4151 || (altsNow && ev.altKey && keyInfo[1] == 0))
4152 {
4153 // it's a special key, and we're on a browser that doesn't call
4154 // onkeypress for special keys - invoke the user callback now
4155
4156 // use the associated mapped event for special keys
4157 var ch = null;
4158 if (keyInfo[3])
4159 ch = keyInfo[3];
4160
4161 // flag that we're suppressing any subsequent keypress for this key
4162 KeyMapper.suppressKeypress = true;
4163
4164 // call the user callback
4165 return callKeyFunc(func, keyInfo, ch, ev, keyCode, ctx);
4166 }
4167 else if (brOS == "Windows" && (brID == "IE" || brID == "Opera")
4168 && keyInfo && !keyInfo[1]
4169 && (ev.ctrlKey || ev.altKey))
4170 {
4171 // process Ctrl and Alt keys in keydown for IE and Opera
4172 return callKeyFunc(func, keyInfo, null, ev, keyCode, ctx);
4173 }
4174 else
4175 {
4176 // proceed to onkeypress
4177 return true;
4178 }
4179 }
4180
4181 // General onkeypress processor
4182 function $kp(ev, func, ctx)
4183 {
4184 // get the actual event object
4185 ev = ev || window.event;
4186
4187 // if we're suppressing the keypress event, ignore it
4188 if (KeyMapper.suppressKeypress)
4189 {
4190 KeyMapper.suppressKeypress = false;
4191 return true;
4192 }
4193
4194 // browser info
4195 var brID = BrowserInfo.browser;
4196 var brVer = BrowserInfo.version;
4197 var brOS = BrowserInfo.OS;
4198
4199 // In keypress, the ASCII character for the key is either in
4200 // event.which or event.charCode.
4201 var ch;
4202 if (KeyMapper.kdInfo && KeyMapper.kdInfo[1])
4203 {
4204 // We've already mapped it to a special key, so ignore any
4205 // character information. Some browsers incorrectly set
4206 // charCode for some or all special keys.
4207 ch = null;
4208
4209 // Exception: if we're on Opera, check event.which to see if it's
4210 // a regular or special key. If we thought it was special, but it
4211 // turns out that it has a character code, it must be a key where
4212 // we couldn't tell the difference in keydown.
4213 if (brID == "Opera" && ev.which)
4214 {
4215 // assume we'll use the character code from event.which
4216 ch = String.fromCharCode(ev.which);
4217
4218 // check the key code
4219 switch (KeyMapper.kdCode)
4220 {
4221 case 45:
4222 // it's actually "-_" or "Keypad -", depending on version
4223 if (brVer >= 9.05
4224 || (brVer >= 7 && brVer < 8 && brOS == "Windows"))
4225 KeyMapper.kdInfo = ["U+002D", 0, 3, 0, 0];
4226 else
4227 KeyMapper.kdInfo = ["U+002D", 0, 0, 0, 0];
4228 break;
4229
4230 case 219:
4231 case 220:
4232 // it's really [{ or \|
4233 KeyMapper.kdInfo =
4234 [KeyMapper.kdCode == 219
4235 ? "U+005B" : "U+005C", 0, 0, 0, 0];
4236
4237 // cancel the Win key timeout, if applicable
4238 var ot = KeyMapper.operaWinKeyTimeout;
4239 if (ot && ot.keyCode == KeyMapper.kdCode)
4240 {
4241 clearTimeout(ot.timeout);
4242 KeyMapper.operaWinKeyTimeout = null;
4243 }
4244 break;
4245
4246 case 78:
4247 // it's really N
4248 KeyMapper.kdInfo = ["U+004E", 0, 0, 0, 0];
4249 break;
4250
4251 default:
4252 // It's not one of the special re-translated keys, so
4253 // it's not a regular key after all. Opera has some
4254 // weirdness where it sets event.which to a non-zero
4255 // value for some special keys, so just ignore that.
4256 ch = null;
4257 break;
4258 }
4259 }
4260 }
4261 else if (ev.which == null)
4262 {
4263 // no event.which, so this must be IE - the char is in keyCode
4264 ch = String.fromCharCode(ev.keyCode);
4265 }
4266 else if (ev.which != 0 && ev.charCode != 0)
4267 {
4268 // we have a non-zero event.which and a non-zero charCode,
4269 // so the char is in 'which'
4270 ch = String.fromCharCode(ev.which);
4271 }
4272 else
4273 {
4274 // otherwise, this must be a special key, so there is no
4275 // character code
4276 ch = null;
4277 }
4278
4279 // work around some Opera bugs
4280 if (brID == "Opera")
4281 {
4282 // Check for a weird special case: if the character is '.',
4283 // and the key code is 78, it's the keypad '.' rather than
4284 // the "N" key.
4285 if (KeyMapper.kdCode == 78 && ch == '.')
4286 KeyMapper.kdInfo = ["U+002E", 0, 3, 0, 0];
4287
4288 // Opera has a particularly strange bug where it generates
4289 // doubled keypress events for the / * - + keys on the numeric
4290 // keypad. Empirically, the first keypress of the pair is the
4291 // erroneous one, in that the browser does its default
4292 // processing on the second keypress. Opera queues both
4293 // keypress events at the same time, which is useful for
4294 // our workaround, because it means that we can set all of
4295 // the cancellation flags on the first keypress without
4296 // blocking or otherwise affecting the second one. So,
4297 // when we see the first of the pair, we'll remember it
4298 // internally, and then cancel it. That will let us recognize
4299 // the second of the pair and process it as the actual event.
4300 if (KeyMapper.kdInfo
4301 && KeyMapper.kdInfo[2] == 3
4302 && [42, 43, 45, 47].indexOf(KeyMapper.kdCode) != -1
4303 && !(KeyMapper.deferredKeyPressInfo
4304 && KeyMapper.deferredKeyPressInfo[2] == 3
4305 && KeyMapper.kdInfo[0] == KeyMapper.deferredKeyPressInfo[0]))
4306 {
4307 // remember the deferred key press for next time - when
4308 // we see the repeated event, we'll know to let it through
4309 KeyMapper.deferredKeyPressInfo = KeyMapper.kdInfo;
4310
4311 // Cancel the bubble and prevent any default processing.
4312 // The entire existence of this event is a bug, so try our
4313 // best to make it look like it never happened.
4314 cancelBubble(ev);
4315 preventDefault(ev);
4316 return false;
4317 }
4318
4319 // we're no longer waiting for a deferred keypress event
4320 KeyMapper.deferredKeyPressInfo = null;
4321 }
4322
4323 // Gecko on Windows generates alphabetic characters for Alt+letter
4324 // combinations. These should actually be treated as special characters.
4325 if ((BrowserInfo.gecko || brID == "Opera") && brOS == "Windows"
4326 && ev.altKey && ch)
4327 ch = null;
4328
4329 // if there's no character code, but we have an explicit character code
4330 // override with our mapping, apply it
4331 if (ch == null && KeyMapper.kdInfo && KeyMapper.kdInfo[3])
4332 ch = KeyMapper.kdInfo[3];
4333
4334 // we don't have any deferred keypress
4335 KeyMapper.deferredKeypressInfo = null;
4336
4337 // don't send Ctrl+Alpha events on Windows, since we've already
4338 // processed those as though they were special keys
4339 if (KeyMapper.kdCode >= 65 && KeyMapper.kdCode <= 90
4340 && ev.ctrlKey
4341 && brOS == "Windows")
4342 return true;
4343
4344 // invoke the handler
4345 return callKeyFunc(func, KeyMapper.kdInfo, ch, ev, KeyMapper.kdCode, ctx);
4346 }
4347
4348 // call the common user event handler for onkeydown/onkeypress
4349 function callKeyFunc(func, keyInfo, ch, ev, keyCode, ctx)
4350 {
4351 // if we have no key info, key code, or character, ignore it
4352 if (!ch && !keyInfo)
4353 return true;
4354
4355 // if it's Ctrl+Alpha, figure the control character
4356 if (!ch
4357 && keyCode >= 65 && keyCode <= 90
4358 && ev.ctrlKey && !ev.altKey)
4359 ch = String.fromCharCode(keyCode - 64);
4360
4361 // set up the key descriptor
4362 var desc = {
4363 // key name, location, and generated character
4364 keyName: keyInfo && keyInfo[0],
4365 keyLoc: keyInfo && keyInfo[2],
4366 ch: ch,
4367
4368 // shift key status
4369 shiftKey: ev.shiftKey,
4370 ctrlKey: ev.ctrlKey,
4371 altKey: ev.altKey,
4372 metaKey: ev.metaKey,
4373
4374 // modifier key flag
4375 modifier: keyInfo && keyInfo[4],
4376
4377 // define the DOM 3 property names as well
4378 keyIdentifier: keyInfo && keyInfo[0],
4379 keyLocation: keyInfo && keyInfo[2],
4380
4381 // include the raw browser key code and event object
4382 keyCode: keyCode,
4383 event: ev
4384 };
4385
4386 // for Mac IE, Command sets Ctrl, whereas it should set Meta
4387 if (BrowserInfo.brID == "IE" && BrowserInfo.OS == "Mac")
4388 {
4389 desc.metaKey = ev.ctrlKey;
4390 desc.ctrlKey = false;
4391 }
4392
4393 // call the user function and return the result
4394 return func(desc, ctx);
4395 }
4396
4397 /* ------------------------------------------------------------------------ */
4398 /*
4399 * Browser detector. Call BrowserInfo.init() during page load to do the
4400 * sensing work, then refer to BrowserInfo.browser for the browser ID, or
4401 * use the various browser-specific properties to test for the respective
4402 * browsers.
4403 *
4404 * This object identifies the specific browser, and separately lets you
4405 * determine if it's based on one of the common browser core libraries
4406 * (WebKit, Gecko), and if so the core library version. The core library
4407 * identification is useful because many special-case quirks are features
4408 * of the library rather than the specific browser, and will apply to any
4409 * browser based on that library. Code to work around (or exploit) such a
4410 * quirk is simpler and more robust if it can just check a library version
4411 * rather than enumerating the individual browsers based on the library.
4412 *
4413 * Credits: adapted from http://www.quirksmode.org/js/detect.html.
4414 */
4415 var BrowserInfo = {
4416 // browser ID string, version number (as a float), and OS platform
4417 browser: "Unknown",
4418 version: 0,
4419 OS: "Unknown",
4420
4421 // Specific browser ID properties. We'll set the appropriate property
4422 // for the detected browser to its version number, as a float.
4423 opera: false,
4424 safari: false,
4425 firefox: false,
4426 ie: false,
4427 konqueror: false,
4428
4429 // WebKit version, if this is a WebKit-based browser
4430 webKit: false,
4431
4432 // Gecko version, if this is a Gecko-based browser
4433 gecko: false,
4434
4435 // initialize
4436 init: function()
4437 {
4438 // get the UA string
4439 var ua = navigator.userAgent;
4440
4441 // identify the browser
4442 this.browser = this.searchString(this.dataBrowser);
4443
4444 // identify the browser version
4445 this.version = this.searchVersion(ua)
4446 || this.searchVersion(navigator.appVersion)
4447 || 0;
4448
4449 // identify the OS platform
4450 this.OS = this.searchString(this.dataOS) || "Unknown";
4451
4452 // determine if it's WebKit-based, and note the version if so
4453 var idx = ua.indexOf("AppleWebKit/");
4454 if (idx != -1)
4455 this.webKit = this.parseVsnFloat(ua.substr(idx + 12));
4456
4457 // detremine if it's a Gecko-based browser
4458 idx = ua.indexOf("Gecko/"), idx2 = ua.indexOf("rv:");
4459 if (idx != -1 && idx2 != -1)
4460 this.gecko = this.parseVsnFloat(ua.substr(idx2 + 3));
4461
4462 // set properties for some specific browser types
4463 this.opera = this.versionIf("Opera");
4464 this.safari = this.versionIf("Safari");
4465 this.firefox = this.versionIf("Firefox");
4466 this.ie = this.versionIf("IE");
4467 this.konqueror = this.versionIf("Konqueror");
4468
4469 // if we're on Opera, customize the text adjustment method
4470 if (this.opera)
4471 {
4472 // opera doesn't render unicode typographical spaces, so replace
4473 // them with ordinary spaces
4474 this.adjustText = function(txt) {
4475 return txt.replace(/\u2002/g, ' ');
4476 };
4477 }
4478 },
4479
4480 versionIf: function(browser)
4481 {
4482 // if the ID matches our detected browser, return the version number
4483 return (this.browser == browser ? this.version : false);
4484 },
4485
4486 searchString: function(data)
4487 {
4488 // search the item list
4489 for (var i = 0 ; i < data.length ; i++)
4490 {
4491 var dataString = data[i].src || navigator.userAgent;
4492 this.versionSearchString = data[i].vsnKey || data[i].id;
4493 if (dataString.indexOf(data[i].key) != -1)
4494 return data[i].id;
4495 }
4496
4497 // not found
4498 return null;
4499 },
4500
4501 searchVersion: function(dataString)
4502 {
4503 var index = dataString.indexOf(this.versionSearchString);
4504 if (index >= 0)
4505 return this.parseVsnFloat(dataString.substring(
4506 index + this.versionSearchString.length + 1));
4507 else
4508 return 0;
4509 },
4510
4511 dataBrowser: [
4512 { key: "Chrome", id: "Chrome" },
4513 { key: "OmniWeb", vsnKey: "OmniWeb/", id: "OmniWeb" },
4514 { src: navigator.vendor, key: "Apple", id: "Safari", vsnKey: "Version" },
4515 { key: "Opera", id: "Opera" },
4516 { src: navigator.vendor, key: "iCab", id: "iCab" },
4517 { src: navigator.vendor, key: "KDE", id: "Konqueror" },
4518 { key: "Firefox", id: "Firefox" },
4519 { src: navigator.vendor, key: "Camino", id: "Camino" },
4520 { key: "Netscape", id: "Netscape" },
4521 { key: "MSIE", id: "IE", vsnKey: "MSIE" },
4522 { key: "Gecko", id: "Gecko", vsnKey: "rv" },
4523 { key: "Mozilla", id: "Netscape", vsnKey: "Mozilla" }
4524 ],
4525
4526 dataOS: [
4527 { src: navigator.platform, key: "Win", id: "Windows" },
4528 { src: navigator.platform, key: "Mac", id: "Mac" },
4529 { src: navigator.userAgent, key: "iPhone", id: "iPhone/iPod" },
4530 { src: navigator.platform, key: "Linux", id: "Linux" }
4531 ],
4532
4533 // Parse a version number as a floating point value. This parses a
4534 // dotted version number string "x.y.z.w" as though it were a floating
4535 // point value, effectively pulling out the "x" as the integer portion
4536 // and the "y" as the fractional portion, ignoring any addition elements.
4537 // We do one extra bit of processing, though: if "y" is only one digit
4538 // long, we treat it as though it were "x.0y", so that we treat version
4539 // "1.9" as less than "1.10". This doesn't generalize indefinitely,
4540 // but it covers the
4541 parseVsnFloat: function(str)
4542 {
4543 return parseFloat(str.replace(
4544 /^(\d+\.)(\d)([^\d]|$)/, function(m, x, y, z) {
4545 return x + "0" + y + z;
4546 }));
4547 },
4548
4549 // perform browser-specific adjustments to text from the server
4550 adjustText: function(txt) { return txt; }
4551 };
4552
4553 /* ------------------------------------------------------------------------ */
4554 /*
4555 * Create a combo box for insertion into a form
4556 */
4557 function createCombo(id, fldSize, options)
4558 {
4559 var optCnt;
4560 if (typeof(options) == "string")
4561 {
4562 var m = options.match(/<option/gi);
4563 optCnt = m ? m.length : 0;
4564 }
4565 else
4566 {
4567 optCnt = options.length;
4568 options = options.map(function(ele) {
4569 ele = ele.htmlify();
4570 return "<option value=\"" + ele + "\">" + ele + "</option>";
4571 }).join("");
4572 }
4573
4574 var s = "<select class=\"comboPopup\" style=\"margin: 0px; padding:0px;\" "
4575 + "size=\"" + (optCnt < 5 ? 5 : optCnt < 20 ? optCnt : 20)
4576 + "\" onkeydown=\"javascript:"
4577 + "return $kd(event, comboSelKey, this);\" "
4578 + "onkeypress=\"javascript:"
4579 + "return $kp(event, comboSelKey, this);\" "
4580 + "onclick=\"javascript:return comboSelClick(event, this);\" "
4581 + "onchange=\"javascript:comboApplySel(event, this);\">"
4582 + options
4583 + "</select>"
4584
4585 + "<div class=\"combobox\" style=\""
4586 + (BrowserInfo.webKit ? "padding: 0px 0px 2px 0px;" :
4587 BrowserInfo.opera ? "padding: 0px 0px 1px 0px;" : "")
4588 + "\">"
4589
4590 // This is an IE bug workaround - don't ask me why it works.
4591 // The bug is triggered by this specific series of elements:
4592 // div.dialogMarginDiv, which sets the margins; then the
4593 // div.combobox, which is an inline block (via the IE zoom:1
4594 // hack), then the input as an inline element. For whatever
4595 // reason, IE makes the <input> "inherit" the dialogMarginDiv's
4596 // left and right margins. Just left and just right; not top
4597 // or bottom. I can't find any way to override this via CSS;
4598 // and in fact the IE Developer Toolbar reports that the margins
4599 // are zeroed out as they should be, so the CSS cascade isn't
4600 // the problem. The bug is pretty clearly deep in the IE layout
4601 // manager; my guess is that this is some block-vs-inline
4602 // weirdness that's making the layout manager seek the nearest
4603 // block-type parent and inheriting its horizontal layout.
4604 // There seem to be two ways to fix it: one is to wrap the
4605 // INPUT in a fresh DIV with zero margins; the layout seems
4606 // to grab that new DIV parent's margins as my theory predicts.
4607 // The other way is to put a &zwsp; just before the INPUT.
4608 // That's basically an invisible space character, and my guess
4609 // is that the text element is unambiguously inline, which
4610 // slaps IE out of its daze about what horizontal mode it's in.
4611 // I'm going with the &zwsp; approach because it's one less
4612 // condition.
4613 + (BrowserInfo.ie ? "&zwsp;" : "")
4614 // or: + (BrowserInfo.ie ? "<div style='margin:0;'>" : "",
4615 // with a compensating </div> after the <input>
4616
4617 + "<input type=\"text\" size=\"" + fldSize
4618 + "\" id=\"" + id + "\" style=\"margin:0px;\" "
4619 + "\" onkeydown=\"javascript:"
4620 + "return $kd(event, comboFldKey, this);\" "
4621 + "onkeypress=\"javascript:"
4622 + "return $kp(event, comboFldKey, this);\">"
4623
4624 + "<a href=\"#\" onmousedown=\"javascript:"
4625 + "return comboArrowClick(event, this);\" "
4626 + "onclick=\"javascript:"
4627 + "return comboArrowClick(event, this);\">"
4628 + "<img src=\"/webuires/comboarrow.gif\">"
4629 + "</a>"
4630
4631 + "</div>";
4632
4633 return s;
4634 }
4635
4636 // given one of the combo elements (input, select, arrow), get another
4637 function comboGetElement(ele, target)
4638 {
4639 // start at the combo wrapper DIV
4640 var eleToDiv = {
4641 "A": ele.parentNode,
4642 "INPUT": ele.parentNode,
4643 "SELECT": ele.nextSibling,
4644 "DIV": ele
4645 };
4646 var div = eleToDiv[ele.nodeName];
4647
4648 // now traverse from the DIV to the desired other element
4649 var divToTarget = {
4650 "A": div.lastChild,
4651 "INPUT": div.lastChild.previousSibling,
4652 "SELECT": div.previousSibling,
4653 "DIV": div
4654 };
4655 return divToTarget[target];
4656 }
4657
4658 var closeComboOnClick = null;
4659 function comboArrowClick(ev, arrow)
4660 {
4661 // get the objects
4662 var sel = comboGetElement(arrow, "SELECT");
4663 var fld = comboGetElement(arrow, "INPUT");
4664 var div = comboGetElement(arrow, "DIV");
4665 var vis = (sel.style.display == "block");
4666 ev = getEvent(ev);
4667
4668 // if it's not already showing, display the popup
4669 if (!vis)
4670 {
4671 // display the popup
4672 var divRc = getObjectRect(div);
4673 moveObject(sel, divRc.x, divRc.y + divRc.height);
4674 sel.style.width = divRc.width + "px";
4675 sel.style.display = "block";
4676
4677 // make it a spring-loaded popup
4678 openPopup(ev, sel, null, fld, arrow);
4679
4680 // if the current field value is in the option list, select that item
4681 setSelectByValue(sel, fld.value);
4682
4683 // don't close it on a subsequent click
4684 closeComboOnClick = null;
4685 }
4686 else
4687 {
4688 // already showing - on mouse down, note that we should close
4689 // it on the following click
4690 if (ev.type == "mousedown")
4691 closeComboOnClick = sel;
4692 else if (closeComboOnClick == sel)
4693 closePopup(sel);
4694 }
4695
4696 // don't process the hyperlink
4697 preventDefault(ev);
4698 return false;
4699 }
4700
4701 function comboSelClick(ev, sel)
4702 {
4703 closePopup(sel);
4704 return false;
4705 }
4706
4707 function comboFldKey(desc, fld)
4708 {
4709 var dir = 1;
4710 switch (desc.keyName)
4711 {
4712 case "Up":
4713 dir = -1;
4714 // fall through...
4715 case "Down":
4716 // Up/Down in the field scan through the list elements
4717 // without popping up the list
4718
4719 // find the current field value in the list
4720 var sel = comboGetElement(fld, "SELECT");
4721 var i = findSelectOptionByValue(sel, fld.value);
4722
4723 // if we didn't find the value, start below the start of the list
4724 if (i == null)
4725 i = -1;
4726
4727 // move to the next/previous option according to the arrow key
4728 i += dir;
4729
4730 // if this is in range, apply this selection
4731 if (i >= 0 && i < sel.length)
4732 {
4733 // set the value, and explicitly synthesize a change event for it
4734 fld.value = sel.options[i].value;
4735 sendEvent(fld, createEvent("Event", "change"));
4736
4737 // select the field contents
4738 setSelRangeInEle(fld);
4739 }
4740
4741 // done with the key
4742 cancelBubble(desc.event);
4743 preventDefault(desc.event);
4744 return false;
4745 }
4746
4747 // use the default handling
4748 return true;
4749 }
4750
4751 function comboSelKey(desc, sel)
4752 {
4753 switch (desc.keyName)
4754 {
4755 case "Enter":
4756 // enter the current selection into the field
4757 comboApplySel(desc.event, sel);
4758
4759 // fall through to the leave-the-field handling
4760
4761 case "U+0009":
4762 // close the popup and swallow the key
4763 closePopup(sel);
4764 cancelBubble(desc.event);
4765 preventDefault(desc.event);
4766 return false;
4767
4768 default:
4769 // do the default handling, but bypass any enclosing handler
4770 cancelBubble(desc.event);
4771 return true;
4772 }
4773 }
4774
4775 function comboApplySel(event, sel)
4776 {
4777 // save the current <select> value in the <input> object
4778 var fld = comboGetElement(sel, "INPUT");
4779 fld.value = sel.value;
4780
4781 // Synthesize an onchange event for the field. The browser won't
4782 // generate a real onchange for us since it thinks we're changing
4783 // the field value programmatically. But this really is a user
4784 // action on our aggregated combo object, so we do want the event.
4785 sendEvent(fld, createEvent("Event", "change"));
4786 }
4787
4788 /* ------------------------------------------------------------------------ */
4789 /*
4790 * Apply CSS styles to this window. 'tab' is an object serving as a table:
4791 * each property key is a CSS selector (converted to upper-case, to allow
4792 * for case-insensitive matching), and each corresponding value is a list
4793 * of [prop, value] entries, where 'prop' is a CSS style property name (
4794 * using the javascript version of the naming convention: 'fontFamily'
4795 * instead of 'font-family', for example), and 'value' is a string giving
4796 * the value for that style property.
4797 */
4798 function applyCSS(tab)
4799 {
4800 // run through all style sheets
4801 for (var i = 0, ss = document.styleSheets ; i < ss.length ; ++i)
4802 {
4803 // get the current style sheet
4804 var s = ss[i];
4805
4806 // get the rule collection for this style sheet - note that we
4807 // have to try the properties "cssRules" and "rules", since the
4808 // name varies by browser
4809 var rr = s.cssRules || s.rules;
4810
4811 // run through the rules in this style sheet
4812 for (var j = 0 ; j < rr.length ; ++j)
4813 {
4814 // get this rule
4815 var r = rr[j];
4816
4817 // get its selector - if it has one, check it against the table
4818 var sel = r.selectorText;
4819 if (sel)
4820 {
4821 // if this selector is in our table, apply the styles from
4822 // the table to the rule
4823 var tabEntry = tab[r.selectorText.toUpperCase()];
4824 if (tabEntry)
4825 {
4826 // got a match - apply each style from the table
4827 tabEntry.forEach(function(e) {
4828 r.style[e[0]] = e[1];
4829 });
4830 }
4831 }
4832 }
4833 }
4834 }
4835