Project

General

Profile

1 601 doc
/*
2 1289 kweitzel
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 601 doc
Code licensed under the BSD License:
4
http://developer.yahoo.net/yui/license.txt
5 1289 kweitzel
version: 2.8.0r4
6 601 doc
*/
7
/**
8
 * The dom module provides helper methods for manipulating Dom elements.
9
 * @module dom
10
 *
11
 */
12
13
(function() {
14 1289 kweitzel
    // for use with generateId (global to save state if Dom is overwritten)
15
    YAHOO.env._id_counter = YAHOO.env._id_counter || 0;
16
17
    // internal shorthand
18
    var Y = YAHOO.util,
19
        lang = YAHOO.lang,
20
        UA = YAHOO.env.ua,
21
        trim = YAHOO.lang.trim,
22 601 doc
        propertyCache = {}, // for faster hyphen converts
23 1289 kweitzel
        reCache = {}, // cache className regexes
24
        RE_TABLE = /^t(?:able|d|h)$/i, // for _calcBorders
25
        RE_COLOR = /color$/i,
26
27
        // DOM aliases
28
        document = window.document,
29
        documentElement = document.documentElement,
30
31
        // string constants
32
        OWNER_DOCUMENT = 'ownerDocument',
33
        DEFAULT_VIEW = 'defaultView',
34
        DOCUMENT_ELEMENT = 'documentElement',
35
        COMPAT_MODE = 'compatMode',
36
        OFFSET_LEFT = 'offsetLeft',
37
        OFFSET_TOP = 'offsetTop',
38
        OFFSET_PARENT = 'offsetParent',
39
        PARENT_NODE = 'parentNode',
40
        NODE_TYPE = 'nodeType',
41
        TAG_NAME = 'tagName',
42
        SCROLL_LEFT = 'scrollLeft',
43
        SCROLL_TOP = 'scrollTop',
44
        GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect',
45
        GET_COMPUTED_STYLE = 'getComputedStyle',
46
        CURRENT_STYLE = 'currentStyle',
47
        CSS1_COMPAT = 'CSS1Compat',
48
        _BACK_COMPAT = 'BackCompat',
49
        _CLASS = 'class', // underscore due to reserved word
50
        CLASS_NAME = 'className',
51
        EMPTY = '',
52
        SPACE = ' ',
53
        C_START = '(?:^|\\s)',
54
        C_END = '(?= |$)',
55
        G = 'g',
56
        POSITION = 'position',
57
        FIXED = 'fixed',
58
        RELATIVE = 'relative',
59
        LEFT = 'left',
60
        TOP = 'top',
61
        MEDIUM = 'medium',
62
        BORDER_LEFT_WIDTH = 'borderLeftWidth',
63
        BORDER_TOP_WIDTH = 'borderTopWidth',
64 601 doc
65
    // brower detection
66 1289 kweitzel
        isOpera = UA.opera,
67
        isSafari = UA.webkit,
68
        isGecko = UA.gecko,
69
        isIE = UA.ie;
70 601 doc
71
    /**
72
     * Provides helper methods for DOM elements.
73
     * @namespace YAHOO.util
74
     * @class Dom
75 1289 kweitzel
     * @requires yahoo, event
76 601 doc
     */
77 1289 kweitzel
    Y.Dom = {
78
        CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8
79
            'for': 'htmlFor',
80
            'class': CLASS_NAME
81
        } : { // w3c
82
            'htmlFor': 'for',
83
            'className': _CLASS
84
        },
85
86
        DOT_ATTRIBUTES: {},
87
88 601 doc
        /**
89
         * Returns an HTMLElement reference.
90
         * @method get
91
         * @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.
92
         * @return {HTMLElement | Array} A DOM reference to an HTML element or an array of HTMLElements.
93
         */
94
        get: function(el) {
95 1289 kweitzel
            var id, nodes, c, i, len, attr;
96 601 doc
97 1289 kweitzel
            if (el) {
98
                if (el[NODE_TYPE] || el.item) { // Node, or NodeList
99
                    return el;
100 601 doc
                }
101 1289 kweitzel
102
                if (typeof el === 'string') { // id
103
                    id = el;
104
                    el = document.getElementById(el);
105
                    attr = (el) ? el.attributes : null;
106
                    if (el && attr && attr.id && attr.id.value === id) { // IE: avoid false match on "name" attribute
107
                        return el;
108
                    } else if (el && document.all) { // filter by name
109
                        el = null;
110
                        nodes = document.all[id];
111
                        for (i = 0, len = nodes.length; i < len; ++i) {
112
                            if (nodes[i].id === id) {
113
                                return nodes[i];
114
                            }
115
                        }
116
                    }
117
                    return el;
118
                }
119 601 doc
120 1289 kweitzel
                if (YAHOO.util.Element && el instanceof YAHOO.util.Element) {
121
                    el = el.get('element');
122
                }
123
124
                if ('length' in el) { // array-like
125
                    c = [];
126
                    for (i = 0, len = el.length; i < len; ++i) {
127
                        c[c.length] = Y.Dom.get(el[i]);
128
                    }
129
130
                    return c;
131
                }
132
133
                return el; // some other object, just pass it back
134 601 doc
            }
135
136 1289 kweitzel
            return null;
137 601 doc
        },
138
139 1289 kweitzel
        getComputedStyle: function(el, property) {
140
            if (window[GET_COMPUTED_STYLE]) {
141
                return el[OWNER_DOCUMENT][DEFAULT_VIEW][GET_COMPUTED_STYLE](el, null)[property];
142
            } else if (el[CURRENT_STYLE]) {
143
                return Y.Dom.IE_ComputedStyle.get(el, property);
144
            }
145
        },
146
147 601 doc
        /**
148
         * Normalizes currentStyle and ComputedStyle.
149
         * @method getStyle
150
         * @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.
151
         * @param {String} property The style property whose value is returned.
152
         * @return {String | Array} The current value of the style property for the element(s).
153
         */
154
        getStyle: function(el, property) {
155 1289 kweitzel
            return Y.Dom.batch(el, Y.Dom._getStyle, property);
156 601 doc
        },
157 1289 kweitzel
158
        // branching at load instead of runtime
159
        _getStyle: function() {
160
            if (window[GET_COMPUTED_STYLE]) { // W3C DOM method
161
                return function(el, property) {
162
                    property = (property === 'float') ? property = 'cssFloat' :
163
                            Y.Dom._toCamel(property);
164
165
                    var value = el.style[property],
166
                        computed;
167
168
                    if (!value) {
169
                        computed = el[OWNER_DOCUMENT][DEFAULT_VIEW][GET_COMPUTED_STYLE](el, null);
170
                        if (computed) { // test computed before touching for safari
171
                            value = computed[property];
172
                        }
173
                    }
174
175
                    return value;
176
                };
177
            } else if (documentElement[CURRENT_STYLE]) {
178
                return function(el, property) {
179
                    var value;
180
181
                    switch(property) {
182
                        case 'opacity' :// IE opacity uses filter
183
                            value = 100;
184
                            try { // will error if no DXImageTransform
185
                                value = el.filters['DXImageTransform.Microsoft.Alpha'].opacity;
186
187
                            } catch(e) {
188
                                try { // make sure its in the document
189
                                    value = el.filters('alpha').opacity;
190
                                } catch(err) {
191
                                }
192
                            }
193
                            return value / 100;
194
                        case 'float': // fix reserved word
195
                            property = 'styleFloat'; // fall through
196
                        default:
197
                            property = Y.Dom._toCamel(property);
198
                            value = el[CURRENT_STYLE] ? el[CURRENT_STYLE][property] : null;
199
                            return ( el.style[property] || value );
200
                    }
201
                };
202
            }
203
        }(),
204 601 doc
205
        /**
206
         * Wrapper for setting style properties of HTMLElements.  Normalizes "opacity" across modern browsers.
207
         * @method setStyle
208
         * @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.
209
         * @param {String} property The style property to be set.
210
         * @param {String} val The value to apply to the given property.
211
         */
212
        setStyle: function(el, property, val) {
213 1289 kweitzel
            Y.Dom.batch(el, Y.Dom._setStyle, { prop: property, val: val });
214 601 doc
        },
215 1289 kweitzel
216
        _setStyle: function() {
217
            if (isIE) {
218
                return function(el, args) {
219
                    var property = Y.Dom._toCamel(args.prop),
220
                        val = args.val;
221
222
                    if (el) {
223
                        switch (property) {
224
                            case 'opacity':
225
                                if ( lang.isString(el.style.filter) ) { // in case not appended
226
                                    el.style.filter = 'alpha(opacity=' + val * 100 + ')';
227
228
                                    if (!el[CURRENT_STYLE] || !el[CURRENT_STYLE].hasLayout) {
229
                                        el.style.zoom = 1; // when no layout or cant tell
230
                                    }
231
                                }
232
                                break;
233
                            case 'float':
234
                                property = 'styleFloat';
235
                            default:
236
                            el.style[property] = val;
237
                        }
238
                    } else {
239
                    }
240
                };
241
            } else {
242
                return function(el, args) {
243
                    var property = Y.Dom._toCamel(args.prop),
244
                        val = args.val;
245
                    if (el) {
246
                        if (property == 'float') {
247
                            property = 'cssFloat';
248
                        }
249
                        el.style[property] = val;
250
                    } else {
251
                    }
252
                };
253
            }
254
255
        }(),
256 601 doc
257
        /**
258 1289 kweitzel
         * Gets the current position of an element based on page coordinates.
259
         * Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
260 601 doc
         * @method getXY
261 1289 kweitzel
         * @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM
262
         * reference, or an Array of IDs and/or HTMLElements
263 601 doc
         * @return {Array} The XY position of the element(s)
264
         */
265
        getXY: function(el) {
266 1289 kweitzel
            return Y.Dom.batch(el, Y.Dom._getXY);
267 601 doc
        },
268 1289 kweitzel
269
        _canPosition: function(el) {
270
            return ( Y.Dom._getStyle(el, 'display') !== 'none' && Y.Dom._inDoc(el) );
271
        },
272
273
        _getXY: function() {
274
            if (document[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) {
275
                return function(node) {
276
                    var scrollLeft, scrollTop, box, doc,
277
                        off1, off2, mode, bLeft, bTop,
278
                        floor = Math.floor, // TODO: round?
279
                        xy = false;
280
281
                    if (Y.Dom._canPosition(node)) {
282
                        box = node[GET_BOUNDING_CLIENT_RECT]();
283
                        doc = node[OWNER_DOCUMENT];
284
                        scrollLeft = Y.Dom.getDocumentScrollLeft(doc);
285
                        scrollTop = Y.Dom.getDocumentScrollTop(doc);
286
                        xy = [floor(box[LEFT]), floor(box[TOP])];
287
288
                        if (isIE && UA.ie < 8) { // IE < 8: viewport off by 2
289
                            off1 = 2;
290
                            off2 = 2;
291
                            mode = doc[COMPAT_MODE];
292
293
                            if (UA.ie === 6) {
294
                                if (mode !== _BACK_COMPAT) {
295
                                    off1 = 0;
296
                                    off2 = 0;
297
                                }
298
                            }
299
300
                            if ((mode === _BACK_COMPAT)) {
301
                                bLeft = _getComputedStyle(doc[DOCUMENT_ELEMENT], BORDER_LEFT_WIDTH);
302
                                bTop = _getComputedStyle(doc[DOCUMENT_ELEMENT], BORDER_TOP_WIDTH);
303
                                if (bLeft !== MEDIUM) {
304
                                    off1 = parseInt(bLeft, 10);
305
                                }
306
                                if (bTop !== MEDIUM) {
307
                                    off2 = parseInt(bTop, 10);
308
                                }
309
                            }
310
311
                            xy[0] -= off1;
312
                            xy[1] -= off2;
313
314
                        }
315
316
                        if ((scrollTop || scrollLeft)) {
317
                            xy[0] += scrollLeft;
318
                            xy[1] += scrollTop;
319
                        }
320
321
                        // gecko may return sub-pixel (non-int) values
322
                        xy[0] = floor(xy[0]);
323
                        xy[1] = floor(xy[1]);
324
                    } else {
325
                    }
326
327
                    return xy;
328
                };
329
            } else {
330
                return function(node) { // ff2, safari: manually calculate by crawling up offsetParents
331
                    var docScrollLeft, docScrollTop,
332
                        scrollTop, scrollLeft,
333
                        bCheck,
334
                        xy = false,
335
                        parentNode = node;
336
337
                    if  (Y.Dom._canPosition(node) ) {
338
                        xy = [node[OFFSET_LEFT], node[OFFSET_TOP]];
339
                        docScrollLeft = Y.Dom.getDocumentScrollLeft(node[OWNER_DOCUMENT]);
340
                        docScrollTop = Y.Dom.getDocumentScrollTop(node[OWNER_DOCUMENT]);
341
342
                        // TODO: refactor with !! or just falsey
343
                        bCheck = ((isGecko || UA.webkit > 519) ? true : false);
344
345
                        // TODO: worth refactoring for TOP/LEFT only?
346
                        while ((parentNode = parentNode[OFFSET_PARENT])) {
347
                            xy[0] += parentNode[OFFSET_LEFT];
348
                            xy[1] += parentNode[OFFSET_TOP];
349
                            if (bCheck) {
350
                                xy = Y.Dom._calcBorders(parentNode, xy);
351
                            }
352
                        }
353
354
                        // account for any scrolled ancestors
355
                        if (Y.Dom._getStyle(node, POSITION) !== FIXED) {
356
                            parentNode = node;
357
358
                            while ((parentNode = parentNode[PARENT_NODE]) && parentNode[TAG_NAME]) {
359
                                scrollTop = parentNode[SCROLL_TOP];
360
                                scrollLeft = parentNode[SCROLL_LEFT];
361
362
                                //Firefox does something funky with borders when overflow is not visible.
363
                                if (isGecko && (Y.Dom._getStyle(parentNode, 'overflow') !== 'visible')) {
364
                                        xy = Y.Dom._calcBorders(parentNode, xy);
365
                                }
366
367
                                if (scrollTop || scrollLeft) {
368
                                    xy[0] -= scrollLeft;
369
                                    xy[1] -= scrollTop;
370
                                }
371
                            }
372
                            xy[0] += docScrollLeft;
373
                            xy[1] += docScrollTop;
374
375
                        } else {
376
                            //Fix FIXED position -- add scrollbars
377
                            if (isOpera) {
378
                                xy[0] -= docScrollLeft;
379
                                xy[1] -= docScrollTop;
380
                            } else if (isSafari || isGecko) {
381
                                xy[0] += docScrollLeft;
382
                                xy[1] += docScrollTop;
383
                            }
384
                        }
385
                        //Round the numbers so we get sane data back
386
                        xy[0] = Math.floor(xy[0]);
387
                        xy[1] = Math.floor(xy[1]);
388
                    } else {
389
                    }
390
                    return xy;
391
                };
392
            }
393
        }(), // NOTE: Executing for loadtime branching
394 601 doc
395
        /**
396
         * 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).
397
         * @method getX
398
         * @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
399
         * @return {Number | Array} The X position of the element(s)
400
         */
401
        getX: function(el) {
402
            var f = function(el) {
403
                return Y.Dom.getXY(el)[0];
404
            };
405
406
            return Y.Dom.batch(el, f, Y.Dom, true);
407
        },
408
409
        /**
410
         * 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).
411
         * @method getY
412
         * @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
413
         * @return {Number | Array} The Y position of the element(s)
414
         */
415
        getY: function(el) {
416
            var f = function(el) {
417
                return Y.Dom.getXY(el)[1];
418
            };
419
420
            return Y.Dom.batch(el, f, Y.Dom, true);
421
        },
422
423
        /**
424
         * Set the position of an html element in page coordinates, regardless of how the element is positioned.
425
         * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
426
         * @method setXY
427
         * @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
428
         * @param {Array} pos Contains X & Y values for new position (coordinates are page-based)
429
         * @param {Boolean} noRetry By default we try and set the position a second time if the first fails
430
         */
431
        setXY: function(el, pos, noRetry) {
432 1289 kweitzel
            Y.Dom.batch(el, Y.Dom._setXY, { pos: pos, noRetry: noRetry });
433
        },
434 601 doc
435 1289 kweitzel
        _setXY: function(node, args) {
436
            var pos = Y.Dom._getStyle(node, POSITION),
437
                setStyle = Y.Dom.setStyle,
438
                xy = args.pos,
439
                noRetry = args.noRetry,
440
441
                delta = [ // assuming pixels; if not we will have to retry
442
                    parseInt( Y.Dom.getComputedStyle(node, LEFT), 10 ),
443
                    parseInt( Y.Dom.getComputedStyle(node, TOP), 10 )
444
                ],
445
446
                currentXY,
447
                newXY;
448 601 doc
449 1289 kweitzel
            if (pos == 'static') { // default to relative
450
                pos = RELATIVE;
451
                setStyle(node, POSITION, pos);
452
            }
453 601 doc
454 1289 kweitzel
            currentXY = Y.Dom._getXY(node);
455
456
            if (!xy || currentXY === false) { // has to be part of doc to have xy
457
                return false;
458
            }
459 601 doc
460 1289 kweitzel
            if ( isNaN(delta[0]) ) {// in case of 'auto'
461
                delta[0] = (pos == RELATIVE) ? 0 : node[OFFSET_LEFT];
462
            }
463
            if ( isNaN(delta[1]) ) { // in case of 'auto'
464
                delta[1] = (pos == RELATIVE) ? 0 : node[OFFSET_TOP];
465
            }
466
467
            if (xy[0] !== null) { // from setX
468
                setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px');
469
            }
470
471
            if (xy[1] !== null) { // from setY
472
                setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px');
473
            }
474
475
            if (!noRetry) {
476
                newXY = Y.Dom._getXY(node);
477
478
                // if retry is true, try one more time if we miss
479
               if ( (xy[0] !== null && newXY[0] != xy[0]) ||
480
                    (xy[1] !== null && newXY[1] != xy[1]) ) {
481
                   Y.Dom._setXY(node, { pos: xy, noRetry: true });
482
               }
483
            }
484
485 601 doc
        },
486
487
        /**
488
         * Set the X position of an html element in page coordinates, regardless of how the element is positioned.
489
         * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
490
         * @method setX
491
         * @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.
492
         * @param {Int} x The value to use as the X coordinate for the element(s).
493
         */
494
        setX: function(el, x) {
495
            Y.Dom.setXY(el, [x, null]);
496
        },
497
498
        /**
499
         * Set the Y position of an html element in page coordinates, regardless of how the element is positioned.
500
         * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
501
         * @method setY
502
         * @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.
503
         * @param {Int} x To use as the Y coordinate for the element(s).
504
         */
505
        setY: function(el, y) {
506
            Y.Dom.setXY(el, [null, y]);
507
        },
508
509
        /**
510
         * Returns the region position of the given element.
511
         * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
512
         * @method getRegion
513
         * @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.
514
         * @return {Region | Array} A Region or array of Region instances containing "top, left, bottom, right" member data.
515
         */
516
        getRegion: function(el) {
517
            var f = function(el) {
518 1289 kweitzel
                var region = false;
519
                if ( Y.Dom._canPosition(el) ) {
520
                    region = Y.Region.getRegion(el);
521
                } else {
522 601 doc
                }
523
524
                return region;
525
            };
526
527
            return Y.Dom.batch(el, f, Y.Dom, true);
528
        },
529
530
        /**
531
         * Returns the width of the client (viewport).
532
         * @method getClientWidth
533
         * @deprecated Now using getViewportWidth.  This interface left intact for back compat.
534
         * @return {Int} The width of the viewable area of the page.
535
         */
536
        getClientWidth: function() {
537
            return Y.Dom.getViewportWidth();
538
        },
539
540
        /**
541
         * Returns the height of the client (viewport).
542
         * @method getClientHeight
543
         * @deprecated Now using getViewportHeight.  This interface left intact for back compat.
544
         * @return {Int} The height of the viewable area of the page.
545
         */
546
        getClientHeight: function() {
547
            return Y.Dom.getViewportHeight();
548
        },
549
550
        /**
551 1289 kweitzel
         * Returns an array of HTMLElements with the given class.
552 601 doc
         * For optimized performance, include a tag and/or root node when possible.
553 1289 kweitzel
         * Note: This method operates against a live collection, so modifying the
554
         * collection in the callback (removing/appending nodes, etc.) will have
555
         * side effects.  Instead you should iterate the returned nodes array,
556
         * as you would with the native "getElementsByTagName" method.
557 601 doc
         * @method getElementsByClassName
558
         * @param {String} className The class name to match against
559
         * @param {String} tag (optional) The tag name of the elements being collected
560 1289 kweitzel
         * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point.
561
         * This element is not included in the className scan.
562 601 doc
         * @param {Function} apply (optional) A function to apply to each element when found
563 1289 kweitzel
         * @param {Any} o (optional) An optional arg that is passed to the supplied method
564
         * @param {Boolean} overrides (optional) Whether or not to override the scope of "method" with "o"
565 601 doc
         * @return {Array} An array of elements that have the given class name
566
         */
567 1289 kweitzel
        getElementsByClassName: function(className, tag, root, apply, o, overrides) {
568 601 doc
            tag = tag || '*';
569
            root = (root) ? Y.Dom.get(root) : null || document;
570
            if (!root) {
571
                return [];
572
            }
573
574
            var nodes = [],
575
                elements = root.getElementsByTagName(tag),
576 1289 kweitzel
                hasClass = Y.Dom.hasClass;
577 601 doc
578
            for (var i = 0, len = elements.length; i < len; ++i) {
579 1289 kweitzel
                if ( hasClass(elements[i], className) ) {
580 601 doc
                    nodes[nodes.length] = elements[i];
581
                }
582
            }
583
584 1289 kweitzel
            if (apply) {
585
                Y.Dom.batch(nodes, apply, o, overrides);
586
            }
587
588 601 doc
            return nodes;
589
        },
590
591
        /**
592
         * Determines whether an HTMLElement has the given className.
593
         * @method hasClass
594
         * @param {String | HTMLElement | Array} el The element or collection to test
595
         * @param {String} className the class name to search for
596
         * @return {Boolean | Array} A boolean value or array of boolean values
597
         */
598
        hasClass: function(el, className) {
599 1289 kweitzel
            return Y.Dom.batch(el, Y.Dom._hasClass, className);
600
        },
601 601 doc
602 1289 kweitzel
        _hasClass: function(el, className) {
603
            var ret = false,
604
                current;
605 601 doc
606 1289 kweitzel
            if (el && className) {
607
                current = Y.Dom._getAttribute(el, CLASS_NAME) || EMPTY;
608
                if (className.exec) {
609
                    ret = className.test(current);
610
                } else {
611
                    ret = className && (SPACE + current + SPACE).
612
                        indexOf(SPACE + className + SPACE) > -1;
613
                }
614
            } else {
615
            }
616
617
            return ret;
618 601 doc
        },
619
620
        /**
621
         * Adds a class name to a given element or collection of elements.
622
         * @method addClass
623
         * @param {String | HTMLElement | Array} el The element or collection to add the class to
624
         * @param {String} className the class name to add to the class attribute
625
         * @return {Boolean | Array} A pass/fail boolean or array of booleans
626
         */
627
        addClass: function(el, className) {
628 1289 kweitzel
            return Y.Dom.batch(el, Y.Dom._addClass, className);
629
        },
630
631
        _addClass: function(el, className) {
632
            var ret = false,
633
                current;
634
635
            if (el && className) {
636
                current = Y.Dom._getAttribute(el, CLASS_NAME) || EMPTY;
637
                if ( !Y.Dom._hasClass(el, className) ) {
638
                    Y.Dom.setAttribute(el, CLASS_NAME, trim(current + SPACE + className));
639
                    ret = true;
640 601 doc
                }
641 1289 kweitzel
            } else {
642
            }
643
644
            return ret;
645 601 doc
        },
646
647
        /**
648
         * Removes a class name from a given element or collection of elements.
649
         * @method removeClass
650
         * @param {String | HTMLElement | Array} el The element or collection to remove the class from
651
         * @param {String} className the class name to remove from the class attribute
652
         * @return {Boolean | Array} A pass/fail boolean or array of booleans
653
         */
654
        removeClass: function(el, className) {
655 1289 kweitzel
            return Y.Dom.batch(el, Y.Dom._removeClass, className);
656
        },
657
658
        _removeClass: function(el, className) {
659
            var ret = false,
660
                current,
661
                newClass,
662
                attr;
663 601 doc
664 1289 kweitzel
            if (el && className) {
665
                current = Y.Dom._getAttribute(el, CLASS_NAME) || EMPTY;
666
                Y.Dom.setAttribute(el, CLASS_NAME, current.replace(Y.Dom._getClassRegex(className), EMPTY));
667
668
                newClass = Y.Dom._getAttribute(el, CLASS_NAME);
669
                if (current !== newClass) { // else nothing changed
670
                    Y.Dom.setAttribute(el, CLASS_NAME, trim(newClass)); // trim after comparing to current class
671
                    ret = true;
672
673
                    if (Y.Dom._getAttribute(el, CLASS_NAME) === '') { // remove class attribute if empty
674
                        attr = (el.hasAttribute && el.hasAttribute(_CLASS)) ? _CLASS : CLASS_NAME;
675
                        el.removeAttribute(attr);
676
                    }
677 601 doc
                }
678
679 1289 kweitzel
            } else {
680
            }
681
682
            return ret;
683 601 doc
        },
684
685
        /**
686
         * Replace a class with another class for a given element or collection of elements.
687
         * If no oldClassName is present, the newClassName is simply added.
688
         * @method replaceClass
689
         * @param {String | HTMLElement | Array} el The element or collection to remove the class from
690
         * @param {String} oldClassName the class name to be replaced
691
         * @param {String} newClassName the class name that will be replacing the old class name
692
         * @return {Boolean | Array} A pass/fail boolean or array of booleans
693
         */
694
        replaceClass: function(el, oldClassName, newClassName) {
695 1289 kweitzel
            return Y.Dom.batch(el, Y.Dom._replaceClass, { from: oldClassName, to: newClassName });
696
        },
697 601 doc
698 1289 kweitzel
        _replaceClass: function(el, classObj) {
699
            var className,
700
                from,
701
                to,
702
                ret = false,
703
                current;
704 601 doc
705 1289 kweitzel
            if (el && classObj) {
706
                from = classObj.from;
707
                to = classObj.to;
708
709
                if (!to) {
710
                    ret = false;
711
                }  else if (!from) { // just add if no "from"
712
                    ret = Y.Dom._addClass(el, classObj.to);
713
                } else if (from !== to) { // else nothing to replace
714
                    // May need to lead with DBLSPACE?
715
                    current = Y.Dom._getAttribute(el, CLASS_NAME) || EMPTY;
716
                    className = (SPACE + current.replace(Y.Dom._getClassRegex(from), SPACE + to)).
717
                               split(Y.Dom._getClassRegex(to));
718
719
                    // insert to into what would have been the first occurrence slot
720
                    className.splice(1, 0, SPACE + to);
721
                    Y.Dom.setAttribute(el, CLASS_NAME, trim(className.join(EMPTY)));
722
                    ret = true;
723 601 doc
                }
724 1289 kweitzel
            } else {
725
            }
726 601 doc
727 1289 kweitzel
            return ret;
728 601 doc
        },
729
730
        /**
731
         * Returns an ID and applies it to the element "el", if provided.
732
         * @method generateId
733
         * @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).
734
         * @param {String} prefix (optional) an optional prefix to use (defaults to "yui-gen").
735
         * @return {String | Array} The generated ID, or array of generated IDs (or original ID if already present on an element)
736
         */
737
        generateId: function(el, prefix) {
738
            prefix = prefix || 'yui-gen';
739
740
            var f = function(el) {
741
                if (el && el.id) { // do not override existing ID
742
                    return el.id;
743 1289 kweitzel
                }
744 601 doc
745 1289 kweitzel
                var id = prefix + YAHOO.env._id_counter++;
746 601 doc
747
                if (el) {
748 1289 kweitzel
                    if (el[OWNER_DOCUMENT] && el[OWNER_DOCUMENT].getElementById(id)) { // in case one already exists
749
                        // use failed id plus prefix to help ensure uniqueness
750
                        return Y.Dom.generateId(el, id + prefix);
751
                    }
752 601 doc
                    el.id = id;
753
                }
754
755
                return id;
756
            };
757
758
            // batch fails when no element, so just generate and return single ID
759
            return Y.Dom.batch(el, f, Y.Dom, true) || f.apply(Y.Dom, arguments);
760
        },
761
762
        /**
763
         * Determines whether an HTMLElement is an ancestor of another HTML element in the DOM hierarchy.
764
         * @method isAncestor
765
         * @param {String | HTMLElement} haystack The possible ancestor
766
         * @param {String | HTMLElement} needle The possible descendent
767
         * @return {Boolean} Whether or not the haystack is an ancestor of needle
768
         */
769
        isAncestor: function(haystack, needle) {
770
            haystack = Y.Dom.get(haystack);
771
            needle = Y.Dom.get(needle);
772
773 1289 kweitzel
            var ret = false;
774 601 doc
775 1289 kweitzel
            if ( (haystack && needle) && (haystack[NODE_TYPE] && needle[NODE_TYPE]) ) {
776
                if (haystack.contains && haystack !== needle) { // contains returns true when equal
777
                    ret = haystack.contains(needle);
778
                }
779
                else if (haystack.compareDocumentPosition) { // gecko
780
                    ret = !!(haystack.compareDocumentPosition(needle) & 16);
781
                }
782
            } else {
783 601 doc
            }
784 1289 kweitzel
            return ret;
785 601 doc
        },
786
787
        /**
788
         * Determines whether an HTMLElement is present in the current document.
789
         * @method inDocument
790
         * @param {String | HTMLElement} el The element to search for
791 1289 kweitzel
         * @param {Object} doc An optional document to search, defaults to element's owner document
792 601 doc
         * @return {Boolean} Whether or not the element is present in the current document
793
         */
794 1289 kweitzel
        inDocument: function(el, doc) {
795
            return Y.Dom._inDoc(Y.Dom.get(el), doc);
796 601 doc
        },
797 1289 kweitzel
798
        _inDoc: function(el, doc) {
799
            var ret = false;
800
            if (el && el[TAG_NAME]) {
801
                doc = doc || el[OWNER_DOCUMENT];
802
                ret = Y.Dom.isAncestor(doc[DOCUMENT_ELEMENT], el);
803
            } else {
804
            }
805
            return ret;
806
        },
807 601 doc
808
        /**
809 1289 kweitzel
         * Returns an array of HTMLElements that pass the test applied by supplied boolean method.
810 601 doc
         * For optimized performance, include a tag and/or root node when possible.
811 1289 kweitzel
         * Note: This method operates against a live collection, so modifying the
812
         * collection in the callback (removing/appending nodes, etc.) will have
813
         * side effects.  Instead you should iterate the returned nodes array,
814
         * as you would with the native "getElementsByTagName" method.
815 601 doc
         * @method getElementsBy
816
         * @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
817
         * @param {String} tag (optional) The tag name of the elements being collected
818
         * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point
819
         * @param {Function} apply (optional) A function to apply to each element when found
820 1289 kweitzel
         * @param {Any} o (optional) An optional arg that is passed to the supplied method
821
         * @param {Boolean} overrides (optional) Whether or not to override the scope of "method" with "o"
822 601 doc
         * @return {Array} Array of HTMLElements
823
         */
824 1289 kweitzel
        getElementsBy: function(method, tag, root, apply, o, overrides, firstOnly) {
825 601 doc
            tag = tag || '*';
826
            root = (root) ? Y.Dom.get(root) : null || document;
827
828
            if (!root) {
829
                return [];
830
            }
831
832
            var nodes = [],
833
                elements = root.getElementsByTagName(tag);
834
835
            for (var i = 0, len = elements.length; i < len; ++i) {
836
                if ( method(elements[i]) ) {
837 1289 kweitzel
                    if (firstOnly) {
838
                        nodes = elements[i];
839
                        break;
840
                    } else {
841
                        nodes[nodes.length] = elements[i];
842 601 doc
                    }
843
                }
844
            }
845
846 1289 kweitzel
            if (apply) {
847
                Y.Dom.batch(nodes, apply, o, overrides);
848
            }
849
850 601 doc
851
            return nodes;
852
        },
853
854
        /**
855 1289 kweitzel
         * Returns the first HTMLElement that passes the test applied by the supplied boolean method.
856
         * @method getElementBy
857
         * @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
858
         * @param {String} tag (optional) The tag name of the elements being collected
859
         * @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point
860
         * @return {HTMLElement}
861
         */
862
        getElementBy: function(method, tag, root) {
863
            return Y.Dom.getElementsBy(method, tag, root, null, null, null, true);
864
        },
865
866
        /**
867 601 doc
         * Runs the supplied method against each item in the Collection/Array.
868
         * The method is called with the element(s) as the first arg, and the optional param as the second ( method(el, o) ).
869
         * @method batch
870
         * @param {String | HTMLElement | Array} el (optional) An element or array of elements to apply the method to
871
         * @param {Function} method The method to apply to the element(s)
872
         * @param {Any} o (optional) An optional arg that is passed to the supplied method
873 1289 kweitzel
         * @param {Boolean} overrides (optional) Whether or not to override the scope of "method" with "o"
874 601 doc
         * @return {Any | Array} The return value(s) from the supplied method
875
         */
876 1289 kweitzel
        batch: function(el, method, o, overrides) {
877
            var collection = [],
878
                scope = (overrides) ? o : window;
879
880
            el = (el && (el[TAG_NAME] || el.item)) ? el : Y.Dom.get(el); // skip get() when possible
881
            if (el && method) {
882
                if (el[TAG_NAME] || el.length === undefined) { // element or not array-like
883
                    return method.call(scope, el, o);
884
                }
885 601 doc
886 1289 kweitzel
                for (var i = 0; i < el.length; ++i) {
887
                    collection[collection.length] = method.call(scope, el[i], o);
888
                }
889
            } else {
890 601 doc
                return false;
891
            }
892
            return collection;
893
        },
894
895
        /**
896
         * Returns the height of the document.
897
         * @method getDocumentHeight
898
         * @return {Int} The height of the actual document (which includes the body and its margin).
899
         */
900
        getDocumentHeight: function() {
901 1289 kweitzel
            var scrollHeight = (document[COMPAT_MODE] != CSS1_COMPAT || isSafari) ? document.body.scrollHeight : documentElement.scrollHeight,
902
                h = Math.max(scrollHeight, Y.Dom.getViewportHeight());
903 601 doc
904
            return h;
905
        },
906
907
        /**
908
         * Returns the width of the document.
909
         * @method getDocumentWidth
910
         * @return {Int} The width of the actual document (which includes the body and its margin).
911
         */
912
        getDocumentWidth: function() {
913 1289 kweitzel
            var scrollWidth = (document[COMPAT_MODE] != CSS1_COMPAT || isSafari) ? document.body.scrollWidth : documentElement.scrollWidth,
914
                w = Math.max(scrollWidth, Y.Dom.getViewportWidth());
915 601 doc
            return w;
916
        },
917
918
        /**
919
         * Returns the current height of the viewport.
920
         * @method getViewportHeight
921
         * @return {Int} The height of the viewable area of the page (excludes scrollbars).
922
         */
923
        getViewportHeight: function() {
924 1289 kweitzel
            var height = self.innerHeight, // Safari, Opera
925
                mode = document[COMPAT_MODE];
926 601 doc
927
            if ( (mode || isIE) && !isOpera ) { // IE, Gecko
928 1289 kweitzel
                height = (mode == CSS1_COMPAT) ?
929
                        documentElement.clientHeight : // Standards
930 601 doc
                        document.body.clientHeight; // Quirks
931
            }
932
933
            return height;
934
        },
935
936
        /**
937
         * Returns the current width of the viewport.
938
         * @method getViewportWidth
939
         * @return {Int} The width of the viewable area of the page (excludes scrollbars).
940
         */
941
942
        getViewportWidth: function() {
943 1289 kweitzel
            var width = self.innerWidth,  // Safari
944
                mode = document[COMPAT_MODE];
945 601 doc
946
            if (mode || isIE) { // IE, Gecko, Opera
947 1289 kweitzel
                width = (mode == CSS1_COMPAT) ?
948
                        documentElement.clientWidth : // Standards
949 601 doc
                        document.body.clientWidth; // Quirks
950
            }
951
            return width;
952
        },
953
954
       /**
955
         * Returns the nearest ancestor that passes the test applied by supplied boolean method.
956
         * For performance reasons, IDs are not accepted and argument validation omitted.
957
         * @method getAncestorBy
958
         * @param {HTMLElement} node The HTMLElement to use as the starting point
959
         * @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
960
         * @return {Object} HTMLElement or null if not found
961
         */
962
        getAncestorBy: function(node, method) {
963 1289 kweitzel
            while ( (node = node[PARENT_NODE]) ) { // NOTE: assignment
964
                if ( Y.Dom._testElement(node, method) ) {
965 601 doc
                    return node;
966
                }
967
            }
968
969
            return null;
970
        },
971
972
        /**
973
         * Returns the nearest ancestor with the given className.
974
         * @method getAncestorByClassName
975
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
976
         * @param {String} className
977
         * @return {Object} HTMLElement
978
         */
979
        getAncestorByClassName: function(node, className) {
980
            node = Y.Dom.get(node);
981
            if (!node) {
982
                return null;
983
            }
984
            var method = function(el) { return Y.Dom.hasClass(el, className); };
985
            return Y.Dom.getAncestorBy(node, method);
986
        },
987
988
        /**
989
         * Returns the nearest ancestor with the given tagName.
990
         * @method getAncestorByTagName
991
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
992
         * @param {String} tagName
993
         * @return {Object} HTMLElement
994
         */
995
        getAncestorByTagName: function(node, tagName) {
996
            node = Y.Dom.get(node);
997
            if (!node) {
998
                return null;
999
            }
1000
            var method = function(el) {
1001 1289 kweitzel
                 return el[TAG_NAME] && el[TAG_NAME].toUpperCase() == tagName.toUpperCase();
1002 601 doc
            };
1003
1004
            return Y.Dom.getAncestorBy(node, method);
1005
        },
1006
1007
        /**
1008
         * Returns the previous sibling that is an HTMLElement.
1009
         * For performance reasons, IDs are not accepted and argument validation omitted.
1010
         * Returns the nearest HTMLElement sibling if no method provided.
1011
         * @method getPreviousSiblingBy
1012
         * @param {HTMLElement} node The HTMLElement to use as the starting point
1013
         * @param {Function} method A boolean function used to test siblings
1014
         * that receives the sibling node being tested as its only argument
1015
         * @return {Object} HTMLElement or null if not found
1016
         */
1017
        getPreviousSiblingBy: function(node, method) {
1018
            while (node) {
1019
                node = node.previousSibling;
1020 1289 kweitzel
                if ( Y.Dom._testElement(node, method) ) {
1021 601 doc
                    return node;
1022
                }
1023
            }
1024
            return null;
1025
        },
1026
1027
        /**
1028
         * Returns the previous sibling that is an HTMLElement
1029
         * @method getPreviousSibling
1030
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
1031
         * @return {Object} HTMLElement or null if not found
1032
         */
1033
        getPreviousSibling: function(node) {
1034
            node = Y.Dom.get(node);
1035
            if (!node) {
1036
                return null;
1037
            }
1038
1039
            return Y.Dom.getPreviousSiblingBy(node);
1040
        },
1041
1042
        /**
1043
         * Returns the next HTMLElement sibling that passes the boolean method.
1044
         * For performance reasons, IDs are not accepted and argument validation omitted.
1045
         * Returns the nearest HTMLElement sibling if no method provided.
1046
         * @method getNextSiblingBy
1047
         * @param {HTMLElement} node The HTMLElement to use as the starting point
1048
         * @param {Function} method A boolean function used to test siblings
1049
         * that receives the sibling node being tested as its only argument
1050
         * @return {Object} HTMLElement or null if not found
1051
         */
1052
        getNextSiblingBy: function(node, method) {
1053
            while (node) {
1054
                node = node.nextSibling;
1055 1289 kweitzel
                if ( Y.Dom._testElement(node, method) ) {
1056 601 doc
                    return node;
1057
                }
1058
            }
1059
            return null;
1060
        },
1061
1062
        /**
1063
         * Returns the next sibling that is an HTMLElement
1064
         * @method getNextSibling
1065
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
1066
         * @return {Object} HTMLElement or null if not found
1067
         */
1068
        getNextSibling: function(node) {
1069
            node = Y.Dom.get(node);
1070
            if (!node) {
1071
                return null;
1072
            }
1073
1074
            return Y.Dom.getNextSiblingBy(node);
1075
        },
1076
1077
        /**
1078
         * Returns the first HTMLElement child that passes the test method.
1079
         * @method getFirstChildBy
1080
         * @param {HTMLElement} node The HTMLElement to use as the starting point
1081
         * @param {Function} method A boolean function used to test children
1082
         * that receives the node being tested as its only argument
1083
         * @return {Object} HTMLElement or null if not found
1084
         */
1085
        getFirstChildBy: function(node, method) {
1086 1289 kweitzel
            var child = ( Y.Dom._testElement(node.firstChild, method) ) ? node.firstChild : null;
1087 601 doc
            return child || Y.Dom.getNextSiblingBy(node.firstChild, method);
1088
        },
1089
1090
        /**
1091
         * Returns the first HTMLElement child.
1092
         * @method getFirstChild
1093
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
1094
         * @return {Object} HTMLElement or null if not found
1095
         */
1096
        getFirstChild: function(node, method) {
1097
            node = Y.Dom.get(node);
1098
            if (!node) {
1099
                return null;
1100
            }
1101
            return Y.Dom.getFirstChildBy(node);
1102
        },
1103
1104
        /**
1105
         * Returns the last HTMLElement child that passes the test method.
1106
         * @method getLastChildBy
1107
         * @param {HTMLElement} node The HTMLElement to use as the starting point
1108
         * @param {Function} method A boolean function used to test children
1109
         * that receives the node being tested as its only argument
1110
         * @return {Object} HTMLElement or null if not found
1111
         */
1112
        getLastChildBy: function(node, method) {
1113
            if (!node) {
1114
                return null;
1115
            }
1116 1289 kweitzel
            var child = ( Y.Dom._testElement(node.lastChild, method) ) ? node.lastChild : null;
1117 601 doc
            return child || Y.Dom.getPreviousSiblingBy(node.lastChild, method);
1118
        },
1119
1120
        /**
1121
         * Returns the last HTMLElement child.
1122
         * @method getLastChild
1123
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
1124
         * @return {Object} HTMLElement or null if not found
1125
         */
1126
        getLastChild: function(node) {
1127
            node = Y.Dom.get(node);
1128
            return Y.Dom.getLastChildBy(node);
1129
        },
1130
1131
        /**
1132
         * Returns an array of HTMLElement childNodes that pass the test method.
1133
         * @method getChildrenBy
1134
         * @param {HTMLElement} node The HTMLElement to start from
1135
         * @param {Function} method A boolean function used to test children
1136
         * that receives the node being tested as its only argument
1137
         * @return {Array} A static array of HTMLElements
1138
         */
1139
        getChildrenBy: function(node, method) {
1140 1289 kweitzel
            var child = Y.Dom.getFirstChildBy(node, method),
1141
                children = child ? [child] : [];
1142 601 doc
1143
            Y.Dom.getNextSiblingBy(child, function(node) {
1144
                if ( !method || method(node) ) {
1145
                    children[children.length] = node;
1146
                }
1147
                return false; // fail test to collect all children
1148
            });
1149
1150
            return children;
1151
        },
1152
1153
        /**
1154
         * Returns an array of HTMLElement childNodes.
1155
         * @method getChildren
1156
         * @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
1157
         * @return {Array} A static array of HTMLElements
1158
         */
1159
        getChildren: function(node) {
1160
            node = Y.Dom.get(node);
1161
            if (!node) {
1162
            }
1163
1164
            return Y.Dom.getChildrenBy(node);
1165
        },
1166 1289 kweitzel
1167 601 doc
        /**
1168
         * Returns the left scroll value of the document
1169
         * @method getDocumentScrollLeft
1170
         * @param {HTMLDocument} document (optional) The document to get the scroll value of
1171
         * @return {Int}  The amount that the document is scrolled to the left
1172
         */
1173
        getDocumentScrollLeft: function(doc) {
1174
            doc = doc || document;
1175 1289 kweitzel
            return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft);
1176 601 doc
        },
1177
1178
        /**
1179
         * Returns the top scroll value of the document
1180
         * @method getDocumentScrollTop
1181
         * @param {HTMLDocument} document (optional) The document to get the scroll value of
1182
         * @return {Int}  The amount that the document is scrolled to the top
1183
         */
1184
        getDocumentScrollTop: function(doc) {
1185
            doc = doc || document;
1186 1289 kweitzel
            return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop);
1187 601 doc
        },
1188
1189
        /**
1190
         * Inserts the new node as the previous sibling of the reference node
1191
         * @method insertBefore
1192
         * @param {String | HTMLElement} newNode The node to be inserted
1193
         * @param {String | HTMLElement} referenceNode The node to insert the new node before
1194
         * @return {HTMLElement} The node that was inserted (or null if insert fails)
1195
         */
1196
        insertBefore: function(newNode, referenceNode) {
1197
            newNode = Y.Dom.get(newNode);
1198
            referenceNode = Y.Dom.get(referenceNode);
1199
1200 1289 kweitzel
            if (!newNode || !referenceNode || !referenceNode[PARENT_NODE]) {
1201 601 doc
                return null;
1202
            }
1203
1204 1289 kweitzel
            return referenceNode[PARENT_NODE].insertBefore(newNode, referenceNode);
1205 601 doc
        },
1206
1207
        /**
1208
         * Inserts the new node as the next sibling of the reference node
1209
         * @method insertAfter
1210
         * @param {String | HTMLElement} newNode The node to be inserted
1211
         * @param {String | HTMLElement} referenceNode The node to insert the new node after
1212
         * @return {HTMLElement} The node that was inserted (or null if insert fails)
1213
         */
1214
        insertAfter: function(newNode, referenceNode) {
1215
            newNode = Y.Dom.get(newNode);
1216
            referenceNode = Y.Dom.get(referenceNode);
1217
1218 1289 kweitzel
            if (!newNode || !referenceNode || !referenceNode[PARENT_NODE]) {
1219 601 doc
                return null;
1220
            }
1221
1222
            if (referenceNode.nextSibling) {
1223 1289 kweitzel
                return referenceNode[PARENT_NODE].insertBefore(newNode, referenceNode.nextSibling);
1224 601 doc
            } else {
1225 1289 kweitzel
                return referenceNode[PARENT_NODE].appendChild(newNode);
1226 601 doc
            }
1227
        },
1228
1229
        /**
1230
         * Creates a Region based on the viewport relative to the document.
1231
         * @method getClientRegion
1232
         * @return {Region} A Region object representing the viewport which accounts for document scroll
1233
         */
1234
        getClientRegion: function() {
1235
            var t = Y.Dom.getDocumentScrollTop(),
1236
                l = Y.Dom.getDocumentScrollLeft(),
1237
                r = Y.Dom.getViewportWidth() + l,
1238
                b = Y.Dom.getViewportHeight() + t;
1239
1240
            return new Y.Region(t, r, b, l);
1241 1289 kweitzel
        },
1242 601 doc
1243 1289 kweitzel
        /**
1244
         * Provides a normalized attribute interface.
1245
         * @method setAttribute
1246
         * @param {String | HTMLElement} el The target element for the attribute.
1247
         * @param {String} attr The attribute to set.
1248
         * @param {String} val The value of the attribute.
1249
         */
1250
        setAttribute: function(el, attr, val) {
1251
            Y.Dom.batch(el, Y.Dom._setAttribute, { attr: attr, val: val });
1252
        },
1253 601 doc
1254 1289 kweitzel
        _setAttribute: function(el, args) {
1255
            var attr = Y.Dom._toCamel(args.attr),
1256
                val = args.val;
1257 601 doc
1258 1289 kweitzel
            if (el && el.setAttribute) {
1259
                if (Y.Dom.DOT_ATTRIBUTES[attr]) {
1260
                    el[attr] = val;
1261
                } else {
1262
                    attr = Y.Dom.CUSTOM_ATTRIBUTES[attr] || attr;
1263
                    el.setAttribute(attr, val);
1264 601 doc
                }
1265 1289 kweitzel
            } else {
1266
            }
1267
        },
1268 601 doc
1269 1289 kweitzel
        /**
1270
         * Provides a normalized attribute interface.
1271
         * @method getAttribute
1272
         * @param {String | HTMLElement} el The target element for the attribute.
1273
         * @param {String} attr The attribute to get.
1274
         * @return {String} The current value of the attribute.
1275
         */
1276
        getAttribute: function(el, attr) {
1277
            return Y.Dom.batch(el, Y.Dom._getAttribute, attr);
1278
        },
1279 601 doc
1280 1289 kweitzel
1281
        _getAttribute: function(el, attr) {
1282
            var val;
1283
            attr = Y.Dom.CUSTOM_ATTRIBUTES[attr] || attr;
1284
1285
            if (el && el.getAttribute) {
1286
                val = el.getAttribute(attr, 2);
1287
            } else {
1288
            }
1289
1290
            return val;
1291
        },
1292
1293
        _toCamel: function(property) {
1294
            var c = propertyCache;
1295
1296
            function tU(x,l) {
1297
                return l.toUpperCase();
1298
            }
1299
1300
            return c[property] || (c[property] = property.indexOf('-') === -1 ?
1301
                                    property :
1302
                                    property.replace( /-([a-z])/gi, tU ));
1303
        },
1304
1305
        _getClassRegex: function(className) {
1306
            var re;
1307
            if (className !== undefined) { // allow empty string to pass
1308
                if (className.exec) { // already a RegExp
1309
                    re = className;
1310
                } else {
1311
                    re = reCache[className];
1312
                    if (!re) {
1313
                        // escape special chars (".", "[", etc.)
1314
                        className = className.replace(Y.Dom._patterns.CLASS_RE_TOKENS, '\\$1');
1315
                        re = reCache[className] = new RegExp(C_START + className + C_END, G);
1316 601 doc
                    }
1317
                }
1318 1289 kweitzel
            }
1319
            return re;
1320
        },
1321 601 doc
1322 1289 kweitzel
        _patterns: {
1323
            ROOT_TAG: /^body|html$/i, // body for quirks mode, html for standards,
1324
            CLASS_RE_TOKENS: /([\.\(\)\^\$\*\+\?\|\[\]\{\}\\])/g
1325
        },
1326
1327
1328
        _testElement: function(node, method) {
1329
            return node && node[NODE_TYPE] == 1 && ( !method || method(node) );
1330
        },
1331
1332
        _calcBorders: function(node, xy2) {
1333
            var t = parseInt(Y.Dom[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0,
1334
                l = parseInt(Y.Dom[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0;
1335
            if (isGecko) {
1336
                if (RE_TABLE.test(node[TAG_NAME])) {
1337
                    t = 0;
1338
                    l = 0;
1339
                }
1340
            }
1341
            xy2[0] += l;
1342
            xy2[1] += t;
1343
            return xy2;
1344 601 doc
        }
1345 1289 kweitzel
    };
1346
1347
    var _getComputedStyle = Y.Dom[GET_COMPUTED_STYLE];
1348
    // fix opera computedStyle default color unit (convert to rgb)
1349
    if (UA.opera) {
1350
        Y.Dom[GET_COMPUTED_STYLE] = function(node, att) {
1351
            var val = _getComputedStyle(node, att);
1352
            if (RE_COLOR.test(att)) {
1353
                val = Y.Dom.Color.toRGB(val);
1354
            }
1355
1356
            return val;
1357
        };
1358
1359
    }
1360
1361
    // safari converts transparent to rgba(), others use "transparent"
1362
    if (UA.webkit) {
1363
        Y.Dom[GET_COMPUTED_STYLE] = function(node, att) {
1364
            var val = _getComputedStyle(node, att);
1365
1366
            if (val === 'rgba(0, 0, 0, 0)') {
1367
                val = 'transparent';
1368
            }
1369
1370
            return val;
1371
        };
1372
1373
    }
1374
1375
    if (UA.ie && UA.ie >= 8 && document.documentElement.hasAttribute) { // IE 8 standards
1376
        Y.Dom.DOT_ATTRIBUTES.type = true; // IE 8 errors on input.setAttribute('type')
1377
    }
1378 601 doc
})();
1379
/**
1380
 * A region is a representation of an object on a grid.  It is defined
1381
 * by the top, right, bottom, left extents, so is rectangular by default.  If
1382
 * other shapes are required, this class could be extended to support it.
1383
 * @namespace YAHOO.util
1384
 * @class Region
1385
 * @param {Int} t the top extent
1386
 * @param {Int} r the right extent
1387
 * @param {Int} b the bottom extent
1388
 * @param {Int} l the left extent
1389
 * @constructor
1390
 */
1391
YAHOO.util.Region = function(t, r, b, l) {
1392
1393
    /**
1394
     * The region's top extent
1395
     * @property top
1396
     * @type Int
1397
     */
1398
    this.top = t;
1399
1400
    /**
1401 1289 kweitzel
     * The region's top extent
1402
     * @property y
1403
     * @type Int
1404
     */
1405
    this.y = t;
1406
1407
    /**
1408 601 doc
     * The region's top extent as index, for symmetry with set/getXY
1409
     * @property 1
1410
     * @type Int
1411
     */
1412
    this[1] = t;
1413
1414
    /**
1415
     * The region's right extent
1416
     * @property right
1417
     * @type int
1418
     */
1419
    this.right = r;
1420
1421
    /**
1422
     * The region's bottom extent
1423
     * @property bottom
1424
     * @type Int
1425
     */
1426
    this.bottom = b;
1427
1428
    /**
1429
     * The region's left extent
1430
     * @property left
1431
     * @type Int
1432
     */
1433
    this.left = l;
1434
1435
    /**
1436 1289 kweitzel
     * The region's left extent
1437
     * @property x
1438
     * @type Int
1439
     */
1440
    this.x = l;
1441
1442
    /**
1443 601 doc
     * The region's left extent as index, for symmetry with set/getXY
1444
     * @property 0
1445
     * @type Int
1446
     */
1447
    this[0] = l;
1448 1289 kweitzel
1449
    /**
1450
     * The region's total width
1451
     * @property width
1452
     * @type Int
1453
     */
1454
    this.width = this.right - this.left;
1455
1456
    /**
1457
     * The region's total height
1458
     * @property height
1459
     * @type Int
1460
     */
1461
    this.height = this.bottom - this.top;
1462 601 doc
};
1463
1464
/**
1465
 * Returns true if this region contains the region passed in
1466
 * @method contains
1467
 * @param  {Region}  region The region to evaluate
1468
 * @return {Boolean}        True if the region is contained with this region,
1469
 *                          else false
1470
 */
1471
YAHOO.util.Region.prototype.contains = function(region) {
1472
    return ( region.left   >= this.left   &&
1473
             region.right  <= this.right  &&
1474
             region.top    >= this.top    &&
1475
             region.bottom <= this.bottom    );
1476
1477
};
1478
1479
/**
1480
 * Returns the area of the region
1481
 * @method getArea
1482
 * @return {Int} the region's area
1483
 */
1484
YAHOO.util.Region.prototype.getArea = function() {
1485
    return ( (this.bottom - this.top) * (this.right - this.left) );
1486
};
1487
1488
/**
1489
 * Returns the region where the passed in region overlaps with this one
1490
 * @method intersect
1491
 * @param  {Region} region The region that intersects
1492
 * @return {Region}        The overlap region, or null if there is no overlap
1493
 */
1494
YAHOO.util.Region.prototype.intersect = function(region) {
1495 1289 kweitzel
    var t = Math.max( this.top,    region.top    ),
1496
        r = Math.min( this.right,  region.right  ),
1497
        b = Math.min( this.bottom, region.bottom ),
1498
        l = Math.max( this.left,   region.left   );
1499 601 doc
1500
    if (b >= t && r >= l) {
1501
        return new YAHOO.util.Region(t, r, b, l);
1502
    } else {
1503
        return null;
1504
    }
1505
};
1506
1507
/**
1508
 * Returns the region representing the smallest region that can contain both
1509
 * the passed in region and this region.
1510
 * @method union
1511
 * @param  {Region} region The region that to create the union with
1512
 * @return {Region}        The union region
1513
 */
1514
YAHOO.util.Region.prototype.union = function(region) {
1515 1289 kweitzel
    var t = Math.min( this.top,    region.top    ),
1516
        r = Math.max( this.right,  region.right  ),
1517
        b = Math.max( this.bottom, region.bottom ),
1518
        l = Math.min( this.left,   region.left   );
1519 601 doc
1520
    return new YAHOO.util.Region(t, r, b, l);
1521
};
1522
1523
/**
1524
 * toString
1525
 * @method toString
1526
 * @return string the region properties
1527
 */
1528
YAHOO.util.Region.prototype.toString = function() {
1529
    return ( "Region {"    +
1530
             "top: "       + this.top    +
1531
             ", right: "   + this.right  +
1532
             ", bottom: "  + this.bottom +
1533
             ", left: "    + this.left   +
1534 1289 kweitzel
             ", height: "  + this.height +
1535
             ", width: "    + this.width   +
1536 601 doc
             "}" );
1537
};
1538
1539
/**
1540
 * Returns a region that is occupied by the DOM element
1541
 * @method getRegion
1542
 * @param  {HTMLElement} el The element
1543
 * @return {Region}         The region that the element occupies
1544
 * @static
1545
 */
1546
YAHOO.util.Region.getRegion = function(el) {
1547 1289 kweitzel
    var p = YAHOO.util.Dom.getXY(el),
1548
        t = p[1],
1549
        r = p[0] + el.offsetWidth,
1550
        b = p[1] + el.offsetHeight,
1551
        l = p[0];
1552 601 doc
1553
    return new YAHOO.util.Region(t, r, b, l);
1554
};
1555
1556
/////////////////////////////////////////////////////////////////////////////
1557
1558
1559
/**
1560
 * A point is a region that is special in that it represents a single point on
1561
 * the grid.
1562
 * @namespace YAHOO.util
1563
 * @class Point
1564
 * @param {Int} x The X position of the point
1565
 * @param {Int} y The Y position of the point
1566
 * @constructor
1567
 * @extends YAHOO.util.Region
1568
 */
1569
YAHOO.util.Point = function(x, y) {
1570
   if (YAHOO.lang.isArray(x)) { // accept input from Dom.getXY, Event.getXY, etc.
1571
      y = x[1]; // dont blow away x yet
1572
      x = x[0];
1573
   }
1574 1289 kweitzel
1575
    YAHOO.util.Point.superclass.constructor.call(this, y, x, y, x);
1576 601 doc
};
1577
1578 1289 kweitzel
YAHOO.extend(YAHOO.util.Point, YAHOO.util.Region);
1579 601 doc
1580 1289 kweitzel
(function() {
1581
/**
1582
 * Add style management functionality to DOM.
1583
 * @module dom
1584
 * @for Dom
1585
 */
1586
1587
var Y = YAHOO.util,
1588
    CLIENT_TOP = 'clientTop',
1589
    CLIENT_LEFT = 'clientLeft',
1590
    PARENT_NODE = 'parentNode',
1591
    RIGHT = 'right',
1592
    HAS_LAYOUT = 'hasLayout',
1593
    PX = 'px',
1594
    OPACITY = 'opacity',
1595
    AUTO = 'auto',
1596
    BORDER_LEFT_WIDTH = 'borderLeftWidth',
1597
    BORDER_TOP_WIDTH = 'borderTopWidth',
1598
    BORDER_RIGHT_WIDTH = 'borderRightWidth',
1599
    BORDER_BOTTOM_WIDTH = 'borderBottomWidth',
1600
    VISIBLE = 'visible',
1601
    TRANSPARENT = 'transparent',
1602
    HEIGHT = 'height',
1603
    WIDTH = 'width',
1604
    STYLE = 'style',
1605
    CURRENT_STYLE = 'currentStyle',
1606
1607
// IE getComputedStyle
1608
// TODO: unit-less lineHeight (e.g. 1.22)
1609
    re_size = /^width|height$/,
1610
    re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i,
1611
1612
    ComputedStyle = {
1613
        get: function(el, property) {
1614
            var value = '',
1615
                current = el[CURRENT_STYLE][property];
1616
1617
            if (property === OPACITY) {
1618
                value = Y.Dom.getStyle(el, OPACITY);
1619
            } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert
1620
                value = current;
1621
            } else if (Y.Dom.IE_COMPUTED[property]) { // use compute function
1622
                value = Y.Dom.IE_COMPUTED[property](el, property);
1623
            } else if (re_unit.test(current)) { // convert to pixel
1624
                value = Y.Dom.IE.ComputedStyle.getPixel(el, property);
1625
            } else {
1626
                value = current;
1627
            }
1628
1629
            return value;
1630
        },
1631
1632
        getOffset: function(el, prop) {
1633
            var current = el[CURRENT_STYLE][prop],                        // value of "width", "top", etc.
1634
                capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc.
1635
                offset = 'offset' + capped,                             // "offsetWidth", "offsetTop", etc.
1636
                pixel = 'pixel' + capped,                               // "pixelWidth", "pixelTop", etc.
1637
                value = '',
1638
                actual;
1639
1640
            if (current == AUTO) {
1641
                actual = el[offset]; // offsetHeight/Top etc.
1642
                if (actual === undefined) { // likely "right" or "bottom"
1643
                    value = 0;
1644
                }
1645
1646
                value = actual;
1647
                if (re_size.test(prop)) { // account for box model diff
1648
                    el[STYLE][prop] = actual;
1649
                    if (el[offset] > actual) {
1650
                        // the difference is padding + border (works in Standards & Quirks modes)
1651
                        value = actual - (el[offset] - actual);
1652
                    }
1653
                    el[STYLE][prop] = AUTO; // revert to auto
1654
                }
1655
            } else { // convert units to px
1656
                if (!el[STYLE][pixel] && !el[STYLE][prop]) { // need to map style.width to currentStyle (no currentStyle.pixelWidth)
1657
                    el[STYLE][prop] = current;              // no style.pixelWidth if no style.width
1658
                }
1659
                value = el[STYLE][pixel];
1660
            }
1661
            return value + PX;
1662
        },
1663
1664
        getBorderWidth: function(el, property) {
1665
            // clientHeight/Width = paddingBox (e.g. offsetWidth - borderWidth)
1666
            // clientTop/Left = borderWidth
1667
            var value = null;
1668
            if (!el[CURRENT_STYLE][HAS_LAYOUT]) { // TODO: unset layout?
1669
                el[STYLE].zoom = 1; // need layout to measure client
1670
            }
1671
1672
            switch(property) {
1673
                case BORDER_TOP_WIDTH:
1674
                    value = el[CLIENT_TOP];
1675
                    break;
1676
                case BORDER_BOTTOM_WIDTH:
1677
                    value = el.offsetHeight - el.clientHeight - el[CLIENT_TOP];
1678
                    break;
1679
                case BORDER_LEFT_WIDTH:
1680
                    value = el[CLIENT_LEFT];
1681
                    break;
1682
                case BORDER_RIGHT_WIDTH:
1683
                    value = el.offsetWidth - el.clientWidth - el[CLIENT_LEFT];
1684
                    break;
1685
            }
1686
            return value + PX;
1687
        },
1688
1689
        getPixel: function(node, att) {
1690
            // use pixelRight to convert to px
1691
            var val = null,
1692
                styleRight = node[CURRENT_STYLE][RIGHT],
1693
                current = node[CURRENT_STYLE][att];
1694
1695
            node[STYLE][RIGHT] = current;
1696
            val = node[STYLE].pixelRight;
1697
            node[STYLE][RIGHT] = styleRight; // revert
1698
1699
            return val + PX;
1700
        },
1701
1702
        getMargin: function(node, att) {
1703
            var val;
1704
            if (node[CURRENT_STYLE][att] == AUTO) {
1705
                val = 0 + PX;
1706
            } else {
1707
                val = Y.Dom.IE.ComputedStyle.getPixel(node, att);
1708
            }
1709
            return val;
1710
        },
1711
1712
        getVisibility: function(node, att) {
1713
            var current;
1714
            while ( (current = node[CURRENT_STYLE]) && current[att] == 'inherit') { // NOTE: assignment in test
1715
                node = node[PARENT_NODE];
1716
            }
1717
            return (current) ? current[att] : VISIBLE;
1718
        },
1719
1720
        getColor: function(node, att) {
1721
            return Y.Dom.Color.toRGB(node[CURRENT_STYLE][att]) || TRANSPARENT;
1722
        },
1723
1724
        getBorderColor: function(node, att) {
1725
            var current = node[CURRENT_STYLE],
1726
                val = current[att] || current.color;
1727
            return Y.Dom.Color.toRGB(Y.Dom.Color.toHex(val));
1728
        }
1729
1730
    },
1731
1732
//fontSize: getPixelFont,
1733
    IEComputed = {};
1734
1735
IEComputed.top = IEComputed.right = IEComputed.bottom = IEComputed.left =
1736
        IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset;
1737
1738
IEComputed.color = ComputedStyle.getColor;
1739
1740
IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] =
1741
        IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] =
1742
        ComputedStyle.getBorderWidth;
1743
1744
IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom =
1745
        IEComputed.marginLeft = ComputedStyle.getMargin;
1746
1747
IEComputed.visibility = ComputedStyle.getVisibility;
1748
IEComputed.borderColor = IEComputed.borderTopColor =
1749
        IEComputed.borderRightColor = IEComputed.borderBottomColor =
1750
        IEComputed.borderLeftColor = ComputedStyle.getBorderColor;
1751
1752
Y.Dom.IE_COMPUTED = IEComputed;
1753
Y.Dom.IE_ComputedStyle = ComputedStyle;
1754
})();
1755
(function() {
1756
/**
1757
 * Add style management functionality to DOM.
1758
 * @module dom
1759
 * @for Dom
1760
 */
1761
1762
var TO_STRING = 'toString',
1763
    PARSE_INT = parseInt,
1764
    RE = RegExp,
1765
    Y = YAHOO.util;
1766
1767
Y.Dom.Color = {
1768
    KEYWORDS: {
1769
        black: '000',
1770
        silver: 'c0c0c0',
1771
        gray: '808080',
1772
        white: 'fff',
1773
        maroon: '800000',
1774
        red: 'f00',
1775
        purple: '800080',
1776
        fuchsia: 'f0f',
1777
        green: '008000',
1778
        lime: '0f0',
1779
        olive: '808000',
1780
        yellow: 'ff0',
1781
        navy: '000080',
1782
        blue: '00f',
1783
        teal: '008080',
1784
        aqua: '0ff'
1785
    },
1786
1787
    re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,
1788
    re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,
1789
    re_hex3: /([0-9A-F])/gi,
1790
1791
    toRGB: function(val) {
1792
        if (!Y.Dom.Color.re_RGB.test(val)) {
1793
            val = Y.Dom.Color.toHex(val);
1794
        }
1795
1796
        if(Y.Dom.Color.re_hex.exec(val)) {
1797
            val = 'rgb(' + [
1798
                PARSE_INT(RE.$1, 16),
1799
                PARSE_INT(RE.$2, 16),
1800
                PARSE_INT(RE.$3, 16)
1801
            ].join(', ') + ')';
1802
        }
1803
        return val;
1804
    },
1805
1806
    toHex: function(val) {
1807
        val = Y.Dom.Color.KEYWORDS[val] || val;
1808
        if (Y.Dom.Color.re_RGB.exec(val)) {
1809
            var r = (RE.$1.length === 1) ? '0' + RE.$1 : Number(RE.$1),
1810
                g = (RE.$2.length === 1) ? '0' + RE.$2 : Number(RE.$2),
1811
                b = (RE.$3.length === 1) ? '0' + RE.$3 : Number(RE.$3);
1812
1813
            val = [
1814
                r[TO_STRING](16),
1815
                g[TO_STRING](16),
1816
                b[TO_STRING](16)
1817
            ].join('');
1818
        }
1819
1820
        if (val.length < 6) {
1821
            val = val.replace(Y.Dom.Color.re_hex3, '$1$1');
1822
        }
1823
1824
        if (val !== 'transparent' && val.indexOf('#') < 0) {
1825
            val = '#' + val;
1826
        }
1827
1828
        return val.toLowerCase();
1829
    }
1830
};
1831
}());
1832
YAHOO.register("dom", YAHOO.util.Dom, {version: "2.8.0r4", build: "2449"});