Project

General

Profile

1
/*
2
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3
Code licensed under the BSD License:
4
http://developer.yahoo.net/yui/license.txt
5
version: 2.4.1
6
*/
7
/**
8
 * The dom module provides helper methods for manipulating Dom elements.
9
 * @module dom
10
 *
11
 */
12

    
13
(function() {
14
    var Y = YAHOO.util,     // internal shorthand
15
        getStyle,           // for load time browser branching
16
        setStyle,           // ditto
17
        id_counter = 0,     // for use with generateId
18
        propertyCache = {}, // for faster hyphen converts
19
        reClassNameCache = {},          // cache regexes for className
20
        document = window.document;     // cache for faster lookups
21
    
22
    // brower detection
23
    var isOpera = YAHOO.env.ua.opera,
24
        isSafari = YAHOO.env.ua.webkit, 
25
        isGecko = YAHOO.env.ua.gecko,
26
        isIE = YAHOO.env.ua.ie; 
27
    
28
    // regex cache
29
    var patterns = {
30
        HYPHEN: /(-[a-z])/i, // to normalize get/setStyle
31
        ROOT_TAG: /^body|html$/i // body for quirks mode, html for standards
32
    };
33

    
34
    var toCamel = function(property) {
35
        if ( !patterns.HYPHEN.test(property) ) {
36
            return property; // no hyphens
37
        }
38
        
39
        if (propertyCache[property]) { // already converted
40
            return propertyCache[property];
41
        }
42
       
43
        var converted = property;
44
 
45
        while( patterns.HYPHEN.exec(converted) ) {
46
            converted = converted.replace(RegExp.$1,
47
                    RegExp.$1.substr(1).toUpperCase());
48
        }
49
        
50
        propertyCache[property] = converted;
51
        return converted;
52
        //return property.replace(/-([a-z])/gi, function(m0, m1) {return m1.toUpperCase()}) // cant use function as 2nd arg yet due to safari bug
53
    };
54
    
55
    var getClassRegEx = function(className) {
56
        var re = reClassNameCache[className];
57
        if (!re) {
58
            re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
59
            reClassNameCache[className] = re;
60
        }
61
        return re;
62
    };
63

    
64
    // branching at load instead of runtime
65
    if (document.defaultView && document.defaultView.getComputedStyle) { // W3C DOM method
66
        getStyle = function(el, property) {
67
            var value = null;
68
            
69
            if (property == 'float') { // fix reserved word
70
                property = 'cssFloat';
71
            }
72

    
73
            var computed = document.defaultView.getComputedStyle(el, '');
74
            if (computed) { // test computed before touching for safari
75
                value = computed[toCamel(property)];
76
            }
77
            
78
            return el.style[property] || value;
79
        };
80
    } else if (document.documentElement.currentStyle && isIE) { // IE method
81
        getStyle = function(el, property) {                         
82
            switch( toCamel(property) ) {
83
                case 'opacity' :// IE opacity uses filter
84
                    var val = 100;
85
                    try { // will error if no DXImageTransform
86
                        val = el.filters['DXImageTransform.Microsoft.Alpha'].opacity;
87

    
88
                    } catch(e) {
89
                        try { // make sure its in the document
90
                            val = el.filters('alpha').opacity;
91
                        } catch(e) {
92
                            YAHOO.log('getStyle: IE filter failed',
93
                                    'error', 'Dom');
94
                        }
95
                    }
96
                    return val / 100;
97
                case 'float': // fix reserved word
98
                    property = 'styleFloat'; // fall through
99
                default: 
100
                    // test currentStyle before touching
101
                    var value = el.currentStyle ? el.currentStyle[property] : null;
102
                    return ( el.style[property] || value );
103
            }
104
        };
105
    } else { // default to inline only
106
        getStyle = function(el, property) { return el.style[property]; };
107
    }
108
    
109
    if (isIE) {
110
        setStyle = function(el, property, val) {
111
            switch (property) {
112
                case 'opacity':
113
                    if ( YAHOO.lang.isString(el.style.filter) ) { // in case not appended
114
                        el.style.filter = 'alpha(opacity=' + val * 100 + ')';
115
                        
116
                        if (!el.currentStyle || !el.currentStyle.hasLayout) {
117
                            el.style.zoom = 1; // when no layout or cant tell
118
                        }
119
                    }
120
                    break;
121
                case 'float':
122
                    property = 'styleFloat';
123
                default:
124
                el.style[property] = val;
125
            }
126
        };
127
    } else {
128
        setStyle = function(el, property, val) {
129
            if (property == 'float') {
130
                property = 'cssFloat';
131
            }
132
            el.style[property] = val;
133
        };
134
    }
135

    
136
    var testElement = function(node, method) {
137
        return node && node.nodeType == 1 && ( !method || method(node) );
138
    };
139

    
140
    /**
141
     * Provides helper methods for DOM elements.
142
     * @namespace YAHOO.util
143
     * @class Dom
144
     */
145
    YAHOO.util.Dom = {
146
        /**
147
         * Returns an HTMLElement reference.
148
         * @method get
149
         * @param {String | HTMLElement |Array} el Accepts a string to use as an ID for getting a DOM reference, an actual DOM reference, or an Array of IDs and/or HTMLElements.
150
         * @return {HTMLElement | Array} A DOM reference to an HTML element or an array of HTMLElements.
151
         */
152
        get: function(el) {
153
            if (el && (el.tagName || el.item)) { // HTMLElement, or HTMLCollection
154
                return el;
155
            }
156

    
157
            if (YAHOO.lang.isString(el) || !el) { // HTMLElement or null
158
                return document.getElementById(el);
159
            }
160
            
161
            if (el.length !== undefined) { // array-like 
162
                var c = [];
163
                for (var i = 0, len = el.length; i < len; ++i) {
164
                    c[c.length] = Y.Dom.get(el[i]);
165
                }
166
                
167
                return c;
168
            }
169

    
170
            return el; // some other object, just pass it back
171
        },
172
    
173
        /**
174
         * Normalizes currentStyle and ComputedStyle.
175
         * @method getStyle
176
         * @param {String | HTMLElement |Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
177
         * @param {String} property The style property whose value is returned.
178
         * @return {String | Array} The current value of the style property for the element(s).
179
         */
180
        getStyle: function(el, property) {
181
            property = toCamel(property);
182
            
183
            var f = function(element) {
184
                return getStyle(element, property);
185
            };
186
            
187
            return Y.Dom.batch(el, f, Y.Dom, true);
188
        },
189
    
190
        /**
191
         * Wrapper for setting style properties of HTMLElements.  Normalizes "opacity" across modern browsers.
192
         * @method setStyle
193
         * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
194
         * @param {String} property The style property to be set.
195
         * @param {String} val The value to apply to the given property.
196
         */
197
        setStyle: function(el, property, val) {
198
            property = toCamel(property);
199
            
200
            var f = function(element) {
201
                setStyle(element, property, val);
202
                YAHOO.log('setStyle setting ' + property + ' to ' + val, 'info', 'Dom');
203
                
204
            };
205
            
206
            Y.Dom.batch(el, f, Y.Dom, true);
207
        },
208
        
209
        /**
210
         * Gets the current position of an element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
211
         * @method getXY
212
         * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
213
         * @return {Array} The XY position of the element(s)
214
         */
215
        getXY: function(el) {
216
            var f = function(el) {
217
                // has to be part of document to have pageXY
218
                if ( (el.parentNode === null || el.offsetParent === null ||
219
                        this.getStyle(el, 'display') == 'none') && el != el.ownerDocument.body) {
220
                    YAHOO.log('getXY failed: element not available', 'error', 'Dom');
221
                    return false;
222
                }
223
                
224
                YAHOO.log('getXY returning ' + getXY(el), 'info', 'Dom');
225
                return getXY(el);
226
            };
227
            
228
            return Y.Dom.batch(el, f, Y.Dom, true);
229
        },
230
        
231
        /**
232
         * Gets the current X position of an element based on page coordinates.  The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
233
         * @method getX
234
         * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
235
         * @return {Number | Array} The X position of the element(s)
236
         */
237
        getX: function(el) {
238
            var f = function(el) {
239
                return Y.Dom.getXY(el)[0];
240
            };
241
            
242
            return Y.Dom.batch(el, f, Y.Dom, true);
243
        },
244
        
245
        /**
246
         * Gets the current Y position of an element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
247
         * @method getY
248
         * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
249
         * @return {Number | Array} The Y position of the element(s)
250
         */
251
        getY: function(el) {
252
            var f = function(el) {
253
                return Y.Dom.getXY(el)[1];
254
            };
255
            
256
            return Y.Dom.batch(el, f, Y.Dom, true);
257
        },
258
        
259
        /**
260
         * Set the position of an html element in page coordinates, regardless of how the element is positioned.
261
         * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
262
         * @method setXY
263
         * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
264
         * @param {Array} pos Contains X & Y values for new position (coordinates are page-based)
265
         * @param {Boolean} noRetry By default we try and set the position a second time if the first fails
266
         */
267
        setXY: function(el, pos, noRetry) {
268
            var f = function(el) {
269
                var style_pos = this.getStyle(el, 'position');
270
                if (style_pos == 'static') { // default to relative
271
                    this.setStyle(el, 'position', 'relative');
272
                    style_pos = 'relative';
273
                }
274

    
275
                var pageXY = this.getXY(el);
276
                if (pageXY === false) { // has to be part of doc to have pageXY
277
                    YAHOO.log('setXY failed: element not available', 'error', 'Dom');
278
                    return false; 
279
                }
280
                
281
                var delta = [ // assuming pixels; if not we will have to retry
282
                    parseInt( this.getStyle(el, 'left'), 10 ),
283
                    parseInt( this.getStyle(el, 'top'), 10 )
284
                ];
285
            
286
                if ( isNaN(delta[0]) ) {// in case of 'auto'
287
                    delta[0] = (style_pos == 'relative') ? 0 : el.offsetLeft;
288
                } 
289
                if ( isNaN(delta[1]) ) { // in case of 'auto'
290
                    delta[1] = (style_pos == 'relative') ? 0 : el.offsetTop;
291
                } 
292
        
293
                if (pos[0] !== null) { el.style.left = pos[0] - pageXY[0] + delta[0] + 'px'; }
294
                if (pos[1] !== null) { el.style.top = pos[1] - pageXY[1] + delta[1] + 'px'; }
295
              
296
                if (!noRetry) {
297
                    var newXY = this.getXY(el);
298

    
299
                    // if retry is true, try one more time if we miss 
300
                   if ( (pos[0] !== null && newXY[0] != pos[0]) || 
301
                        (pos[1] !== null && newXY[1] != pos[1]) ) {
302
                       this.setXY(el, pos, true);
303
                   }
304
                }        
305
        
306
                YAHOO.log('setXY setting position to ' + pos, 'info', 'Dom');
307
            };
308
            
309
            Y.Dom.batch(el, f, Y.Dom, true);
310
        },
311
        
312
        /**
313
         * Set the X position of an html element in page coordinates, regardless of how the element is positioned.
314
         * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
315
         * @method setX
316
         * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
317
         * @param {Int} x The value to use as the X coordinate for the element(s).
318
         */
319
        setX: function(el, x) {
320
            Y.Dom.setXY(el, [x, null]);
321
        },
322
        
323
        /**
324
         * Set the Y position of an html element in page coordinates, regardless of how the element is positioned.
325
         * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
326
         * @method setY
327
         * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
328
         * @param {Int} x To use as the Y coordinate for the element(s).
329
         */
330
        setY: function(el, y) {
331
            Y.Dom.setXY(el, [null, y]);
332
        },
333
        
334
        /**
335
         * Returns the region position of the given element.
336
         * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
337
         * @method getRegion
338
         * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
339
         * @return {Region | Array} A Region or array of Region instances containing "top, left, bottom, right" member data.
340
         */
341
        getRegion: function(el) {
342
            var f = function(el) {
343
                if ( (el.parentNode === null || el.offsetParent === null ||
344
                        this.getStyle(el, 'display') == 'none') && el != document.body) {
345
                    YAHOO.log('getRegion failed: element not available', 'error', 'Dom');
346
                    return false;
347
                }
348

    
349
                var region = Y.Region.getRegion(el);
350
                YAHOO.log('getRegion returning ' + region, 'info', 'Dom');
351
                return region;
352
            };
353
            
354
            return Y.Dom.batch(el, f, Y.Dom, true);
355
        },
356
        
357
        /**
358
         * Returns the width of the client (viewport).
359
         * @method getClientWidth
360
         * @deprecated Now using getViewportWidth.  This interface left intact for back compat.
361
         * @return {Int} The width of the viewable area of the page.
362
         */
363
        getClientWidth: function() {
364
            return Y.Dom.getViewportWidth();
365
        },
366
        
367
        /**
368
         * Returns the height of the client (viewport).
369
         * @method getClientHeight
370
         * @deprecated Now using getViewportHeight.  This interface left intact for back compat.
371
         * @return {Int} The height of the viewable area of the page.
372
         */
373
        getClientHeight: function() {
374
            return Y.Dom.getViewportHeight();
375
        },
376

    
377
        /**
378
         * Returns a array of HTMLElements with the given class.
379
         * For optimized performance, include a tag and/or root node when possible.
380
         * @method getElementsByClassName
381
         * @param {String} className The class name to match against
382
         * @param {String} tag (optional) The tag name of the elements being collected
383
         * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point 
384
         * @param {Function} apply (optional) A function to apply to each element when found 
385
         * @return {Array} An array of elements that have the given class name
386
         */
387
        getElementsByClassName: function(className, tag, root, apply) {
388
            tag = tag || '*';
389
            root = (root) ? Y.Dom.get(root) : null || document; 
390
            if (!root) {
391
                return [];
392
            }
393

    
394
            var nodes = [],
395
                elements = root.getElementsByTagName(tag),
396
                re = getClassRegEx(className);
397

    
398
            for (var i = 0, len = elements.length; i < len; ++i) {
399
                if ( re.test(elements[i].className) ) {
400
                    nodes[nodes.length] = elements[i];
401
                    if (apply) {
402
                        apply.call(elements[i], elements[i]);
403
                    }
404
                }
405
            }
406
            
407
            return nodes;
408
        },
409

    
410
        /**
411
         * Determines whether an HTMLElement has the given className.
412
         * @method hasClass
413
         * @param {String | HTMLElement | Array} el The element or collection to test
414
         * @param {String} className the class name to search for
415
         * @return {Boolean | Array} A boolean value or array of boolean values
416
         */
417
        hasClass: function(el, className) {
418
            var re = getClassRegEx(className);
419

    
420
            var f = function(el) {
421
                YAHOO.log('hasClass returning ' + re.test(el.className), 'info', 'Dom');
422
                return re.test(el.className);
423
            };
424
            
425
            return Y.Dom.batch(el, f, Y.Dom, true);
426
        },
427
    
428
        /**
429
         * Adds a class name to a given element or collection of elements.
430
         * @method addClass         
431
         * @param {String | HTMLElement | Array} el The element or collection to add the class to
432
         * @param {String} className the class name to add to the class attribute
433
         * @return {Boolean | Array} A pass/fail boolean or array of booleans
434
         */
435
        addClass: function(el, className) {
436
            var f = function(el) {
437
                if (this.hasClass(el, className)) {
438
                    return false; // already present
439
                }
440
                
441
                YAHOO.log('addClass adding ' + className, 'info', 'Dom');
442
                
443
                el.className = YAHOO.lang.trim([el.className, className].join(' '));
444
                return true;
445
            };
446
            
447
            return Y.Dom.batch(el, f, Y.Dom, true);
448
        },
449
    
450
        /**
451
         * Removes a class name from a given element or collection of elements.
452
         * @method removeClass         
453
         * @param {String | HTMLElement | Array} el The element or collection to remove the class from
454
         * @param {String} className the class name to remove from the class attribute
455
         * @return {Boolean | Array} A pass/fail boolean or array of booleans
456
         */
457
        removeClass: function(el, className) {
458
            var re = getClassRegEx(className);
459
            
460
            var f = function(el) {
461
                if (!this.hasClass(el, className)) {
462
                    return false; // not present
463
                }                 
464

    
465
                YAHOO.log('removeClass removing ' + className, 'info', 'Dom');
466
                
467
                var c = el.className;
468
                el.className = c.replace(re, ' ');
469
                if ( this.hasClass(el, className) ) { // in case of multiple adjacent
470
                    this.removeClass(el, className);
471
                }
472

    
473
                el.className = YAHOO.lang.trim(el.className); // remove any trailing spaces
474
                return true;
475
            };
476
            
477
            return Y.Dom.batch(el, f, Y.Dom, true);
478
        },
479
        
480
        /**
481
         * Replace a class with another class for a given element or collection of elements.
482
         * If no oldClassName is present, the newClassName is simply added.
483
         * @method replaceClass  
484
         * @param {String | HTMLElement | Array} el The element or collection to remove the class from
485
         * @param {String} oldClassName the class name to be replaced
486
         * @param {String} newClassName the class name that will be replacing the old class name
487
         * @return {Boolean | Array} A pass/fail boolean or array of booleans
488
         */
489
        replaceClass: function(el, oldClassName, newClassName) {
490
            if (!newClassName || oldClassName === newClassName) { // avoid infinite loop
491
                return false;
492
            }
493
            
494
            var re = getClassRegEx(oldClassName);
495

    
496
            var f = function(el) {
497
                YAHOO.log('replaceClass replacing ' + oldClassName + ' with ' + newClassName, 'info', 'Dom');
498
            
499
                if ( !this.hasClass(el, oldClassName) ) {
500
                    this.addClass(el, newClassName); // just add it if nothing to replace
501
                    return true; // NOTE: return
502
                }
503
            
504
                el.className = el.className.replace(re, ' ' + newClassName + ' ');
505

    
506
                if ( this.hasClass(el, oldClassName) ) { // in case of multiple adjacent
507
                    this.replaceClass(el, oldClassName, newClassName);
508
                }
509

    
510
                el.className = YAHOO.lang.trim(el.className); // remove any trailing spaces
511
                return true;
512
            };
513
            
514
            return Y.Dom.batch(el, f, Y.Dom, true);
515
        },
516
        
517
        /**
518
         * Returns an ID and applies it to the element "el", if provided.
519
         * @method generateId  
520
         * @param {String | HTMLElement | Array} el (optional) An optional element array of elements to add an ID to (no ID is added if one is already present).
521
         * @param {String} prefix (optional) an optional prefix to use (defaults to "yui-gen").
522
         * @return {String | Array} The generated ID, or array of generated IDs (or original ID if already present on an element)
523
         */
524
        generateId: function(el, prefix) {
525
            prefix = prefix || 'yui-gen';
526

    
527
            var f = function(el) {
528
                if (el && el.id) { // do not override existing ID
529
                    YAHOO.log('generateId returning existing id ' + el.id, 'info', 'Dom');
530
                    return el.id;
531
                } 
532

    
533
                var id = prefix + id_counter++;
534
                YAHOO.log('generateId generating ' + id, 'info', 'Dom');
535

    
536
                if (el) {
537
                    el.id = id;
538
                }
539
                
540
                return id;
541
            };
542

    
543
            // batch fails when no element, so just generate and return single ID
544
            return Y.Dom.batch(el, f, Y.Dom, true) || f.apply(Y.Dom, arguments);
545
        },
546
        
547
        /**
548
         * Determines whether an HTMLElement is an ancestor of another HTML element in the DOM hierarchy.
549
         * @method isAncestor
550
         * @param {String | HTMLElement} haystack The possible ancestor
551
         * @param {String | HTMLElement} needle The possible descendent
552
         * @return {Boolean} Whether or not the haystack is an ancestor of needle
553
         */
554
        isAncestor: function(haystack, needle) {
555
            haystack = Y.Dom.get(haystack);
556
            needle = Y.Dom.get(needle);
557
            
558
            if (!haystack || !needle) {
559
                return false;
560
            }
561

    
562
            if (haystack.contains && needle.nodeType && !isSafari) { // safari contains is broken
563
                YAHOO.log('isAncestor returning ' + haystack.contains(needle), 'info', 'Dom');
564
                return haystack.contains(needle);
565
            }
566
            else if ( haystack.compareDocumentPosition && needle.nodeType ) {
567
                YAHOO.log('isAncestor returning ' + !!(haystack.compareDocumentPosition(needle) & 16), 'info', 'Dom');
568
                return !!(haystack.compareDocumentPosition(needle) & 16);
569
            } else if (needle.nodeType) {
570
                // fallback to crawling up (safari)
571
                return !!this.getAncestorBy(needle, function(el) {
572
                    return el == haystack; 
573
                }); 
574
            }
575
            YAHOO.log('isAncestor failed; most likely needle is not an HTMLElement', 'error', 'Dom');
576
            return false;
577
        },
578
        
579
        /**
580
         * Determines whether an HTMLElement is present in the current document.
581
         * @method inDocument         
582
         * @param {String | HTMLElement} el The element to search for
583
         * @return {Boolean} Whether or not the element is present in the current document
584
         */
585
        inDocument: function(el) {
586
            return this.isAncestor(document.documentElement, el);
587
        },
588
        
589
        /**
590
         * Returns a array of HTMLElements that pass the test applied by supplied boolean method.
591
         * For optimized performance, include a tag and/or root node when possible.
592
         * @method getElementsBy
593
         * @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
594
         * @param {String} tag (optional) The tag name of the elements being collected
595
         * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point 
596
         * @param {Function} apply (optional) A function to apply to each element when found 
597
         * @return {Array} Array of HTMLElements
598
         */
599
        getElementsBy: function(method, tag, root, apply) {
600
            tag = tag || '*';
601
            root = (root) ? Y.Dom.get(root) : null || document; 
602

    
603
            if (!root) {
604
                return [];
605
            }
606

    
607
            var nodes = [],
608
                elements = root.getElementsByTagName(tag);
609
            
610
            for (var i = 0, len = elements.length; i < len; ++i) {
611
                if ( method(elements[i]) ) {
612
                    nodes[nodes.length] = elements[i];
613
                    if (apply) {
614
                        apply(elements[i]);
615
                    }
616
                }
617
            }
618

    
619
            YAHOO.log('getElementsBy returning ' + nodes, 'info', 'Dom');
620
            
621
            return nodes;
622
        },
623
        
624
        /**
625
         * Runs the supplied method against each item in the Collection/Array.
626
         * The method is called with the element(s) as the first arg, and the optional param as the second ( method(el, o) ).
627
         * @method batch
628
         * @param {String | HTMLElement | Array} el (optional) An element or array of elements to apply the method to
629
         * @param {Function} method The method to apply to the element(s)
630
         * @param {Any} o (optional) An optional arg that is passed to the supplied method
631
         * @param {Boolean} override (optional) Whether or not to override the scope of "method" with "o"
632
         * @return {Any | Array} The return value(s) from the supplied method
633
         */
634
        batch: function(el, method, o, override) {
635
            el = (el && (el.tagName || el.item)) ? el : Y.Dom.get(el); // skip get() when possible
636

    
637
            if (!el || !method) {
638
                YAHOO.log('batch failed: invalid arguments', 'error', 'Dom');
639
                return false;
640
            } 
641
            var scope = (override) ? o : window;
642
            
643
            if (el.tagName || el.length === undefined) { // element or not array-like 
644
                return method.call(scope, el, o);
645
            } 
646

    
647
            var collection = [];
648
            
649
            for (var i = 0, len = el.length; i < len; ++i) {
650
                collection[collection.length] = method.call(scope, el[i], o);
651
            }
652
            
653
            return collection;
654
        },
655
        
656
        /**
657
         * Returns the height of the document.
658
         * @method getDocumentHeight
659
         * @return {Int} The height of the actual document (which includes the body and its margin).
660
         */
661
        getDocumentHeight: function() {
662
            var scrollHeight = (document.compatMode != 'CSS1Compat') ? document.body.scrollHeight : document.documentElement.scrollHeight;
663

    
664
            var h = Math.max(scrollHeight, Y.Dom.getViewportHeight());
665
            YAHOO.log('getDocumentHeight returning ' + h, 'info', 'Dom');
666
            return h;
667
        },
668
        
669
        /**
670
         * Returns the width of the document.
671
         * @method getDocumentWidth
672
         * @return {Int} The width of the actual document (which includes the body and its margin).
673
         */
674
        getDocumentWidth: function() {
675
            var scrollWidth = (document.compatMode != 'CSS1Compat') ? document.body.scrollWidth : document.documentElement.scrollWidth;
676
            var w = Math.max(scrollWidth, Y.Dom.getViewportWidth());
677
            YAHOO.log('getDocumentWidth returning ' + w, 'info', 'Dom');
678
            return w;
679
        },
680

    
681
        /**
682
         * Returns the current height of the viewport.
683
         * @method getViewportHeight
684
         * @return {Int} The height of the viewable area of the page (excludes scrollbars).
685
         */
686
        getViewportHeight: function() {
687
            var height = self.innerHeight; // Safari, Opera
688
            var mode = document.compatMode;
689
        
690
            if ( (mode || isIE) && !isOpera ) { // IE, Gecko
691
                height = (mode == 'CSS1Compat') ?
692
                        document.documentElement.clientHeight : // Standards
693
                        document.body.clientHeight; // Quirks
694
            }
695
        
696
            YAHOO.log('getViewportHeight returning ' + height, 'info', 'Dom');
697
            return height;
698
        },
699
        
700
        /**
701
         * Returns the current width of the viewport.
702
         * @method getViewportWidth
703
         * @return {Int} The width of the viewable area of the page (excludes scrollbars).
704
         */
705
        
706
        getViewportWidth: function() {
707
            var width = self.innerWidth;  // Safari
708
            var mode = document.compatMode;
709
            
710
            if (mode || isIE) { // IE, Gecko, Opera
711
                width = (mode == 'CSS1Compat') ?
712
                        document.documentElement.clientWidth : // Standards
713
                        document.body.clientWidth; // Quirks
714
            }
715
            YAHOO.log('getViewportWidth returning ' + width, 'info', 'Dom');
716
            return width;
717
        },
718

    
719
       /**
720
         * Returns the nearest ancestor that passes the test applied by supplied boolean method.
721
         * For performance reasons, IDs are not accepted and argument validation omitted.
722
         * @method getAncestorBy
723
         * @param {HTMLElement} node The HTMLElement to use as the starting point 
724
         * @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
725
         * @return {Object} HTMLElement or null if not found
726
         */
727
        getAncestorBy: function(node, method) {
728
            while (node = node.parentNode) { // NOTE: assignment
729
                if ( testElement(node, method) ) {
730
                    YAHOO.log('getAncestorBy returning ' + node, 'info', 'Dom');
731
                    return node;
732
                }
733
            } 
734

    
735
            YAHOO.log('getAncestorBy returning null (no ancestor passed test)', 'error', 'Dom');
736
            return null;
737
        },
738
        
739
        /**
740
         * Returns the nearest ancestor with the given className.
741
         * @method getAncestorByClassName
742
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point 
743
         * @param {String} className
744
         * @return {Object} HTMLElement
745
         */
746
        getAncestorByClassName: function(node, className) {
747
            node = Y.Dom.get(node);
748
            if (!node) {
749
                YAHOO.log('getAncestorByClassName failed: invalid node argument', 'error', 'Dom');
750
                return null;
751
            }
752
            var method = function(el) { return Y.Dom.hasClass(el, className); };
753
            return Y.Dom.getAncestorBy(node, method);
754
        },
755

    
756
        /**
757
         * Returns the nearest ancestor with the given tagName.
758
         * @method getAncestorByTagName
759
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point 
760
         * @param {String} tagName
761
         * @return {Object} HTMLElement
762
         */
763
        getAncestorByTagName: function(node, tagName) {
764
            node = Y.Dom.get(node);
765
            if (!node) {
766
                YAHOO.log('getAncestorByTagName failed: invalid node argument', 'error', 'Dom');
767
                return null;
768
            }
769
            var method = function(el) {
770
                 return el.tagName && el.tagName.toUpperCase() == tagName.toUpperCase();
771
            };
772

    
773
            return Y.Dom.getAncestorBy(node, method);
774
        },
775

    
776
        /**
777
         * Returns the previous sibling that is an HTMLElement. 
778
         * For performance reasons, IDs are not accepted and argument validation omitted.
779
         * Returns the nearest HTMLElement sibling if no method provided.
780
         * @method getPreviousSiblingBy
781
         * @param {HTMLElement} node The HTMLElement to use as the starting point 
782
         * @param {Function} method A boolean function used to test siblings
783
         * that receives the sibling node being tested as its only argument
784
         * @return {Object} HTMLElement or null if not found
785
         */
786
        getPreviousSiblingBy: function(node, method) {
787
            while (node) {
788
                node = node.previousSibling;
789
                if ( testElement(node, method) ) {
790
                    return node;
791
                }
792
            }
793
            return null;
794
        }, 
795

    
796
        /**
797
         * Returns the previous sibling that is an HTMLElement 
798
         * @method getPreviousSibling
799
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point 
800
         * @return {Object} HTMLElement or null if not found
801
         */
802
        getPreviousSibling: function(node) {
803
            node = Y.Dom.get(node);
804
            if (!node) {
805
                YAHOO.log('getPreviousSibling failed: invalid node argument', 'error', 'Dom');
806
                return null;
807
            }
808

    
809
            return Y.Dom.getPreviousSiblingBy(node);
810
        }, 
811

    
812
        /**
813
         * Returns the next HTMLElement sibling that passes the boolean method. 
814
         * For performance reasons, IDs are not accepted and argument validation omitted.
815
         * Returns the nearest HTMLElement sibling if no method provided.
816
         * @method getNextSiblingBy
817
         * @param {HTMLElement} node The HTMLElement to use as the starting point 
818
         * @param {Function} method A boolean function used to test siblings
819
         * that receives the sibling node being tested as its only argument
820
         * @return {Object} HTMLElement or null if not found
821
         */
822
        getNextSiblingBy: function(node, method) {
823
            while (node) {
824
                node = node.nextSibling;
825
                if ( testElement(node, method) ) {
826
                    return node;
827
                }
828
            }
829
            return null;
830
        }, 
831

    
832
        /**
833
         * Returns the next sibling that is an HTMLElement 
834
         * @method getNextSibling
835
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point 
836
         * @return {Object} HTMLElement or null if not found
837
         */
838
        getNextSibling: function(node) {
839
            node = Y.Dom.get(node);
840
            if (!node) {
841
                YAHOO.log('getNextSibling failed: invalid node argument', 'error', 'Dom');
842
                return null;
843
            }
844

    
845
            return Y.Dom.getNextSiblingBy(node);
846
        }, 
847

    
848
        /**
849
         * Returns the first HTMLElement child that passes the test method. 
850
         * @method getFirstChildBy
851
         * @param {HTMLElement} node The HTMLElement to use as the starting point 
852
         * @param {Function} method A boolean function used to test children
853
         * that receives the node being tested as its only argument
854
         * @return {Object} HTMLElement or null if not found
855
         */
856
        getFirstChildBy: function(node, method) {
857
            var child = ( testElement(node.firstChild, method) ) ? node.firstChild : null;
858
            return child || Y.Dom.getNextSiblingBy(node.firstChild, method);
859
        }, 
860

    
861
        /**
862
         * Returns the first HTMLElement child. 
863
         * @method getFirstChild
864
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point 
865
         * @return {Object} HTMLElement or null if not found
866
         */
867
        getFirstChild: function(node, method) {
868
            node = Y.Dom.get(node);
869
            if (!node) {
870
                YAHOO.log('getFirstChild failed: invalid node argument', 'error', 'Dom');
871
                return null;
872
            }
873
            return Y.Dom.getFirstChildBy(node);
874
        }, 
875

    
876
        /**
877
         * Returns the last HTMLElement child that passes the test method. 
878
         * @method getLastChildBy
879
         * @param {HTMLElement} node The HTMLElement to use as the starting point 
880
         * @param {Function} method A boolean function used to test children
881
         * that receives the node being tested as its only argument
882
         * @return {Object} HTMLElement or null if not found
883
         */
884
        getLastChildBy: function(node, method) {
885
            if (!node) {
886
                YAHOO.log('getLastChild failed: invalid node argument', 'error', 'Dom');
887
                return null;
888
            }
889
            var child = ( testElement(node.lastChild, method) ) ? node.lastChild : null;
890
            return child || Y.Dom.getPreviousSiblingBy(node.lastChild, method);
891
        }, 
892

    
893
        /**
894
         * Returns the last HTMLElement child. 
895
         * @method getLastChild
896
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point 
897
         * @return {Object} HTMLElement or null if not found
898
         */
899
        getLastChild: function(node) {
900
            node = Y.Dom.get(node);
901
            return Y.Dom.getLastChildBy(node);
902
        }, 
903

    
904
        /**
905
         * Returns an array of HTMLElement childNodes that pass the test method. 
906
         * @method getChildrenBy
907
         * @param {HTMLElement} node The HTMLElement to start from
908
         * @param {Function} method A boolean function used to test children
909
         * that receives the node being tested as its only argument
910
         * @return {Array} A static array of HTMLElements
911
         */
912
        getChildrenBy: function(node, method) {
913
            var child = Y.Dom.getFirstChildBy(node, method);
914
            var children = child ? [child] : [];
915

    
916
            Y.Dom.getNextSiblingBy(child, function(node) {
917
                if ( !method || method(node) ) {
918
                    children[children.length] = node;
919
                }
920
                return false; // fail test to collect all children
921
            });
922

    
923
            return children;
924
        },
925
 
926
        /**
927
         * Returns an array of HTMLElement childNodes. 
928
         * @method getChildren
929
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point 
930
         * @return {Array} A static array of HTMLElements
931
         */
932
        getChildren: function(node) {
933
            node = Y.Dom.get(node);
934
            if (!node) {
935
                YAHOO.log('getChildren failed: invalid node argument', 'error', 'Dom');
936
            }
937

    
938
            return Y.Dom.getChildrenBy(node);
939
        },
940
 
941
        /**
942
         * Returns the left scroll value of the document 
943
         * @method getDocumentScrollLeft
944
         * @param {HTMLDocument} document (optional) The document to get the scroll value of
945
         * @return {Int}  The amount that the document is scrolled to the left
946
         */
947
        getDocumentScrollLeft: function(doc) {
948
            doc = doc || document;
949
            return Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);
950
        }, 
951

    
952
        /**
953
         * Returns the top scroll value of the document 
954
         * @method getDocumentScrollTop
955
         * @param {HTMLDocument} document (optional) The document to get the scroll value of
956
         * @return {Int}  The amount that the document is scrolled to the top
957
         */
958
        getDocumentScrollTop: function(doc) {
959
            doc = doc || document;
960
            return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
961
        },
962

    
963
        /**
964
         * Inserts the new node as the previous sibling of the reference node 
965
         * @method insertBefore
966
         * @param {String | HTMLElement} newNode The node to be inserted
967
         * @param {String | HTMLElement} referenceNode The node to insert the new node before 
968
         * @return {HTMLElement} The node that was inserted (or null if insert fails) 
969
         */
970
        insertBefore: function(newNode, referenceNode) {
971
            newNode = Y.Dom.get(newNode); 
972
            referenceNode = Y.Dom.get(referenceNode); 
973
            
974
            if (!newNode || !referenceNode || !referenceNode.parentNode) {
975
                YAHOO.log('insertAfter failed: missing or invalid arg(s)', 'error', 'Dom');
976
                return null;
977
            }       
978

    
979
            return referenceNode.parentNode.insertBefore(newNode, referenceNode); 
980
        },
981

    
982
        /**
983
         * Inserts the new node as the next sibling of the reference node 
984
         * @method insertAfter
985
         * @param {String | HTMLElement} newNode The node to be inserted
986
         * @param {String | HTMLElement} referenceNode The node to insert the new node after 
987
         * @return {HTMLElement} The node that was inserted (or null if insert fails) 
988
         */
989
        insertAfter: function(newNode, referenceNode) {
990
            newNode = Y.Dom.get(newNode); 
991
            referenceNode = Y.Dom.get(referenceNode); 
992
            
993
            if (!newNode || !referenceNode || !referenceNode.parentNode) {
994
                YAHOO.log('insertAfter failed: missing or invalid arg(s)', 'error', 'Dom');
995
                return null;
996
            }       
997

    
998
            if (referenceNode.nextSibling) {
999
                return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); 
1000
            } else {
1001
                return referenceNode.parentNode.appendChild(newNode);
1002
            }
1003
        },
1004

    
1005
        /**
1006
         * Creates a Region based on the viewport relative to the document. 
1007
         * @method getClientRegion
1008
         * @return {Region} A Region object representing the viewport which accounts for document scroll
1009
         */
1010
        getClientRegion: function() {
1011
            var t = Y.Dom.getDocumentScrollTop(),
1012
                l = Y.Dom.getDocumentScrollLeft(),
1013
                r = Y.Dom.getViewportWidth() + l,
1014
                b = Y.Dom.getViewportHeight() + t;
1015

    
1016
            return new Y.Region(t, r, b, l);
1017
        }
1018
    };
1019
    
1020
    var getXY = function() {
1021
        if (document.documentElement.getBoundingClientRect) { // IE
1022
            return function(el) {
1023
                var box = el.getBoundingClientRect();
1024

    
1025
                var rootNode = el.ownerDocument;
1026
                return [box.left + Y.Dom.getDocumentScrollLeft(rootNode), box.top +
1027
                        Y.Dom.getDocumentScrollTop(rootNode)];
1028
            };
1029
        } else {
1030
            return function(el) { // manually calculate by crawling up offsetParents
1031
                var pos = [el.offsetLeft, el.offsetTop];
1032
                var parentNode = el.offsetParent;
1033

    
1034
                // safari: subtract body offsets if el is abs (or any offsetParent), unless body is offsetParent
1035
                var accountForBody = (isSafari &&
1036
                        Y.Dom.getStyle(el, 'position') == 'absolute' &&
1037
                        el.offsetParent == el.ownerDocument.body);
1038

    
1039
                if (parentNode != el) {
1040
                    while (parentNode) {
1041
                        pos[0] += parentNode.offsetLeft;
1042
                        pos[1] += parentNode.offsetTop;
1043
                        if (!accountForBody && isSafari && 
1044
                                Y.Dom.getStyle(parentNode,'position') == 'absolute' ) { 
1045
                            accountForBody = true;
1046
                        }
1047
                        parentNode = parentNode.offsetParent;
1048
                    }
1049
                }
1050

    
1051
                if (accountForBody) { //safari doubles in this case
1052
                    pos[0] -= el.ownerDocument.body.offsetLeft;
1053
                    pos[1] -= el.ownerDocument.body.offsetTop;
1054
                } 
1055
                parentNode = el.parentNode;
1056

    
1057
                // account for any scrolled ancestors
1058
                while ( parentNode.tagName && !patterns.ROOT_TAG.test(parentNode.tagName) ) 
1059
                {
1060
                   // work around opera inline/table scrollLeft/Top bug
1061
                   if (Y.Dom.getStyle(parentNode, 'display').search(/^inline|table-row.*$/i)) { 
1062
                        pos[0] -= parentNode.scrollLeft;
1063
                        pos[1] -= parentNode.scrollTop;
1064
                    }
1065
                    
1066
                    parentNode = parentNode.parentNode; 
1067
                }
1068

    
1069
                return pos;
1070
            };
1071
        }
1072
    }() // NOTE: Executing for loadtime branching
1073
})();
1074
/**
1075
 * A region is a representation of an object on a grid.  It is defined
1076
 * by the top, right, bottom, left extents, so is rectangular by default.  If 
1077
 * other shapes are required, this class could be extended to support it.
1078
 * @namespace YAHOO.util
1079
 * @class Region
1080
 * @param {Int} t the top extent
1081
 * @param {Int} r the right extent
1082
 * @param {Int} b the bottom extent
1083
 * @param {Int} l the left extent
1084
 * @constructor
1085
 */
1086
YAHOO.util.Region = function(t, r, b, l) {
1087

    
1088
    /**
1089
     * The region's top extent
1090
     * @property top
1091
     * @type Int
1092
     */
1093
    this.top = t;
1094
    
1095
    /**
1096
     * The region's top extent as index, for symmetry with set/getXY
1097
     * @property 1
1098
     * @type Int
1099
     */
1100
    this[1] = t;
1101

    
1102
    /**
1103
     * The region's right extent
1104
     * @property right
1105
     * @type int
1106
     */
1107
    this.right = r;
1108

    
1109
    /**
1110
     * The region's bottom extent
1111
     * @property bottom
1112
     * @type Int
1113
     */
1114
    this.bottom = b;
1115

    
1116
    /**
1117
     * The region's left extent
1118
     * @property left
1119
     * @type Int
1120
     */
1121
    this.left = l;
1122
    
1123
    /**
1124
     * The region's left extent as index, for symmetry with set/getXY
1125
     * @property 0
1126
     * @type Int
1127
     */
1128
    this[0] = l;
1129
};
1130

    
1131
/**
1132
 * Returns true if this region contains the region passed in
1133
 * @method contains
1134
 * @param  {Region}  region The region to evaluate
1135
 * @return {Boolean}        True if the region is contained with this region, 
1136
 *                          else false
1137
 */
1138
YAHOO.util.Region.prototype.contains = function(region) {
1139
    return ( region.left   >= this.left   && 
1140
             region.right  <= this.right  && 
1141
             region.top    >= this.top    && 
1142
             region.bottom <= this.bottom    );
1143

    
1144
    // this.logger.debug("does " + this + " contain " + region + " ... " + ret);
1145
};
1146

    
1147
/**
1148
 * Returns the area of the region
1149
 * @method getArea
1150
 * @return {Int} the region's area
1151
 */
1152
YAHOO.util.Region.prototype.getArea = function() {
1153
    return ( (this.bottom - this.top) * (this.right - this.left) );
1154
};
1155

    
1156
/**
1157
 * Returns the region where the passed in region overlaps with this one
1158
 * @method intersect
1159
 * @param  {Region} region The region that intersects
1160
 * @return {Region}        The overlap region, or null if there is no overlap
1161
 */
1162
YAHOO.util.Region.prototype.intersect = function(region) {
1163
    var t = Math.max( this.top,    region.top    );
1164
    var r = Math.min( this.right,  region.right  );
1165
    var b = Math.min( this.bottom, region.bottom );
1166
    var l = Math.max( this.left,   region.left   );
1167
    
1168
    if (b >= t && r >= l) {
1169
        return new YAHOO.util.Region(t, r, b, l);
1170
    } else {
1171
        return null;
1172
    }
1173
};
1174

    
1175
/**
1176
 * Returns the region representing the smallest region that can contain both
1177
 * the passed in region and this region.
1178
 * @method union
1179
 * @param  {Region} region The region that to create the union with
1180
 * @return {Region}        The union region
1181
 */
1182
YAHOO.util.Region.prototype.union = function(region) {
1183
    var t = Math.min( this.top,    region.top    );
1184
    var r = Math.max( this.right,  region.right  );
1185
    var b = Math.max( this.bottom, region.bottom );
1186
    var l = Math.min( this.left,   region.left   );
1187

    
1188
    return new YAHOO.util.Region(t, r, b, l);
1189
};
1190

    
1191
/**
1192
 * toString
1193
 * @method toString
1194
 * @return string the region properties
1195
 */
1196
YAHOO.util.Region.prototype.toString = function() {
1197
    return ( "Region {"    +
1198
             "top: "       + this.top    + 
1199
             ", right: "   + this.right  + 
1200
             ", bottom: "  + this.bottom + 
1201
             ", left: "    + this.left   + 
1202
             "}" );
1203
};
1204

    
1205
/**
1206
 * Returns a region that is occupied by the DOM element
1207
 * @method getRegion
1208
 * @param  {HTMLElement} el The element
1209
 * @return {Region}         The region that the element occupies
1210
 * @static
1211
 */
1212
YAHOO.util.Region.getRegion = function(el) {
1213
    var p = YAHOO.util.Dom.getXY(el);
1214

    
1215
    var t = p[1];
1216
    var r = p[0] + el.offsetWidth;
1217
    var b = p[1] + el.offsetHeight;
1218
    var l = p[0];
1219

    
1220
    return new YAHOO.util.Region(t, r, b, l);
1221
};
1222

    
1223
/////////////////////////////////////////////////////////////////////////////
1224

    
1225

    
1226
/**
1227
 * A point is a region that is special in that it represents a single point on 
1228
 * the grid.
1229
 * @namespace YAHOO.util
1230
 * @class Point
1231
 * @param {Int} x The X position of the point
1232
 * @param {Int} y The Y position of the point
1233
 * @constructor
1234
 * @extends YAHOO.util.Region
1235
 */
1236
YAHOO.util.Point = function(x, y) {
1237
   if (YAHOO.lang.isArray(x)) { // accept input from Dom.getXY, Event.getXY, etc.
1238
      y = x[1]; // dont blow away x yet
1239
      x = x[0];
1240
   }
1241
   
1242
    /**
1243
     * The X position of the point, which is also the right, left and index zero (for Dom.getXY symmetry)
1244
     * @property x
1245
     * @type Int
1246
     */
1247

    
1248
    this.x = this.right = this.left = this[0] = x;
1249
     
1250
    /**
1251
     * The Y position of the point, which is also the top, bottom and index one (for Dom.getXY symmetry)
1252
     * @property y
1253
     * @type Int
1254
     */
1255
    this.y = this.top = this.bottom = this[1] = y;
1256
};
1257

    
1258
YAHOO.util.Point.prototype = new YAHOO.util.Region();
1259

    
1260
YAHOO.register("dom", YAHOO.util.Dom, {version: "2.4.1", build: "742"});
(2-2/4)