/lenasys/trunk

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/lenasys/trunk
12.4.2 by Adam Ringhede
Adds PIE for CSS3 compatability issues with IE
1
/*
2
PIE: CSS3 rendering for IE
3
Version 1.0.0
4
http://css3pie.com
5
Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2.
6
*/
7
(function(){
8
var doc = document;var PIE = window['PIE'];
9
10
if( !PIE ) {
11
    PIE = window['PIE'] = {
12
        CSS_PREFIX: '-pie-',
13
        STYLE_PREFIX: 'Pie',
14
        CLASS_PREFIX: 'pie_',
15
        tableCellTags: {
16
            'TD': 1,
17
            'TH': 1
18
        },
19
20
        /**
21
         * Lookup table of elements which cannot take custom children.
22
         */
23
        childlessElements: {
24
            'TABLE':1,
25
            'THEAD':1,
26
            'TBODY':1,
27
            'TFOOT':1,
28
            'TR':1,
29
            'INPUT':1,
30
            'TEXTAREA':1,
31
            'SELECT':1,
32
            'OPTION':1,
33
            'IMG':1,
34
            'HR':1
35
        },
36
37
        /**
38
         * Elements that can receive user focus
39
         */
40
        focusableElements: {
41
            'A':1,
42
            'INPUT':1,
43
            'TEXTAREA':1,
44
            'SELECT':1,
45
            'BUTTON':1
46
        },
47
48
        /**
49
         * Values of the type attribute for input elements displayed as buttons
50
         */
51
        inputButtonTypes: {
52
            'submit':1,
53
            'button':1,
54
            'reset':1
55
        },
56
57
        emptyFn: function() {}
58
    };
59
60
    // Force the background cache to be used. No reason it shouldn't be.
61
    try {
62
        doc.execCommand( 'BackgroundImageCache', false, true );
63
    } catch(e) {}
64
65
    (function() {
66
        /*
67
         * IE version detection approach by James Padolsey, with modifications -- from
68
         * http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
69
         */
70
        var ieVersion = 4,
71
            div = doc.createElement('div'),
72
            all = div.getElementsByTagName('i'),
73
            shape;
74
        while (
75
            div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->',
76
            all[0]
77
        ) {}
78
        PIE.ieVersion = ieVersion;
79
80
        // Detect IE6
81
        if( ieVersion === 6 ) {
82
            // IE6 can't access properties with leading dash, but can without it.
83
            PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' );
84
        }
85
86
        PIE.ieDocMode = doc.documentMode || PIE.ieVersion;
87
88
        // Detect VML support (a small number of IE installs don't have a working VML engine)
89
        div.innerHTML = '<v:shape adj="1"/>';
90
        shape = div.firstChild;
91
        shape.style['behavior'] = 'url(#default#VML)';
92
        PIE.supportsVML = (typeof shape['adj'] === "object");
93
    }());
94
/**
95
 * Utility functions
96
 */
97
(function() {
98
    var vmlCreatorDoc,
99
        idNum = 0,
100
        imageSizes = {};
101
102
103
    PIE.Util = {
104
105
        /**
106
         * To create a VML element, it must be created by a Document which has the VML
107
         * namespace set. Unfortunately, if you try to add the namespace programatically
108
         * into the main document, you will get an "Unspecified error" when trying to
109
         * access document.namespaces before the document is finished loading. To get
110
         * around this, we create a DocumentFragment, which in IE land is apparently a
111
         * full-fledged Document. It allows adding namespaces immediately, so we add the
112
         * namespace there and then have it create the VML element.
113
         * @param {string} tag The tag name for the VML element
114
         * @return {Element} The new VML element
115
         */
116
        createVmlElement: function( tag ) {
117
            var vmlPrefix = 'css3vml';
118
            if( !vmlCreatorDoc ) {
119
                vmlCreatorDoc = doc.createDocumentFragment();
120
                vmlCreatorDoc.namespaces.add( vmlPrefix, 'urn:schemas-microsoft-com:vml' );
121
            }
122
            return vmlCreatorDoc.createElement( vmlPrefix + ':' + tag );
123
        },
124
125
126
        /**
127
         * Generate and return a unique ID for a given object. The generated ID is stored
128
         * as a property of the object for future reuse.
129
         * @param {Object} obj
130
         */
131
        getUID: function( obj ) {
132
            return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + ++idNum );
133
        },
134
135
136
        /**
137
         * Simple utility for merging objects
138
         * @param {Object} obj1 The main object into which all others will be merged
139
         * @param {...Object} var_args Other objects which will be merged into the first, in order
140
         */
141
        merge: function( obj1 ) {
142
            var i, len, p, objN, args = arguments;
143
            for( i = 1, len = args.length; i < len; i++ ) {
144
                objN = args[i];
145
                for( p in objN ) {
146
                    if( objN.hasOwnProperty( p ) ) {
147
                        obj1[ p ] = objN[ p ];
148
                    }
149
                }
150
            }
151
            return obj1;
152
        },
153
154
155
        /**
156
         * Execute a callback function, passing it the dimensions of a given image once
157
         * they are known.
158
         * @param {string} src The source URL of the image
159
         * @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known
160
         * @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function
161
         */
162
        withImageSize: function( src, func, ctx ) {
163
            var size = imageSizes[ src ], img, queue;
164
            if( size ) {
165
                // If we have a queue, add to it
166
                if( Object.prototype.toString.call( size ) === '[object Array]' ) {
167
                    size.push( [ func, ctx ] );
168
                }
169
                // Already have the size cached, call func right away
170
                else {
171
                    func.call( ctx, size );
172
                }
173
            } else {
174
                queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue
175
                img = new Image();
176
                img.onload = function() {
177
                    size = imageSizes[ src ] = { w: img.width, h: img.height };
178
                    for( var i = 0, len = queue.length; i < len; i++ ) {
179
                        queue[ i ][ 0 ].call( queue[ i ][ 1 ], size );
180
                    }
181
                    img.onload = null;
182
                };
183
                img.src = src;
184
            }
185
        }
186
    };
187
})();/**
188
 * Utility functions for handling gradients
189
 */
190
PIE.GradientUtil = {
191
192
    getGradientMetrics: function( el, width, height, gradientInfo ) {
193
        var angle = gradientInfo.angle,
194
            startPos = gradientInfo.gradientStart,
195
            startX, startY,
196
            endX, endY,
197
            startCornerX, startCornerY,
198
            endCornerX, endCornerY,
199
            deltaX, deltaY,
200
            p, UNDEF;
201
202
        // Find the "start" and "end" corners; these are the corners furthest along the gradient line.
203
        // This is used below to find the start/end positions of the CSS3 gradient-line, and also in finding
204
        // the total length of the VML rendered gradient-line corner to corner.
205
        function findCorners() {
206
            startCornerX = ( angle >= 90 && angle < 270 ) ? width : 0;
207
            startCornerY = angle < 180 ? height : 0;
208
            endCornerX = width - startCornerX;
209
            endCornerY = height - startCornerY;
210
        }
211
212
        // Normalize the angle to a value between [0, 360)
213
        function normalizeAngle() {
214
            while( angle < 0 ) {
215
                angle += 360;
216
            }
217
            angle = angle % 360;
218
        }
219
220
        // Find the start and end points of the gradient
221
        if( startPos ) {
222
            startPos = startPos.coords( el, width, height );
223
            startX = startPos.x;
224
            startY = startPos.y;
225
        }
226
        if( angle ) {
227
            angle = angle.degrees();
228
229
            normalizeAngle();
230
            findCorners();
231
232
            // If no start position was specified, then choose a corner as the starting point.
233
            if( !startPos ) {
234
                startX = startCornerX;
235
                startY = startCornerY;
236
            }
237
238
            // Find the end position by extending a perpendicular line from the gradient-line which
239
            // intersects the corner opposite from the starting corner.
240
            p = PIE.GradientUtil.perpendicularIntersect( startX, startY, angle, endCornerX, endCornerY );
241
            endX = p[0];
242
            endY = p[1];
243
        }
244
        else if( startPos ) {
245
            // Start position but no angle specified: find the end point by rotating 180deg around the center
246
            endX = width - startX;
247
            endY = height - startY;
248
        }
249
        else {
250
            // Neither position nor angle specified; create vertical gradient from top to bottom
251
            startX = startY = endX = 0;
252
            endY = height;
253
        }
254
        deltaX = endX - startX;
255
        deltaY = endY - startY;
256
257
        if( angle === UNDEF ) {
258
            // Get the angle based on the change in x/y from start to end point. Checks first for horizontal
259
            // or vertical angles so they get exact whole numbers rather than what atan2 gives.
260
            angle = ( !deltaX ? ( deltaY < 0 ? 90 : 270 ) :
261
                        ( !deltaY ? ( deltaX < 0 ? 180 : 0 ) :
262
                            -Math.atan2( deltaY, deltaX ) / Math.PI * 180
263
                        )
264
                    );
265
            normalizeAngle();
266
            findCorners();
267
        }
268
269
        return {
270
            angle: angle,
271
            startX: startX,
272
            startY: startY,
273
            endX: endX,
274
            endY: endY,
275
            startCornerX: startCornerX,
276
            startCornerY: startCornerY,
277
            endCornerX: endCornerX,
278
            endCornerY: endCornerY,
279
            deltaX: deltaX,
280
            deltaY: deltaY,
281
            lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY )
282
        }
283
    },
284
285
    /**
286
     * Find the point along a given line (defined by a starting point and an angle), at which
287
     * that line is intersected by a perpendicular line extending through another point.
288
     * @param x1 - x coord of the starting point
289
     * @param y1 - y coord of the starting point
290
     * @param angle - angle of the line extending from the starting point (in degrees)
291
     * @param x2 - x coord of point along the perpendicular line
292
     * @param y2 - y coord of point along the perpendicular line
293
     * @return [ x, y ]
294
     */
295
    perpendicularIntersect: function( x1, y1, angle, x2, y2 ) {
296
        // Handle straight vertical and horizontal angles, for performance and to avoid
297
        // divide-by-zero errors.
298
        if( angle === 0 || angle === 180 ) {
299
            return [ x2, y1 ];
300
        }
301
        else if( angle === 90 || angle === 270 ) {
302
            return [ x1, y2 ];
303
        }
304
        else {
305
            // General approach: determine the Ax+By=C formula for each line (the slope of the second
306
            // line is the negative inverse of the first) and then solve for where both formulas have
307
            // the same x/y values.
308
            var a1 = Math.tan( -angle * Math.PI / 180 ),
309
                c1 = a1 * x1 - y1,
310
                a2 = -1 / a1,
311
                c2 = a2 * x2 - y2,
312
                d = a2 - a1,
313
                endX = ( c2 - c1 ) / d,
314
                endY = ( a1 * c2 - a2 * c1 ) / d;
315
            return [ endX, endY ];
316
        }
317
    },
318
319
    /**
320
     * Find the distance between two points
321
     * @param {Number} p1x
322
     * @param {Number} p1y
323
     * @param {Number} p2x
324
     * @param {Number} p2y
325
     * @return {Number} the distance
326
     */
327
    distance: function( p1x, p1y, p2x, p2y ) {
328
        var dx = p2x - p1x,
329
            dy = p2y - p1y;
330
        return Math.abs(
331
            dx === 0 ? dy :
332
            dy === 0 ? dx :
333
            Math.sqrt( dx * dx + dy * dy )
334
        );
335
    }
336
337
};/**
338
 * 
339
 */
340
PIE.Observable = function() {
341
    /**
342
     * List of registered observer functions
343
     */
344
    this.observers = [];
345
346
    /**
347
     * Hash of function ids to their position in the observers list, for fast lookup
348
     */
349
    this.indexes = {};
350
};
351
PIE.Observable.prototype = {
352
353
    observe: function( fn ) {
354
        var id = PIE.Util.getUID( fn ),
355
            indexes = this.indexes,
356
            observers = this.observers;
357
        if( !( id in indexes ) ) {
358
            indexes[ id ] = observers.length;
359
            observers.push( fn );
360
        }
361
    },
362
363
    unobserve: function( fn ) {
364
        var id = PIE.Util.getUID( fn ),
365
            indexes = this.indexes;
366
        if( id && id in indexes ) {
367
            delete this.observers[ indexes[ id ] ];
368
            delete indexes[ id ];
369
        }
370
    },
371
372
    fire: function() {
373
        var o = this.observers,
374
            i = o.length;
375
        while( i-- ) {
376
            o[ i ] && o[ i ]();
377
        }
378
    }
379
380
};/*
381
 * Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not
382
 * always firing the onmove and onresize events when elements are moved or resized. We check a few
383
 * times every second to make sure the elements have the correct position and size. See Element.js
384
 * which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9
385
 * and false elsewhere.
386
 */
387
388
PIE.Heartbeat = new PIE.Observable();
389
PIE.Heartbeat.run = function() {
390
    var me = this,
391
        interval;
392
    if( !me.running ) {
393
        interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250;
394
        (function beat() {
395
            me.fire();
396
            setTimeout(beat, interval);
397
        })();
398
        me.running = 1;
399
    }
400
};
401
/**
402
 * Create an observable listener for the onunload event
403
 */
404
(function() {
405
    PIE.OnUnload = new PIE.Observable();
406
407
    function handleUnload() {
408
        PIE.OnUnload.fire();
409
        window.detachEvent( 'onunload', handleUnload );
410
        window[ 'PIE' ] = null;
411
    }
412
413
    window.attachEvent( 'onunload', handleUnload );
414
415
    /**
416
     * Attach an event which automatically gets detached onunload
417
     */
418
    PIE.OnUnload.attachManagedEvent = function( target, name, handler ) {
419
        target.attachEvent( name, handler );
420
        this.observe( function() {
421
            target.detachEvent( name, handler );
422
        } );
423
    };
424
})()/**
425
 * Create a single observable listener for window resize events.
426
 */
427
PIE.OnResize = new PIE.Observable();
428
429
PIE.OnUnload.attachManagedEvent( window, 'onresize', function() { PIE.OnResize.fire(); } );
430
/**
431
 * Create a single observable listener for scroll events. Used for lazy loading based
432
 * on the viewport, and for fixed position backgrounds.
433
 */
434
(function() {
435
    PIE.OnScroll = new PIE.Observable();
436
437
    function scrolled() {
438
        PIE.OnScroll.fire();
439
    }
440
441
    PIE.OnUnload.attachManagedEvent( window, 'onscroll', scrolled );
442
443
    PIE.OnResize.observe( scrolled );
444
})();
445
/**
446
 * Listen for printing events, destroy all active PIE instances when printing, and
447
 * restore them afterward.
448
 */
449
(function() {
450
451
    var elements;
452
453
    function beforePrint() {
454
        elements = PIE.Element.destroyAll();
455
    }
456
457
    function afterPrint() {
458
        if( elements ) {
459
            for( var i = 0, len = elements.length; i < len; i++ ) {
460
                PIE[ 'attach' ]( elements[i] );
461
            }
462
            elements = 0;
463
        }
464
    }
465
466
    if( PIE.ieDocMode < 9 ) {
467
        PIE.OnUnload.attachManagedEvent( window, 'onbeforeprint', beforePrint );
468
        PIE.OnUnload.attachManagedEvent( window, 'onafterprint', afterPrint );
469
    }
470
471
})();/**
472
 * Create a single observable listener for document mouseup events.
473
 */
474
PIE.OnMouseup = new PIE.Observable();
475
476
PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } );
477
/**
478
 * Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique
479
 * value is returned from PIE.getLength() - always use that instead of instantiating directly.
480
 * @constructor
481
 * @param {string} val The CSS string representing the length. It is assumed that this will already have
482
 *                 been validated as a valid length or percentage syntax.
483
 */
484
PIE.Length = (function() {
485
    var lengthCalcEl = doc.createElement( 'length-calc' ),
486
        parent = doc.body || doc.documentElement,
487
        s = lengthCalcEl.style,
488
        conversions = {},
489
        units = [ 'mm', 'cm', 'in', 'pt', 'pc' ],
490
        i = units.length,
491
        instances = {};
492
493
    s.position = 'absolute';
494
    s.top = s.left = '-9999px';
495
496
    parent.appendChild( lengthCalcEl );
497
    while( i-- ) {
498
        s.width = '100' + units[i];
499
        conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100;
500
    }
501
    parent.removeChild( lengthCalcEl );
502
503
    // All calcs from here on will use 1em
504
    s.width = '1em';
505
506
507
    function Length( val ) {
508
        this.val = val;
509
    }
510
    Length.prototype = {
511
        /**
512
         * Regular expression for matching the length unit
513
         * @private
514
         */
515
        unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/,
516
517
        /**
518
         * Get the numeric value of the length
519
         * @return {number} The value
520
         */
521
        getNumber: function() {
522
            var num = this.num,
523
                UNDEF;
524
            if( num === UNDEF ) {
525
                num = this.num = parseFloat( this.val );
526
            }
527
            return num;
528
        },
529
530
        /**
531
         * Get the unit of the length
532
         * @return {string} The unit
533
         */
534
        getUnit: function() {
535
            var unit = this.unit,
536
                m;
537
            if( !unit ) {
538
                m = this.val.match( this.unitRE );
539
                unit = this.unit = ( m && m[0] ) || 'px';
540
            }
541
            return unit;
542
        },
543
544
        /**
545
         * Determine whether this is a percentage length value
546
         * @return {boolean}
547
         */
548
        isPercentage: function() {
549
            return this.getUnit() === '%';
550
        },
551
552
        /**
553
         * Resolve this length into a number of pixels.
554
         * @param {Element} el - the context element, used to resolve font-relative values
555
         * @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a
556
         *                  function which will be called to return the number.
557
         */
558
        pixels: function( el, pct100 ) {
559
            var num = this.getNumber(),
560
                unit = this.getUnit();
561
            switch( unit ) {
562
                case "px":
563
                    return num;
564
                case "%":
565
                    return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100;
566
                case "em":
567
                    return num * this.getEmPixels( el );
568
                case "ex":
569
                    return num * this.getEmPixels( el ) / 2;
570
                default:
571
                    return num * conversions[ unit ];
572
            }
573
        },
574
575
        /**
576
         * The em and ex units are relative to the font-size of the current element,
577
         * however if the font-size is set using non-pixel units then we get that value
578
         * rather than a pixel conversion. To get around this, we keep a floating element
579
         * with width:1em which we insert into the target element and then read its offsetWidth.
580
         * For elements that won't accept a child we insert into the parent node and perform
581
         * additional calculation. If the font-size *is* specified in pixels, then we use that
582
         * directly to avoid the expensive DOM manipulation.
583
         * @param {Element} el
584
         * @return {number}
585
         */
586
        getEmPixels: function( el ) {
587
            var fs = el.currentStyle.fontSize,
588
                px, parent, me;
589
590
            if( fs.indexOf( 'px' ) > 0 ) {
591
                return parseFloat( fs );
592
            }
593
            else if( el.tagName in PIE.childlessElements ) {
594
                me = this;
595
                parent = el.parentNode;
596
                return PIE.getLength( fs ).pixels( parent, function() {
597
                    return me.getEmPixels( parent );
598
                } );
599
            }
600
            else {
601
                el.appendChild( lengthCalcEl );
602
                px = lengthCalcEl.offsetWidth;
603
                if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is
604
                    el.removeChild( lengthCalcEl );
605
                }
606
                return px;
607
            }
608
        }
609
    };
610
611
612
    /**
613
     * Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value.
614
     * @param {string} val The CSS string representing the length. It is assumed that this will already have
615
     *                 been validated as a valid length or percentage syntax.
616
     */
617
    PIE.getLength = function( val ) {
618
        return instances[ val ] || ( instances[ val ] = new Length( val ) );
619
    };
620
621
    return Length;
622
})();
623
/**
624
 * Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages.
625
 * @constructor
626
 * @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value.
627
 */
628
PIE.BgPosition = (function() {
629
630
    var length_fifty = PIE.getLength( '50%' ),
631
        vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 },
632
        horiz_idents = { 'left': 1, 'center': 1, 'right': 1 };
633
634
635
    function BgPosition( tokens ) {
636
        this.tokens = tokens;
637
    }
638
    BgPosition.prototype = {
639
        /**
640
         * Normalize the values into the form:
641
         * [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ]
642
         * where: xOffsetSide is either 'left' or 'right',
643
         *        yOffsetSide is either 'top' or 'bottom',
644
         *        and x/yOffsetLength are both PIE.Length objects.
645
         * @return {Array}
646
         */
647
        getValues: function() {
648
            if( !this._values ) {
649
                var tokens = this.tokens,
650
                    len = tokens.length,
651
                    Tokenizer = PIE.Tokenizer,
652
                    identType = Tokenizer.Type,
653
                    length_zero = PIE.getLength( '0' ),
654
                    type_ident = identType.IDENT,
655
                    type_length = identType.LENGTH,
656
                    type_percent = identType.PERCENT,
657
                    type, value,
658
                    vals = [ 'left', length_zero, 'top', length_zero ];
659
660
                // If only one value, the second is assumed to be 'center'
661
                if( len === 1 ) {
662
                    tokens.push( new Tokenizer.Token( type_ident, 'center' ) );
663
                    len++;
664
                }
665
666
                // Two values - CSS2
667
                if( len === 2 ) {
668
                    // If both idents, they can appear in either order, so switch them if needed
669
                    if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) &&
670
                        tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) {
671
                        tokens.push( tokens.shift() );
672
                    }
673
                    if( tokens[0].tokenType & type_ident ) {
674
                        if( tokens[0].tokenValue === 'center' ) {
675
                            vals[1] = length_fifty;
676
                        } else {
677
                            vals[0] = tokens[0].tokenValue;
678
                        }
679
                    }
680
                    else if( tokens[0].isLengthOrPercent() ) {
681
                        vals[1] = PIE.getLength( tokens[0].tokenValue );
682
                    }
683
                    if( tokens[1].tokenType & type_ident ) {
684
                        if( tokens[1].tokenValue === 'center' ) {
685
                            vals[3] = length_fifty;
686
                        } else {
687
                            vals[2] = tokens[1].tokenValue;
688
                        }
689
                    }
690
                    else if( tokens[1].isLengthOrPercent() ) {
691
                        vals[3] = PIE.getLength( tokens[1].tokenValue );
692
                    }
693
                }
694
695
                // Three or four values - CSS3
696
                else {
697
                    // TODO
698
                }
699
700
                this._values = vals;
701
            }
702
            return this._values;
703
        },
704
705
        /**
706
         * Find the coordinates of the background image from the upper-left corner of the background area.
707
         * Note that these coordinate values are not rounded.
708
         * @param {Element} el
709
         * @param {number} width - the width for percentages (background area width minus image width)
710
         * @param {number} height - the height for percentages (background area height minus image height)
711
         * @return {Object} { x: Number, y: Number }
712
         */
713
        coords: function( el, width, height ) {
714
            var vals = this.getValues(),
715
                pxX = vals[1].pixels( el, width ),
716
                pxY = vals[3].pixels( el, height );
717
718
            return {
719
                x: vals[0] === 'right' ? width - pxX : pxX,
720
                y: vals[2] === 'bottom' ? height - pxY : pxY
721
            };
722
        }
723
    };
724
725
    return BgPosition;
726
})();
727
/**
728
 * Wrapper for a CSS3 background-size value.
729
 * @constructor
730
 * @param {String|PIE.Length} w The width parameter
731
 * @param {String|PIE.Length} h The height parameter, if any
732
 */
733
PIE.BgSize = (function() {
734
735
    var CONTAIN = 'contain',
736
        COVER = 'cover',
737
        AUTO = 'auto';
738
739
740
    function BgSize( w, h ) {
741
        this.w = w;
742
        this.h = h;
743
    }
744
    BgSize.prototype = {
745
746
        pixels: function( el, areaW, areaH, imgW, imgH ) {
747
            var me = this,
748
                w = me.w,
749
                h = me.h,
750
                areaRatio = areaW / areaH,
751
                imgRatio = imgW / imgH;
752
753
            if ( w === CONTAIN ) {
754
                w = imgRatio > areaRatio ? areaW : areaH * imgRatio;
755
                h = imgRatio > areaRatio ? areaW / imgRatio : areaH;
756
            }
757
            else if ( w === COVER ) {
758
                w = imgRatio < areaRatio ? areaW : areaH * imgRatio;
759
                h = imgRatio < areaRatio ? areaW / imgRatio : areaH;
760
            }
761
            else if ( w === AUTO ) {
762
                h = ( h === AUTO ? imgH : h.pixels( el, areaH ) );
763
                w = h * imgRatio;
764
            }
765
            else {
766
                w = w.pixels( el, areaW );
767
                h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) );
768
            }
769
770
            return { w: w, h: h };
771
        }
772
773
    };
774
775
    BgSize.DEFAULT = new BgSize( AUTO, AUTO );
776
777
    return BgSize;
778
})();
779
/**
780
 * Wrapper for angle values; handles conversion to degrees from all allowed angle units
781
 * @constructor
782
 * @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated.
783
 */
784
PIE.Angle = (function() {
785
    function Angle( val ) {
786
        this.val = val;
787
    }
788
    Angle.prototype = {
789
        unitRE: /[a-z]+$/i,
790
791
        /**
792
         * @return {string} The unit of the angle value
793
         */
794
        getUnit: function() {
795
            return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() );
796
        },
797
798
        /**
799
         * Get the numeric value of the angle in degrees.
800
         * @return {number} The degrees value
801
         */
802
        degrees: function() {
803
            var deg = this._deg, u, n;
804
            if( deg === undefined ) {
805
                u = this.getUnit();
806
                n = parseFloat( this.val, 10 );
807
                deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 );
808
            }
809
            return deg;
810
        }
811
    };
812
813
    return Angle;
814
})();/**
815
 * Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique
816
 * value is returned from PIE.getColor() - always use that instead of instantiating directly.
817
 * @constructor
818
 * @param {string} val The raw CSS string value for the color
819
 */
820
PIE.Color = (function() {
821
    var instances = {};
822
823
    function Color( val ) {
824
        this.val = val;
825
    }
826
827
    /**
828
     * Regular expression for matching rgba colors and extracting their components
829
     * @type {RegExp}
830
     */
831
    Color.rgbaRE = /\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d+|\d*\.\d+)\s*\)\s*/;
832
833
    Color.names = {
834
        "aliceblue":"F0F8FF", "antiquewhite":"FAEBD7", "aqua":"0FF",
835
        "aquamarine":"7FFFD4", "azure":"F0FFFF", "beige":"F5F5DC",
836
        "bisque":"FFE4C4", "black":"000", "blanchedalmond":"FFEBCD",
837
        "blue":"00F", "blueviolet":"8A2BE2", "brown":"A52A2A",
838
        "burlywood":"DEB887", "cadetblue":"5F9EA0", "chartreuse":"7FFF00",
839
        "chocolate":"D2691E", "coral":"FF7F50", "cornflowerblue":"6495ED",
840
        "cornsilk":"FFF8DC", "crimson":"DC143C", "cyan":"0FF",
841
        "darkblue":"00008B", "darkcyan":"008B8B", "darkgoldenrod":"B8860B",
842
        "darkgray":"A9A9A9", "darkgreen":"006400", "darkkhaki":"BDB76B",
843
        "darkmagenta":"8B008B", "darkolivegreen":"556B2F", "darkorange":"FF8C00",
844
        "darkorchid":"9932CC", "darkred":"8B0000", "darksalmon":"E9967A",
845
        "darkseagreen":"8FBC8F", "darkslateblue":"483D8B", "darkslategray":"2F4F4F",
846
        "darkturquoise":"00CED1", "darkviolet":"9400D3", "deeppink":"FF1493",
847
        "deepskyblue":"00BFFF", "dimgray":"696969", "dodgerblue":"1E90FF",
848
        "firebrick":"B22222", "floralwhite":"FFFAF0", "forestgreen":"228B22",
849
        "fuchsia":"F0F", "gainsboro":"DCDCDC", "ghostwhite":"F8F8FF",
850
        "gold":"FFD700", "goldenrod":"DAA520", "gray":"808080",
851
        "green":"008000", "greenyellow":"ADFF2F", "honeydew":"F0FFF0",
852
        "hotpink":"FF69B4", "indianred":"CD5C5C", "indigo":"4B0082",
853
        "ivory":"FFFFF0", "khaki":"F0E68C", "lavender":"E6E6FA",
854
        "lavenderblush":"FFF0F5", "lawngreen":"7CFC00", "lemonchiffon":"FFFACD",
855
        "lightblue":"ADD8E6", "lightcoral":"F08080", "lightcyan":"E0FFFF",
856
        "lightgoldenrodyellow":"FAFAD2", "lightgreen":"90EE90", "lightgrey":"D3D3D3",
857
        "lightpink":"FFB6C1", "lightsalmon":"FFA07A", "lightseagreen":"20B2AA",
858
        "lightskyblue":"87CEFA", "lightslategray":"789", "lightsteelblue":"B0C4DE",
859
        "lightyellow":"FFFFE0", "lime":"0F0", "limegreen":"32CD32",
860
        "linen":"FAF0E6", "magenta":"F0F", "maroon":"800000",
861
        "mediumauqamarine":"66CDAA", "mediumblue":"0000CD", "mediumorchid":"BA55D3",
862
        "mediumpurple":"9370D8", "mediumseagreen":"3CB371", "mediumslateblue":"7B68EE",
863
        "mediumspringgreen":"00FA9A", "mediumturquoise":"48D1CC", "mediumvioletred":"C71585",
864
        "midnightblue":"191970", "mintcream":"F5FFFA", "mistyrose":"FFE4E1",
865
        "moccasin":"FFE4B5", "navajowhite":"FFDEAD", "navy":"000080",
866
        "oldlace":"FDF5E6", "olive":"808000", "olivedrab":"688E23",
867
        "orange":"FFA500", "orangered":"FF4500", "orchid":"DA70D6",
868
        "palegoldenrod":"EEE8AA", "palegreen":"98FB98", "paleturquoise":"AFEEEE",
869
        "palevioletred":"D87093", "papayawhip":"FFEFD5", "peachpuff":"FFDAB9",
870
        "peru":"CD853F", "pink":"FFC0CB", "plum":"DDA0DD",
871
        "powderblue":"B0E0E6", "purple":"800080", "red":"F00",
872
        "rosybrown":"BC8F8F", "royalblue":"4169E1", "saddlebrown":"8B4513",
873
        "salmon":"FA8072", "sandybrown":"F4A460", "seagreen":"2E8B57",
874
        "seashell":"FFF5EE", "sienna":"A0522D", "silver":"C0C0C0",
875
        "skyblue":"87CEEB", "slateblue":"6A5ACD", "slategray":"708090",
876
        "snow":"FFFAFA", "springgreen":"00FF7F", "steelblue":"4682B4",
877
        "tan":"D2B48C", "teal":"008080", "thistle":"D8BFD8",
878
        "tomato":"FF6347", "turquoise":"40E0D0", "violet":"EE82EE",
879
        "wheat":"F5DEB3", "white":"FFF", "whitesmoke":"F5F5F5",
880
        "yellow":"FF0", "yellowgreen":"9ACD32"
881
    };
882
883
    Color.prototype = {
884
        /**
885
         * @private
886
         */
887
        parse: function() {
888
            if( !this._color ) {
889
                var me = this,
890
                    v = me.val,
891
                    vLower,
892
                    m = v.match( Color.rgbaRE );
893
                if( m ) {
894
                    me._color = 'rgb(' + m[1] + ',' + m[2] + ',' + m[3] + ')';
895
                    me._alpha = parseFloat( m[4] );
896
                }
897
                else {
898
                    if( ( vLower = v.toLowerCase() ) in Color.names ) {
899
                        v = '#' + Color.names[vLower];
900
                    }
901
                    me._color = v;
902
                    me._alpha = ( v === 'transparent' ? 0 : 1 );
903
                }
904
            }
905
        },
906
907
        /**
908
         * Retrieve the value of the color in a format usable by IE natively. This will be the same as
909
         * the raw input value, except for rgba values which will be converted to an rgb value.
910
         * @param {Element} el The context element, used to get 'currentColor' keyword value.
911
         * @return {string} Color value
912
         */
913
        colorValue: function( el ) {
914
            this.parse();
915
            return this._color === 'currentColor' ? el.currentStyle.color : this._color;
916
        },
917
918
        /**
919
         * Retrieve the alpha value of the color. Will be 1 for all values except for rgba values
920
         * with an alpha component.
921
         * @return {number} The alpha value, from 0 to 1.
922
         */
923
        alpha: function() {
924
            this.parse();
925
            return this._alpha;
926
        }
927
    };
928
929
930
    /**
931
     * Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value.
932
     * @param {string} val The CSS string representing the color. It is assumed that this will already have
933
     *                 been validated as a valid color syntax.
934
     */
935
    PIE.getColor = function(val) {
936
        return instances[ val ] || ( instances[ val ] = new Color( val ) );
937
    };
938
939
    return Color;
940
})();/**
941
 * A tokenizer for CSS value strings.
942
 * @constructor
943
 * @param {string} css The CSS value string
944
 */
945
PIE.Tokenizer = (function() {
946
    function Tokenizer( css ) {
947
        this.css = css;
948
        this.ch = 0;
949
        this.tokens = [];
950
        this.tokenIndex = 0;
951
    }
952
953
    /**
954
     * Enumeration of token type constants.
955
     * @enum {number}
956
     */
957
    var Type = Tokenizer.Type = {
958
        ANGLE: 1,
959
        CHARACTER: 2,
960
        COLOR: 4,
961
        DIMEN: 8,
962
        FUNCTION: 16,
963
        IDENT: 32,
964
        LENGTH: 64,
965
        NUMBER: 128,
966
        OPERATOR: 256,
967
        PERCENT: 512,
968
        STRING: 1024,
969
        URL: 2048
970
    };
971
972
    /**
973
     * A single token
974
     * @constructor
975
     * @param {number} type The type of the token - see PIE.Tokenizer.Type
976
     * @param {string} value The value of the token
977
     */
978
    Tokenizer.Token = function( type, value ) {
979
        this.tokenType = type;
980
        this.tokenValue = value;
981
    };
982
    Tokenizer.Token.prototype = {
983
        isLength: function() {
984
            return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' );
985
        },
986
        isLengthOrPercent: function() {
987
            return this.isLength() || this.tokenType & Type.PERCENT;
988
        }
989
    };
990
991
    Tokenizer.prototype = {
992
        whitespace: /\s/,
993
        number: /^[\+\-]?(\d*\.)?\d+/,
994
        url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i,
995
        ident: /^\-?[_a-z][\w-]*/i,
996
        string: /^("([^"]*)"|'([^']*)')/,
997
        operator: /^[\/,]/,
998
        hash: /^#[\w]+/,
999
        hashColor: /^#([\da-f]{6}|[\da-f]{3})/i,
1000
1001
        unitTypes: {
1002
            'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH,
1003
            'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH,
1004
            'pt': Type.LENGTH, 'pc': Type.LENGTH,
1005
            'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE
1006
        },
1007
1008
        colorFunctions: {
1009
            'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1
1010
        },
1011
1012
1013
        /**
1014
         * Advance to and return the next token in the CSS string. If the end of the CSS string has
1015
         * been reached, null will be returned.
1016
         * @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev().
1017
         * @return {PIE.Tokenizer.Token}
1018
         */
1019
        next: function( forget ) {
1020
            var css, ch, firstChar, match, val,
1021
                me = this;
1022
1023
            function newToken( type, value ) {
1024
                var tok = new Tokenizer.Token( type, value );
1025
                if( !forget ) {
1026
                    me.tokens.push( tok );
1027
                    me.tokenIndex++;
1028
                }
1029
                return tok;
1030
            }
1031
            function failure() {
1032
                me.tokenIndex++;
1033
                return null;
1034
            }
1035
1036
            // In case we previously backed up, return the stored token in the next slot
1037
            if( this.tokenIndex < this.tokens.length ) {
1038
                return this.tokens[ this.tokenIndex++ ];
1039
            }
1040
1041
            // Move past leading whitespace characters
1042
            while( this.whitespace.test( this.css.charAt( this.ch ) ) ) {
1043
                this.ch++;
1044
            }
1045
            if( this.ch >= this.css.length ) {
1046
                return failure();
1047
            }
1048
1049
            ch = this.ch;
1050
            css = this.css.substring( this.ch );
1051
            firstChar = css.charAt( 0 );
1052
            switch( firstChar ) {
1053
                case '#':
1054
                    if( match = css.match( this.hashColor ) ) {
1055
                        this.ch += match[0].length;
1056
                        return newToken( Type.COLOR, match[0] );
1057
                    }
1058
                    break;
1059
1060
                case '"':
1061
                case "'":
1062
                    if( match = css.match( this.string ) ) {
1063
                        this.ch += match[0].length;
1064
                        return newToken( Type.STRING, match[2] || match[3] || '' );
1065
                    }
1066
                    break;
1067
1068
                case "/":
1069
                case ",":
1070
                    this.ch++;
1071
                    return newToken( Type.OPERATOR, firstChar );
1072
1073
                case 'u':
1074
                    if( match = css.match( this.url ) ) {
1075
                        this.ch += match[0].length;
1076
                        return newToken( Type.URL, match[2] || match[3] || match[4] || '' );
1077
                    }
1078
            }
1079
1080
            // Numbers and values starting with numbers
1081
            if( match = css.match( this.number ) ) {
1082
                val = match[0];
1083
                this.ch += val.length;
1084
1085
                // Check if it is followed by a unit
1086
                if( css.charAt( val.length ) === '%' ) {
1087
                    this.ch++;
1088
                    return newToken( Type.PERCENT, val + '%' );
1089
                }
1090
                if( match = css.substring( val.length ).match( this.ident ) ) {
1091
                    val += match[0];
1092
                    this.ch += match[0].length;
1093
                    return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val );
1094
                }
1095
1096
                // Plain ol' number
1097
                return newToken( Type.NUMBER, val );
1098
            }
1099
1100
            // Identifiers
1101
            if( match = css.match( this.ident ) ) {
1102
                val = match[0];
1103
                this.ch += val.length;
1104
1105
                // Named colors
1106
                if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) {
1107
                    return newToken( Type.COLOR, val );
1108
                }
1109
1110
                // Functions
1111
                if( css.charAt( val.length ) === '(' ) {
1112
                    this.ch++;
1113
1114
                    // Color values in function format: rgb, rgba, hsl, hsla
1115
                    if( val.toLowerCase() in this.colorFunctions ) {
1116
                        function isNum( tok ) {
1117
                            return tok && tok.tokenType & Type.NUMBER;
1118
                        }
1119
                        function isNumOrPct( tok ) {
1120
                            return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) );
1121
                        }
1122
                        function isValue( tok, val ) {
1123
                            return tok && tok.tokenValue === val;
1124
                        }
1125
                        function next() {
1126
                            return me.next( 1 );
1127
                        }
1128
1129
                        if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) &&
1130
                            isValue( next(), ',' ) &&
1131
                            isNumOrPct( next() ) &&
1132
                            isValue( next(), ',' ) &&
1133
                            isNumOrPct( next() ) &&
1134
                            ( val === 'rgb' || val === 'hsa' || (
1135
                                isValue( next(), ',' ) &&
1136
                                isNum( next() )
1137
                            ) ) &&
1138
                            isValue( next(), ')' ) ) {
1139
                            return newToken( Type.COLOR, this.css.substring( ch, this.ch ) );
1140
                        }
1141
                        return failure();
1142
                    }
1143
1144
                    return newToken( Type.FUNCTION, val );
1145
                }
1146
1147
                // Other identifier
1148
                return newToken( Type.IDENT, val );
1149
            }
1150
1151
            // Standalone character
1152
            this.ch++;
1153
            return newToken( Type.CHARACTER, firstChar );
1154
        },
1155
1156
        /**
1157
         * Determine whether there is another token
1158
         * @return {boolean}
1159
         */
1160
        hasNext: function() {
1161
            var next = this.next();
1162
            this.prev();
1163
            return !!next;
1164
        },
1165
1166
        /**
1167
         * Back up and return the previous token
1168
         * @return {PIE.Tokenizer.Token}
1169
         */
1170
        prev: function() {
1171
            return this.tokens[ this.tokenIndex-- - 2 ];
1172
        },
1173
1174
        /**
1175
         * Retrieve all the tokens in the CSS string
1176
         * @return {Array.<PIE.Tokenizer.Token>}
1177
         */
1178
        all: function() {
1179
            while( this.next() ) {}
1180
            return this.tokens;
1181
        },
1182
1183
        /**
1184
         * Return a list of tokens from the current position until the given function returns
1185
         * true. The final token will not be included in the list.
1186
         * @param {function():boolean} func - test function
1187
         * @param {boolean} require - if true, then if the end of the CSS string is reached
1188
         *        before the test function returns true, null will be returned instead of the
1189
         *        tokens that have been found so far.
1190
         * @return {Array.<PIE.Tokenizer.Token>}
1191
         */
1192
        until: function( func, require ) {
1193
            var list = [], t, hit;
1194
            while( t = this.next() ) {
1195
                if( func( t ) ) {
1196
                    hit = true;
1197
                    this.prev();
1198
                    break;
1199
                }
1200
                list.push( t );
1201
            }
1202
            return require && !hit ? null : list;
1203
        }
1204
    };
1205
1206
    return Tokenizer;
1207
})();/**
1208
 * Handles calculating, caching, and detecting changes to size and position of the element.
1209
 * @constructor
1210
 * @param {Element} el the target element
1211
 */
1212
PIE.BoundsInfo = function( el ) {
1213
    this.targetElement = el;
1214
};
1215
PIE.BoundsInfo.prototype = {
1216
1217
    _locked: 0,
1218
1219
    positionChanged: function() {
1220
        var last = this._lastBounds,
1221
            bounds;
1222
        return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) );
1223
    },
1224
1225
    sizeChanged: function() {
1226
        var last = this._lastBounds,
1227
            bounds;
1228
        return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) );
1229
    },
1230
1231
    getLiveBounds: function() {
1232
        var el = this.targetElement,
1233
            rect = el.getBoundingClientRect(),
1234
            isIE9 = PIE.ieDocMode === 9,
1235
            isIE7 = PIE.ieVersion === 7,
1236
            width = rect.right - rect.left;
1237
        return {
1238
            x: rect.left,
1239
            y: rect.top,
1240
            // In some cases scrolling the page will cause IE9 to report incorrect dimensions
1241
            // in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height
1242
            // instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements
1243
            // so we must calculate the ratio and use it in certain places as a position adjustment.
1244
            w: isIE9 || isIE7 ? el.offsetWidth : width,
1245
            h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top,
1246
            logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1
1247
        };
1248
    },
1249
1250
    getBounds: function() {
1251
        return this._locked ? 
1252
                ( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) :
1253
                this.getLiveBounds();
1254
    },
1255
1256
    hasBeenQueried: function() {
1257
        return !!this._lastBounds;
1258
    },
1259
1260
    lock: function() {
1261
        ++this._locked;
1262
    },
1263
1264
    unlock: function() {
1265
        if( !--this._locked ) {
1266
            if( this._lockedBounds ) this._lastBounds = this._lockedBounds;
1267
            this._lockedBounds = null;
1268
        }
1269
    }
1270
1271
};
1272
(function() {
1273
1274
function cacheWhenLocked( fn ) {
1275
    var uid = PIE.Util.getUID( fn );
1276
    return function() {
1277
        if( this._locked ) {
1278
            var cache = this._lockedValues || ( this._lockedValues = {} );
1279
            return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) );
1280
        } else {
1281
            return fn.call( this );
1282
        }
1283
    }
1284
}
1285
1286
1287
PIE.StyleInfoBase = {
1288
1289
    _locked: 0,
1290
1291
    /**
1292
     * Create a new StyleInfo class, with the standard constructor, and augmented by
1293
     * the StyleInfoBase's members.
1294
     * @param proto
1295
     */
1296
    newStyleInfo: function( proto ) {
1297
        function StyleInfo( el ) {
1298
            this.targetElement = el;
1299
            this._lastCss = this.getCss();
1300
        }
1301
        PIE.Util.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto );
1302
        StyleInfo._propsCache = {};
1303
        return StyleInfo;
1304
    },
1305
1306
    /**
1307
     * Get an object representation of the target CSS style, caching it for each unique
1308
     * CSS value string.
1309
     * @return {Object}
1310
     */
1311
    getProps: function() {
1312
        var css = this.getCss(),
1313
            cache = this.constructor._propsCache;
1314
        return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null;
1315
    },
1316
1317
    /**
1318
     * Get the raw CSS value for the target style
1319
     * @return {string}
1320
     */
1321
    getCss: cacheWhenLocked( function() {
1322
        var el = this.targetElement,
1323
            ctor = this.constructor,
1324
            s = el.style,
1325
            cs = el.currentStyle,
1326
            cssProp = this.cssProperty,
1327
            styleProp = this.styleProperty,
1328
            prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ),
1329
            prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) );
1330
        return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp );
1331
    } ),
1332
1333
    /**
1334
     * Determine whether the target CSS style is active.
1335
     * @return {boolean}
1336
     */
1337
    isActive: cacheWhenLocked( function() {
1338
        return !!this.getProps();
1339
    } ),
1340
1341
    /**
1342
     * Determine whether the target CSS style has changed since the last time it was used.
1343
     * @return {boolean}
1344
     */
1345
    changed: cacheWhenLocked( function() {
1346
        var currentCss = this.getCss(),
1347
            changed = currentCss !== this._lastCss;
1348
        this._lastCss = currentCss;
1349
        return changed;
1350
    } ),
1351
1352
    cacheWhenLocked: cacheWhenLocked,
1353
1354
    lock: function() {
1355
        ++this._locked;
1356
    },
1357
1358
    unlock: function() {
1359
        if( !--this._locked ) {
1360
            delete this._lockedValues;
1361
        }
1362
    }
1363
};
1364
1365
})();/**
1366
 * Handles parsing, caching, and detecting changes to background (and -pie-background) CSS
1367
 * @constructor
1368
 * @param {Element} el the target element
1369
 */
1370
PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1371
1372
    cssProperty: PIE.CSS_PREFIX + 'background',
1373
    styleProperty: PIE.STYLE_PREFIX + 'Background',
1374
1375
    attachIdents: { 'scroll':1, 'fixed':1, 'local':1 },
1376
    repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 },
1377
    originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 },
1378
    positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 },
1379
    sizeIdents: { 'contain':1, 'cover':1 },
1380
    propertyNames: {
1381
        CLIP: 'backgroundClip',
1382
        COLOR: 'backgroundColor',
1383
        IMAGE: 'backgroundImage',
1384
        ORIGIN: 'backgroundOrigin',
1385
        POSITION: 'backgroundPosition',
1386
        REPEAT: 'backgroundRepeat',
1387
        SIZE: 'backgroundSize'
1388
    },
1389
1390
    /**
1391
     * For background styles, we support the -pie-background property but fall back to the standard
1392
     * backround* properties.  The reason we have to use the prefixed version is that IE natively
1393
     * parses the standard properties and if it sees something it doesn't know how to parse, for example
1394
     * multiple values or gradient definitions, it will throw that away and not make it available through
1395
     * currentStyle.
1396
     *
1397
     * Format of return object:
1398
     * {
1399
     *     color: <PIE.Color>,
1400
     *     bgImages: [
1401
     *         {
1402
     *             imgType: 'image',
1403
     *             imgUrl: 'image.png',
1404
     *             imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>,
1405
     *             bgPosition: <PIE.BgPosition>,
1406
     *             bgAttachment: <'scroll' | 'fixed' | 'local'>,
1407
     *             bgOrigin: <'border-box' | 'padding-box' | 'content-box'>,
1408
     *             bgClip: <'border-box' | 'padding-box'>,
1409
     *             bgSize: <PIE.BgSize>,
1410
     *             origString: 'url(img.png) no-repeat top left'
1411
     *         },
1412
     *         {
1413
     *             imgType: 'linear-gradient',
1414
     *             gradientStart: <PIE.BgPosition>,
1415
     *             angle: <PIE.Angle>,
1416
     *             stops: [
1417
     *                 { color: <PIE.Color>, offset: <PIE.Length> },
1418
     *                 { color: <PIE.Color>, offset: <PIE.Length> }, ...
1419
     *             ]
1420
     *         }
1421
     *     ]
1422
     * }
1423
     * @param {String} css
1424
     * @override
1425
     */
1426
    parseCss: function( css ) {
1427
        var el = this.targetElement,
1428
            cs = el.currentStyle,
1429
            tokenizer, token, image,
1430
            tok_type = PIE.Tokenizer.Type,
1431
            type_operator = tok_type.OPERATOR,
1432
            type_ident = tok_type.IDENT,
1433
            type_color = tok_type.COLOR,
1434
            tokType, tokVal,
1435
            beginCharIndex = 0,
1436
            positionIdents = this.positionIdents,
1437
            gradient, stop, width, height,
1438
            props = { bgImages: [] };
1439
1440
        function isBgPosToken( token ) {
1441
            return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents );
1442
        }
1443
1444
        function sizeToken( token ) {
1445
            return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) );
1446
        }
1447
1448
        // If the CSS3-specific -pie-background property is present, parse it
1449
        if( this.getCss3() ) {
1450
            tokenizer = new PIE.Tokenizer( css );
1451
            image = {};
1452
1453
            while( token = tokenizer.next() ) {
1454
                tokType = token.tokenType;
1455
                tokVal = token.tokenValue;
1456
1457
                if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) {
1458
                    gradient = { stops: [], imgType: tokVal };
1459
                    stop = {};
1460
                    while( token = tokenizer.next() ) {
1461
                        tokType = token.tokenType;
1462
                        tokVal = token.tokenValue;
1463
1464
                        // If we reached the end of the function and had at least 2 stops, flush the info
1465
                        if( tokType & tok_type.CHARACTER && tokVal === ')' ) {
1466
                            if( stop.color ) {
1467
                                gradient.stops.push( stop );
1468
                            }
1469
                            if( gradient.stops.length > 1 ) {
1470
                                PIE.Util.merge( image, gradient );
1471
                            }
1472
                            break;
1473
                        }
1474
1475
                        // Color stop - must start with color
1476
                        if( tokType & type_color ) {
1477
                            // if we already have an angle/position, make sure that the previous token was a comma
1478
                            if( gradient.angle || gradient.gradientStart ) {
1479
                                token = tokenizer.prev();
1480
                                if( token.tokenType !== type_operator ) {
1481
                                    break; //fail
1482
                                }
1483
                                tokenizer.next();
1484
                            }
1485
1486
                            stop = {
1487
                                color: PIE.getColor( tokVal )
1488
                            };
1489
                            // check for offset following color
1490
                            token = tokenizer.next();
1491
                            if( token.isLengthOrPercent() ) {
1492
                                stop.offset = PIE.getLength( token.tokenValue );
1493
                            } else {
1494
                                tokenizer.prev();
1495
                            }
1496
                        }
1497
                        // Angle - can only appear in first spot
1498
                        else if( tokType & tok_type.ANGLE && !gradient.angle && !stop.color && !gradient.stops.length ) {
1499
                            gradient.angle = new PIE.Angle( token.tokenValue );
1500
                        }
1501
                        else if( isBgPosToken( token ) && !gradient.gradientStart && !stop.color && !gradient.stops.length ) {
1502
                            tokenizer.prev();
1503
                            gradient.gradientStart = new PIE.BgPosition(
1504
                                tokenizer.until( function( t ) {
1505
                                    return !isBgPosToken( t );
1506
                                }, false )
1507
                            );
1508
                        }
1509
                        else if( tokType & type_operator && tokVal === ',' ) {
1510
                            if( stop.color ) {
1511
                                gradient.stops.push( stop );
1512
                                stop = {};
1513
                            }
1514
                        }
1515
                        else {
1516
                            // Found something we didn't recognize; fail without adding image
1517
                            break;
1518
                        }
1519
                    }
1520
                }
1521
                else if( !image.imgType && tokType & tok_type.URL ) {
1522
                    image.imgUrl = tokVal;
1523
                    image.imgType = 'image';
1524
                }
1525
                else if( isBgPosToken( token ) && !image.bgPosition ) {
1526
                    tokenizer.prev();
1527
                    image.bgPosition = new PIE.BgPosition(
1528
                        tokenizer.until( function( t ) {
1529
                            return !isBgPosToken( t );
1530
                        }, false )
1531
                    );
1532
                }
1533
                else if( tokType & type_ident ) {
1534
                    if( tokVal in this.repeatIdents && !image.imgRepeat ) {
1535
                        image.imgRepeat = tokVal;
1536
                    }
1537
                    else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) {
1538
                        image.bgOrigin = tokVal;
1539
                        if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) &&
1540
                            token.tokenValue in this.originAndClipIdents ) {
1541
                            image.bgClip = token.tokenValue;
1542
                        } else {
1543
                            image.bgClip = tokVal;
1544
                            tokenizer.prev();
1545
                        }
1546
                    }
1547
                    else if( tokVal in this.attachIdents && !image.bgAttachment ) {
1548
                        image.bgAttachment = tokVal;
1549
                    }
1550
                    else {
1551
                        return null;
1552
                    }
1553
                }
1554
                else if( tokType & type_color && !props.color ) {
1555
                    props.color = PIE.getColor( tokVal );
1556
                }
1557
                else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) {
1558
                    // background size
1559
                    token = tokenizer.next();
1560
                    if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) {
1561
                        image.bgSize = new PIE.BgSize( token.tokenValue );
1562
                    }
1563
                    else if( width = sizeToken( token ) ) {
1564
                        height = sizeToken( tokenizer.next() );
1565
                        if ( !height ) {
1566
                            height = width;
1567
                            tokenizer.prev();
1568
                        }
1569
                        image.bgSize = new PIE.BgSize( width, height );
1570
                    }
1571
                    else {
1572
                        return null;
1573
                    }
1574
                }
1575
                // new layer
1576
                else if( tokType & type_operator && tokVal === ',' && image.imgType ) {
1577
                    image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 );
1578
                    beginCharIndex = tokenizer.ch;
1579
                    props.bgImages.push( image );
1580
                    image = {};
1581
                }
1582
                else {
1583
                    // Found something unrecognized; chuck everything
1584
                    return null;
1585
                }
1586
            }
1587
1588
            // leftovers
1589
            if( image.imgType ) {
1590
                image.origString = css.substring( beginCharIndex );
1591
                props.bgImages.push( image );
1592
            }
1593
        }
1594
1595
        // Otherwise, use the standard background properties; let IE give us the values rather than parsing them
1596
        else {
1597
            this.withActualBg( PIE.ieDocMode < 9 ?
1598
                function() {
1599
                    var propNames = this.propertyNames,
1600
                        posX = cs[propNames.POSITION + 'X'],
1601
                        posY = cs[propNames.POSITION + 'Y'],
1602
                        img = cs[propNames.IMAGE],
1603
                        color = cs[propNames.COLOR];
1604
1605
                    if( color !== 'transparent' ) {
1606
                        props.color = PIE.getColor( color )
1607
                    }
1608
                    if( img !== 'none' ) {
1609
                        props.bgImages = [ {
1610
                            imgType: 'image',
1611
                            imgUrl: new PIE.Tokenizer( img ).next().tokenValue,
1612
                            imgRepeat: cs[propNames.REPEAT],
1613
                            bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() )
1614
                        } ];
1615
                    }
1616
                } :
1617
                function() {
1618
                    var propNames = this.propertyNames,
1619
                        splitter = /\s*,\s*/,
1620
                        images = cs[propNames.IMAGE].split( splitter ),
1621
                        color = cs[propNames.COLOR],
1622
                        repeats, positions, origins, clips, sizes, i, len, image, sizeParts;
1623
1624
                    if( color !== 'transparent' ) {
1625
                        props.color = PIE.getColor( color )
1626
                    }
1627
1628
                    len = images.length;
1629
                    if( len && images[0] !== 'none' ) {
1630
                        repeats = cs[propNames.REPEAT].split( splitter );
1631
                        positions = cs[propNames.POSITION].split( splitter );
1632
                        origins = cs[propNames.ORIGIN].split( splitter );
1633
                        clips = cs[propNames.CLIP].split( splitter );
1634
                        sizes = cs[propNames.SIZE].split( splitter );
1635
1636
                        props.bgImages = [];
1637
                        for( i = 0; i < len; i++ ) {
1638
                            image = images[ i ];
1639
                            if( image && image !== 'none' ) {
1640
                                sizeParts = sizes[i].split( ' ' );
1641
                                props.bgImages.push( {
1642
                                    origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' +
1643
                                                origins[ i ] + ' ' + clips[ i ],
1644
                                    imgType: 'image',
1645
                                    imgUrl: new PIE.Tokenizer( image ).next().tokenValue,
1646
                                    imgRepeat: repeats[ i ],
1647
                                    bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ),
1648
                                    bgOrigin: origins[ i ],
1649
                                    bgClip: clips[ i ],
1650
                                    bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] )
1651
                                } );
1652
                            }
1653
                        }
1654
                    }
1655
                }
1656
            );
1657
        }
1658
1659
        return ( props.color || props.bgImages[0] ) ? props : null;
1660
    },
1661
1662
    /**
1663
     * Execute a function with the actual background styles (not overridden with runtimeStyle
1664
     * properties set by the renderers) available via currentStyle.
1665
     * @param fn
1666
     */
1667
    withActualBg: function( fn ) {
1668
        var isIE9 = PIE.ieDocMode > 8,
1669
            propNames = this.propertyNames,
1670
            rs = this.targetElement.runtimeStyle,
1671
            rsImage = rs[propNames.IMAGE],
1672
            rsColor = rs[propNames.COLOR],
1673
            rsRepeat = rs[propNames.REPEAT],
1674
            rsClip, rsOrigin, rsSize, rsPosition, ret;
1675
1676
        if( rsImage ) rs[propNames.IMAGE] = '';
1677
        if( rsColor ) rs[propNames.COLOR] = '';
1678
        if( rsRepeat ) rs[propNames.REPEAT] = '';
1679
        if( isIE9 ) {
1680
            rsClip = rs[propNames.CLIP];
1681
            rsOrigin = rs[propNames.ORIGIN];
1682
            rsPosition = rs[propNames.POSITION];
1683
            rsSize = rs[propNames.SIZE];
1684
            if( rsClip ) rs[propNames.CLIP] = '';
1685
            if( rsOrigin ) rs[propNames.ORIGIN] = '';
1686
            if( rsPosition ) rs[propNames.POSITION] = '';
1687
            if( rsSize ) rs[propNames.SIZE] = '';
1688
        }
1689
1690
        ret = fn.call( this );
1691
1692
        if( rsImage ) rs[propNames.IMAGE] = rsImage;
1693
        if( rsColor ) rs[propNames.COLOR] = rsColor;
1694
        if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat;
1695
        if( isIE9 ) {
1696
            if( rsClip ) rs[propNames.CLIP] = rsClip;
1697
            if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin;
1698
            if( rsPosition ) rs[propNames.POSITION] = rsPosition;
1699
            if( rsSize ) rs[propNames.SIZE] = rsSize;
1700
        }
1701
1702
        return ret;
1703
    },
1704
1705
    getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
1706
        return this.getCss3() ||
1707
               this.withActualBg( function() {
1708
                   var cs = this.targetElement.currentStyle,
1709
                       propNames = this.propertyNames;
1710
                   return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' +
1711
                   cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y'];
1712
               } );
1713
    } ),
1714
1715
    getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() {
1716
        var el = this.targetElement;
1717
        return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty );
1718
    } ),
1719
1720
    /**
1721
     * Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6.
1722
     */
1723
    isPngFix: function() {
1724
        var val = 0, el;
1725
        if( PIE.ieVersion < 7 ) {
1726
            el = this.targetElement;
1727
            val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' );
1728
        }
1729
        return val;
1730
    },
1731
    
1732
    /**
1733
     * The isActive logic is slightly different, because getProps() always returns an object
1734
     * even if it is just falling back to the native background properties.  But we only want
1735
     * to report is as being "active" if either the -pie-background override property is present
1736
     * and parses successfully or '-pie-png-fix' is set to true in IE6.
1737
     */
1738
    isActive: PIE.StyleInfoBase.cacheWhenLocked( function() {
1739
        return (this.getCss3() || this.isPngFix()) && !!this.getProps();
1740
    } )
1741
1742
} );/**
1743
 * Handles parsing, caching, and detecting changes to border CSS
1744
 * @constructor
1745
 * @param {Element} el the target element
1746
 */
1747
PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1748
1749
    sides: [ 'Top', 'Right', 'Bottom', 'Left' ],
1750
    namedWidths: {
1751
        'thin': '1px',
1752
        'medium': '3px',
1753
        'thick': '5px'
1754
    },
1755
1756
    parseCss: function( css ) {
1757
        var w = {},
1758
            s = {},
1759
            c = {},
1760
            active = false,
1761
            colorsSame = true,
1762
            stylesSame = true,
1763
            widthsSame = true;
1764
1765
        this.withActualBorder( function() {
1766
            var el = this.targetElement,
1767
                cs = el.currentStyle,
1768
                i = 0,
1769
                style, color, width, lastStyle, lastColor, lastWidth, side, ltr;
1770
            for( ; i < 4; i++ ) {
1771
                side = this.sides[ i ];
1772
1773
                ltr = side.charAt(0).toLowerCase();
1774
                style = s[ ltr ] = cs[ 'border' + side + 'Style' ];
1775
                color = cs[ 'border' + side + 'Color' ];
1776
                width = cs[ 'border' + side + 'Width' ];
1777
1778
                if( i > 0 ) {
1779
                    if( style !== lastStyle ) { stylesSame = false; }
1780
                    if( color !== lastColor ) { colorsSame = false; }
1781
                    if( width !== lastWidth ) { widthsSame = false; }
1782
                }
1783
                lastStyle = style;
1784
                lastColor = color;
1785
                lastWidth = width;
1786
1787
                c[ ltr ] = PIE.getColor( color );
1788
1789
                width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) );
1790
                if( width.pixels( this.targetElement ) > 0 ) {
1791
                    active = true;
1792
                }
1793
            }
1794
        } );
1795
1796
        return active ? {
1797
            widths: w,
1798
            styles: s,
1799
            colors: c,
1800
            widthsSame: widthsSame,
1801
            colorsSame: colorsSame,
1802
            stylesSame: stylesSame
1803
        } : null;
1804
    },
1805
1806
    getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
1807
        var el = this.targetElement,
1808
            cs = el.currentStyle,
1809
            css;
1810
1811
        // Don't redraw or hide borders for cells in border-collapse:collapse tables
1812
        if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) {
1813
            this.withActualBorder( function() {
1814
                css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor;
1815
            } );
1816
        }
1817
        return css;
1818
    } ),
1819
1820
    /**
1821
     * Execute a function with the actual border styles (not overridden with runtimeStyle
1822
     * properties set by the renderers) available via currentStyle.
1823
     * @param fn
1824
     */
1825
    withActualBorder: function( fn ) {
1826
        var rs = this.targetElement.runtimeStyle,
1827
            rsWidth = rs.borderWidth,
1828
            rsColor = rs.borderColor,
1829
            ret;
1830
1831
        if( rsWidth ) rs.borderWidth = '';
1832
        if( rsColor ) rs.borderColor = '';
1833
1834
        ret = fn.call( this );
1835
1836
        if( rsWidth ) rs.borderWidth = rsWidth;
1837
        if( rsColor ) rs.borderColor = rsColor;
1838
1839
        return ret;
1840
    }
1841
1842
} );
1843
/**
1844
 * Handles parsing, caching, and detecting changes to border-radius CSS
1845
 * @constructor
1846
 * @param {Element} el the target element
1847
 */
1848
(function() {
1849
1850
PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1851
1852
    cssProperty: 'border-radius',
1853
    styleProperty: 'borderRadius',
1854
1855
    parseCss: function( css ) {
1856
        var p = null, x, y,
1857
            tokenizer, token, length,
1858
            hasNonZero = false;
1859
1860
        if( css ) {
1861
            tokenizer = new PIE.Tokenizer( css );
1862
1863
            function collectLengths() {
1864
                var arr = [], num;
1865
                while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) {
1866
                    length = PIE.getLength( token.tokenValue );
1867
                    num = length.getNumber();
1868
                    if( num < 0 ) {
1869
                        return null;
1870
                    }
1871
                    if( num > 0 ) {
1872
                        hasNonZero = true;
1873
                    }
1874
                    arr.push( length );
1875
                }
1876
                return arr.length > 0 && arr.length < 5 ? {
1877
                        'tl': arr[0],
1878
                        'tr': arr[1] || arr[0],
1879
                        'br': arr[2] || arr[0],
1880
                        'bl': arr[3] || arr[1] || arr[0]
1881
                    } : null;
1882
            }
1883
1884
            // Grab the initial sequence of lengths
1885
            if( x = collectLengths() ) {
1886
                // See if there is a slash followed by more lengths, for the y-axis radii
1887
                if( token ) {
1888
                    if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) {
1889
                        y = collectLengths();
1890
                    }
1891
                } else {
1892
                    y = x;
1893
                }
1894
1895
                // Treat all-zero values the same as no value
1896
                if( hasNonZero && x && y ) {
1897
                    p = { x: x, y : y };
1898
                }
1899
            }
1900
        }
1901
1902
        return p;
1903
    }
1904
} );
1905
1906
var zero = PIE.getLength( '0' ),
1907
    zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero };
1908
PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros };
1909
1910
})();/**
1911
 * Handles parsing, caching, and detecting changes to border-image CSS
1912
 * @constructor
1913
 * @param {Element} el the target element
1914
 */
1915
PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1916
1917
    cssProperty: 'border-image',
1918
    styleProperty: 'borderImage',
1919
1920
    repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 },
1921
1922
    parseCss: function( css ) {
1923
        var p = null, tokenizer, token, type, value,
1924
            slices, widths, outsets,
1925
            slashCount = 0,
1926
            Type = PIE.Tokenizer.Type,
1927
            IDENT = Type.IDENT,
1928
            NUMBER = Type.NUMBER,
1929
            PERCENT = Type.PERCENT;
1930
1931
        if( css ) {
1932
            tokenizer = new PIE.Tokenizer( css );
1933
            p = {};
1934
1935
            function isSlash( token ) {
1936
                return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' );
1937
            }
1938
1939
            function isFillIdent( token ) {
1940
                return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' );
1941
            }
1942
1943
            function collectSlicesEtc() {
1944
                slices = tokenizer.until( function( tok ) {
1945
                    return !( tok.tokenType & ( NUMBER | PERCENT ) );
1946
                } );
1947
1948
                if( isFillIdent( tokenizer.next() ) && !p.fill ) {
1949
                    p.fill = true;
1950
                } else {
1951
                    tokenizer.prev();
1952
                }
1953
1954
                if( isSlash( tokenizer.next() ) ) {
1955
                    slashCount++;
1956
                    widths = tokenizer.until( function( token ) {
1957
                        return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' );
1958
                    } );
1959
1960
                    if( isSlash( tokenizer.next() ) ) {
1961
                        slashCount++;
1962
                        outsets = tokenizer.until( function( token ) {
1963
                            return !token.isLength();
1964
                        } );
1965
                    }
1966
                } else {
1967
                    tokenizer.prev();
1968
                }
1969
            }
1970
1971
            while( token = tokenizer.next() ) {
1972
                type = token.tokenType;
1973
                value = token.tokenValue;
1974
1975
                // Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values
1976
                if( type & ( NUMBER | PERCENT ) && !slices ) {
1977
                    tokenizer.prev();
1978
                    collectSlicesEtc();
1979
                }
1980
                else if( isFillIdent( token ) && !p.fill ) {
1981
                    p.fill = true;
1982
                    collectSlicesEtc();
1983
                }
1984
1985
                // Idents: one or values for 'repeat'
1986
                else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) {
1987
                    p.repeat = { h: value };
1988
                    if( token = tokenizer.next() ) {
1989
                        if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) {
1990
                            p.repeat.v = token.tokenValue;
1991
                        } else {
1992
                            tokenizer.prev();
1993
                        }
1994
                    }
1995
                }
1996
1997
                // URL of the image
1998
                else if( ( type & Type.URL ) && !p.src ) {
1999
                    p.src =  value;
2000
                }
2001
2002
                // Found something unrecognized; exit.
2003
                else {
2004
                    return null;
2005
                }
2006
            }
2007
2008
            // Validate what we collected
2009
            if( !p.src || !slices || slices.length < 1 || slices.length > 4 ||
2010
                ( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) ||
2011
                ( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) {
2012
                return null;
2013
            }
2014
2015
            // Fill in missing values
2016
            if( !p.repeat ) {
2017
                p.repeat = { h: 'stretch' };
2018
            }
2019
            if( !p.repeat.v ) {
2020
                p.repeat.v = p.repeat.h;
2021
            }
2022
2023
            function distributeSides( tokens, convertFn ) {
2024
                return {
2025
                    't': convertFn( tokens[0] ),
2026
                    'r': convertFn( tokens[1] || tokens[0] ),
2027
                    'b': convertFn( tokens[2] || tokens[0] ),
2028
                    'l': convertFn( tokens[3] || tokens[1] || tokens[0] )
2029
                };
2030
            }
2031
2032
            p.slice = distributeSides( slices, function( tok ) {
2033
                return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue );
2034
            } );
2035
2036
            if( widths && widths[0] ) {
2037
                p.widths = distributeSides( widths, function( tok ) {
2038
                    return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
2039
                } );
2040
            }
2041
2042
            if( outsets && outsets[0] ) {
2043
                p.outset = distributeSides( outsets, function( tok ) {
2044
                    return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
2045
                } );
2046
            }
2047
        }
2048
2049
        return p;
2050
    }
2051
2052
} );/**
2053
 * Handles parsing, caching, and detecting changes to box-shadow CSS
2054
 * @constructor
2055
 * @param {Element} el the target element
2056
 */
2057
PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
2058
2059
    cssProperty: 'box-shadow',
2060
    styleProperty: 'boxShadow',
2061
2062
    parseCss: function( css ) {
2063
        var props,
2064
            getLength = PIE.getLength,
2065
            Type = PIE.Tokenizer.Type,
2066
            tokenizer;
2067
2068
        if( css ) {
2069
            tokenizer = new PIE.Tokenizer( css );
2070
            props = { outset: [], inset: [] };
2071
2072
            function parseItem() {
2073
                var token, type, value, color, lengths, inset, len;
2074
2075
                while( token = tokenizer.next() ) {
2076
                    value = token.tokenValue;
2077
                    type = token.tokenType;
2078
2079
                    if( type & Type.OPERATOR && value === ',' ) {
2080
                        break;
2081
                    }
2082
                    else if( token.isLength() && !lengths ) {
2083
                        tokenizer.prev();
2084
                        lengths = tokenizer.until( function( token ) {
2085
                            return !token.isLength();
2086
                        } );
2087
                    }
2088
                    else if( type & Type.COLOR && !color ) {
2089
                        color = value;
2090
                    }
2091
                    else if( type & Type.IDENT && value === 'inset' && !inset ) {
2092
                        inset = true;
2093
                    }
2094
                    else { //encountered an unrecognized token; fail.
2095
                        return false;
2096
                    }
2097
                }
2098
2099
                len = lengths && lengths.length;
2100
                if( len > 1 && len < 5 ) {
2101
                    ( inset ? props.inset : props.outset ).push( {
2102
                        xOffset: getLength( lengths[0].tokenValue ),
2103
                        yOffset: getLength( lengths[1].tokenValue ),
2104
                        blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ),
2105
                        spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ),
2106
                        color: PIE.getColor( color || 'currentColor' )
2107
                    } );
2108
                    return true;
2109
                }
2110
                return false;
2111
            }
2112
2113
            while( parseItem() ) {}
2114
        }
2115
2116
        return props && ( props.inset.length || props.outset.length ) ? props : null;
2117
    }
2118
} );
2119
/**
2120
 * Retrieves the state of the element's visibility and display
2121
 * @constructor
2122
 * @param {Element} el the target element
2123
 */
2124
PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
2125
2126
    getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
2127
        var cs = this.targetElement.currentStyle;
2128
        return cs.visibility + '|' + cs.display;
2129
    } ),
2130
2131
    parseCss: function() {
2132
        var el = this.targetElement,
2133
            rs = el.runtimeStyle,
2134
            cs = el.currentStyle,
2135
            rsVis = rs.visibility,
2136
            csVis;
2137
2138
        rs.visibility = '';
2139
        csVis = cs.visibility;
2140
        rs.visibility = rsVis;
2141
2142
        return {
2143
            visible: csVis !== 'hidden',
2144
            displayed: cs.display !== 'none'
2145
        }
2146
    },
2147
2148
    /**
2149
     * Always return false for isActive, since this property alone will not trigger
2150
     * a renderer to do anything.
2151
     */
2152
    isActive: function() {
2153
        return false;
2154
    }
2155
2156
} );
2157
PIE.RendererBase = {
2158
2159
    /**
2160
     * Create a new Renderer class, with the standard constructor, and augmented by
2161
     * the RendererBase's members.
2162
     * @param proto
2163
     */
2164
    newRenderer: function( proto ) {
2165
        function Renderer( el, boundsInfo, styleInfos, parent ) {
2166
            this.targetElement = el;
2167
            this.boundsInfo = boundsInfo;
2168
            this.styleInfos = styleInfos;
2169
            this.parent = parent;
2170
        }
2171
        PIE.Util.merge( Renderer.prototype, PIE.RendererBase, proto );
2172
        return Renderer;
2173
    },
2174
2175
    /**
2176
     * Flag indicating the element has already been positioned at least once.
2177
     * @type {boolean}
2178
     */
2179
    isPositioned: false,
2180
2181
    /**
2182
     * Determine if the renderer needs to be updated
2183
     * @return {boolean}
2184
     */
2185
    needsUpdate: function() {
2186
        return false;
2187
    },
2188
2189
    /**
2190
     * Run any preparation logic that would affect the main update logic of this
2191
     * renderer or any of the other renderers, e.g. things that might affect the
2192
     * element's size or style properties.
2193
     */
2194
    prepareUpdate: PIE.emptyFn,
2195
2196
    /**
2197
     * Tell the renderer to update based on modified properties
2198
     */
2199
    updateProps: function() {
2200
        this.destroy();
2201
        if( this.isActive() ) {
2202
            this.draw();
2203
        }
2204
    },
2205
2206
    /**
2207
     * Tell the renderer to update based on modified element position
2208
     */
2209
    updatePos: function() {
2210
        this.isPositioned = true;
2211
    },
2212
2213
    /**
2214
     * Tell the renderer to update based on modified element dimensions
2215
     */
2216
    updateSize: function() {
2217
        if( this.isActive() ) {
2218
            this.draw();
2219
        } else {
2220
            this.destroy();
2221
        }
2222
    },
2223
2224
2225
    /**
2226
     * Add a layer element, with the given z-order index, to the renderer's main box element. We can't use
2227
     * z-index because that breaks when the root rendering box's z-index is 'auto' in IE8+ standards mode.
2228
     * So instead we make sure they are inserted into the DOM in the correct order.
2229
     * @param {number} index
2230
     * @param {Element} el
2231
     */
2232
    addLayer: function( index, el ) {
2233
        this.removeLayer( index );
2234
        for( var layers = this._layers || ( this._layers = [] ), i = index + 1, len = layers.length, layer; i < len; i++ ) {
2235
            layer = layers[i];
2236
            if( layer ) {
2237
                break;
2238
            }
2239
        }
2240
        layers[index] = el;
2241
        this.getBox().insertBefore( el, layer || null );
2242
    },
2243
2244
    /**
2245
     * Retrieve a layer element by its index, or null if not present
2246
     * @param {number} index
2247
     * @return {Element}
2248
     */
2249
    getLayer: function( index ) {
2250
        var layers = this._layers;
2251
        return layers && layers[index] || null;
2252
    },
2253
2254
    /**
2255
     * Remove a layer element by its index
2256
     * @param {number} index
2257
     */
2258
    removeLayer: function( index ) {
2259
        var layer = this.getLayer( index ),
2260
            box = this._box;
2261
        if( layer && box ) {
2262
            box.removeChild( layer );
2263
            this._layers[index] = null;
2264
        }
2265
    },
2266
2267
2268
    /**
2269
     * Get a VML shape by name, creating it if necessary.
2270
     * @param {string} name A name identifying the element
2271
     * @param {string=} subElName If specified a subelement of the shape will be created with this tag name
2272
     * @param {Element} parent The parent element for the shape; will be ignored if 'group' is specified
2273
     * @param {number=} group If specified, an ordinal group for the shape. 1 or greater. Groups are rendered
2274
     *                  using container elements in the correct order, to get correct z stacking without z-index.
2275
     */
2276
    getShape: function( name, subElName, parent, group ) {
2277
        var shapes = this._shapes || ( this._shapes = {} ),
2278
            shape = shapes[ name ],
2279
            s;
2280
2281
        if( !shape ) {
2282
            shape = shapes[ name ] = PIE.Util.createVmlElement( 'shape' );
2283
            if( subElName ) {
2284
                shape.appendChild( shape[ subElName ] = PIE.Util.createVmlElement( subElName ) );
2285
            }
2286
2287
            if( group ) {
2288
                parent = this.getLayer( group );
2289
                if( !parent ) {
2290
                    this.addLayer( group, doc.createElement( 'group' + group ) );
2291
                    parent = this.getLayer( group );
2292
                }
2293
            }
2294
2295
            parent.appendChild( shape );
2296
2297
            s = shape.style;
2298
            s.position = 'absolute';
2299
            s.left = s.top = 0;
2300
            s['behavior'] = 'url(#default#VML)';
2301
        }
2302
        return shape;
2303
    },
2304
2305
    /**
2306
     * Delete a named shape which was created by getShape(). Returns true if a shape with the
2307
     * given name was found and deleted, or false if there was no shape of that name.
2308
     * @param {string} name
2309
     * @return {boolean}
2310
     */
2311
    deleteShape: function( name ) {
2312
        var shapes = this._shapes,
2313
            shape = shapes && shapes[ name ];
2314
        if( shape ) {
2315
            shape.parentNode.removeChild( shape );
2316
            delete shapes[ name ];
2317
        }
2318
        return !!shape;
2319
    },
2320
2321
2322
    /**
2323
     * For a given set of border radius length/percentage values, convert them to concrete pixel
2324
     * values based on the current size of the target element.
2325
     * @param {Object} radii
2326
     * @return {Object}
2327
     */
2328
    getRadiiPixels: function( radii ) {
2329
        var el = this.targetElement,
2330
            bounds = this.boundsInfo.getBounds(),
2331
            w = bounds.w,
2332
            h = bounds.h,
2333
            tlX, tlY, trX, trY, brX, brY, blX, blY, f;
2334
2335
        tlX = radii.x['tl'].pixels( el, w );
2336
        tlY = radii.y['tl'].pixels( el, h );
2337
        trX = radii.x['tr'].pixels( el, w );
2338
        trY = radii.y['tr'].pixels( el, h );
2339
        brX = radii.x['br'].pixels( el, w );
2340
        brY = radii.y['br'].pixels( el, h );
2341
        blX = radii.x['bl'].pixels( el, w );
2342
        blY = radii.y['bl'].pixels( el, h );
2343
2344
        // If any corner ellipses overlap, reduce them all by the appropriate factor. This formula
2345
        // is taken straight from the CSS3 Backgrounds and Borders spec.
2346
        f = Math.min(
2347
            w / ( tlX + trX ),
2348
            h / ( trY + brY ),
2349
            w / ( blX + brX ),
2350
            h / ( tlY + blY )
2351
        );
2352
        if( f < 1 ) {
2353
            tlX *= f;
2354
            tlY *= f;
2355
            trX *= f;
2356
            trY *= f;
2357
            brX *= f;
2358
            brY *= f;
2359
            blX *= f;
2360
            blY *= f;
2361
        }
2362
2363
        return {
2364
            x: {
2365
                'tl': tlX,
2366
                'tr': trX,
2367
                'br': brX,
2368
                'bl': blX
2369
            },
2370
            y: {
2371
                'tl': tlY,
2372
                'tr': trY,
2373
                'br': brY,
2374
                'bl': blY
2375
            }
2376
        }
2377
    },
2378
2379
    /**
2380
     * Return the VML path string for the element's background box, with corners rounded.
2381
     * @param {Object.<{t:number, r:number, b:number, l:number}>} shrink - if present, specifies number of
2382
     *        pixels to shrink the box path inward from the element's four sides.
2383
     * @param {number=} mult If specified, all coordinates will be multiplied by this number
2384
     * @param {Object=} radii If specified, this will be used for the corner radii instead of the properties
2385
     *        from this renderer's borderRadiusInfo object.
2386
     * @return {string} the VML path
2387
     */
2388
    getBoxPath: function( shrink, mult, radii ) {
2389
        mult = mult || 1;
2390
2391
        var r, str,
2392
            bounds = this.boundsInfo.getBounds(),
2393
            w = bounds.w * mult,
2394
            h = bounds.h * mult,
2395
            radInfo = this.styleInfos.borderRadiusInfo,
2396
            floor = Math.floor, ceil = Math.ceil,
2397
            shrinkT = shrink ? shrink.t * mult : 0,
2398
            shrinkR = shrink ? shrink.r * mult : 0,
2399
            shrinkB = shrink ? shrink.b * mult : 0,
2400
            shrinkL = shrink ? shrink.l * mult : 0,
2401
            tlX, tlY, trX, trY, brX, brY, blX, blY;
2402
2403
        if( radii || radInfo.isActive() ) {
2404
            r = this.getRadiiPixels( radii || radInfo.getProps() );
2405
2406
            tlX = r.x['tl'] * mult;
2407
            tlY = r.y['tl'] * mult;
2408
            trX = r.x['tr'] * mult;
2409
            trY = r.y['tr'] * mult;
2410
            brX = r.x['br'] * mult;
2411
            brY = r.y['br'] * mult;
2412
            blX = r.x['bl'] * mult;
2413
            blY = r.y['bl'] * mult;
2414
2415
            str = 'm' + floor( shrinkL ) + ',' + floor( tlY ) +
2416
                'qy' + floor( tlX ) + ',' + floor( shrinkT ) +
2417
                'l' + ceil( w - trX ) + ',' + floor( shrinkT ) +
2418
                'qx' + ceil( w - shrinkR ) + ',' + floor( trY ) +
2419
                'l' + ceil( w - shrinkR ) + ',' + ceil( h - brY ) +
2420
                'qy' + ceil( w - brX ) + ',' + ceil( h - shrinkB ) +
2421
                'l' + floor( blX ) + ',' + ceil( h - shrinkB ) +
2422
                'qx' + floor( shrinkL ) + ',' + ceil( h - blY ) + ' x e';
2423
        } else {
2424
            // simplified path for non-rounded box
2425
            str = 'm' + floor( shrinkL ) + ',' + floor( shrinkT ) +
2426
                  'l' + ceil( w - shrinkR ) + ',' + floor( shrinkT ) +
2427
                  'l' + ceil( w - shrinkR ) + ',' + ceil( h - shrinkB ) +
2428
                  'l' + floor( shrinkL ) + ',' + ceil( h - shrinkB ) +
2429
                  'xe';
2430
        }
2431
        return str;
2432
    },
2433
2434
2435
    /**
2436
     * Get the container element for the shapes, creating it if necessary.
2437
     */
2438
    getBox: function() {
2439
        var box = this.parent.getLayer( this.boxZIndex ), s;
2440
2441
        if( !box ) {
2442
            box = doc.createElement( this.boxName );
2443
            s = box.style;
2444
            s.position = 'absolute';
2445
            s.top = s.left = 0;
2446
            this.parent.addLayer( this.boxZIndex, box );
2447
        }
2448
2449
        return box;
2450
    },
2451
2452
2453
    /**
2454
     * Hide the actual border of the element. In IE7 and up we can just set its color to transparent;
2455
     * however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements
2456
     * like form buttons require removing the border width altogether, so for those we increase the padding
2457
     * by the border size.
2458
     */
2459
    hideBorder: function() {
2460
        var el = this.targetElement,
2461
            cs = el.currentStyle,
2462
            rs = el.runtimeStyle,
2463
            tag = el.tagName,
2464
            isIE6 = PIE.ieVersion === 6,
2465
            sides, side, i;
2466
2467
        if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) ||
2468
                tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) {
2469
            rs.borderWidth = '';
2470
            sides = this.styleInfos.borderInfo.sides;
2471
            for( i = sides.length; i--; ) {
2472
                side = sides[ i ];
2473
                rs[ 'padding' + side ] = '';
2474
                rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) +
2475
                                         ( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) +
2476
                                         ( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away
2477
            }
2478
            rs.borderWidth = 0;
2479
        }
2480
        else if( isIE6 ) {
2481
            // Wrap all the element's children in a custom element, set the element to visiblity:hidden,
2482
            // and set the wrapper element to visiblity:visible. This hides the outer element's decorations
2483
            // (background and border) but displays all the contents.
2484
            // TODO find a better way to do this that doesn't mess up the DOM parent-child relationship,
2485
            // as this can interfere with other author scripts which add/modify/delete children. Also, this
2486
            // won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into
2487
            // using a compositor filter or some other filter which masks the border.
2488
            if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) {
2489
                var cont = doc.createElement( 'ie6-mask' ),
2490
                    s = cont.style, child;
2491
                s.visibility = 'visible';
2492
                s.zoom = 1;
2493
                while( child = el.firstChild ) {
2494
                    cont.appendChild( child );
2495
                }
2496
                el.appendChild( cont );
2497
                rs.visibility = 'hidden';
2498
            }
2499
        }
2500
        else {
2501
            rs.borderColor = 'transparent';
2502
        }
2503
    },
2504
2505
    unhideBorder: function() {
2506
        
2507
    },
2508
2509
2510
    /**
2511
     * Destroy the rendered objects. This is a base implementation which handles common renderer
2512
     * structures, but individual renderers may override as necessary.
2513
     */
2514
    destroy: function() {
2515
        this.parent.removeLayer( this.boxZIndex );
2516
        delete this._shapes;
2517
        delete this._layers;
2518
    }
2519
};
2520
/**
2521
 * Root renderer; creates the outermost container element and handles keeping it aligned
2522
 * with the target element's size and position.
2523
 * @param {Element} el The target element
2524
 * @param {Object} styleInfos The StyleInfo objects
2525
 */
2526
PIE.RootRenderer = PIE.RendererBase.newRenderer( {
2527
2528
    isActive: function() {
2529
        var children = this.childRenderers;
2530
        for( var i in children ) {
2531
            if( children.hasOwnProperty( i ) && children[ i ].isActive() ) {
2532
                return true;
2533
            }
2534
        }
2535
        return false;
2536
    },
2537
2538
    needsUpdate: function() {
2539
        return this.styleInfos.visibilityInfo.changed();
2540
    },
2541
2542
    updatePos: function() {
2543
        if( this.isActive() ) {
2544
            var el = this.getPositioningElement(),
2545
                par = el,
2546
                docEl,
2547
                parRect,
2548
                tgtCS = el.currentStyle,
2549
                tgtPos = tgtCS.position,
2550
                boxPos,
2551
                s = this.getBox().style, cs,
2552
                x = 0, y = 0,
2553
                elBounds = this.boundsInfo.getBounds(),
2554
                logicalZoomRatio = elBounds.logicalZoomRatio;
2555
2556
            if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) {
2557
                x = elBounds.x * logicalZoomRatio;
2558
                y = elBounds.y * logicalZoomRatio;
2559
                boxPos = tgtPos;
2560
            } else {
2561
                // Get the element's offsets from its nearest positioned ancestor. Uses
2562
                // getBoundingClientRect for accuracy and speed.
2563
                do {
2564
                    par = par.offsetParent;
2565
                } while( par && ( par.currentStyle.position === 'static' ) );
2566
                if( par ) {
2567
                    parRect = par.getBoundingClientRect();
2568
                    cs = par.currentStyle;
2569
                    x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 );
2570
                    y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 );
2571
                } else {
2572
                    docEl = doc.documentElement;
2573
                    x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio;
2574
                    y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio;
2575
                }
2576
                boxPos = 'absolute';
2577
            }
2578
2579
            s.position = boxPos;
2580
            s.left = x;
2581
            s.top = y;
2582
            s.zIndex = tgtPos === 'static' ? -1 : tgtCS.zIndex;
2583
            this.isPositioned = true;
2584
        }
2585
    },
2586
2587
    updateSize: PIE.emptyFn,
2588
2589
    updateVisibility: function() {
2590
        var vis = this.styleInfos.visibilityInfo.getProps();
2591
        this.getBox().style.display = ( vis.visible && vis.displayed ) ? '' : 'none';
2592
    },
2593
2594
    updateProps: function() {
2595
        if( this.isActive() ) {
2596
            this.updateVisibility();
2597
        } else {
2598
            this.destroy();
2599
        }
2600
    },
2601
2602
    getPositioningElement: function() {
2603
        var el = this.targetElement;
2604
        return el.tagName in PIE.tableCellTags ? el.offsetParent : el;
2605
    },
2606
2607
    getBox: function() {
2608
        var box = this._box, el;
2609
        if( !box ) {
2610
            el = this.getPositioningElement();
2611
            box = this._box = doc.createElement( 'css3-container' );
2612
            box.style['direction'] = 'ltr'; //fix positioning bug in rtl environments
2613
2614
            this.updateVisibility();
2615
2616
            el.parentNode.insertBefore( box, el );
2617
        }
2618
        return box;
2619
    },
2620
2621
    finishUpdate: PIE.emptyFn,
2622
2623
    destroy: function() {
2624
        var box = this._box, par;
2625
        if( box && ( par = box.parentNode ) ) {
2626
            par.removeChild( box );
2627
        }
2628
        delete this._box;
2629
        delete this._layers;
2630
    }
2631
2632
} );
2633
/**
2634
 * Renderer for element backgrounds.
2635
 * @constructor
2636
 * @param {Element} el The target element
2637
 * @param {Object} styleInfos The StyleInfo objects
2638
 * @param {PIE.RootRenderer} parent
2639
 */
2640
PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( {
2641
2642
    boxZIndex: 2,
2643
    boxName: 'background',
2644
2645
    needsUpdate: function() {
2646
        var si = this.styleInfos;
2647
        return si.backgroundInfo.changed() || si.borderRadiusInfo.changed();
2648
    },
2649
2650
    isActive: function() {
2651
        var si = this.styleInfos;
2652
        return si.borderImageInfo.isActive() ||
2653
               si.borderRadiusInfo.isActive() ||
2654
               si.backgroundInfo.isActive() ||
2655
               ( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset );
2656
    },
2657
2658
    /**
2659
     * Draw the shapes
2660
     */
2661
    draw: function() {
2662
        var bounds = this.boundsInfo.getBounds();
2663
        if( bounds.w && bounds.h ) {
2664
            this.drawBgColor();
2665
            this.drawBgImages();
2666
        }
2667
    },
2668
2669
    /**
2670
     * Draw the background color shape
2671
     */
2672
    drawBgColor: function() {
2673
        var props = this.styleInfos.backgroundInfo.getProps(),
2674
            bounds = this.boundsInfo.getBounds(),
2675
            el = this.targetElement,
2676
            color = props && props.color,
2677
            shape, w, h, s, alpha;
2678
2679
        if( color && color.alpha() > 0 ) {
2680
            this.hideBackground();
2681
2682
            shape = this.getShape( 'bgColor', 'fill', this.getBox(), 1 );
2683
            w = bounds.w;
2684
            h = bounds.h;
2685
            shape.stroked = false;
2686
            shape.coordsize = w * 2 + ',' + h * 2;
2687
            shape.coordorigin = '1,1';
2688
            shape.path = this.getBoxPath( null, 2 );
2689
            s = shape.style;
2690
            s.width = w;
2691
            s.height = h;
2692
            shape.fill.color = color.colorValue( el );
2693
2694
            alpha = color.alpha();
2695
            if( alpha < 1 ) {
2696
                shape.fill.opacity = alpha;
2697
            }
2698
        } else {
2699
            this.deleteShape( 'bgColor' );
2700
        }
2701
    },
2702
2703
    /**
2704
     * Draw all the background image layers
2705
     */
2706
    drawBgImages: function() {
2707
        var props = this.styleInfos.backgroundInfo.getProps(),
2708
            bounds = this.boundsInfo.getBounds(),
2709
            images = props && props.bgImages,
2710
            img, shape, w, h, s, i;
2711
2712
        if( images ) {
2713
            this.hideBackground();
2714
2715
            w = bounds.w;
2716
            h = bounds.h;
2717
2718
            i = images.length;
2719
            while( i-- ) {
2720
                img = images[i];
2721
                shape = this.getShape( 'bgImage' + i, 'fill', this.getBox(), 2 );
2722
2723
                shape.stroked = false;
2724
                shape.fill.type = 'tile';
2725
                shape.fillcolor = 'none';
2726
                shape.coordsize = w * 2 + ',' + h * 2;
2727
                shape.coordorigin = '1,1';
2728
                shape.path = this.getBoxPath( 0, 2 );
2729
                s = shape.style;
2730
                s.width = w;
2731
                s.height = h;
2732
2733
                if( img.imgType === 'linear-gradient' ) {
2734
                    this.addLinearGradient( shape, img );
2735
                }
2736
                else {
2737
                    shape.fill.src = img.imgUrl;
2738
                    this.positionBgImage( shape, i );
2739
                }
2740
            }
2741
        }
2742
2743
        // Delete any bgImage shapes previously created which weren't used above
2744
        i = images ? images.length : 0;
2745
        while( this.deleteShape( 'bgImage' + i++ ) ) {}
2746
    },
2747
2748
2749
    /**
2750
     * Set the position and clipping of the background image for a layer
2751
     * @param {Element} shape
2752
     * @param {number} index
2753
     */
2754
    positionBgImage: function( shape, index ) {
2755
        var me = this;
2756
        PIE.Util.withImageSize( shape.fill.src, function( size ) {
2757
            var el = me.targetElement,
2758
                bounds = me.boundsInfo.getBounds(),
2759
                elW = bounds.w,
2760
                elH = bounds.h;
2761
2762
            // It's possible that the element dimensions are zero now but weren't when the original
2763
            // update executed, make sure that's not the case to avoid divide-by-zero error
2764
            if( elW && elH ) {
2765
                var fill = shape.fill,
2766
                    si = me.styleInfos,
2767
                    border = si.borderInfo.getProps(),
2768
                    bw = border && border.widths,
2769
                    bwT = bw ? bw['t'].pixels( el ) : 0,
2770
                    bwR = bw ? bw['r'].pixels( el ) : 0,
2771
                    bwB = bw ? bw['b'].pixels( el ) : 0,
2772
                    bwL = bw ? bw['l'].pixels( el ) : 0,
2773
                    bg = si.backgroundInfo.getProps().bgImages[ index ],
2774
                    bgPos = bg.bgPosition ? bg.bgPosition.coords( el, elW - size.w - bwL - bwR, elH - size.h - bwT - bwB ) : { x:0, y:0 },
2775
                    repeat = bg.imgRepeat,
2776
                    pxX, pxY,
2777
                    clipT = 0, clipL = 0,
2778
                    clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel)
2779
                    clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region
2780
2781
                // Positioning - find the pixel offset from the top/left and convert to a ratio
2782
                // The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is
2783
                // needed to fix antialiasing but makes the bg image fuzzy.
2784
                pxX = Math.round( bgPos.x ) + bwL + 0.5;
2785
                pxY = Math.round( bgPos.y ) + bwT + 0.5;
2786
                fill.position = ( pxX / elW ) + ',' + ( pxY / elH );
2787
2788
                // Set the size of the image. We have to actually set it to px values otherwise it will not honor
2789
                // the user's browser zoom level and always display at its natural screen size.
2790
                fill['size']['x'] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird!
2791
                fill['size'] = size.w + 'px,' + size.h + 'px';
2792
2793
                // Repeating - clip the image shape
2794
                if( repeat && repeat !== 'repeat' ) {
2795
                    if( repeat === 'repeat-x' || repeat === 'no-repeat' ) {
2796
                        clipT = pxY + 1;
2797
                        clipB = pxY + size.h + clipAdjust;
2798
                    }
2799
                    if( repeat === 'repeat-y' || repeat === 'no-repeat' ) {
2800
                        clipL = pxX + 1;
2801
                        clipR = pxX + size.w + clipAdjust;
2802
                    }
2803
                    shape.style.clip = 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)';
2804
                }
2805
            }
2806
        } );
2807
    },
2808
2809
2810
    /**
2811
     * Draw the linear gradient for a gradient layer
2812
     * @param {Element} shape
2813
     * @param {Object} info The object holding the information about the gradient
2814
     */
2815
    addLinearGradient: function( shape, info ) {
2816
        var el = this.targetElement,
2817
            bounds = this.boundsInfo.getBounds(),
2818
            w = bounds.w,
2819
            h = bounds.h,
2820
            fill = shape.fill,
2821
            stops = info.stops,
2822
            stopCount = stops.length,
2823
            PI = Math.PI,
2824
            GradientUtil = PIE.GradientUtil,
2825
            perpendicularIntersect = GradientUtil.perpendicularIntersect,
2826
            distance = GradientUtil.distance,
2827
            metrics = GradientUtil.getGradientMetrics( el, w, h, info ),
2828
            angle = metrics.angle,
2829
            startX = metrics.startX,
2830
            startY = metrics.startY,
2831
            startCornerX = metrics.startCornerX,
2832
            startCornerY = metrics.startCornerY,
2833
            endCornerX = metrics.endCornerX,
2834
            endCornerY = metrics.endCornerY,
2835
            deltaX = metrics.deltaX,
2836
            deltaY = metrics.deltaY,
2837
            lineLength = metrics.lineLength,
2838
            vmlAngle, vmlGradientLength, vmlColors,
2839
            stopPx, vmlOffsetPct,
2840
            p, i, j, before, after;
2841
2842
        // In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's
2843
        // bounding box; for example specifying a 45 deg angle actually results in a gradient
2844
        // drawn diagonally from one corner to its opposite corner, which will only appear to the
2845
        // viewer as 45 degrees if the shape is equilateral.  We adjust for this by taking the x/y deltas
2846
        // between the start and end points, multiply one of them by the shape's aspect ratio,
2847
        // and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly
2848
        // horizontal or vertical then we don't need to do this conversion.
2849
        vmlAngle = ( angle % 90 ) ? Math.atan2( deltaX * w / h, deltaY ) / PI * 180 : ( angle + 90 );
2850
2851
        // VML angles are 180 degrees offset from CSS angles
2852
        vmlAngle += 180;
2853
        vmlAngle = vmlAngle % 360;
2854
2855
        // Add all the stops to the VML 'colors' list, including the first and last stops.
2856
        // For each, we find its pixel offset along the gradient-line; if the offset of a stop is less
2857
        // than that of its predecessor we increase it to be equal. We then map that pixel offset to a
2858
        // percentage along the VML gradient-line, which runs from shape corner to corner.
2859
        p = perpendicularIntersect( startCornerX, startCornerY, angle, endCornerX, endCornerY );
2860
        vmlGradientLength = distance( startCornerX, startCornerY, p[0], p[1] );
2861
        vmlColors = [];
2862
        p = perpendicularIntersect( startX, startY, angle, startCornerX, startCornerY );
2863
        vmlOffsetPct = distance( startX, startY, p[0], p[1] ) / vmlGradientLength * 100;
2864
2865
        // Find the pixel offsets along the CSS3 gradient-line for each stop.
2866
        stopPx = [];
2867
        for( i = 0; i < stopCount; i++ ) {
2868
            stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) :
2869
                         i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
2870
        }
2871
        // Fill in gaps with evenly-spaced offsets
2872
        for( i = 1; i < stopCount; i++ ) {
2873
            if( stopPx[ i ] === null ) {
2874
                before = stopPx[ i - 1 ];
2875
                j = i;
2876
                do {
2877
                    after = stopPx[ ++j ];
2878
                } while( after === null );
2879
                stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
2880
            }
2881
            // Make sure each stop's offset is no less than the one before it
2882
            stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] );
2883
        }
2884
2885
        // Convert to percentage along the VML gradient line and add to the VML 'colors' value
2886
        for( i = 0; i < stopCount; i++ ) {
2887
            vmlColors.push(
2888
                ( vmlOffsetPct + ( stopPx[ i ] / vmlGradientLength * 100 ) ) + '% ' + stops[i].color.colorValue( el )
2889
            );
2890
        }
2891
2892
        // Now, finally, we're ready to render the gradient fill. Set the start and end colors to
2893
        // the first and last stop colors; this just sets outer bounds for the gradient.
2894
        fill['angle'] = vmlAngle;
2895
        fill['type'] = 'gradient';
2896
        fill['method'] = 'sigma';
2897
        fill['color'] = stops[0].color.colorValue( el );
2898
        fill['color2'] = stops[stopCount - 1].color.colorValue( el );
2899
        if( fill['colors'] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?)
2900
            fill['colors'].value = vmlColors.join( ',' );
2901
        } else {
2902
            fill['colors'] = vmlColors.join( ',' );
2903
        }
2904
    },
2905
2906
2907
    /**
2908
     * Hide the actual background image and color of the element.
2909
     */
2910
    hideBackground: function() {
2911
        var rs = this.targetElement.runtimeStyle;
2912
        rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events
2913
        rs.backgroundColor = 'transparent';
2914
    },
2915
2916
    destroy: function() {
2917
        PIE.RendererBase.destroy.call( this );
2918
        var rs = this.targetElement.runtimeStyle;
2919
        rs.backgroundImage = rs.backgroundColor = '';
2920
    }
2921
2922
} );
2923
/**
2924
 * Renderer for element borders.
2925
 * @constructor
2926
 * @param {Element} el The target element
2927
 * @param {Object} styleInfos The StyleInfo objects
2928
 * @param {PIE.RootRenderer} parent
2929
 */
2930
PIE.BorderRenderer = PIE.RendererBase.newRenderer( {
2931
2932
    boxZIndex: 4,
2933
    boxName: 'border',
2934
2935
    needsUpdate: function() {
2936
        var si = this.styleInfos;
2937
        return si.borderInfo.changed() || si.borderRadiusInfo.changed();
2938
    },
2939
2940
    isActive: function() {
2941
        var si = this.styleInfos;
2942
        return si.borderRadiusInfo.isActive() &&
2943
               !si.borderImageInfo.isActive() &&
2944
               si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive
2945
    },
2946
2947
    /**
2948
     * Draw the border shape(s)
2949
     */
2950
    draw: function() {
2951
        var el = this.targetElement,
2952
            props = this.styleInfos.borderInfo.getProps(),
2953
            bounds = this.boundsInfo.getBounds(),
2954
            w = bounds.w,
2955
            h = bounds.h,
2956
            shape, stroke, s,
2957
            segments, seg, i, len;
2958
2959
        if( props ) {
2960
            this.hideBorder();
2961
2962
            segments = this.getBorderSegments( 2 );
2963
            for( i = 0, len = segments.length; i < len; i++) {
2964
                seg = segments[i];
2965
                shape = this.getShape( 'borderPiece' + i, seg.stroke ? 'stroke' : 'fill', this.getBox() );
2966
                shape.coordsize = w * 2 + ',' + h * 2;
2967
                shape.coordorigin = '1,1';
2968
                shape.path = seg.path;
2969
                s = shape.style;
2970
                s.width = w;
2971
                s.height = h;
2972
2973
                shape.filled = !!seg.fill;
2974
                shape.stroked = !!seg.stroke;
2975
                if( seg.stroke ) {
2976
                    stroke = shape.stroke;
2977
                    stroke['weight'] = seg.weight + 'px';
2978
                    stroke.color = seg.color.colorValue( el );
2979
                    stroke['dashstyle'] = seg.stroke === 'dashed' ? '2 2' : seg.stroke === 'dotted' ? '1 1' : 'solid';
2980
                    stroke['linestyle'] = seg.stroke === 'double' && seg.weight > 2 ? 'ThinThin' : 'Single';
2981
                } else {
2982
                    shape.fill.color = seg.fill.colorValue( el );
2983
                }
2984
            }
2985
2986
            // remove any previously-created border shapes which didn't get used above
2987
            while( this.deleteShape( 'borderPiece' + i++ ) ) {}
2988
        }
2989
    },
2990
2991
2992
    /**
2993
     * Get the VML path definitions for the border segment(s).
2994
     * @param {number=} mult If specified, all coordinates will be multiplied by this number
2995
     * @return {Array.<string>}
2996
     */
2997
    getBorderSegments: function( mult ) {
2998
        var el = this.targetElement,
2999
            bounds, elW, elH,
3000
            borderInfo = this.styleInfos.borderInfo,
3001
            segments = [],
3002
            floor, ceil, wT, wR, wB, wL,
3003
            round = Math.round,
3004
            borderProps, radiusInfo, radii, widths, styles, colors;
3005
3006
        if( borderInfo.isActive() ) {
3007
            borderProps = borderInfo.getProps();
3008
3009
            widths = borderProps.widths;
3010
            styles = borderProps.styles;
3011
            colors = borderProps.colors;
3012
3013
            if( borderProps.widthsSame && borderProps.stylesSame && borderProps.colorsSame ) {
3014
                if( colors['t'].alpha() > 0 ) {
3015
                    // shortcut for identical border on all sides - only need 1 stroked shape
3016
                    wT = widths['t'].pixels( el ); //thickness
3017
                    wR = wT / 2; //shrink
3018
                    segments.push( {
3019
                        path: this.getBoxPath( { t: wR, r: wR, b: wR, l: wR }, mult ),
3020
                        stroke: styles['t'],
3021
                        color: colors['t'],
3022
                        weight: wT
3023
                    } );
3024
                }
3025
            }
3026
            else {
3027
                mult = mult || 1;
3028
                bounds = this.boundsInfo.getBounds();
3029
                elW = bounds.w;
3030
                elH = bounds.h;
3031
3032
                wT = round( widths['t'].pixels( el ) );
3033
                wR = round( widths['r'].pixels( el ) );
3034
                wB = round( widths['b'].pixels( el ) );
3035
                wL = round( widths['l'].pixels( el ) );
3036
                var pxWidths = {
3037
                    't': wT,
3038
                    'r': wR,
3039
                    'b': wB,
3040
                    'l': wL
3041
                };
3042
3043
                radiusInfo = this.styleInfos.borderRadiusInfo;
3044
                if( radiusInfo.isActive() ) {
3045
                    radii = this.getRadiiPixels( radiusInfo.getProps() );
3046
                }
3047
3048
                floor = Math.floor;
3049
                ceil = Math.ceil;
3050
3051
                function radius( xy, corner ) {
3052
                    return radii ? radii[ xy ][ corner ] : 0;
3053
                }
3054
3055
                function curve( corner, shrinkX, shrinkY, startAngle, ccw, doMove ) {
3056
                    var rx = radius( 'x', corner),
3057
                        ry = radius( 'y', corner),
3058
                        deg = 65535,
3059
                        isRight = corner.charAt( 1 ) === 'r',
3060
                        isBottom = corner.charAt( 0 ) === 'b';
3061
                    return ( rx > 0 && ry > 0 ) ?
3062
                                ( doMove ? 'al' : 'ae' ) +
3063
                                ( isRight ? ceil( elW - rx ) : floor( rx ) ) * mult + ',' + // center x
3064
                                ( isBottom ? ceil( elH - ry ) : floor( ry ) ) * mult + ',' + // center y
3065
                                ( floor( rx ) - shrinkX ) * mult + ',' + // width
3066
                                ( floor( ry ) - shrinkY ) * mult + ',' + // height
3067
                                ( startAngle * deg ) + ',' + // start angle
3068
                                ( 45 * deg * ( ccw ? 1 : -1 ) // angle change
3069
                            ) : (
3070
                                ( doMove ? 'm' : 'l' ) +
3071
                                ( isRight ? elW - shrinkX : shrinkX ) * mult + ',' +
3072
                                ( isBottom ? elH - shrinkY : shrinkY ) * mult
3073
                            );
3074
                }
3075
3076
                function line( side, shrink, ccw, doMove ) {
3077
                    var
3078
                        start = (
3079
                            side === 't' ?
3080
                                floor( radius( 'x', 'tl') ) * mult + ',' + ceil( shrink ) * mult :
3081
                            side === 'r' ?
3082
                                ceil( elW - shrink ) * mult + ',' + floor( radius( 'y', 'tr') ) * mult :
3083
                            side === 'b' ?
3084
                                ceil( elW - radius( 'x', 'br') ) * mult + ',' + floor( elH - shrink ) * mult :
3085
                            // side === 'l' ?
3086
                                floor( shrink ) * mult + ',' + ceil( elH - radius( 'y', 'bl') ) * mult
3087
                        ),
3088
                        end = (
3089
                            side === 't' ?
3090
                                ceil( elW - radius( 'x', 'tr') ) * mult + ',' + ceil( shrink ) * mult :
3091
                            side === 'r' ?
3092
                                ceil( elW - shrink ) * mult + ',' + ceil( elH - radius( 'y', 'br') ) * mult :
3093
                            side === 'b' ?
3094
                                floor( radius( 'x', 'bl') ) * mult + ',' + floor( elH - shrink ) * mult :
3095
                            // side === 'l' ?
3096
                                floor( shrink ) * mult + ',' + floor( radius( 'y', 'tl') ) * mult
3097
                        );
3098
                    return ccw ? ( doMove ? 'm' + end : '' ) + 'l' + start :
3099
                                 ( doMove ? 'm' + start : '' ) + 'l' + end;
3100
                }
3101
3102
3103
                function addSide( side, sideBefore, sideAfter, cornerBefore, cornerAfter, baseAngle ) {
3104
                    var vert = side === 'l' || side === 'r',
3105
                        sideW = pxWidths[ side ],
3106
                        beforeX, beforeY, afterX, afterY;
3107
3108
                    if( sideW > 0 && styles[ side ] !== 'none' && colors[ side ].alpha() > 0 ) {
3109
                        beforeX = pxWidths[ vert ? side : sideBefore ];
3110
                        beforeY = pxWidths[ vert ? sideBefore : side ];
3111
                        afterX = pxWidths[ vert ? side : sideAfter ];
3112
                        afterY = pxWidths[ vert ? sideAfter : side ];
3113
3114
                        if( styles[ side ] === 'dashed' || styles[ side ] === 'dotted' ) {
3115
                            segments.push( {
3116
                                path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) +
3117
                                      curve( cornerBefore, 0, 0, baseAngle, 1, 0 ),
3118
                                fill: colors[ side ]
3119
                            } );
3120
                            segments.push( {
3121
                                path: line( side, sideW / 2, 0, 1 ),
3122
                                stroke: styles[ side ],
3123
                                weight: sideW,
3124
                                color: colors[ side ]
3125
                            } );
3126
                            segments.push( {
3127
                                path: curve( cornerAfter, afterX, afterY, baseAngle, 0, 1 ) +
3128
                                      curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ),
3129
                                fill: colors[ side ]
3130
                            } );
3131
                        }
3132
                        else {
3133
                            segments.push( {
3134
                                path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) +
3135
                                      line( side, sideW, 0, 0 ) +
3136
                                      curve( cornerAfter, afterX, afterY, baseAngle, 0, 0 ) +
3137
3138
                                      ( styles[ side ] === 'double' && sideW > 2 ?
3139
                                              curve( cornerAfter, afterX - floor( afterX / 3 ), afterY - floor( afterY / 3 ), baseAngle - 45, 1, 0 ) +
3140
                                              line( side, ceil( sideW / 3 * 2 ), 1, 0 ) +
3141
                                              curve( cornerBefore, beforeX - floor( beforeX / 3 ), beforeY - floor( beforeY / 3 ), baseAngle, 1, 0 ) +
3142
                                              'x ' +
3143
                                              curve( cornerBefore, floor( beforeX / 3 ), floor( beforeY / 3 ), baseAngle + 45, 0, 1 ) +
3144
                                              line( side, floor( sideW / 3 ), 1, 0 ) +
3145
                                              curve( cornerAfter, floor( afterX / 3 ), floor( afterY / 3 ), baseAngle, 0, 0 )
3146
                                          : '' ) +
3147
3148
                                      curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ) +
3149
                                      line( side, 0, 1, 0 ) +
3150
                                      curve( cornerBefore, 0, 0, baseAngle, 1, 0 ),
3151
                                fill: colors[ side ]
3152
                            } );
3153
                        }
3154
                    }
3155
                }
3156
3157
                addSide( 't', 'l', 'r', 'tl', 'tr', 90 );
3158
                addSide( 'r', 't', 'b', 'tr', 'br', 0 );
3159
                addSide( 'b', 'r', 'l', 'br', 'bl', -90 );
3160
                addSide( 'l', 'b', 't', 'bl', 'tl', -180 );
3161
            }
3162
        }
3163
3164
        return segments;
3165
    },
3166
3167
    destroy: function() {
3168
        var me = this;
3169
        if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) {
3170
            me.targetElement.runtimeStyle.borderColor = '';
3171
        }
3172
        PIE.RendererBase.destroy.call( me );
3173
    }
3174
3175
3176
} );
3177
/**
3178
 * Renderer for border-image
3179
 * @constructor
3180
 * @param {Element} el The target element
3181
 * @param {Object} styleInfos The StyleInfo objects
3182
 * @param {PIE.RootRenderer} parent
3183
 */
3184
PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( {
3185
3186
    boxZIndex: 5,
3187
    pieceNames: [ 't', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl', 'c' ],
3188
3189
    needsUpdate: function() {
3190
        return this.styleInfos.borderImageInfo.changed();
3191
    },
3192
3193
    isActive: function() {
3194
        return this.styleInfos.borderImageInfo.isActive();
3195
    },
3196
3197
    draw: function() {
3198
        this.getBox(); //make sure pieces are created
3199
3200
        var props = this.styleInfos.borderImageInfo.getProps(),
3201
            borderProps = this.styleInfos.borderInfo.getProps(),
3202
            bounds = this.boundsInfo.getBounds(),
3203
            el = this.targetElement,
3204
            pieces = this.pieces;
3205
3206
        PIE.Util.withImageSize( props.src, function( imgSize ) {
3207
            var elW = bounds.w,
3208
                elH = bounds.h,
3209
                zero = PIE.getLength( '0' ),
3210
                widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
3211
                widthT = widths['t'].pixels( el ),
3212
                widthR = widths['r'].pixels( el ),
3213
                widthB = widths['b'].pixels( el ),
3214
                widthL = widths['l'].pixels( el ),
3215
                slices = props.slice,
3216
                sliceT = slices['t'].pixels( el ),
3217
                sliceR = slices['r'].pixels( el ),
3218
                sliceB = slices['b'].pixels( el ),
3219
                sliceL = slices['l'].pixels( el );
3220
3221
            // Piece positions and sizes
3222
            function setSizeAndPos( piece, w, h, x, y ) {
3223
                var s = pieces[piece].style,
3224
                    max = Math.max;
3225
                s.width = max(w, 0);
3226
                s.height = max(h, 0);
3227
                s.left = x;
3228
                s.top = y;
3229
            }
3230
            setSizeAndPos( 'tl', widthL, widthT, 0, 0 );
3231
            setSizeAndPos( 't', elW - widthL - widthR, widthT, widthL, 0 );
3232
            setSizeAndPos( 'tr', widthR, widthT, elW - widthR, 0 );
3233
            setSizeAndPos( 'r', widthR, elH - widthT - widthB, elW - widthR, widthT );
3234
            setSizeAndPos( 'br', widthR, widthB, elW - widthR, elH - widthB );
3235
            setSizeAndPos( 'b', elW - widthL - widthR, widthB, widthL, elH - widthB );
3236
            setSizeAndPos( 'bl', widthL, widthB, 0, elH - widthB );
3237
            setSizeAndPos( 'l', widthL, elH - widthT - widthB, 0, widthT );
3238
            setSizeAndPos( 'c', elW - widthL - widthR, elH - widthT - widthB, widthL, widthT );
3239
3240
3241
            // image croppings
3242
            function setCrops( sides, crop, val ) {
3243
                for( var i=0, len=sides.length; i < len; i++ ) {
3244
                    pieces[ sides[i] ]['imagedata'][ crop ] = val;
3245
                }
3246
            }
3247
3248
            // corners
3249
            setCrops( [ 'tl', 't', 'tr' ], 'cropBottom', ( imgSize.h - sliceT ) / imgSize.h );
3250
            setCrops( [ 'tl', 'l', 'bl' ], 'cropRight', ( imgSize.w - sliceL ) / imgSize.w );
3251
            setCrops( [ 'bl', 'b', 'br' ], 'cropTop', ( imgSize.h - sliceB ) / imgSize.h );
3252
            setCrops( [ 'tr', 'r', 'br' ], 'cropLeft', ( imgSize.w - sliceR ) / imgSize.w );
3253
3254
            // edges and center
3255
            // TODO right now this treats everything like 'stretch', need to support other schemes
3256
            //if( props.repeat.v === 'stretch' ) {
3257
                setCrops( [ 'l', 'r', 'c' ], 'cropTop', sliceT / imgSize.h );
3258
                setCrops( [ 'l', 'r', 'c' ], 'cropBottom', sliceB / imgSize.h );
3259
            //}
3260
            //if( props.repeat.h === 'stretch' ) {
3261
                setCrops( [ 't', 'b', 'c' ], 'cropLeft', sliceL / imgSize.w );
3262
                setCrops( [ 't', 'b', 'c' ], 'cropRight', sliceR / imgSize.w );
3263
            //}
3264
3265
            // center fill
3266
            pieces['c'].style.display = props.fill ? '' : 'none';
3267
        }, this );
3268
    },
3269
3270
    getBox: function() {
3271
        var box = this.parent.getLayer( this.boxZIndex ),
3272
            s, piece, i,
3273
            pieceNames = this.pieceNames,
3274
            len = pieceNames.length;
3275
3276
        if( !box ) {
3277
            box = doc.createElement( 'border-image' );
3278
            s = box.style;
3279
            s.position = 'absolute';
3280
3281
            this.pieces = {};
3282
3283
            for( i = 0; i < len; i++ ) {
3284
                piece = this.pieces[ pieceNames[i] ] = PIE.Util.createVmlElement( 'rect' );
3285
                piece.appendChild( PIE.Util.createVmlElement( 'imagedata' ) );
3286
                s = piece.style;
3287
                s['behavior'] = 'url(#default#VML)';
3288
                s.position = "absolute";
3289
                s.top = s.left = 0;
3290
                piece['imagedata'].src = this.styleInfos.borderImageInfo.getProps().src;
3291
                piece.stroked = false;
3292
                piece.filled = false;
3293
                box.appendChild( piece );
3294
            }
3295
3296
            this.parent.addLayer( this.boxZIndex, box );
3297
        }
3298
3299
        return box;
3300
    },
3301
3302
    prepareUpdate: function() {
3303
        if (this.isActive()) {
3304
            var me = this,
3305
                el = me.targetElement,
3306
                rs = el.runtimeStyle,
3307
                widths = me.styleInfos.borderImageInfo.getProps().widths;
3308
3309
            // Force border-style to solid so it doesn't collapse
3310
            rs.borderStyle = 'solid';
3311
3312
            // If widths specified in border-image shorthand, override border-width
3313
            // NOTE px units needed here as this gets used by the IE9 renderer too
3314
            if ( widths ) {
3315
                rs.borderTopWidth = widths['t'].pixels( el ) + 'px';
3316
                rs.borderRightWidth = widths['r'].pixels( el ) + 'px';
3317
                rs.borderBottomWidth = widths['b'].pixels( el ) + 'px';
3318
                rs.borderLeftWidth = widths['l'].pixels( el ) + 'px';
3319
            }
3320
3321
            // Make the border transparent
3322
            me.hideBorder();
3323
        }
3324
    },
3325
3326
    destroy: function() {
3327
        var me = this,
3328
            rs = me.targetElement.runtimeStyle;
3329
        rs.borderStyle = '';
3330
        if (me.finalized || !me.styleInfos.borderInfo.isActive()) {
3331
            rs.borderColor = rs.borderWidth = '';
3332
        }
3333
        PIE.RendererBase.destroy.call( this );
3334
    }
3335
3336
} );
3337
/**
3338
 * Renderer for outset box-shadows
3339
 * @constructor
3340
 * @param {Element} el The target element
3341
 * @param {Object} styleInfos The StyleInfo objects
3342
 * @param {PIE.RootRenderer} parent
3343
 */
3344
PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( {
3345
3346
    boxZIndex: 1,
3347
    boxName: 'outset-box-shadow',
3348
3349
    needsUpdate: function() {
3350
        var si = this.styleInfos;
3351
        return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed();
3352
    },
3353
3354
    isActive: function() {
3355
        var boxShadowInfo = this.styleInfos.boxShadowInfo;
3356
        return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0];
3357
    },
3358
3359
    draw: function() {
3360
        var me = this,
3361
            el = this.targetElement,
3362
            box = this.getBox(),
3363
            styleInfos = this.styleInfos,
3364
            shadowInfos = styleInfos.boxShadowInfo.getProps().outset,
3365
            radii = styleInfos.borderRadiusInfo.getProps(),
3366
            len = shadowInfos.length,
3367
            i = len, j,
3368
            bounds = this.boundsInfo.getBounds(),
3369
            w = bounds.w,
3370
            h = bounds.h,
3371
            clipAdjust = PIE.ieVersion === 8 ? 1 : 0, //workaround for IE8 bug where VML leaks out top/left of clip region by 1px
3372
            corners = [ 'tl', 'tr', 'br', 'bl' ], corner,
3373
            shadowInfo, shape, fill, ss, xOff, yOff, spread, blur, shrink, color, alpha, path,
3374
            totalW, totalH, focusX, focusY, isBottom, isRight;
3375
3376
3377
        function getShadowShape( index, corner, xOff, yOff, color, blur, path ) {
3378
            var shape = me.getShape( 'shadow' + index + corner, 'fill', box, len - index ),
3379
                fill = shape.fill;
3380
3381
            // Position and size
3382
            shape['coordsize'] = w * 2 + ',' + h * 2;
3383
            shape['coordorigin'] = '1,1';
3384
3385
            // Color and opacity
3386
            shape['stroked'] = false;
3387
            shape['filled'] = true;
3388
            fill.color = color.colorValue( el );
3389
            if( blur ) {
3390
                fill['type'] = 'gradienttitle'; //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?!
3391
                fill['color2'] = fill.color;
3392
                fill['opacity'] = 0;
3393
            }
3394
3395
            // Path
3396
            shape.path = path;
3397
3398
            // This needs to go last for some reason, to prevent rendering at incorrect size
3399
            ss = shape.style;
3400
            ss.left = xOff;
3401
            ss.top = yOff;
3402
            ss.width = w;
3403
            ss.height = h;
3404
3405
            return shape;
3406
        }
3407
3408
3409
        while( i-- ) {
3410
            shadowInfo = shadowInfos[ i ];
3411
            xOff = shadowInfo.xOffset.pixels( el );
3412
            yOff = shadowInfo.yOffset.pixels( el );
3413
            spread = shadowInfo.spread.pixels( el );
3414
            blur = shadowInfo.blur.pixels( el );
3415
            color = shadowInfo.color;
3416
            // Shape path
3417
            shrink = -spread - blur;
3418
            if( !radii && blur ) {
3419
                // If blurring, use a non-null border radius info object so that getBoxPath will
3420
                // round the corners of the expanded shadow shape rather than squaring them off.
3421
                radii = PIE.BorderRadiusStyleInfo.ALL_ZERO;
3422
            }
3423
            path = this.getBoxPath( { t: shrink, r: shrink, b: shrink, l: shrink }, 2, radii );
3424
3425
            if( blur ) {
3426
                totalW = ( spread + blur ) * 2 + w;
3427
                totalH = ( spread + blur ) * 2 + h;
3428
                focusX = totalW ? blur * 2 / totalW : 0;
3429
                focusY = totalH ? blur * 2 / totalH : 0;
3430
                if( blur - spread > w / 2 || blur - spread > h / 2 ) {
3431
                    // If the blur is larger than half the element's narrowest dimension, we cannot do
3432
                    // this with a single shape gradient, because its focussize would have to be less than
3433
                    // zero which results in ugly artifacts. Instead we create four shapes, each with its
3434
                    // gradient focus past center, and then clip them so each only shows the quadrant
3435
                    // opposite the focus.
3436
                    for( j = 4; j--; ) {
3437
                        corner = corners[j];
3438
                        isBottom = corner.charAt( 0 ) === 'b';
3439
                        isRight = corner.charAt( 1 ) === 'r';
3440
                        shape = getShadowShape( i, corner, xOff, yOff, color, blur, path );
3441
                        fill = shape.fill;
3442
                        fill['focusposition'] = ( isRight ? 1 - focusX : focusX ) + ',' +
3443
                                                ( isBottom ? 1 - focusY : focusY );
3444
                        fill['focussize'] = '0,0';
3445
3446
                        // Clip to show only the appropriate quadrant. Add 1px to the top/left clip values
3447
                        // in IE8 to prevent a bug where IE8 displays one pixel outside the clip region.
3448
                        shape.style.clip = 'rect(' + ( ( isBottom ? totalH / 2 : 0 ) + clipAdjust ) + 'px,' +
3449
                                                     ( isRight ? totalW : totalW / 2 ) + 'px,' +
3450
                                                     ( isBottom ? totalH : totalH / 2 ) + 'px,' +
3451
                                                     ( ( isRight ? totalW / 2 : 0 ) + clipAdjust ) + 'px)';
3452
                    }
3453
                } else {
3454
                    // TODO delete old quadrant shapes if resizing expands past the barrier
3455
                    shape = getShadowShape( i, '', xOff, yOff, color, blur, path );
3456
                    fill = shape.fill;
3457
                    fill['focusposition'] = focusX + ',' + focusY;
3458
                    fill['focussize'] = ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 );
3459
                }
3460
            } else {
3461
                shape = getShadowShape( i, '', xOff, yOff, color, blur, path );
3462
                alpha = color.alpha();
3463
                if( alpha < 1 ) {
3464
                    // shape.style.filter = 'alpha(opacity=' + ( alpha * 100 ) + ')';
3465
                    // ss.filter = 'progid:DXImageTransform.Microsoft.BasicImage(opacity=' + ( alpha  ) + ')';
3466
                    shape.fill.opacity = alpha;
3467
                }
3468
            }
3469
        }
3470
    }
3471
3472
} );
3473
/**
3474
 * Renderer for re-rendering img elements using VML. Kicks in if the img has
3475
 * a border-radius applied, or if the -pie-png-fix flag is set.
3476
 * @constructor
3477
 * @param {Element} el The target element
3478
 * @param {Object} styleInfos The StyleInfo objects
3479
 * @param {PIE.RootRenderer} parent
3480
 */
3481
PIE.ImgRenderer = PIE.RendererBase.newRenderer( {
3482
3483
    boxZIndex: 6,
3484
    boxName: 'imgEl',
3485
3486
    needsUpdate: function() {
3487
        var si = this.styleInfos;
3488
        return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed();
3489
    },
3490
3491
    isActive: function() {
3492
        var si = this.styleInfos;
3493
        return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix();
3494
    },
3495
3496
    draw: function() {
3497
        this._lastSrc = src;
3498
        this.hideActualImg();
3499
3500
        var shape = this.getShape( 'img', 'fill', this.getBox() ),
3501
            fill = shape.fill,
3502
            bounds = this.boundsInfo.getBounds(),
3503
            w = bounds.w,
3504
            h = bounds.h,
3505
            borderProps = this.styleInfos.borderInfo.getProps(),
3506
            borderWidths = borderProps && borderProps.widths,
3507
            el = this.targetElement,
3508
            src = el.src,
3509
            round = Math.round,
3510
            cs = el.currentStyle,
3511
            getLength = PIE.getLength,
3512
            s, zero;
3513
3514
        // In IE6, the BorderRenderer will have hidden the border by moving the border-width to
3515
        // the padding; therefore we want to pretend the borders have no width so they aren't doubled
3516
        // when adding in the current padding value below.
3517
        if( !borderWidths || PIE.ieVersion < 7 ) {
3518
            zero = PIE.getLength( '0' );
3519
            borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero };
3520
        }
3521
3522
        shape.stroked = false;
3523
        fill.type = 'frame';
3524
        fill.src = src;
3525
        fill.position = (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0);
3526
        shape.coordsize = w * 2 + ',' + h * 2;
3527
        shape.coordorigin = '1,1';
3528
        shape.path = this.getBoxPath( {
3529
            t: round( borderWidths['t'].pixels( el ) + getLength( cs.paddingTop ).pixels( el ) ),
3530
            r: round( borderWidths['r'].pixels( el ) + getLength( cs.paddingRight ).pixels( el ) ),
3531
            b: round( borderWidths['b'].pixels( el ) + getLength( cs.paddingBottom ).pixels( el ) ),
3532
            l: round( borderWidths['l'].pixels( el ) + getLength( cs.paddingLeft ).pixels( el ) )
3533
        }, 2 );
3534
        s = shape.style;
3535
        s.width = w;
3536
        s.height = h;
3537
    },
3538
3539
    hideActualImg: function() {
3540
        this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)';
3541
    },
3542
3543
    destroy: function() {
3544
        PIE.RendererBase.destroy.call( this );
3545
        this.targetElement.runtimeStyle.filter = '';
3546
    }
3547
3548
} );
3549
/**
3550
 * Root renderer for IE9; manages the rendering layers in the element's background
3551
 * @param {Element} el The target element
3552
 * @param {Object} styleInfos The StyleInfo objects
3553
 */
3554
PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( {
3555
3556
    updatePos: PIE.emptyFn,
3557
    updateSize: PIE.emptyFn,
3558
    updateVisibility: PIE.emptyFn,
3559
    updateProps: PIE.emptyFn,
3560
3561
    outerCommasRE: /^,+|,+$/g,
3562
    innerCommasRE: /,+/g,
3563
3564
    setBackgroundLayer: function(zIndex, bg) {
3565
        var me = this,
3566
            bgLayers = me._bgLayers || ( me._bgLayers = [] ),
3567
            undef;
3568
        bgLayers[zIndex] = bg || undef;
3569
    },
3570
3571
    finishUpdate: function() {
3572
        var me = this,
3573
            bgLayers = me._bgLayers,
3574
            bg;
3575
        if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) {
3576
            me._lastBg = me.targetElement.runtimeStyle.background = bg;
3577
        }
3578
    },
3579
3580
    destroy: function() {
3581
        this.targetElement.runtimeStyle.background = '';
3582
        delete this._bgLayers;
3583
    }
3584
3585
} );
3586
/**
3587
 * Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients
3588
 * to an equivalent SVG data URI.
3589
 * @constructor
3590
 * @param {Element} el The target element
3591
 * @param {Object} styleInfos The StyleInfo objects
3592
 */
3593
PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( {
3594
3595
    bgLayerZIndex: 1,
3596
3597
    needsUpdate: function() {
3598
        var si = this.styleInfos;
3599
        return si.backgroundInfo.changed();
3600
    },
3601
3602
    isActive: function() {
3603
        var si = this.styleInfos;
3604
        return si.backgroundInfo.isActive() || si.borderImageInfo.isActive();
3605
    },
3606
3607
    draw: function() {
3608
        var me = this,
3609
            props = me.styleInfos.backgroundInfo.getProps(),
3610
            bg, images, i = 0, img, bgAreaSize, bgSize;
3611
3612
        if ( props ) {
3613
            bg = [];
3614
3615
            images = props.bgImages;
3616
            if ( images ) {
3617
                while( img = images[ i++ ] ) {
3618
                    if (img.imgType === 'linear-gradient' ) {
3619
                        bgAreaSize = me.getBgAreaSize( img.bgOrigin );
3620
                        bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels(
3621
                            me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h
3622
                        ),
3623
                        bg.push(
3624
                            'url(data:image/svg+xml,' + escape( me.getGradientSvg( img, bgSize.w, bgSize.h ) ) + ') ' +
3625
                            me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' +
3626
                            ( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' )
3627
                        );
3628
                    } else {
3629
                        bg.push( img.origString );
3630
                    }
3631
                }
3632
            }
3633
3634
            if ( props.color ) {
3635
                bg.push( props.color.val );
3636
            }
3637
3638
            me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(','));
3639
        }
3640
    },
3641
3642
    bgPositionToString: function( bgPosition ) {
3643
        return bgPosition ? bgPosition.tokens.map(function(token) {
3644
            return token.tokenValue;
3645
        }).join(' ') : '0 0';
3646
    },
3647
3648
    getBgAreaSize: function( bgOrigin ) {
3649
        var me = this,
3650
            el = me.targetElement,
3651
            bounds = me.boundsInfo.getBounds(),
3652
            elW = bounds.w,
3653
            elH = bounds.h,
3654
            w = elW,
3655
            h = elH,
3656
            borders, getLength, cs;
3657
3658
        if( bgOrigin !== 'border-box' ) {
3659
            borders = me.styleInfos.borderInfo.getProps();
3660
            if( borders && ( borders = borders.widths ) ) {
3661
                w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el );
3662
                h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el );
3663
            }
3664
        }
3665
3666
        if ( bgOrigin === 'content-box' ) {
3667
            getLength = PIE.getLength;
3668
            cs = el.currentStyle;
3669
            w -= getLength( cs.paddingLeft ).pixels( el ) + getLength( cs.paddingRight ).pixels( el );
3670
            h -= getLength( cs.paddingTop ).pixels( el ) + getLength( cs.paddingBottom ).pixels( el );
3671
        }
3672
3673
        return { w: w, h: h };
3674
    },
3675
3676
    getGradientSvg: function( info, bgWidth, bgHeight ) {
3677
        var el = this.targetElement,
3678
            stopsInfo = info.stops,
3679
            stopCount = stopsInfo.length,
3680
            metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ),
3681
            startX = metrics.startX,
3682
            startY = metrics.startY,
3683
            endX = metrics.endX,
3684
            endY = metrics.endY,
3685
            lineLength = metrics.lineLength,
3686
            stopPx,
3687
            i, j, before, after,
3688
            svg;
3689
3690
        // Find the pixel offsets along the CSS3 gradient-line for each stop.
3691
        stopPx = [];
3692
        for( i = 0; i < stopCount; i++ ) {
3693
            stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) :
3694
                         i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
3695
        }
3696
        // Fill in gaps with evenly-spaced offsets
3697
        for( i = 1; i < stopCount; i++ ) {
3698
            if( stopPx[ i ] === null ) {
3699
                before = stopPx[ i - 1 ];
3700
                j = i;
3701
                do {
3702
                    after = stopPx[ ++j ];
3703
                } while( after === null );
3704
                stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
3705
            }
3706
        }
3707
3708
        svg = [
3709
            '<svg width="' + bgWidth + '" height="' + bgHeight + '" xmlns="http://www.w3.org/2000/svg">' +
3710
                '<defs>' +
3711
                    '<linearGradient id="g" gradientUnits="userSpaceOnUse"' +
3712
                    ' x1="' + ( startX / bgWidth * 100 ) + '%" y1="' + ( startY / bgHeight * 100 ) + '%" x2="' + ( endX / bgWidth * 100 ) + '%" y2="' + ( endY / bgHeight * 100 ) + '%">'
3713
        ];
3714
3715
        // Convert to percentage along the SVG gradient line and add to the stops list
3716
        for( i = 0; i < stopCount; i++ ) {
3717
            svg.push(
3718
                '<stop offset="' + ( stopPx[ i ] / lineLength ) +
3719
                    '" stop-color="' + stopsInfo[i].color.colorValue( el ) +
3720
                    '" stop-opacity="' + stopsInfo[i].color.alpha() + '"/>'
3721
            );
3722
        }
3723
3724
        svg.push(
3725
                    '</linearGradient>' +
3726
                '</defs>' +
3727
                '<rect width="100%" height="100%" fill="url(#g)"/>' +
3728
            '</svg>'
3729
        );
3730
3731
        return svg.join( '' );
3732
    },
3733
3734
    destroy: function() {
3735
        this.parent.setBackgroundLayer( this.bgLayerZIndex );
3736
    }
3737
3738
} );
3739
/**
3740
 * Renderer for border-image
3741
 * @constructor
3742
 * @param {Element} el The target element
3743
 * @param {Object} styleInfos The StyleInfo objects
3744
 * @param {PIE.RootRenderer} parent
3745
 */
3746
PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( {
3747
3748
    REPEAT: 'repeat',
3749
    STRETCH: 'stretch',
3750
    ROUND: 'round',
3751
3752
    bgLayerZIndex: 0,
3753
3754
    needsUpdate: function() {
3755
        return this.styleInfos.borderImageInfo.changed();
3756
    },
3757
3758
    isActive: function() {
3759
        return this.styleInfos.borderImageInfo.isActive();
3760
    },
3761
3762
    draw: function() {
3763
        var me = this,
3764
            props = me.styleInfos.borderImageInfo.getProps(),
3765
            borderProps = me.styleInfos.borderInfo.getProps(),
3766
            bounds = me.boundsInfo.getBounds(),
3767
            repeat = props.repeat,
3768
            repeatH = repeat.h,
3769
            repeatV = repeat.v,
3770
            el = me.targetElement,
3771
            isAsync = 0;
3772
3773
        PIE.Util.withImageSize( props.src, function( imgSize ) {
3774
            var elW = bounds.w,
3775
                elH = bounds.h,
3776
                imgW = imgSize.w,
3777
                imgH = imgSize.h,
3778
3779
                // The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange
3780
                // security exception (perhaps due to cross-origin policy within data URIs?) Therefore we
3781
                // work around this by converting the image data into a data URI itself using a transient
3782
                // canvas. This unfortunately requires the border-image src to be within the same domain,
3783
                // which isn't a limitation in true border-image, so we need to try and find a better fix.
3784
                imgSrc = me.imageToDataURI( props.src, imgW, imgH ),
3785
3786
                REPEAT = me.REPEAT,
3787
                STRETCH = me.STRETCH,
3788
                ROUND = me.ROUND,
3789
                ceil = Math.ceil,
3790
3791
                zero = PIE.getLength( '0' ),
3792
                widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
3793
                widthT = widths['t'].pixels( el ),
3794
                widthR = widths['r'].pixels( el ),
3795
                widthB = widths['b'].pixels( el ),
3796
                widthL = widths['l'].pixels( el ),
3797
                slices = props.slice,
3798
                sliceT = slices['t'].pixels( el ),
3799
                sliceR = slices['r'].pixels( el ),
3800
                sliceB = slices['b'].pixels( el ),
3801
                sliceL = slices['l'].pixels( el ),
3802
                centerW = elW - widthL - widthR,
3803
                middleH = elH - widthT - widthB,
3804
                imgCenterW = imgW - sliceL - sliceR,
3805
                imgMiddleH = imgH - sliceT - sliceB,
3806
3807
                // Determine the size of each tile - 'round' is handled below
3808
                tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT,
3809
                tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR,
3810
                tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB,
3811
                tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL,
3812
3813
                svg,
3814
                patterns = [],
3815
                rects = [],
3816
                i = 0;
3817
3818
            // For 'round', subtract from each tile's size enough so that they fill the space a whole number of times
3819
            if (repeatH === ROUND) {
3820
                tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT);
3821
                tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB);
3822
            }
3823
            if (repeatV === ROUND) {
3824
                tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR);
3825
                tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL);
3826
            }
3827
3828
3829
            // Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched
3830
            // or repeated as the fill of a rect of appropriate size.
3831
            svg = [
3832
                '<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">'
3833
            ];
3834
3835
            function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) {
3836
                patterns.push(
3837
                    '<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' +
3838
                            'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' +
3839
                            'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' +
3840
                            'width="' + tileW + '" height="' + tileH + '">' +
3841
                        '<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' +
3842
                            '<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' +
3843
                        '</svg>' +
3844
                    '</pattern>'
3845
                );
3846
                rects.push(
3847
                    '<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />'
3848
                );
3849
                i++;
3850
            }
3851
            addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left
3852
            addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center
3853
            addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right
3854
            addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left
3855
            if ( props.fill ) { // center fill
3856
                addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH, 
3857
                          tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH );
3858
            }
3859
            addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right
3860
            addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left
3861
            addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center
3862
            addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right
3863
3864
            svg.push(
3865
                    '<defs>' +
3866
                        patterns.join('\n') +
3867
                    '</defs>' +
3868
                    rects.join('\n') +
3869
                '</svg>'
3870
            );
3871
3872
            me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' );
3873
3874
            // If the border-image's src wasn't immediately available, the SVG for its background layer
3875
            // will have been created asynchronously after the main element's update has finished; we'll
3876
            // therefore need to force the root renderer to sync to the final background once finished.
3877
            if( isAsync ) {
3878
                me.parent.finishUpdate();
3879
            }
3880
        }, me );
3881
3882
        isAsync = 1;
3883
    },
3884
3885
    /**
3886
     * Convert a given image to a data URI
3887
     */
3888
    imageToDataURI: (function() {
3889
        var uris = {};
3890
        return function( src, width, height ) {
3891
            var uri = uris[ src ],
3892
                image, canvas;
3893
            if ( !uri ) {
3894
                image = new Image();
3895
                canvas = doc.createElement( 'canvas' );
3896
                image.src = src;
3897
                canvas.width = width;
3898
                canvas.height = height;
3899
                canvas.getContext( '2d' ).drawImage( image, 0, 0 );
3900
                uri = uris[ src ] = canvas.toDataURL();
3901
            }
3902
            return uri;
3903
        }
3904
    })(),
3905
3906
    prepareUpdate: PIE.BorderImageRenderer.prototype.prepareUpdate,
3907
3908
    destroy: function() {
3909
        var me = this,
3910
            rs = me.targetElement.runtimeStyle;
3911
        me.parent.setBackgroundLayer( me.bgLayerZIndex );
3912
        rs.borderColor = rs.borderStyle = rs.borderWidth = '';
3913
    }
3914
3915
} );
3916
3917
PIE.Element = (function() {
3918
3919
    var wrappers = {},
3920
        lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init',
3921
        pollCssProp = PIE.CSS_PREFIX + 'poll',
3922
        trackActiveCssProp = PIE.CSS_PREFIX + 'track-active',
3923
        trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover',
3924
        hoverClass = PIE.CLASS_PREFIX + 'hover',
3925
        activeClass = PIE.CLASS_PREFIX + 'active',
3926
        focusClass = PIE.CLASS_PREFIX + 'focus',
3927
        firstChildClass = PIE.CLASS_PREFIX + 'first-child',
3928
        ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 },
3929
        classNameRegExes = {},
3930
        dummyArray = [];
3931
3932
3933
    function addClass( el, className ) {
3934
        el.className += ' ' + className;
3935
    }
3936
3937
    function removeClass( el, className ) {
3938
        var re = classNameRegExes[ className ] ||
3939
            ( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) );
3940
        el.className = el.className.replace( re, '' );
3941
    }
3942
3943
    function delayAddClass( el, className /*, className2*/ ) {
3944
        var classes = dummyArray.slice.call( arguments, 1 ),
3945
            i = classes.length;
3946
        setTimeout( function() {
3947
            if( el ) {
3948
                while( i-- ) {
3949
                    addClass( el, classes[ i ] );
3950
                }
3951
            }
3952
        }, 0 );
3953
    }
3954
3955
    function delayRemoveClass( el, className /*, className2*/ ) {
3956
        var classes = dummyArray.slice.call( arguments, 1 ),
3957
            i = classes.length;
3958
        setTimeout( function() {
3959
            if( el ) {
3960
                while( i-- ) {
3961
                    removeClass( el, classes[ i ] );
3962
                }
3963
            }
3964
        }, 0 );
3965
    }
3966
3967
3968
3969
    function Element( el ) {
3970
        var renderers,
3971
            rootRenderer,
3972
            boundsInfo = new PIE.BoundsInfo( el ),
3973
            styleInfos,
3974
            styleInfosArr,
3975
            initializing,
3976
            initialized,
3977
            eventsAttached,
3978
            eventListeners = [],
3979
            delayed,
3980
            destroyed,
3981
            poll;
3982
3983
        /**
3984
         * Initialize PIE for this element.
3985
         */
3986
        function init() {
3987
            if( !initialized ) {
3988
                var docEl,
3989
                    bounds,
3990
                    ieDocMode = PIE.ieDocMode,
3991
                    cs = el.currentStyle,
3992
                    lazy = cs.getAttribute( lazyInitCssProp ) === 'true',
3993
                    trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false',
3994
                    trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false',
3995
                    childRenderers;
3996
3997
                // Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll
3998
                poll = cs.getAttribute( pollCssProp );
3999
                poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true';
4000
4001
                // Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes
4002
                // after load, but make sure it only gets called the first time through to avoid recursive calls to init().
4003
                if( !initializing ) {
4004
                    initializing = 1;
4005
                    el.runtimeStyle.zoom = 1;
4006
                    initFirstChildPseudoClass();
4007
                }
4008
4009
                boundsInfo.lock();
4010
4011
                // If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization
4012
                if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) &&
4013
                        ( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) {
4014
                    if( !delayed ) {
4015
                        delayed = 1;
4016
                        PIE.OnScroll.observe( init );
4017
                    }
4018
                } else {
4019
                    initialized = 1;
4020
                    delayed = initializing = 0;
4021
                    PIE.OnScroll.unobserve( init );
4022
4023
                    // Create the style infos and renderers
4024
                    if ( ieDocMode === 9 ) {
4025
                        styleInfos = {
4026
                            backgroundInfo: new PIE.BackgroundStyleInfo( el ),
4027
                            borderImageInfo: new PIE.BorderImageStyleInfo( el ),
4028
                            borderInfo: new PIE.BorderStyleInfo( el )
4029
                        };
4030
                        styleInfosArr = [
4031
                            styleInfos.backgroundInfo,
4032
                            styleInfos.borderImageInfo
4033
                        ];
4034
                        rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos );
4035
                        childRenderers = [
4036
                            new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4037
                            new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
4038
                        ];
4039
                    } else {
4040
4041
                        styleInfos = {
4042
                            backgroundInfo: new PIE.BackgroundStyleInfo( el ),
4043
                            borderInfo: new PIE.BorderStyleInfo( el ),
4044
                            borderImageInfo: new PIE.BorderImageStyleInfo( el ),
4045
                            borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ),
4046
                            boxShadowInfo: new PIE.BoxShadowStyleInfo( el ),
4047
                            visibilityInfo: new PIE.VisibilityStyleInfo( el )
4048
                        };
4049
                        styleInfosArr = [
4050
                            styleInfos.backgroundInfo,
4051
                            styleInfos.borderInfo,
4052
                            styleInfos.borderImageInfo,
4053
                            styleInfos.borderRadiusInfo,
4054
                            styleInfos.boxShadowInfo,
4055
                            styleInfos.visibilityInfo
4056
                        ];
4057
                        rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos );
4058
                        childRenderers = [
4059
                            new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4060
                            new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4061
                            //new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4062
                            new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4063
                            new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
4064
                        ];
4065
                        if( el.tagName === 'IMG' ) {
4066
                            childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) );
4067
                        }
4068
                        rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way?
4069
                    }
4070
                    renderers = [ rootRenderer ].concat( childRenderers );
4071
4072
                    // Add property change listeners to ancestors if requested
4073
                    initAncestorEventListeners();
4074
4075
                    // Add to list of polled elements in IE8
4076
                    if( poll ) {
4077
                        PIE.Heartbeat.observe( update );
4078
                        PIE.Heartbeat.run();
4079
                    }
4080
4081
                    // Trigger rendering
4082
                    update( 1 );
4083
                }
4084
4085
                if( !eventsAttached ) {
4086
                    eventsAttached = 1;
4087
                    if( ieDocMode < 9 ) {
4088
                        addListener( el, 'onmove', handleMoveOrResize );
4089
                    }
4090
                    addListener( el, 'onresize', handleMoveOrResize );
4091
                    addListener( el, 'onpropertychange', propChanged );
4092
                    if( trackHover ) {
4093
                        addListener( el, 'onmouseenter', mouseEntered );
4094
                    }
4095
                    if( trackHover || trackActive ) {
4096
                        addListener( el, 'onmouseleave', mouseLeft );
4097
                    }
4098
                    if( trackActive ) {
4099
                        addListener( el, 'onmousedown', mousePressed );
4100
                    }
4101
                    if( el.tagName in PIE.focusableElements ) {
4102
                        addListener( el, 'onfocus', focused );
4103
                        addListener( el, 'onblur', blurred );
4104
                    }
4105
                    PIE.OnResize.observe( handleMoveOrResize );
4106
4107
                    PIE.OnUnload.observe( removeEventListeners );
4108
                }
4109
4110
                boundsInfo.unlock();
4111
            }
4112
        }
4113
4114
4115
4116
4117
        /**
4118
         * Event handler for onmove and onresize events. Invokes update() only if the element's
4119
         * bounds have previously been calculated, to prevent multiple runs during page load when
4120
         * the element has no initial CSS3 properties.
4121
         */
4122
        function handleMoveOrResize() {
4123
            if( boundsInfo && boundsInfo.hasBeenQueried() ) {
4124
                update();
4125
            }
4126
        }
4127
4128
4129
        /**
4130
         * Update position and/or size as necessary. Both move and resize events call
4131
         * this rather than the updatePos/Size functions because sometimes, particularly
4132
         * during page load, one will fire but the other won't.
4133
         */
4134
        function update( force ) {
4135
            if( !destroyed ) {
4136
                if( initialized ) {
4137
                    var i, len = renderers.length;
4138
4139
                    lockAll();
4140
                    for( i = 0; i < len; i++ ) {
4141
                        renderers[i].prepareUpdate();
4142
                    }
4143
                    if( force || boundsInfo.positionChanged() ) {
4144
                        /* TODO just using getBoundingClientRect (used internally by BoundsInfo) for detecting
4145
                           position changes may not always be accurate; it's possible that
4146
                           an element will actually move relative to its positioning parent, but its position
4147
                           relative to the viewport will stay the same. Need to come up with a better way to
4148
                           track movement. The most accurate would be the same logic used in RootRenderer.updatePos()
4149
                           but that is a more expensive operation since it does some DOM walking, and we want this
4150
                           check to be as fast as possible. */
4151
                        for( i = 0; i < len; i++ ) {
4152
                            renderers[i].updatePos();
4153
                        }
4154
                    }
4155
                    if( force || boundsInfo.sizeChanged() ) {
4156
                        for( i = 0; i < len; i++ ) {
4157
                            renderers[i].updateSize();
4158
                        }
4159
                    }
4160
                    rootRenderer.finishUpdate();
4161
                    unlockAll();
4162
                }
4163
                else if( !initializing ) {
4164
                    init();
4165
                }
4166
            }
4167
        }
4168
4169
        /**
4170
         * Handle property changes to trigger update when appropriate.
4171
         */
4172
        function propChanged() {
4173
            var i, len = renderers.length,
4174
                renderer,
4175
                e = event;
4176
4177
            // Some elements like <table> fire onpropertychange events for old-school background properties
4178
            // ('background', 'bgColor') when runtimeStyle background properties are changed, which
4179
            // results in an infinite loop; therefore we filter out those property names. Also, 'display'
4180
            // is ignored because size calculations don't work correctly immediately when its onpropertychange
4181
            // event fires, and because it will trigger an onresize event anyway.
4182
            if( !destroyed && !( e && e.propertyName in ignorePropertyNames ) ) {
4183
                if( initialized ) {
4184
                    lockAll();
4185
                    for( i = 0; i < len; i++ ) {
4186
                        renderers[i].prepareUpdate();
4187
                    }
4188
                    for( i = 0; i < len; i++ ) {
4189
                        renderer = renderers[i];
4190
                        // Make sure position is synced if the element hasn't already been rendered.
4191
                        // TODO this feels sloppy - look into merging propChanged and update functions
4192
                        if( !renderer.isPositioned ) {
4193
                            renderer.updatePos();
4194
                        }
4195
                        if( renderer.needsUpdate() ) {
4196
                            renderer.updateProps();
4197
                        }
4198
                    }
4199
                    rootRenderer.finishUpdate();
4200
                    unlockAll();
4201
                }
4202
                else if( !initializing ) {
4203
                    init();
4204
                }
4205
            }
4206
        }
4207
4208
4209
        /**
4210
         * Handle mouseenter events. Adds a custom class to the element to allow IE6 to add
4211
         * hover styles to non-link elements, and to trigger a propertychange update.
4212
         */
4213
        function mouseEntered() {
4214
            //must delay this because the mouseenter event fires before the :hover styles are added.
4215
            delayAddClass( el, hoverClass );
4216
        }
4217
4218
        /**
4219
         * Handle mouseleave events
4220
         */
4221
        function mouseLeft() {
4222
            //must delay this because the mouseleave event fires before the :hover styles are removed.
4223
            delayRemoveClass( el, hoverClass, activeClass );
4224
        }
4225
4226
        /**
4227
         * Handle mousedown events. Adds a custom class to the element to allow IE6 to add
4228
         * active styles to non-link elements, and to trigger a propertychange update.
4229
         */
4230
        function mousePressed() {
4231
            //must delay this because the mousedown event fires before the :active styles are added.
4232
            delayAddClass( el, activeClass );
4233
4234
            // listen for mouseups on the document; can't just be on the element because the user might
4235
            // have dragged out of the element while the mouse button was held down
4236
            PIE.OnMouseup.observe( mouseReleased );
4237
        }
4238
4239
        /**
4240
         * Handle mouseup events
4241
         */
4242
        function mouseReleased() {
4243
            //must delay this because the mouseup event fires before the :active styles are removed.
4244
            delayRemoveClass( el, activeClass );
4245
4246
            PIE.OnMouseup.unobserve( mouseReleased );
4247
        }
4248
4249
        /**
4250
         * Handle focus events. Adds a custom class to the element to trigger a propertychange update.
4251
         */
4252
        function focused() {
4253
            //must delay this because the focus event fires before the :focus styles are added.
4254
            delayAddClass( el, focusClass );
4255
        }
4256
4257
        /**
4258
         * Handle blur events
4259
         */
4260
        function blurred() {
4261
            //must delay this because the blur event fires before the :focus styles are removed.
4262
            delayRemoveClass( el, focusClass );
4263
        }
4264
4265
4266
        /**
4267
         * Handle property changes on ancestors of the element; see initAncestorEventListeners()
4268
         * which adds these listeners as requested with the -pie-watch-ancestors CSS property.
4269
         */
4270
        function ancestorPropChanged() {
4271
            var name = event.propertyName;
4272
            if( name === 'className' || name === 'id' ) {
4273
                propChanged();
4274
            }
4275
        }
4276
4277
        function lockAll() {
4278
            boundsInfo.lock();
4279
            for( var i = styleInfosArr.length; i--; ) {
4280
                styleInfosArr[i].lock();
4281
            }
4282
        }
4283
4284
        function unlockAll() {
4285
            for( var i = styleInfosArr.length; i--; ) {
4286
                styleInfosArr[i].unlock();
4287
            }
4288
            boundsInfo.unlock();
4289
        }
4290
4291
4292
        function addListener( targetEl, type, handler ) {
4293
            targetEl.attachEvent( type, handler );
4294
            eventListeners.push( [ targetEl, type, handler ] );
4295
        }
4296
4297
        /**
4298
         * Remove all event listeners from the element and any monitored ancestors.
4299
         */
4300
        function removeEventListeners() {
4301
            if (eventsAttached) {
4302
                var i = eventListeners.length,
4303
                    listener;
4304
4305
                while( i-- ) {
4306
                    listener = eventListeners[ i ];
4307
                    listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] );
4308
                }
4309
4310
                PIE.OnUnload.unobserve( removeEventListeners );
4311
                eventsAttached = 0;
4312
                eventListeners = [];
4313
            }
4314
        }
4315
4316
4317
        /**
4318
         * Clean everything up when the behavior is removed from the element, or the element
4319
         * is manually destroyed.
4320
         */
4321
        function destroy() {
4322
            if( !destroyed ) {
4323
                var i, len;
4324
4325
                removeEventListeners();
4326
4327
                destroyed = 1;
4328
4329
                // destroy any active renderers
4330
                if( renderers ) {
4331
                    for( i = 0, len = renderers.length; i < len; i++ ) {
4332
                        renderers[i].finalized = 1;
4333
                        renderers[i].destroy();
4334
                    }
4335
                }
4336
4337
                // Remove from list of polled elements in IE8
4338
                if( poll ) {
4339
                    PIE.Heartbeat.unobserve( update );
4340
                }
4341
                // Stop onresize listening
4342
                PIE.OnResize.unobserve( update );
4343
4344
                // Kill references
4345
                renderers = boundsInfo = styleInfos = styleInfosArr = el = null;
4346
            }
4347
        }
4348
4349
4350
        /**
4351
         * If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and
4352
         * other event listeners to ancestor(s) of the element so we can pick up style changes
4353
         * based on CSS rules using descendant selectors.
4354
         */
4355
        function initAncestorEventListeners() {
4356
            var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ),
4357
                i, a;
4358
            if( watch ) {
4359
                watch = parseInt( watch, 10 );
4360
                i = 0;
4361
                a = el.parentNode;
4362
                while( a && ( watch === 'NaN' || i++ < watch ) ) {
4363
                    addListener( a, 'onpropertychange', ancestorPropChanged );
4364
                    addListener( a, 'onmouseenter', mouseEntered );
4365
                    addListener( a, 'onmouseleave', mouseLeft );
4366
                    addListener( a, 'onmousedown', mousePressed );
4367
                    if( a.tagName in PIE.focusableElements ) {
4368
                        addListener( a, 'onfocus', focused );
4369
                        addListener( a, 'onblur', blurred );
4370
                    }
4371
                    a = a.parentNode;
4372
                }
4373
            }
4374
        }
4375
4376
4377
        /**
4378
         * If the target element is a first child, add a pie_first-child class to it. This allows using
4379
         * the added class as a workaround for the fact that PIE's rendering element breaks the :first-child
4380
         * pseudo-class selector.
4381
         */
4382
        function initFirstChildPseudoClass() {
4383
            var tmpEl = el,
4384
                isFirst = 1;
4385
            while( tmpEl = tmpEl.previousSibling ) {
4386
                if( tmpEl.nodeType === 1 ) {
4387
                    isFirst = 0;
4388
                    break;
4389
                }
4390
            }
4391
            if( isFirst ) {
4392
                addClass( el, firstChildClass );
4393
            }
4394
        }
4395
4396
4397
        // These methods are all already bound to this instance so there's no need to wrap them
4398
        // in a closure to maintain the 'this' scope object when calling them.
4399
        this.init = init;
4400
        this.update = update;
4401
        this.destroy = destroy;
4402
        this.el = el;
4403
    }
4404
4405
    Element.getInstance = function( el ) {
4406
        var id = PIE.Util.getUID( el );
4407
        return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) );
4408
    };
4409
4410
    Element.destroy = function( el ) {
4411
        var id = PIE.Util.getUID( el ),
4412
            wrapper = wrappers[ id ];
4413
        if( wrapper ) {
4414
            wrapper.destroy();
4415
            delete wrappers[ id ];
4416
        }
4417
    };
4418
4419
    Element.destroyAll = function() {
4420
        var els = [], wrapper;
4421
        if( wrappers ) {
4422
            for( var w in wrappers ) {
4423
                if( wrappers.hasOwnProperty( w ) ) {
4424
                    wrapper = wrappers[ w ];
4425
                    els.push( wrapper.el );
4426
                    wrapper.destroy();
4427
                }
4428
            }
4429
            wrappers = {};
4430
        }
4431
        return els;
4432
    };
4433
4434
    return Element;
4435
})();
4436
4437
/*
4438
 * This file exposes the public API for invoking PIE.
4439
 */
4440
4441
4442
/**
4443
 * @property supportsVML
4444
 * True if the current IE browser environment has a functioning VML engine. Should be true
4445
 * in most IEs, but in rare cases may be false. If false, PIE will exit immediately when
4446
 * attached to an element; this property may be used for debugging or by external scripts
4447
 * to perform some special action when VML support is absent.
4448
 * @type {boolean}
4449
 */
4450
PIE[ 'supportsVML' ] = PIE.supportsVML;
4451
4452
4453
/**
4454
 * Programatically attach PIE to a single element.
4455
 * @param {Element} el
4456
 */
4457
PIE[ 'attach' ] = function( el ) {
4458
    if (PIE.ieDocMode < 10 && PIE.supportsVML) {
4459
        PIE.Element.getInstance( el ).init();
4460
    }
4461
};
4462
4463
4464
/**
4465
 * Programatically detach PIE from a single element.
4466
 * @param {Element} el
4467
 */
4468
PIE[ 'detach' ] = function( el ) {
4469
    PIE.Element.destroy( el );
4470
};
4471
4472
4473
} // if( !PIE )
4474
})();