/lenasys/trunk

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/lenasys/trunk

« back to all changes in this revision

Viewing changes to etc/PIE/PIE_uncompressed.htc

  • Committer: Erik Wikström
  • Date: 2013-04-09 09:09:31 UTC
  • mfrom: (21 lenasys)
  • mto: (21.1.1 lenasys)
  • mto: This revision was merged to the branch mainline in revision 22.
  • Revision ID: wikxen@gmail.com-20130409090931-9jcs9kzg8et0912g
Remerged! Changed password hashes to VARCHAR(32)

Show diffs side-by-side

added added

removed removed

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