1// script.aculo.us effects.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
2
3// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
4// Contributors:
5//  Justin Palmer (http://encytemedia.com/)
6//  Mark Pilgrim (http://diveintomark.org/)
7//  Martin Bialasinki
8//
9// script.aculo.us is freely distributable under the terms of an MIT-style license.
10// For details, see the script.aculo.us web site: http://script.aculo.us/
11
12// converts rgb() and #xxx to #xxxxxx format,
13// returns self (or first argument) if not convertable
14String.prototype.parseColor = function() {
15  var color = '#';
16  if (this.slice(0,4) == 'rgb(') {
17    var cols = this.slice(4,this.length-1).split(',');
18    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
19  } else {
20    if (this.slice(0,1) == '#') {
21      if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
22      if (this.length==7) color = this.toLowerCase();
23    }
24  }
25  return (color.length==7 ? color : (arguments[0] || this));
26};
27
28/*--------------------------------------------------------------------------*/
29
30Element.collectTextNodes = function(element) {
31  return $A($(element).childNodes).collect( function(node) {
32    return (node.nodeType==3 ? node.nodeValue :
33      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
34  }).flatten().join('');
35};
36
37Element.collectTextNodesIgnoreClass = function(element, className) {
38  return $A($(element).childNodes).collect( function(node) {
39    return (node.nodeType==3 ? node.nodeValue :
40      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
41        Element.collectTextNodesIgnoreClass(node, className) : ''));
42  }).flatten().join('');
43};
44
45Element.setContentZoom = function(element, percent) {
46  element = $(element);
47  element.setStyle({fontSize: (percent/100) + 'em'});
48  if (Prototype.Browser.WebKit) window.scrollBy(0,0);
49  return element;
50};
51
52Element.getInlineOpacity = function(element){
53  return $(element).style.opacity || '';
54};
55
56Element.forceRerendering = function(element) {
57  try {
58    element = $(element);
59    var n = document.createTextNode(' ');
60    element.appendChild(n);
61    element.removeChild(n);
62  } catch(e) { }
63};
64
65/*--------------------------------------------------------------------------*/
66
67var Effect = {
68  _elementDoesNotExistError: {
69    name: 'ElementDoesNotExistError',
70    message: 'The specified DOM element does not exist, but is required for this effect to operate'
71  },
72  Transitions: {
73    linear: Prototype.K,
74    sinoidal: function(pos) {
75      return (-Math.cos(pos*Math.PI)/2) + .5;
76    },
77    reverse: function(pos) {
78      return 1-pos;
79    },
80    flicker: function(pos) {
81      var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
82      return pos > 1 ? 1 : pos;
83    },
84    wobble: function(pos) {
85      return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
86    },
87    pulse: function(pos, pulses) {
88      return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
89    },
90    spring: function(pos) {
91      return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
92    },
93    none: function(pos) {
94      return 0;
95    },
96    full: function(pos) {
97      return 1;
98    }
99  },
100  DefaultOptions: {
101    duration:   1.0,   // seconds
102    fps:        100,   // 100= assume 66fps max.
103    sync:       false, // true for combining
104    from:       0.0,
105    to:         1.0,
106    delay:      0.0,
107    queue:      'parallel'
108  },
109  tagifyText: function(element) {
110    var tagifyStyle = 'position:relative';
111    if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
112
113    element = $(element);
114    $A(element.childNodes).each( function(child) {
115      if (child.nodeType==3) {
116        child.nodeValue.toArray().each( function(character) {
117          element.insertBefore(
118            new Element('span', {style: tagifyStyle}).update(
119              character == ' ' ? String.fromCharCode(160) : character),
120              child);
121        });
122        Element.remove(child);
123      }
124    });
125  },
126  multiple: function(element, effect) {
127    var elements;
128    if (((typeof element == 'object') ||
129        Object.isFunction(element)) &&
130       (element.length))
131      elements = element;
132    else
133      elements = $(element).childNodes;
134
135    var options = Object.extend({
136      speed: 0.1,
137      delay: 0.0
138    }, arguments[2] || { });
139    var masterDelay = options.delay;
140
141    $A(elements).each( function(element, index) {
142      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
143    });
144  },
145  PAIRS: {
146    'slide':  ['SlideDown','SlideUp'],
147    'blind':  ['BlindDown','BlindUp'],
148    'appear': ['Appear','Fade']
149  },
150  toggle: function(element, effect, options) {
151    element = $(element);
152    effect  = (effect || 'appear').toLowerCase();
153
154    return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({
155      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
156    }, options || {}));
157  }
158};
159
160Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;
161
162/* ------------- core effects ------------- */
163
164Effect.ScopedQueue = Class.create(Enumerable, {
165  initialize: function() {
166    this.effects  = [];
167    this.interval = null;
168  },
169  _each: function(iterator) {
170    this.effects._each(iterator);
171  },
172  add: function(effect) {
173    var timestamp = new Date().getTime();
174
175    var position = Object.isString(effect.options.queue) ?
176      effect.options.queue : effect.options.queue.position;
177
178    switch(position) {
179      case 'front':
180        // move unstarted effects after this effect
181        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
182            e.startOn  += effect.finishOn;
183            e.finishOn += effect.finishOn;
184          });
185        break;
186      case 'with-last':
187        timestamp = this.effects.pluck('startOn').max() || timestamp;
188        break;
189      case 'end':
190        // start effect after last queued effect has finished
191        timestamp = this.effects.pluck('finishOn').max() || timestamp;
192        break;
193    }
194
195    effect.startOn  += timestamp;
196    effect.finishOn += timestamp;
197
198    if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
199      this.effects.push(effect);
200
201    if (!this.interval)
202      this.interval = setInterval(this.loop.bind(this), 15);
203  },
204  remove: function(effect) {
205    this.effects = this.effects.reject(function(e) { return e==effect });
206    if (this.effects.length == 0) {
207      clearInterval(this.interval);
208      this.interval = null;
209    }
210  },
211  loop: function() {
212    var timePos = new Date().getTime();
213    for(var i=0, len=this.effects.length;i<len;i++)
214      this.effects[i] && this.effects[i].loop(timePos);
215  }
216});
217
218Effect.Queues = {
219  instances: $H(),
220  get: function(queueName) {
221    if (!Object.isString(queueName)) return queueName;
222
223    return this.instances.get(queueName) ||
224      this.instances.set(queueName, new Effect.ScopedQueue());
225  }
226};
227Effect.Queue = Effect.Queues.get('global');
228
229Effect.Base = Class.create({
230  position: null,
231  start: function(options) {
232    if (options && options.transition === false) options.transition = Effect.Transitions.linear;
233    this.options      = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
234    this.currentFrame = 0;
235    this.state        = 'idle';
236    this.startOn      = this.options.delay*1000;
237    this.finishOn     = this.startOn+(this.options.duration*1000);
238    this.fromToDelta  = this.options.to-this.options.from;
239    this.totalTime    = this.finishOn-this.startOn;
240    this.totalFrames  = this.options.fps*this.options.duration;
241
242    this.render = (function() {
243      function dispatch(effect, eventName) {
244        if (effect.options[eventName + 'Internal'])
245          effect.options[eventName + 'Internal'](effect);
246        if (effect.options[eventName])
247          effect.options[eventName](effect);
248      }
249
250      return function(pos) {
251        if (this.state === "idle") {
252          this.state = "running";
253          dispatch(this, 'beforeSetup');
254          if (this.setup) this.setup();
255          dispatch(this, 'afterSetup');
256        }
257        if (this.state === "running") {
258          pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
259          this.position = pos;
260          dispatch(this, 'beforeUpdate');
261          if (this.update) this.update(pos);
262          dispatch(this, 'afterUpdate');
263        }
264      };
265    })();
266
267    this.event('beforeStart');
268    if (!this.options.sync)
269      Effect.Queues.get(Object.isString(this.options.queue) ?
270        'global' : this.options.queue.scope).add(this);
271  },
272  loop: function(timePos) {
273    if (timePos >= this.startOn) {
274      if (timePos >= this.finishOn) {
275        this.render(1.0);
276        this.cancel();
277        this.event('beforeFinish');
278        if (this.finish) this.finish();
279        this.event('afterFinish');
280        return;
281      }
282      var pos   = (timePos - this.startOn) / this.totalTime,
283          frame = (pos * this.totalFrames).round();
284      if (frame > this.currentFrame) {
285        this.render(pos);
286        this.currentFrame = frame;
287      }
288    }
289  },
290  cancel: function() {
291    if (!this.options.sync)
292      Effect.Queues.get(Object.isString(this.options.queue) ?
293        'global' : this.options.queue.scope).remove(this);
294    this.state = 'finished';
295  },
296  event: function(eventName) {
297    if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
298    if (this.options[eventName]) this.options[eventName](this);
299  },
300  inspect: function() {
301    var data = $H();
302    for(property in this)
303      if (!Object.isFunction(this[property])) data.set(property, this[property]);
304    return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
305  }
306});
307
308Effect.Parallel = Class.create(Effect.Base, {
309  initialize: function(effects) {
310    this.effects = effects || [];
311    this.start(arguments[1]);
312  },
313  update: function(position) {
314    this.effects.invoke('render', position);
315  },
316  finish: function(position) {
317    this.effects.each( function(effect) {
318      effect.render(1.0);
319      effect.cancel();
320      effect.event('beforeFinish');
321      if (effect.finish) effect.finish(position);
322      effect.event('afterFinish');
323    });
324  }
325});
326
327Effect.Tween = Class.create(Effect.Base, {
328  initialize: function(object, from, to) {
329    object = Object.isString(object) ? $(object) : object;
330    var args = $A(arguments), method = args.last(),
331      options = args.length == 5 ? args[3] : null;
332    this.method = Object.isFunction(method) ? method.bind(object) :
333      Object.isFunction(object[method]) ? object[method].bind(object) :
334      function(value) { object[method] = value };
335    this.start(Object.extend({ from: from, to: to }, options || { }));
336  },
337  update: function(position) {
338    this.method(position);
339  }
340});
341
342Effect.Event = Class.create(Effect.Base, {
343  initialize: function() {
344    this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
345  },
346  update: Prototype.emptyFunction
347});
348
349Effect.Opacity = Class.create(Effect.Base, {
350  initialize: function(element) {
351    this.element = $(element);
352    if (!this.element) throw(Effect._elementDoesNotExistError);
353    // make this work on IE on elements without 'layout'
354    if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
355      this.element.setStyle({zoom: 1});
356    var options = Object.extend({
357      from: this.element.getOpacity() || 0.0,
358      to:   1.0
359    }, arguments[1] || { });
360    this.start(options);
361  },
362  update: function(position) {
363    this.element.setOpacity(position);
364  }
365});
366
367Effect.Move = Class.create(Effect.Base, {
368  initialize: function(element) {
369    this.element = $(element);
370    if (!this.element) throw(Effect._elementDoesNotExistError);
371    var options = Object.extend({
372      x:    0,
373      y:    0,
374      mode: 'relative'
375    }, arguments[1] || { });
376    this.start(options);
377  },
378  setup: function() {
379    this.element.makePositioned();
380    this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
381    this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
382    if (this.options.mode == 'absolute') {
383      this.options.x = this.options.x - this.originalLeft;
384      this.options.y = this.options.y - this.originalTop;
385    }
386  },
387  update: function(position) {
388    this.element.setStyle({
389      left: (this.options.x  * position + this.originalLeft).round() + 'px',
390      top:  (this.options.y  * position + this.originalTop).round()  + 'px'
391    });
392  }
393});
394
395// for backwards compatibility
396Effect.MoveBy = function(element, toTop, toLeft) {
397  return new Effect.Move(element,
398    Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
399};
400
401Effect.Scale = Class.create(Effect.Base, {
402  initialize: function(element, percent) {
403    this.element = $(element);
404    if (!this.element) throw(Effect._elementDoesNotExistError);
405    var options = Object.extend({
406      scaleX: true,
407      scaleY: true,
408      scaleContent: true,
409      scaleFromCenter: false,
410      scaleMode: 'box',        // 'box' or 'contents' or { } with provided values
411      scaleFrom: 100.0,
412      scaleTo:   percent
413    }, arguments[2] || { });
414    this.start(options);
415  },
416  setup: function() {
417    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
418    this.elementPositioning = this.element.getStyle('position');
419
420    this.originalStyle = { };
421    ['top','left','width','height','fontSize'].each( function(k) {
422      this.originalStyle[k] = this.element.style[k];
423    }.bind(this));
424
425    this.originalTop  = this.element.offsetTop;
426    this.originalLeft = this.element.offsetLeft;
427
428    var fontSize = this.element.getStyle('font-size') || '100%';
429    ['em','px','%','pt'].each( function(fontSizeType) {
430      if (fontSize.indexOf(fontSizeType)>0) {
431        this.fontSize     = parseFloat(fontSize);
432        this.fontSizeType = fontSizeType;
433      }
434    }.bind(this));
435
436    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
437
438    this.dims = null;
439    if (this.options.scaleMode=='box')
440      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
441    if (/^content/.test(this.options.scaleMode))
442      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
443    if (!this.dims)
444      this.dims = [this.options.scaleMode.originalHeight,
445                   this.options.scaleMode.originalWidth];
446  },
447  update: function(position) {
448    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
449    if (this.options.scaleContent && this.fontSize)
450      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
451    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
452  },
453  finish: function(position) {
454    if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
455  },
456  setDimensions: function(height, width) {
457    var d = { };
458    if (this.options.scaleX) d.width = width.round() + 'px';
459    if (this.options.scaleY) d.height = height.round() + 'px';
460    if (this.options.scaleFromCenter) {
461      var topd  = (height - this.dims[0])/2;
462      var leftd = (width  - this.dims[1])/2;
463      if (this.elementPositioning == 'absolute') {
464        if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
465        if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
466      } else {
467        if (this.options.scaleY) d.top = -topd + 'px';
468        if (this.options.scaleX) d.left = -leftd + 'px';
469      }
470    }
471    this.element.setStyle(d);
472  }
473});
474
475Effect.Highlight = Class.create(Effect.Base, {
476  initialize: function(element) {
477    this.element = $(element);
478    if (!this.element) throw(Effect._elementDoesNotExistError);
479    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
480    this.start(options);
481  },
482  setup: function() {
483    // Prevent executing on elements not in the layout flow
484    if (this.element.getStyle('display')=='none') { this.cancel(); return; }
485    // Disable background image during the effect
486    this.oldStyle = { };
487    if (!this.options.keepBackgroundImage) {
488      this.oldStyle.backgroundImage = this.element.getStyle('background-image');
489      this.element.setStyle({backgroundImage: 'none'});
490    }
491    if (!this.options.endcolor)
492      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
493    if (!this.options.restorecolor)
494      this.options.restorecolor = this.element.getStyle('background-color');
495    // init color calculations
496    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
497    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
498  },
499  update: function(position) {
500    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
501      return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
502  },
503  finish: function() {
504    this.element.setStyle(Object.extend(this.oldStyle, {
505      backgroundColor: this.options.restorecolor
506    }));
507  }
508});
509
510Effect.ScrollTo = function(element) {
511  var options = arguments[1] || { },
512  scrollOffsets = document.viewport.getScrollOffsets(),
513  elementOffsets = $(element).cumulativeOffset();
514
515  if (options.offset) elementOffsets[1] += options.offset;
516
517  return new Effect.Tween(null,
518    scrollOffsets.top,
519    elementOffsets[1],
520    options,
521    function(p){ scrollTo(scrollOffsets.left, p.round()); }
522  );
523};
524
525/* ------------- combination effects ------------- */
526
527Effect.Fade = function(element) {
528  element = $(element);
529  try {
530  var oldOpacity = element.getInlineOpacity();
531  var options = Object.extend({
532    from: element.getOpacity() || 1.0,
533    to:   0.0,
534    afterFinishInternal: function(effect) {
535      if (effect.options.to!=0) return;
536      effect.element.hide().setStyle({opacity: oldOpacity});
537    }
538  }, arguments[1] || { });
539  return new Effect.Opacity(element,options);
540 } catch (err) {}
541};
542
543Effect.Appear = function(element) {
544  element = $(element);
545  try {
546  var options = Object.extend({
547  from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
548  to:   1.0,
549  // force Safari to render floated elements properly
550  afterFinishInternal: function(effect) {
551    effect.element.forceRerendering();
552  },
553  beforeSetup: function(effect) {
554    effect.element.setOpacity(effect.options.from).show();
555  }}, arguments[1] || { });
556  return new Effect.Opacity(element,options);
557 } catch (err) {}
558};
559
560Effect.Puff = function(element) {
561  element = $(element);
562  try {
563  var oldStyle = {
564    opacity: element.getInlineOpacity(),
565    position: element.getStyle('position'),
566    top:  element.style.top,
567    left: element.style.left,
568    width: element.style.width,
569    height: element.style.height
570  };
571  return new Effect.Parallel(
572   [ new Effect.Scale(element, 200,
573      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
574     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
575     Object.extend({ duration: 1.0,
576      beforeSetupInternal: function(effect) {
577        Position.absolutize(effect.effects[0].element);
578      },
579      afterFinishInternal: function(effect) {
580         effect.effects[0].element.hide().setStyle(oldStyle); }
581     }, arguments[1] || { })
582   );
583 } catch (err) {}
584};
585
586Effect.BlindUp = function(element) {
587  element = $(element);
588  element.makeClipping();
589  return new Effect.Scale(element, 0,
590    Object.extend({ scaleContent: false,
591      scaleX: false,
592      restoreAfterFinish: true,
593      afterFinishInternal: function(effect) {
594        effect.element.hide().undoClipping();
595      }
596    }, arguments[1] || { })
597  );
598};
599
600Effect.BlindDown = function(element) {
601  element = $(element);
602  var elementDimensions = element.getDimensions();
603  return new Effect.Scale(element, 100, Object.extend({
604    scaleContent: false,
605    scaleX: false,
606    scaleFrom: 0,
607    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
608    restoreAfterFinish: true,
609    afterSetup: function(effect) {
610      effect.element.makeClipping().setStyle({height: '0px'}).show();
611    },
612    afterFinishInternal: function(effect) {
613      effect.element.undoClipping();
614    }
615  }, arguments[1] || { }));
616};
617
618Effect.SwitchOff = function(element) {
619  element = $(element);
620  var oldOpacity = element.getInlineOpacity();
621  return new Effect.Appear(element, Object.extend({
622    duration: 0.4,
623    from: 0,
624    transition: Effect.Transitions.flicker,
625    afterFinishInternal: function(effect) {
626      new Effect.Scale(effect.element, 1, {
627        duration: 0.3, scaleFromCenter: true,
628        scaleX: false, scaleContent: false, restoreAfterFinish: true,
629        beforeSetup: function(effect) {
630          effect.element.makePositioned().makeClipping();
631        },
632        afterFinishInternal: function(effect) {
633          effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
634        }
635      });
636    }
637  }, arguments[1] || { }));
638};
639
640Effect.DropOut = function(element) {
641  element = $(element);
642  try {
643  var oldStyle = {
644    top: element.getStyle('top'),
645    left: element.getStyle('left'),
646    opacity: element.getInlineOpacity() };
647  return new Effect.Parallel(
648    [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
649      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
650    Object.extend(
651      { duration: 0.5,
652        beforeSetup: function(effect) {
653          effect.effects[0].element.makePositioned();
654        },
655        afterFinishInternal: function(effect) {
656          effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
657        }
658      }, arguments[1] || { }));
659 } catch (err) {}
660};
661
662Effect.Shake = function(element) {
663  element = $(element);
664  var options = Object.extend({
665    distance: 20,
666    duration: 0.5
667  }, arguments[1] || {});
668  var distance = parseFloat(options.distance);
669  var split = parseFloat(options.duration) / 10.0;
670  try {
671    var oldStyle = {
672    top: element.getStyle('top'),
673    left: element.getStyle('left') };
674    return new Effect.Move(element,
675      { x:  distance, y: 0, duration: split, afterFinishInternal: function(effect) {
676    new Effect.Move(effect.element,
677      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
678    new Effect.Move(effect.element,
679      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
680    new Effect.Move(effect.element,
681      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
682    new Effect.Move(effect.element,
683      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
684    new Effect.Move(effect.element,
685      { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
686        effect.element.undoPositioned().setStyle(oldStyle);
687  }}); }}); }}); }}); }}); }});
688 } catch (err) {}
689};
690
691Effect.SlideDown = function(element) {
692  try {
693  element = $(element).cleanWhitespace();
694  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
695  var oldInnerBottom = element.down().getStyle('bottom');
696  var elementDimensions = element.getDimensions();
697  return new Effect.Scale(element, 100, Object.extend({
698    scaleContent: false,
699    scaleX: false,
700    scaleFrom: window.opera ? 0 : 1,
701    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
702    restoreAfterFinish: true,
703    afterSetup: function(effect) {
704      effect.element.makePositioned();
705      effect.element.down().makePositioned();
706      if (window.opera) effect.element.setStyle({top: ''});
707      effect.element.makeClipping().setStyle({height: '0px'}).show();
708    },
709    afterUpdateInternal: function(effect) {
710      effect.element.down().setStyle({bottom:
711        (effect.dims[0] - effect.element.clientHeight) + 'px' });
712    },
713    afterFinishInternal: function(effect) {
714      effect.element.undoClipping().undoPositioned();
715      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
716    }, arguments[1] || { })
717  );
718 } catch (err) {}
719};
720
721Effect.SlideUp = function(element) {
722  try {
723  element = $(element).cleanWhitespace();
724  var oldInnerBottom = element.down().getStyle('bottom');
725  var elementDimensions = element.getDimensions();
726  return new Effect.Scale(element, window.opera ? 0 : 1,
727   Object.extend({ scaleContent: false,
728    scaleX: false,
729    scaleMode: 'box',
730    scaleFrom: 100,
731    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
732    restoreAfterFinish: true,
733    afterSetup: function(effect) {
734      effect.element.makePositioned();
735      effect.element.down().makePositioned();
736      if (window.opera) effect.element.setStyle({top: ''});
737      effect.element.makeClipping().show();
738    },
739    afterUpdateInternal: function(effect) {
740      effect.element.down().setStyle({bottom:
741        (effect.dims[0] - effect.element.clientHeight) + 'px' });
742    },
743    afterFinishInternal: function(effect) {
744      effect.element.hide().undoClipping().undoPositioned();
745      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
746    }
747   }, arguments[1] || { })
748  );
749 } catch (err) {}
750};
751
752// Bug in opera makes the TD containing this element expand for a instance after finish
753Effect.Squish = function(element) {
754  return new Effect.Scale(element, window.opera ? 1 : 0, {
755    restoreAfterFinish: true,
756    beforeSetup: function(effect) {
757      effect.element.makeClipping();
758    },
759    afterFinishInternal: function(effect) {
760      effect.element.hide().undoClipping();
761    }
762  });
763};
764
765Effect.Grow = function(element) {
766  element = $(element);
767  var options = Object.extend({
768    direction: 'center',
769    moveTransition: Effect.Transitions.sinoidal,
770    scaleTransition: Effect.Transitions.sinoidal,
771    opacityTransition: Effect.Transitions.full
772  }, arguments[1] || { });
773  var oldStyle = {
774    top: element.style.top,
775    left: element.style.left,
776    height: element.style.height,
777    width: element.style.width,
778    opacity: element.getInlineOpacity() };
779
780  var dims = element.getDimensions();
781  var initialMoveX, initialMoveY;
782  var moveX, moveY;
783
784  switch (options.direction) {
785    case 'top-left':
786      initialMoveX = initialMoveY = moveX = moveY = 0;
787      break;
788    case 'top-right':
789      initialMoveX = dims.width;
790      initialMoveY = moveY = 0;
791      moveX = -dims.width;
792      break;
793    case 'bottom-left':
794      initialMoveX = moveX = 0;
795      initialMoveY = dims.height;
796      moveY = -dims.height;
797      break;
798    case 'bottom-right':
799      initialMoveX = dims.width;
800      initialMoveY = dims.height;
801      moveX = -dims.width;
802      moveY = -dims.height;
803      break;
804    case 'center':
805      initialMoveX = dims.width / 2;
806      initialMoveY = dims.height / 2;
807      moveX = -dims.width / 2;
808      moveY = -dims.height / 2;
809      break;
810  }
811
812  return new Effect.Move(element, {
813    x: initialMoveX,
814    y: initialMoveY,
815    duration: 0.01,
816    beforeSetup: function(effect) {
817      effect.element.hide().makeClipping().makePositioned();
818    },
819    afterFinishInternal: function(effect) {
820      new Effect.Parallel(
821        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
822          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
823          new Effect.Scale(effect.element, 100, {
824            scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
825            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
826        ], Object.extend({
827             beforeSetup: function(effect) {
828               effect.effects[0].element.setStyle({height: '0px'}).show();
829             },
830             afterFinishInternal: function(effect) {
831               effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
832             }
833           }, options)
834      );
835    }
836  });
837};
838
839Effect.Shrink = function(element) {
840  element = $(element);
841  var options = Object.extend({
842    direction: 'center',
843    moveTransition: Effect.Transitions.sinoidal,
844    scaleTransition: Effect.Transitions.sinoidal,
845    opacityTransition: Effect.Transitions.none
846  }, arguments[1] || { });
847  var oldStyle = {
848    top: element.style.top,
849    left: element.style.left,
850    height: element.style.height,
851    width: element.style.width,
852    opacity: element.getInlineOpacity() };
853
854  var dims = element.getDimensions();
855  var moveX, moveY;
856
857  switch (options.direction) {
858    case 'top-left':
859      moveX = moveY = 0;
860      break;
861    case 'top-right':
862      moveX = dims.width;
863      moveY = 0;
864      break;
865    case 'bottom-left':
866      moveX = 0;
867      moveY = dims.height;
868      break;
869    case 'bottom-right':
870      moveX = dims.width;
871      moveY = dims.height;
872      break;
873    case 'center':
874      moveX = dims.width / 2;
875      moveY = dims.height / 2;
876      break;
877  }
878
879  return new Effect.Parallel(
880    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
881      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
882      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
883    ], Object.extend({
884         beforeStartInternal: function(effect) {
885           effect.effects[0].element.makePositioned().makeClipping();
886         },
887         afterFinishInternal: function(effect) {
888           effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
889       }, options)
890  );
891};
892
893Effect.Pulsate = function(element) {
894  element = $(element);
895  var options    = arguments[1] || { },
896    oldOpacity = element.getInlineOpacity(),
897    transition = options.transition || Effect.Transitions.linear,
898    reverser   = function(pos){
899      return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
900    };
901
902  return new Effect.Opacity(element,
903    Object.extend(Object.extend({  duration: 2.0, from: 0,
904      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
905    }, options), {transition: reverser}));
906};
907
908Effect.Fold = function(element) {
909  element = $(element);
910  try {
911  var oldStyle = {
912    top: element.style.top,
913    left: element.style.left,
914    width: element.style.width,
915    height: element.style.height };
916  element.makeClipping();
917  return new Effect.Scale(element, 5, Object.extend({
918    scaleContent: false,
919    scaleX: false,
920    afterFinishInternal: function(effect) {
921    new Effect.Scale(element, 1, {
922      scaleContent: false,
923      scaleY: false,
924      afterFinishInternal: function(effect) {
925        effect.element.hide().undoClipping().setStyle(oldStyle);
926      } });
927  }}, arguments[1] || { }));
928  } catch (err) {}
929};
930
931Effect.Morph = Class.create(Effect.Base, {
932  initialize: function(element) {
933    this.element = $(element);
934    if (!this.element) throw(Effect._elementDoesNotExistError);
935    var options = Object.extend({
936      style: { }
937    }, arguments[1] || { });
938
939    if (!Object.isString(options.style)) this.style = $H(options.style);
940    else {
941      if (options.style.include(':'))
942        this.style = options.style.parseStyle();
943      else {
944        this.element.addClassName(options.style);
945        this.style = $H(this.element.getStyles());
946        this.element.removeClassName(options.style);
947        var css = this.element.getStyles();
948        this.style = this.style.reject(function(style) {
949          return style.value == css[style.key];
950        });
951        options.afterFinishInternal = function(effect) {
952          effect.element.addClassName(effect.options.style);
953          effect.transforms.each(function(transform) {
954            effect.element.style[transform.style] = '';
955          });
956        };
957      }
958    }
959    this.start(options);
960  },
961
962  setup: function(){
963    function parseColor(color){
964      if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
965      color = color.parseColor();
966      return $R(0,2).map(function(i){
967        return parseInt( color.slice(i*2+1,i*2+3), 16 );
968      });
969    }
970    this.transforms = this.style.map(function(pair){
971      var property = pair[0], value = pair[1], unit = null;
972
973      if (value.parseColor('#zzzzzz') != '#zzzzzz') {
974        value = value.parseColor();
975        unit  = 'color';
976      } else if (property == 'opacity') {
977        value = parseFloat(value);
978        if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
979          this.element.setStyle({zoom: 1});
980      } else if (Element.CSS_LENGTH.test(value)) {
981          var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
982          value = parseFloat(components[1]);
983          unit = (components.length == 3) ? components[2] : null;
984      }
985
986      var originalValue = this.element.getStyle(property);
987      return {
988        style: property.camelize(),
989        originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
990        targetValue: unit=='color' ? parseColor(value) : value,
991        unit: unit
992      };
993    }.bind(this)).reject(function(transform){
994      return (
995        (transform.originalValue == transform.targetValue) ||
996        (
997          transform.unit != 'color' &&
998          (isNaN(transform.originalValue) || isNaN(transform.targetValue))
999        )
1000      );
1001    });
1002  },
1003  update: function(position) {
1004    var style = { }, transform, i = this.transforms.length;
1005    while(i--)
1006      style[(transform = this.transforms[i]).style] =
1007        transform.unit=='color' ? '#'+
1008          (Math.round(transform.originalValue[0]+
1009            (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
1010          (Math.round(transform.originalValue[1]+
1011            (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
1012          (Math.round(transform.originalValue[2]+
1013            (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
1014        (transform.originalValue +
1015          (transform.targetValue - transform.originalValue) * position).toFixed(3) +
1016            (transform.unit === null ? '' : transform.unit);
1017    this.element.setStyle(style, true);
1018  }
1019});
1020
1021Effect.Transform = Class.create({
1022  initialize: function(tracks){
1023    this.tracks  = [];
1024    this.options = arguments[1] || { };
1025    this.addTracks(tracks);
1026  },
1027  addTracks: function(tracks){
1028    tracks.each(function(track){
1029      track = $H(track);
1030      var data = track.values().first();
1031      this.tracks.push($H({
1032        ids:     track.keys().first(),
1033        effect:  Effect.Morph,
1034        options: { style: data }
1035      }));
1036    }.bind(this));
1037    return this;
1038  },
1039  play: function(){
1040    return new Effect.Parallel(
1041      this.tracks.map(function(track){
1042        var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
1043        var elements = [$(ids) || $$(ids)].flatten();
1044        return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
1045      }).flatten(),
1046      this.options
1047    );
1048  }
1049});
1050
1051Element.CSS_PROPERTIES = $w(
1052  'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
1053  'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
1054  'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
1055  'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
1056  'fontSize fontWeight height left letterSpacing lineHeight ' +
1057  'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
1058  'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
1059  'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
1060  'right textIndent top width wordSpacing zIndex');
1061
1062Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
1063
1064String.__parseStyleElement = document.createElement('div');
1065String.prototype.parseStyle = function(){
1066  var style, styleRules = $H();
1067  if (Prototype.Browser.WebKit)
1068    style = new Element('div',{style:this}).style;
1069  else {
1070    String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
1071    style = String.__parseStyleElement.childNodes[0].style;
1072  }
1073
1074  Element.CSS_PROPERTIES.each(function(property){
1075    if (style[property]) styleRules.set(property, style[property]);
1076  });
1077
1078  if (Prototype.Browser.IE && this.include('opacity'))
1079    styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
1080
1081  return styleRules;
1082};
1083
1084if (document.defaultView && document.defaultView.getComputedStyle) {
1085  Element.getStyles = function(element) {
1086    var css = document.defaultView.getComputedStyle($(element), null);
1087    return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
1088      styles[property] = css[property];
1089      return styles;
1090    });
1091  };
1092} else {
1093  Element.getStyles = function(element) {
1094    element = $(element);
1095    var css = element.currentStyle, styles;
1096    styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
1097      results[property] = css[property];
1098      return results;
1099    });
1100    if (!styles.opacity) styles.opacity = element.getOpacity();
1101    return styles;
1102  };
1103}
1104
1105Effect.Methods = {
1106  morph: function(element, style) {
1107    element = $(element);
1108    new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
1109    return element;
1110  },
1111  visualEffect: function(element, effect, options) {
1112    element = $(element);
1113    var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
1114    new Effect[klass](element, options);
1115    return element;
1116  },
1117  highlight: function(element, options) {
1118    element = $(element);
1119    new Effect.Highlight(element, options);
1120    return element;
1121  }
1122};
1123
1124$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
1125  'pulsate shake puff squish switchOff dropOut').each(
1126  function(effect) {
1127    Effect.Methods[effect] = function(element, options){
1128      element = $(element);
1129      Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
1130      return element;
1131    };
1132  }
1133);
1134
1135$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
1136  function(f) { Effect.Methods[f] = Element[f]; }
1137);
1138
1139Element.addMethods(Effect.Methods);