effects.js 32.9 KB
Newer Older
D
David Heinemeier Hansson 已提交
1
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
2 3 4 5
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
D
David Heinemeier Hansson 已提交
6
// 
T
Thomas Fuchs 已提交
7 8 9 10 11
// See scriptaculous.js for full license.  

// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
T
Thomas Fuchs 已提交
12 13
  var color = '#';  
  if(this.slice(0,4) == 'rgb(') {  
T
Thomas Fuchs 已提交
14 15 16 17 18 19 20
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if(this.slice(0,1) == '#') {  
      if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if(this.length==7) color = this.toLowerCase();  
    }  
21
  }  
T
Thomas Fuchs 已提交
22
  return(color.length==7 ? color : (arguments[0] || this));  
23
}
T
Thomas Fuchs 已提交
24

T
Thomas Fuchs 已提交
25 26
/*--------------------------------------------------------------------------*/

27 28 29 30 31
Element.collectTextNodes = function(element) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
32 33
}

34 35 36 37
Element.collectTextNodesIgnoreClass = function(element, className) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
38
        Element.collectTextNodesIgnoreClass(node, className) : ''));
39 40 41
  }).flatten().join('');
}

T
Thomas Fuchs 已提交
42 43
Element.setContentZoom = function(element, percent) {
  element = $(element);  
T
Thomas Fuchs 已提交
44
  Element.setStyle(element, {fontSize: (percent/100) + 'em'});   
T
Thomas Fuchs 已提交
45
  if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
T
Thomas Fuchs 已提交
46 47 48
}

Element.getOpacity = function(element){  
T
Thomas Fuchs 已提交
49 50
  var opacity;
  if (opacity = Element.getStyle(element, 'opacity'))  
T
Thomas Fuchs 已提交
51
    return parseFloat(opacity);  
T
Thomas Fuchs 已提交
52
  if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/))  
T
Thomas Fuchs 已提交
53 54 55 56 57 58
    if(opacity[1]) return parseFloat(opacity[1]) / 100;  
  return 1.0;  
}

Element.setOpacity = function(element, value){  
  element= $(element);  
T
Thomas Fuchs 已提交
59 60 61
  if (value == 1){
    Element.setStyle(element, { opacity: 
      (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 
62 63
      0.999999 : 1.0 });
    if(/MSIE/.test(navigator.userAgent) && !window.opera)  
T
Thomas Fuchs 已提交
64
      Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')});  
T
Thomas Fuchs 已提交
65 66
  } else {  
    if(value < 0.00001) value = 0;  
T
Thomas Fuchs 已提交
67
    Element.setStyle(element, {opacity: value});
68
    if(/MSIE/.test(navigator.userAgent) && !window.opera)  
T
Thomas Fuchs 已提交
69 70 71
     Element.setStyle(element, 
       { filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') +
                 'alpha(opacity='+value*100+')' });  
T
Thomas Fuchs 已提交
72
  }
T
Thomas Fuchs 已提交
73 74 75
}  
 
Element.getInlineOpacity = function(element){  
T
Thomas Fuchs 已提交
76
  return $(element).style.opacity || '';
T
Thomas Fuchs 已提交
77
}  
T
Thomas Fuchs 已提交
78

79
Element.childrenWithClassName = function(element, className, findFirst) {
80 81 82 83 84 85
  var classNameRegExp = new RegExp("(^|\\s)" + className + "(\\s|$)");
  var results = $A($(element).getElementsByTagName('*'))[findFirst ? 'detect' : 'select']( function(c) { 
    return (c.className && c.className.match(classNameRegExp));
  });
  if(!results) results = [];
  return results;
T
Thomas Fuchs 已提交
86 87
}

88
Element.forceRerendering = function(element) {
89 90 91 92 93
  try {
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    element.removeChild(n);
T
Thomas Fuchs 已提交
94 95 96 97
  } catch(e) { }
};

/*--------------------------------------------------------------------------*/
98

T
Thomas Fuchs 已提交
99 100 101 102 103
Array.prototype.call = function() {
  var args = arguments;
  this.each(function(f){ f.apply(this, args) });
}

104 105
/*--------------------------------------------------------------------------*/

106
var Effect = {
107 108 109 110
  _elementDoesNotExistError: {
    name: 'ElementDoesNotExistError',
    message: 'The specified DOM element does not exist, but is required for this effect to operate'
  },
111
  tagifyText: function(element) {
112 113 114
    if(typeof Builder == 'undefined')
      throw("Effect.tagifyText requires including script.aculo.us' builder.js library");
      
T
Thomas Fuchs 已提交
115
    var tagifyStyle = 'position:relative';
116
    if(/MSIE/.test(navigator.userAgent) && !window.opera) tagifyStyle += ';zoom:1';
117 118 119 120 121 122
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if(child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            Builder.node('span',{style: tagifyStyle},
T
Thomas Fuchs 已提交
123
              character == ' ' ? String.fromCharCode(160) : character), 
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if(((typeof element == 'object') || 
        (typeof element == 'function')) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || {});
T
Thomas Fuchs 已提交
143
    var masterDelay = options.delay;
D
David Heinemeier Hansson 已提交
144

145
    $A(elements).each( function(element, index) {
T
Thomas Fuchs 已提交
146
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
147
    });
148 149 150 151 152 153 154 155 156 157
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
158
      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
159
    }, arguments[2] || {});
T
Thomas Fuchs 已提交
160
    Effect[element.visible() ? 
161
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
162 163
  }
};
D
David Heinemeier Hansson 已提交
164

165
var Effect2 = Effect; // deprecated
D
David Heinemeier Hansson 已提交
166 167 168 169 170

/* ------------- transitions ------------- */

Effect.Transitions = {}

171 172
Effect.Transitions.linear = Prototype.K;

D
David Heinemeier Hansson 已提交
173 174 175 176 177 178 179
Effect.Transitions.sinoidal = function(pos) {
  return (-Math.cos(pos*Math.PI)/2) + 0.5;
}
Effect.Transitions.reverse  = function(pos) {
  return 1-pos;
}
Effect.Transitions.flicker = function(pos) {
180
  return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
D
David Heinemeier Hansson 已提交
181 182 183 184 185
}
Effect.Transitions.wobble = function(pos) {
  return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
}
Effect.Transitions.pulse = function(pos) {
186
  return (Math.floor(pos*10) % 2 == 0 ? 
D
David Heinemeier Hansson 已提交
187 188 189
    (pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10)));
}
Effect.Transitions.none = function(pos) {
190
  return 0;
D
David Heinemeier Hansson 已提交
191 192
}
Effect.Transitions.full = function(pos) {
193 194 195
  return 1;
}

196
/* ------------- core effects ------------- */
197

198 199 200 201 202 203
Effect.ScopedQueue = Class.create();
Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
  initialize: function() {
    this.effects  = [];
    this.interval = null;
  },
T
Thomas Fuchs 已提交
204 205 206
  _each: function(iterator) {
    this.effects._each(iterator);
  },
207 208 209
  add: function(effect) {
    var timestamp = new Date().getTime();
    
210 211 212 213
    var position = (typeof effect.options.queue == 'string') ? 
      effect.options.queue : effect.options.queue.position;
    
    switch(position) {
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;
229 230 231 232

    if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);
    
233 234 235 236 237 238 239 240 241 242 243 244 245 246
    if(!this.interval) 
      this.interval = setInterval(this.loop.bind(this), 40);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if(this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    this.effects.invoke('loop', timePos);
  }
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if(typeof queueName != 'string') return queueName;
    
    if(!this.instances[queueName])
      this.instances[queueName] = new Effect.ScopedQueue();
      
    return this.instances[queueName];
  }
}
Effect.Queue = Effect.Queues.get('global');

Effect.DefaultOptions = {
  transition: Effect.Transitions.sinoidal,
  duration:   1.0,   // seconds
  fps:        25.0,  // max. 25fps due to Effect.Queue implementation
  sync:       false, // true for combining
  from:       0.0,
  to:         1.0,
  delay:      0.0,
  queue:      'parallel'
D
David Heinemeier Hansson 已提交
271 272 273 274
}

Effect.Base = function() {};
Effect.Base.prototype = {
275
  position: null,
D
David Heinemeier Hansson 已提交
276
  start: function(options) {
277
    this.options      = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
278
    this.currentFrame = 0;
279 280
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
281
    this.finishOn     = this.startOn + (this.options.duration*1000);
282
    this.event('beforeStart');
283 284 285
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).add(this);
D
David Heinemeier Hansson 已提交
286
  },
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
  loop: function(timePos) {
    if(timePos >= this.startOn) {
      if(timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if(this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / (this.finishOn - this.startOn);
      var frame = Math.round(pos * this.options.fps * this.options.duration);
      if(frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
D
David Heinemeier Hansson 已提交
303 304 305
    }
  },
  render: function(pos) {
306 307 308 309 310 311
    if(this.state == 'idle') {
      this.state = 'running';
      this.event('beforeSetup');
      if(this.setup) this.setup();
      this.event('afterSetup');
    }
T
Thomas Fuchs 已提交
312 313 314 315 316 317 318 319 320
    if(this.state == 'running') {
      if(this.options.transition) pos = this.options.transition(pos);
      pos *= (this.options.to-this.options.from);
      pos += this.options.from;
      this.position = pos;
      this.event('beforeUpdate');
      if(this.update) this.update(pos);
      this.event('afterUpdate');
    }
D
David Heinemeier Hansson 已提交
321 322
  },
  cancel: function() {
323 324 325
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).remove(this);
326 327 328 329 330
    this.state = 'finished';
  },
  event: function(eventName) {
    if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if(this.options[eventName]) this.options[eventName](this);
T
Thomas Fuchs 已提交
331 332 333
  },
  inspect: function() {
    return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>';
D
David Heinemeier Hansson 已提交
334 335 336 337
  }
}

Effect.Parallel = Class.create();
338
Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
339 340 341 342 343
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
344
    this.effects.invoke('render', position);
345 346
  },
  finish: function(position) {
347 348 349 350 351 352 353
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if(effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
354 355
  }
});
D
David Heinemeier Hansson 已提交
356 357

Effect.Opacity = Class.create();
358
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
D
David Heinemeier Hansson 已提交
359 360
  initialize: function(element) {
    this.element = $(element);
361
    if(!this.element) throw(Effect._elementDoesNotExistError);
362
    // make this work on IE on elements without 'layout'
363
    if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout))
T
Thomas Fuchs 已提交
364
      this.element.setStyle({zoom: 1});
365
    var options = Object.extend({
T
Thomas Fuchs 已提交
366
      from: this.element.getOpacity() || 0.0,
D
David Heinemeier Hansson 已提交
367
      to:   1.0
368
    }, arguments[1] || {});
D
David Heinemeier Hansson 已提交
369 370 371
    this.start(options);
  },
  update: function(position) {
T
Thomas Fuchs 已提交
372
    this.element.setOpacity(position);
D
David Heinemeier Hansson 已提交
373 374 375
  }
});

376 377 378 379
Effect.Move = Class.create();
Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
380
    if(!this.element) throw(Effect._elementDoesNotExistError);
381 382 383 384 385 386
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || {});
    this.start(options);
387
  },
388 389 390 391
  setup: function() {
    // Bug in Opera: Opera returns the "real" position of a static element or
    // relative element that does not have top/left explicitly set.
    // ==> Always set top and left for position relative elements in your stylesheets 
T
Thomas Fuchs 已提交
392
    // (to 0 if you do not need them) 
T
Thomas Fuchs 已提交
393 394 395
    this.element.makePositioned();
    this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
    this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
396 397 398 399 400
    if(this.options.mode == 'absolute') {
      // absolute movement, so we need to calc deltaX and deltaY
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
401
  },
402
  update: function(position) {
T
Thomas Fuchs 已提交
403
    this.element.setStyle({
404 405
      left: Math.round(this.options.x  * position + this.originalLeft) + 'px',
      top:  Math.round(this.options.y  * position + this.originalTop)  + 'px'
T
Thomas Fuchs 已提交
406
    });
407
  }
D
David Heinemeier Hansson 已提交
408 409
});

410 411 412 413 414 415
// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
  return new Effect.Move(element, 
    Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
};

D
David Heinemeier Hansson 已提交
416
Effect.Scale = Class.create();
417
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
D
David Heinemeier Hansson 已提交
418
  initialize: function(element, percent) {
419 420
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
421
    var options = Object.extend({
D
David Heinemeier Hansson 已提交
422 423 424 425 426
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
427 428
      scaleFrom: 100.0,
      scaleTo:   percent
429
    }, arguments[2] || {});
430 431 432 433
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
T
Thomas Fuchs 已提交
434
    this.elementPositioning = this.element.getStyle('position');
435
    
T
Thomas Fuchs 已提交
436
    this.originalStyle = {};
437
    ['top','left','width','height','fontSize'].each( function(k) {
T
Thomas Fuchs 已提交
438 439
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
440 441 442 443
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
T
Thomas Fuchs 已提交
444
    var fontSize = this.element.getStyle('font-size') || '100%';
445
    ['em','px','%','pt'].each( function(fontSizeType) {
446
      if(fontSize.indexOf(fontSizeType)>0) {
T
Thomas Fuchs 已提交
447 448
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
449
      }
T
Thomas Fuchs 已提交
450
    }.bind(this));
451
    
452
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
453 454 455
    
    this.dims = null;
    if(this.options.scaleMode=='box')
T
Thomas Fuchs 已提交
456 457
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if(/^content/.test(this.options.scaleMode))
458 459 460 461
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
D
David Heinemeier Hansson 已提交
462 463
  },
  update: function(position) {
464 465
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if(this.options.scaleContent && this.fontSize)
T
Thomas Fuchs 已提交
466
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
467
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
D
David Heinemeier Hansson 已提交
468
  },
469
  finish: function(position) {
T
Thomas Fuchs 已提交
470
    if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
471
  },
472
  setDimensions: function(height, width) {
T
Thomas Fuchs 已提交
473
    var d = {};
474 475
    if(this.options.scaleX) d.width = Math.round(width) + 'px';
    if(this.options.scaleY) d.height = Math.round(height) + 'px';
D
David Heinemeier Hansson 已提交
476
    if(this.options.scaleFromCenter) {
477 478
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
479
      if(this.elementPositioning == 'absolute') {
T
Thomas Fuchs 已提交
480 481
        if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
D
David Heinemeier Hansson 已提交
482
      } else {
T
Thomas Fuchs 已提交
483 484
        if(this.options.scaleY) d.top = -topd + 'px';
        if(this.options.scaleX) d.left = -leftd + 'px';
D
David Heinemeier Hansson 已提交
485 486
      }
    }
T
Thomas Fuchs 已提交
487
    this.element.setStyle(d);
D
David Heinemeier Hansson 已提交
488 489 490 491
  }
});

Effect.Highlight = Class.create();
492
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
D
David Heinemeier Hansson 已提交
493 494
  initialize: function(element) {
    this.element = $(element);
495
    if(!this.element) throw(Effect._elementDoesNotExistError);
T
Thomas Fuchs 已提交
496
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
497 498 499
    this.start(options);
  },
  setup: function() {
T
Thomas Fuchs 已提交
500
    // Prevent executing on elements not in the layout flow
T
Thomas Fuchs 已提交
501
    if(this.element.getStyle('display')=='none') { this.cancel(); return; }
502
    // Disable background image during the effect
T
Thomas Fuchs 已提交
503
    this.oldStyle = {
T
Thomas Fuchs 已提交
504 505
      backgroundImage: this.element.getStyle('background-image') };
    this.element.setStyle({backgroundImage: 'none'});
506
    if(!this.options.endcolor)
T
Thomas Fuchs 已提交
507
      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
T
Thomas Fuchs 已提交
508
    if(!this.options.restorecolor)
T
Thomas Fuchs 已提交
509
      this.options.restorecolor = this.element.getStyle('background-color');
D
David Heinemeier Hansson 已提交
510
    // init color calculations
T
Thomas Fuchs 已提交
511 512
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    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));
D
David Heinemeier Hansson 已提交
513 514
  },
  update: function(position) {
T
Thomas Fuchs 已提交
515
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
T
Thomas Fuchs 已提交
516
      return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
517 518
  },
  finish: function() {
T
Thomas Fuchs 已提交
519
    this.element.setStyle(Object.extend(this.oldStyle, {
T
Thomas Fuchs 已提交
520 521
      backgroundColor: this.options.restorecolor
    }));
D
David Heinemeier Hansson 已提交
522 523 524
  }
});

525
Effect.ScrollTo = Class.create();
526
Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
527 528
  initialize: function(element) {
    this.element = $(element);
529 530 531
    this.start(arguments[1] || {});
  },
  setup: function() {
532 533
    Position.prepare();
    var offsets = Position.cumulativeOffset(this.element);
T
Thomas Fuchs 已提交
534
    if(this.options.offset) offsets[1] += this.options.offset;
535 536 537 538 539 540
    var max = window.innerHeight ? 
      window.height - window.innerHeight :
      document.body.scrollHeight - 
        (document.documentElement.clientHeight ? 
          document.documentElement.clientHeight : document.body.clientHeight);
    this.scrollStart = Position.deltaY;
541
    this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
542 543 544 545 546 547 548
  },
  update: function(position) {
    Position.prepare();
    window.scrollTo(Position.deltaX, 
      this.scrollStart + (position*this.delta));
  }
});
D
David Heinemeier Hansson 已提交
549

550
/* ------------- combination effects ------------- */
D
David Heinemeier Hansson 已提交
551

552
Effect.Fade = function(element) {
T
Thomas Fuchs 已提交
553 554
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
555
  var options = Object.extend({
T
Thomas Fuchs 已提交
556
  from: element.getOpacity() || 1.0,
D
David Heinemeier Hansson 已提交
557
  to:   0.0,
T
Thomas Fuchs 已提交
558
  afterFinishInternal: function(effect) { 
T
Thomas Fuchs 已提交
559
    if(effect.options.to!=0) return;
T
Thomas Fuchs 已提交
560 561 562
    effect.element.hide();
    effect.element.setStyle({opacity: oldOpacity}); 
  }}, arguments[1] || {});
563
  return new Effect.Opacity(element,options);
D
David Heinemeier Hansson 已提交
564 565
}

566
Effect.Appear = function(element) {
T
Thomas Fuchs 已提交
567
  element = $(element);
568
  var options = Object.extend({
T
Thomas Fuchs 已提交
569
  from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
D
David Heinemeier Hansson 已提交
570
  to:   1.0,
571 572
  // force Safari to render floated elements properly
  afterFinishInternal: function(effect) {
T
Thomas Fuchs 已提交
573
    effect.element.forceRerendering();
574
  },
T
Thomas Fuchs 已提交
575 576 577 578
  beforeSetup: function(effect) {
    effect.element.setOpacity(effect.options.from);
    effect.element.show(); 
  }}, arguments[1] || {});
579
  return new Effect.Opacity(element,options);
D
David Heinemeier Hansson 已提交
580 581 582
}

Effect.Puff = function(element) {
583
  element = $(element);
584 585 586 587 588 589 590 591
  var oldStyle = { 
    opacity: element.getInlineOpacity(), 
    position: element.getStyle('position'),
    top:  element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height
  };
592 593 594 595 596
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
T
Thomas Fuchs 已提交
597
      beforeSetupInternal: function(effect) {
598 599
        Position.absolutize(effect.effects[0].element)
      },
T
Thomas Fuchs 已提交
600
      afterFinishInternal: function(effect) {
T
Thomas Fuchs 已提交
601 602
         effect.effects[0].element.hide();
         effect.effects[0].element.setStyle(oldStyle); }
603
     }, arguments[1] || {})
D
David Heinemeier Hansson 已提交
604 605 606 607
   );
}

Effect.BlindUp = function(element) {
608
  element = $(element);
T
Thomas Fuchs 已提交
609
  element.makeClipping();
610
  return new Effect.Scale(element, 0,
611
    Object.extend({ scaleContent: false, 
D
David Heinemeier Hansson 已提交
612
      scaleX: false, 
613
      restoreAfterFinish: true,
T
Thomas Fuchs 已提交
614 615 616 617
      afterFinishInternal: function(effect) {
        effect.element.hide();
        effect.element.undoClipping();
      } 
618
    }, arguments[1] || {})
D
David Heinemeier Hansson 已提交
619 620 621 622
  );
}

Effect.BlindDown = function(element) {
623
  element = $(element);
T
Thomas Fuchs 已提交
624
  var elementDimensions = element.getDimensions();
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping();
      effect.element.setStyle({height: '0px'});
      effect.element.show(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || {}));
D
David Heinemeier Hansson 已提交
640 641 642
}

Effect.SwitchOff = function(element) {
643
  element = $(element);
T
Thomas Fuchs 已提交
644
  var oldOpacity = element.getInlineOpacity();
645
  return new Effect.Appear(element, Object.extend({
646 647 648 649 650 651 652
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
T
Thomas Fuchs 已提交
653 654 655 656 657 658 659
        beforeSetup: function(effect) { 
          effect.element.makePositioned();
          effect.element.makeClipping();
        },
        afterFinishInternal: function(effect) {
          effect.element.hide();
          effect.element.undoClipping();
T
Thomas Fuchs 已提交
660
          effect.element.undoPositioned();
T
Thomas Fuchs 已提交
661 662
          effect.element.setStyle({opacity: oldOpacity});
        }
663 664
      })
    }
665
  }, arguments[1] || {}));
D
David Heinemeier Hansson 已提交
666 667 668
}

Effect.DropOut = function(element) {
669
  element = $(element);
T
Thomas Fuchs 已提交
670
  var oldStyle = {
T
Thomas Fuchs 已提交
671 672 673
    top: element.getStyle('top'),
    left: element.getStyle('left'),
    opacity: element.getInlineOpacity() };
674
  return new Effect.Parallel(
675
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
676 677 678
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
T
Thomas Fuchs 已提交
679 680 681 682 683 684 685 686
        beforeSetup: function(effect) {
          effect.effects[0].element.makePositioned(); 
        },
        afterFinishInternal: function(effect) {
          effect.effects[0].element.hide();
          effect.effects[0].element.undoPositioned();
          effect.effects[0].element.setStyle(oldStyle);
        } 
687
      }, arguments[1] || {}));
D
David Heinemeier Hansson 已提交
688 689 690
}

Effect.Shake = function(element) {
691
  element = $(element);
T
Thomas Fuchs 已提交
692
  var oldStyle = {
T
Thomas Fuchs 已提交
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    top: element.getStyle('top'),
    left: element.getStyle('left') };
    return new Effect.Move(element, 
      { x:  20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
        effect.element.undoPositioned();
        effect.element.setStyle(oldStyle);
  }}) }}) }}) }}) }}) }});
D
David Heinemeier Hansson 已提交
710 711 712
}

Effect.SlideDown = function(element) {
713
  element = $(element);
T
Thomas Fuchs 已提交
714
  element.cleanWhitespace();
715
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
T
Thomas Fuchs 已提交
716 717
  var oldInnerBottom = $(element.firstChild).getStyle('bottom');
  var elementDimensions = element.getDimensions();
T
Thomas Fuchs 已提交
718 719
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
D
David Heinemeier Hansson 已提交
720
    scaleX: false, 
721
    scaleFrom: window.opera ? 0 : 1,
T
Thomas Fuchs 已提交
722
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
723
    restoreAfterFinish: true,
T
Thomas Fuchs 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.firstChild.makePositioned();
      if(window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping();
      effect.element.setStyle({height: '0px'});
      effect.element.show(); },
    afterUpdateInternal: function(effect) {
      effect.element.firstChild.setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); 
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping(); 
737
      // IE will crash if child is undoPositioned first
738
      if(/MSIE/.test(navigator.userAgent) && !window.opera){
T
Thomas Fuchs 已提交
739 740
        effect.element.undoPositioned();
        effect.element.firstChild.undoPositioned();
741
      }else{
T
Thomas Fuchs 已提交
742 743
        effect.element.firstChild.undoPositioned();
        effect.element.undoPositioned();
744
      }
T
Thomas Fuchs 已提交
745
      effect.element.firstChild.setStyle({bottom: oldInnerBottom}); }
746
    }, arguments[1] || {})
D
David Heinemeier Hansson 已提交
747 748
  );
}
749

D
David Heinemeier Hansson 已提交
750
Effect.SlideUp = function(element) {
751
  element = $(element);
T
Thomas Fuchs 已提交
752 753
  element.cleanWhitespace();
  var oldInnerBottom = $(element.firstChild).getStyle('bottom');
754
  return new Effect.Scale(element, window.opera ? 0 : 1,
755
   Object.extend({ scaleContent: false, 
D
David Heinemeier Hansson 已提交
756
    scaleX: false, 
757 758 759
    scaleMode: 'box',
    scaleFrom: 100,
    restoreAfterFinish: true,
T
Thomas Fuchs 已提交
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
    beforeStartInternal: function(effect) {
      effect.element.makePositioned();
      effect.element.firstChild.makePositioned();
      if(window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping();
      effect.element.show(); },  
    afterUpdateInternal: function(effect) {
      effect.element.firstChild.setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); },
    afterFinishInternal: function(effect) {
      effect.element.hide();
      effect.element.undoClipping();
      effect.element.firstChild.undoPositioned();
      effect.element.undoPositioned();
      effect.element.setStyle({bottom: oldInnerBottom}); }
775
   }, arguments[1] || {})
D
David Heinemeier Hansson 已提交
776 777 778
  );
}

T
Thomas Fuchs 已提交
779
// Bug in opera makes the TD containing this element expand for a instance after finish 
D
David Heinemeier Hansson 已提交
780
Effect.Squish = function(element) {
781 782
  return new Effect.Scale(element, window.opera ? 1 : 0, 
    { restoreAfterFinish: true,
T
Thomas Fuchs 已提交
783 784 785 786 787
      beforeSetup: function(effect) {
        effect.element.makeClipping(effect.element); },  
      afterFinishInternal: function(effect) {
        effect.element.hide(effect.element); 
        effect.element.undoClipping(effect.element); }
788
  });
D
David Heinemeier Hansson 已提交
789 790 791 792
}

Effect.Grow = function(element) {
  element = $(element);
T
Thomas Fuchs 已提交
793 794
  var options = Object.extend({
    direction: 'center',
795
    moveTransition: Effect.Transitions.sinoidal,
T
Thomas Fuchs 已提交
796 797 798 799 800 801 802 803
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
T
Thomas Fuchs 已提交
804
    opacity: element.getInlineOpacity() };
T
Thomas Fuchs 已提交
805

T
Thomas Fuchs 已提交
806
  var dims = element.getDimensions();    
D
David Heinemeier Hansson 已提交
807 808 809
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
T
Thomas Fuchs 已提交
810
  switch (options.direction) {
D
David Heinemeier Hansson 已提交
811 812 813 814
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
T
Thomas Fuchs 已提交
815
      initialMoveX = dims.width;
D
David Heinemeier Hansson 已提交
816
      initialMoveY = moveY = 0;
T
Thomas Fuchs 已提交
817
      moveX = -dims.width;
D
David Heinemeier Hansson 已提交
818 819 820
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
T
Thomas Fuchs 已提交
821 822
      initialMoveY = dims.height;
      moveY = -dims.height;
D
David Heinemeier Hansson 已提交
823 824
      break;
    case 'bottom-right':
T
Thomas Fuchs 已提交
825 826 827 828
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
D
David Heinemeier Hansson 已提交
829 830
      break;
    case 'center':
T
Thomas Fuchs 已提交
831 832 833 834
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
D
David Heinemeier Hansson 已提交
835 836 837
      break;
  }
  
838 839 840
  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
D
David Heinemeier Hansson 已提交
841
    duration: 0.01, 
T
Thomas Fuchs 已提交
842 843 844 845 846
    beforeSetup: function(effect) {
      effect.element.hide();
      effect.element.makeClipping();
      effect.element.makePositioned();
    },
847
    afterFinishInternal: function(effect) {
D
David Heinemeier Hansson 已提交
848
      new Effect.Parallel(
T
Thomas Fuchs 已提交
849
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
850
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
851
          new Effect.Scale(effect.element, 100, {
T
Thomas Fuchs 已提交
852 853
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
854
        ], Object.extend({
T
Thomas Fuchs 已提交
855 856 857 858 859 860 861 862 863
             beforeSetup: function(effect) {
               effect.effects[0].element.setStyle({height: '0px'});
               effect.effects[0].element.show(); 
             },
             afterFinishInternal: function(effect) {
               effect.effects[0].element.undoClipping();
               effect.effects[0].element.undoPositioned();
               effect.effects[0].element.setStyle(oldStyle); 
             }
864 865 866 867
           }, options)
      )
    }
  });
D
David Heinemeier Hansson 已提交
868 869 870 871
}

Effect.Shrink = function(element) {
  element = $(element);
T
Thomas Fuchs 已提交
872 873
  var options = Object.extend({
    direction: 'center',
874
    moveTransition: Effect.Transitions.sinoidal,
T
Thomas Fuchs 已提交
875 876 877 878 879 880 881 882
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
T
Thomas Fuchs 已提交
883
    opacity: element.getInlineOpacity() };
T
Thomas Fuchs 已提交
884

T
Thomas Fuchs 已提交
885
  var dims = element.getDimensions();
D
David Heinemeier Hansson 已提交
886 887
  var moveX, moveY;
  
T
Thomas Fuchs 已提交
888
  switch (options.direction) {
D
David Heinemeier Hansson 已提交
889 890 891 892
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
T
Thomas Fuchs 已提交
893
      moveX = dims.width;
D
David Heinemeier Hansson 已提交
894 895 896 897
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
T
Thomas Fuchs 已提交
898
      moveY = dims.height;
D
David Heinemeier Hansson 已提交
899 900
      break;
    case 'bottom-right':
T
Thomas Fuchs 已提交
901 902
      moveX = dims.width;
      moveY = dims.height;
D
David Heinemeier Hansson 已提交
903 904
      break;
    case 'center':  
T
Thomas Fuchs 已提交
905 906
      moveX = dims.width / 2;
      moveY = dims.height / 2;
D
David Heinemeier Hansson 已提交
907 908 909
      break;
  }
  
910
  return new Effect.Parallel(
T
Thomas Fuchs 已提交
911 912
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
913
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
914
    ], Object.extend({            
T
Thomas Fuchs 已提交
915 916 917 918 919 920 921 922
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned();
           effect.effects[0].element.makeClipping(); },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.hide();
           effect.effects[0].element.undoClipping();
           effect.effects[0].element.undoPositioned();
           effect.effects[0].element.setStyle(oldStyle); }
923 924
       }, options)
  );
D
David Heinemeier Hansson 已提交
925 926 927
}

Effect.Pulsate = function(element) {
928
  element = $(element);
D
David Heinemeier Hansson 已提交
929
  var options    = arguments[1] || {};
T
Thomas Fuchs 已提交
930
  var oldOpacity = element.getInlineOpacity();
D
David Heinemeier Hansson 已提交
931 932 933
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) };
  reverser.bind(transition);
934 935
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 3.0, from: 0,
T
Thomas Fuchs 已提交
936
      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
937
    }, options), {transition: reverser}));
D
David Heinemeier Hansson 已提交
938 939 940
}

Effect.Fold = function(element) {
941
  element = $(element);
T
Thomas Fuchs 已提交
942 943 944 945 946
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
947 948 949 950 951 952 953 954
  Element.makeClipping(element);
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
T
Thomas Fuchs 已提交
955 956 957 958 959
      afterFinishInternal: function(effect) {
        effect.element.hide();
        effect.element.undoClipping(); 
        effect.element.setStyle(oldStyle);
      } });
960
  }}, arguments[1] || {}));
961 962 963 964 965 966
};

['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom',
 'collectTextNodes','collectTextNodesIgnoreClass','childrenWithClassName'].each( 
  function(f) { Element.Methods[f] = Element[f]; }
);
967

T
Thomas Fuchs 已提交
968 969 970 971 972
Element.Methods.visualEffect = function(element, effect, options) {
  s = effect.gsub(/_/, '-').camelize();
  effect_class = s.charAt(0).toUpperCase() + s.substring(1);
  new Effect[effect_class](element, options);
  return $(element);
973 974 975
};

Element.addMethods();