- Changed ReflectionBasedDictionaryAdapter to ignore calls to Remove instead of throw...
[castle.git] / MonoRail / Castle.MonoRail.Framework / Controllers / Effects2.resx
blob43e4d49181f28a8cbb6b7099e994aaf53e0de2ff
1 <?xml version="1.0" encoding="utf-8"?>
2 <root>
3 <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
4 <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
5 <xsd:element name="root" msdata:IsDataSet="true">
6 <xsd:complexType>
7 <xsd:choice maxOccurs="unbounded">
8 <xsd:element name="metadata">
9 <xsd:complexType>
10 <xsd:sequence>
11 <xsd:element name="value" type="xsd:string" minOccurs="0" />
12 </xsd:sequence>
13 <xsd:attribute name="name" use="required" type="xsd:string" />
14 <xsd:attribute name="type" type="xsd:string" />
15 <xsd:attribute name="mimetype" type="xsd:string" />
16 <xsd:attribute ref="xml:space" />
17 </xsd:complexType>
18 </xsd:element>
19 <xsd:element name="assembly">
20 <xsd:complexType>
21 <xsd:attribute name="alias" type="xsd:string" />
22 <xsd:attribute name="name" type="xsd:string" />
23 </xsd:complexType>
24 </xsd:element>
25 <xsd:element name="data">
26 <xsd:complexType>
27 <xsd:sequence>
28 <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
29 <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
30 </xsd:sequence>
31 <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
32 <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
33 <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
34 <xsd:attribute ref="xml:space" />
35 </xsd:complexType>
36 </xsd:element>
37 <xsd:element name="resheader">
38 <xsd:complexType>
39 <xsd:sequence>
40 <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
41 </xsd:sequence>
42 <xsd:attribute name="name" type="xsd:string" use="required" />
43 </xsd:complexType>
44 </xsd:element>
45 </xsd:choice>
46 </xsd:complexType>
47 </xsd:element>
48 </xsd:schema>
49 <resheader name="resmimetype">
50 <value>text/microsoft-resx</value>
51 </resheader>
52 <resheader name="version">
53 <value>2.0</value>
54 </resheader>
55 <resheader name="reader">
56 <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
57 </resheader>
58 <resheader name="writer">
59 <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
60 </resheader>
61 <data name="functions" xml:space="preserve">
62 <value><![CDATA[
64 // script.aculo.us scriptaculous.js v1.7.1_beta3, Fri May 25 17:19:41 +0200 2007
66 // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
67 //
68 // Permission is hereby granted, free of charge, to any person obtaining
69 // a copy of this software and associated documentation files (the
70 // "Software"), to deal in the Software without restriction, including
71 // without limitation the rights to use, copy, modify, merge, publish,
72 // distribute, sublicense, and/or sell copies of the Software, and to
73 // permit persons to whom the Software is furnished to do so, subject to
74 // the following conditions:
75 //
76 // The above copyright notice and this permission notice shall be
77 // included in all copies or substantial portions of the Software.
79 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
80 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
81 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
82 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
83 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
84 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
85 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
87 // For details, see the script.aculo.us web site: http://script.aculo.us/
89 var Scriptaculous = {
90 Version: '1.7.1_beta3',
91 require: function(libraryName) {
92 // inserting via DOM fails in Safari 2.0, so brute force approach
93 document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
95 REQUIRED_PROTOTYPE: '1.5.1',
96 load: function() {
97 function convertVersionString(versionString){
98 var r = versionString.split('.');
99 return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
102 if((typeof Prototype=='undefined') ||
103 (typeof Element == 'undefined') ||
104 (typeof Element.Methods=='undefined') ||
105 (convertVersionString(Prototype.Version) <
106 convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
107 throw("script.aculo.us requires the Prototype JavaScript framework >= " +
108 Scriptaculous.REQUIRED_PROTOTYPE);
112 Scriptaculous.load();
114 var Builder = {
115 NODEMAP: {
116 AREA: 'map',
117 CAPTION: 'table',
118 COL: 'table',
119 COLGROUP: 'table',
120 LEGEND: 'fieldset',
121 OPTGROUP: 'select',
122 OPTION: 'select',
123 PARAM: 'object',
124 TBODY: 'table',
125 TD: 'table',
126 TFOOT: 'table',
127 TH: 'table',
128 THEAD: 'table',
129 TR: 'table'
131 // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
132 // due to a Firefox bug
133 node: function(elementName) {
134 elementName = elementName.toUpperCase();
136 // try innerHTML approach
137 var parentTag = this.NODEMAP[elementName] || 'div';
138 var parentElement = document.createElement(parentTag);
139 try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
140 parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
141 } catch(e) {}
142 var element = parentElement.firstChild || null;
144 // see if browser added wrapping tags
145 if(element && (element.tagName.toUpperCase() != elementName))
146 element = element.getElementsByTagName(elementName)[0];
148 // fallback to createElement approach
149 if(!element) element = document.createElement(elementName);
151 // abort if nothing could be created
152 if(!element) return;
154 // attributes (or text)
155 if(arguments[1])
156 if(this._isStringOrNumber(arguments[1]) ||
157 (arguments[1] instanceof Array) ||
158 arguments[1].tagName) {
159 this._children(element, arguments[1]);
160 } else {
161 var attrs = this._attributes(arguments[1]);
162 if(attrs.length) {
163 try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
164 parentElement.innerHTML = "<" +elementName + " " +
165 attrs + "></" + elementName + ">";
166 } catch(e) {}
167 element = parentElement.firstChild || null;
168 // workaround firefox 1.0.X bug
169 if(!element) {
170 element = document.createElement(elementName);
171 for(attr in arguments[1])
172 element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
174 if(element.tagName.toUpperCase() != elementName)
175 element = parentElement.getElementsByTagName(elementName)[0];
179 // text, or array of children
180 if(arguments[2])
181 this._children(element, arguments[2]);
183 return element;
185 _text: function(text) {
186 return document.createTextNode(text);
189 ATTR_MAP: {
190 'className': 'class',
191 'htmlFor': 'for'
194 _attributes: function(attributes) {
195 var attrs = [];
196 for(attribute in attributes)
197 attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
198 '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"');
199 return attrs.join(" ");
201 _children: function(element, children) {
202 if(children.tagName) {
203 element.appendChild(children);
204 return;
206 if(typeof children=='object') { // array can hold nodes and text
207 children.flatten().each( function(e) {
208 if(typeof e=='object')
209 element.appendChild(e)
210 else
211 if(Builder._isStringOrNumber(e))
212 element.appendChild(Builder._text(e));
214 } else
215 if(Builder._isStringOrNumber(children))
216 element.appendChild(Builder._text(children));
218 _isStringOrNumber: function(param) {
219 return(typeof param=='string' || typeof param=='number');
221 build: function(html) {
222 var element = this.node('div');
223 $(element).update(html.strip());
224 return element.down();
226 dump: function(scope) {
227 if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
229 var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
230 "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
231 "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
232 "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
233 "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
234 "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
236 tags.each( function(tag){
237 scope[tag] = function() {
238 return Builder.node.apply(Builder, [tag].concat($A(arguments)));
245 // converts rgb() and #xxx to #xxxxxx format,
246 // returns self (or first argument) if not convertable
247 String.prototype.parseColor = function() {
248 var color = '#';
249 if(this.slice(0,4) == 'rgb(') {
250 var cols = this.slice(4,this.length-1).split(',');
251 var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
252 } else {
253 if(this.slice(0,1) == '#') {
254 if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
255 if(this.length==7) color = this.toLowerCase();
258 return(color.length==7 ? color : (arguments[0] || this));
261 /*--------------------------------------------------------------------------*/
263 Element.collectTextNodes = function(element) {
264 return $A($(element).childNodes).collect( function(node) {
265 return (node.nodeType==3 ? node.nodeValue :
266 (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
267 }).flatten().join('');
270 Element.collectTextNodesIgnoreClass = function(element, className) {
271 return $A($(element).childNodes).collect( function(node) {
272 return (node.nodeType==3 ? node.nodeValue :
273 ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
274 Element.collectTextNodesIgnoreClass(node, className) : ''));
275 }).flatten().join('');
278 Element.setContentZoom = function(element, percent) {
279 element = $(element);
280 element.setStyle({fontSize: (percent/100) + 'em'});
281 if(Prototype.Browser.WebKit) window.scrollBy(0,0);
282 return element;
285 Element.getInlineOpacity = function(element){
286 return $(element).style.opacity || '';
289 Element.forceRerendering = function(element) {
290 try {
291 element = $(element);
292 var n = document.createTextNode(' ');
293 element.appendChild(n);
294 element.removeChild(n);
295 } catch(e) { }
298 /*--------------------------------------------------------------------------*/
300 Array.prototype.call = function() {
301 var args = arguments;
302 this.each(function(f){ f.apply(this, args) });
305 /*--------------------------------------------------------------------------*/
307 var Effect = {
308 _elementDoesNotExistError: {
309 name: 'ElementDoesNotExistError',
310 message: 'The specified DOM element does not exist, but is required for this effect to operate'
312 tagifyText: function(element) {
313 if(typeof Builder == 'undefined')
314 throw("Effect.tagifyText requires including script.aculo.us' builder.js library");
316 var tagifyStyle = 'position:relative';
317 if(Prototype.Browser.IE) tagifyStyle += ';zoom:1';
319 element = $(element);
320 $A(element.childNodes).each( function(child) {
321 if(child.nodeType==3) {
322 child.nodeValue.toArray().each( function(character) {
323 element.insertBefore(
324 Builder.node('span',{style: tagifyStyle},
325 character == ' ' ? String.fromCharCode(160) : character),
326 child);
328 Element.remove(child);
332 multiple: function(element, effect) {
333 var elements;
334 if(((typeof element == 'object') ||
335 (typeof element == 'function')) &&
336 (element.length))
337 elements = element;
338 else
339 elements = $(element).childNodes;
341 var options = Object.extend({
342 speed: 0.1,
343 delay: 0.0
344 }, arguments[2] || {});
345 var masterDelay = options.delay;
347 $A(elements).each( function(element, index) {
348 new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
351 PAIRS: {
352 'slide': ['SlideDown','SlideUp'],
353 'blind': ['BlindDown','BlindUp'],
354 'appear': ['Appear','Fade']
356 toggle: function(element, effect) {
357 element = $(element);
358 effect = (effect || 'appear').toLowerCase();
359 var options = Object.extend({
360 queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
361 }, arguments[2] || {});
362 Effect[element.visible() ?
363 Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
367 var Effect2 = Effect; // deprecated
369 /* ------------- transitions ------------- */
371 Effect.Transitions = {
372 linear: Prototype.K,
373 sinoidal: function(pos) {
374 return (-Math.cos(pos*Math.PI)/2) + 0.5;
376 reverse: function(pos) {
377 return 1-pos;
379 flicker: function(pos) {
380 var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
381 return (pos > 1 ? 1 : pos);
383 wobble: function(pos) {
384 return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
386 pulse: function(pos, pulses) {
387 pulses = pulses || 5;
388 return (
389 Math.round((pos % (1/pulses)) * pulses) == 0 ?
390 ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) :
391 1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2))
394 none: function(pos) {
395 return 0;
397 full: function(pos) {
398 return 1;
402 /* ------------- core effects ------------- */
404 Effect.ScopedQueue = Class.create();
405 Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
406 initialize: function() {
407 this.effects = [];
408 this.interval = null;
410 _each: function(iterator) {
411 this.effects._each(iterator);
413 add: function(effect) {
414 var timestamp = new Date().getTime();
416 var position = (typeof effect.options.queue == 'string') ?
417 effect.options.queue : effect.options.queue.position;
419 switch(position) {
420 case 'front':
421 // move unstarted effects after this effect
422 this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
423 e.startOn += effect.finishOn;
424 e.finishOn += effect.finishOn;
426 break;
427 case 'with-last':
428 timestamp = this.effects.pluck('startOn').max() || timestamp;
429 break;
430 case 'end':
431 // start effect after last queued effect has finished
432 timestamp = this.effects.pluck('finishOn').max() || timestamp;
433 break;
436 effect.startOn += timestamp;
437 effect.finishOn += timestamp;
439 if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
440 this.effects.push(effect);
442 if(!this.interval)
443 this.interval = setInterval(this.loop.bind(this), 15);
445 remove: function(effect) {
446 this.effects = this.effects.reject(function(e) { return e==effect });
447 if(this.effects.length == 0) {
448 clearInterval(this.interval);
449 this.interval = null;
452 loop: function() {
453 var timePos = new Date().getTime();
454 for(var i=0, len=this.effects.length;i<len;i++)
455 this.effects[i] && this.effects[i].loop(timePos);
459 Effect.Queues = {
460 instances: $H(),
461 get: function(queueName) {
462 if(typeof queueName != 'string') return queueName;
464 if(!this.instances[queueName])
465 this.instances[queueName] = new Effect.ScopedQueue();
467 return this.instances[queueName];
470 Effect.Queue = Effect.Queues.get('global');
472 Effect.DefaultOptions = {
473 transition: Effect.Transitions.sinoidal,
474 duration: 1.0, // seconds
475 fps: 100, // 100= assume 66fps max.
476 sync: false, // true for combining
477 from: 0.0,
478 to: 1.0,
479 delay: 0.0,
480 queue: 'parallel'
483 Effect.Base = function() {};
484 Effect.Base.prototype = {
485 position: null,
486 start: function(options) {
487 function codeForEvent(options,eventName){
488 return (
489 (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
490 (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
493 if(options.transition === false) options.transition = Effect.Transitions.linear;
494 this.options = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
495 this.currentFrame = 0;
496 this.state = 'idle';
497 this.startOn = this.options.delay*1000;
498 this.finishOn = this.startOn+(this.options.duration*1000);
499 this.fromToDelta = this.options.to-this.options.from;
500 this.totalTime = this.finishOn-this.startOn;
501 this.totalFrames = this.options.fps*this.options.duration;
503 eval('this.render = function(pos){ '+
504 'if(this.state=="idle"){this.state="running";'+
505 codeForEvent(options,'beforeSetup')+
506 (this.setup ? 'this.setup();':'')+
507 codeForEvent(options,'afterSetup')+
508 '};if(this.state=="running"){'+
509 'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
510 'this.position=pos;'+
511 codeForEvent(options,'beforeUpdate')+
512 (this.update ? 'this.update(pos);':'')+
513 codeForEvent(options,'afterUpdate')+
514 '}}');
516 this.event('beforeStart');
517 if(!this.options.sync)
518 Effect.Queues.get(typeof this.options.queue == 'string' ?
519 'global' : this.options.queue.scope).add(this);
521 loop: function(timePos) {
522 if(timePos >= this.startOn) {
523 if(timePos >= this.finishOn) {
524 this.render(1.0);
525 this.cancel();
526 this.event('beforeFinish');
527 if(this.finish) this.finish();
528 this.event('afterFinish');
529 return;
531 var pos = (timePos - this.startOn) / this.totalTime,
532 frame = Math.round(pos * this.totalFrames);
533 if(frame > this.currentFrame) {
534 this.render(pos);
535 this.currentFrame = frame;
539 cancel: function() {
540 if(!this.options.sync)
541 Effect.Queues.get(typeof this.options.queue == 'string' ?
542 'global' : this.options.queue.scope).remove(this);
543 this.state = 'finished';
545 event: function(eventName) {
546 if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
547 if(this.options[eventName]) this.options[eventName](this);
549 inspect: function() {
550 var data = $H();
551 for(property in this)
552 if(typeof this[property] != 'function') data[property] = this[property];
553 return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
557 Effect.Parallel = Class.create();
558 Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
559 initialize: function(effects) {
560 this.effects = effects || [];
561 this.start(arguments[1]);
563 update: function(position) {
564 this.effects.invoke('render', position);
566 finish: function(position) {
567 this.effects.each( function(effect) {
568 effect.render(1.0);
569 effect.cancel();
570 effect.event('beforeFinish');
571 if(effect.finish) effect.finish(position);
572 effect.event('afterFinish');
577 Effect.Event = Class.create();
578 Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), {
579 initialize: function() {
580 var options = Object.extend({
581 duration: 0
582 }, arguments[0] || {});
583 this.start(options);
585 update: Prototype.emptyFunction
588 Effect.Opacity = Class.create();
589 Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
590 initialize: function(element) {
591 this.element = $(element);
592 if(!this.element) throw(Effect._elementDoesNotExistError);
593 // make this work on IE on elements without 'layout'
594 if(Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
595 this.element.setStyle({zoom: 1});
596 var options = Object.extend({
597 from: this.element.getOpacity() || 0.0,
598 to: 1.0
599 }, arguments[1] || {});
600 this.start(options);
602 update: function(position) {
603 this.element.setOpacity(position);
607 Effect.Move = Class.create();
608 Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
609 initialize: function(element) {
610 this.element = $(element);
611 if(!this.element) throw(Effect._elementDoesNotExistError);
612 var options = Object.extend({
613 x: 0,
614 y: 0,
615 mode: 'relative'
616 }, arguments[1] || {});
617 this.start(options);
619 setup: function() {
620 // Bug in Opera: Opera returns the "real" position of a static element or
621 // relative element that does not have top/left explicitly set.
622 // ==> Always set top and left for position relative elements in your stylesheets
623 // (to 0 if you do not need them)
624 this.element.makePositioned();
625 this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
626 this.originalTop = parseFloat(this.element.getStyle('top') || '0');
627 if(this.options.mode == 'absolute') {
628 // absolute movement, so we need to calc deltaX and deltaY
629 this.options.x = this.options.x - this.originalLeft;
630 this.options.y = this.options.y - this.originalTop;
633 update: function(position) {
634 this.element.setStyle({
635 left: Math.round(this.options.x * position + this.originalLeft) + 'px',
636 top: Math.round(this.options.y * position + this.originalTop) + 'px'
641 // for backwards compatibility
642 Effect.MoveBy = function(element, toTop, toLeft) {
643 return new Effect.Move(element,
644 Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
647 Effect.Scale = Class.create();
648 Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
649 initialize: function(element, percent) {
650 this.element = $(element);
651 if(!this.element) throw(Effect._elementDoesNotExistError);
652 var options = Object.extend({
653 scaleX: true,
654 scaleY: true,
655 scaleContent: true,
656 scaleFromCenter: false,
657 scaleMode: 'box', // 'box' or 'contents' or {} with provided values
658 scaleFrom: 100.0,
659 scaleTo: percent
660 }, arguments[2] || {});
661 this.start(options);
663 setup: function() {
664 this.restoreAfterFinish = this.options.restoreAfterFinish || false;
665 this.elementPositioning = this.element.getStyle('position');
667 this.originalStyle = {};
668 ['top','left','width','height','fontSize'].each( function(k) {
669 this.originalStyle[k] = this.element.style[k];
670 }.bind(this));
672 this.originalTop = this.element.offsetTop;
673 this.originalLeft = this.element.offsetLeft;
675 var fontSize = this.element.getStyle('font-size') || '100%';
676 ['em','px','%','pt'].each( function(fontSizeType) {
677 if(fontSize.indexOf(fontSizeType)>0) {
678 this.fontSize = parseFloat(fontSize);
679 this.fontSizeType = fontSizeType;
681 }.bind(this));
683 this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
685 this.dims = null;
686 if(this.options.scaleMode=='box')
687 this.dims = [this.element.offsetHeight, this.element.offsetWidth];
688 if(/^content/.test(this.options.scaleMode))
689 this.dims = [this.element.scrollHeight, this.element.scrollWidth];
690 if(!this.dims)
691 this.dims = [this.options.scaleMode.originalHeight,
692 this.options.scaleMode.originalWidth];
694 update: function(position) {
695 var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
696 if(this.options.scaleContent && this.fontSize)
697 this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
698 this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
700 finish: function(position) {
701 if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
703 setDimensions: function(height, width) {
704 var d = {};
705 if(this.options.scaleX) d.width = Math.round(width) + 'px';
706 if(this.options.scaleY) d.height = Math.round(height) + 'px';
707 if(this.options.scaleFromCenter) {
708 var topd = (height - this.dims[0])/2;
709 var leftd = (width - this.dims[1])/2;
710 if(this.elementPositioning == 'absolute') {
711 if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
712 if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
713 } else {
714 if(this.options.scaleY) d.top = -topd + 'px';
715 if(this.options.scaleX) d.left = -leftd + 'px';
718 this.element.setStyle(d);
722 Effect.Highlight = Class.create();
723 Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
724 initialize: function(element) {
725 this.element = $(element);
726 if(!this.element) throw(Effect._elementDoesNotExistError);
727 var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
728 this.start(options);
730 setup: function() {
731 // Prevent executing on elements not in the layout flow
732 if(this.element.getStyle('display')=='none') { this.cancel(); return; }
733 // Disable background image during the effect
734 this.oldStyle = {};
735 if (!this.options.keepBackgroundImage) {
736 this.oldStyle.backgroundImage = this.element.getStyle('background-image');
737 this.element.setStyle({backgroundImage: 'none'});
739 if(!this.options.endcolor)
740 this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
741 if(!this.options.restorecolor)
742 this.options.restorecolor = this.element.getStyle('background-color');
743 // init color calculations
744 this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
745 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));
747 update: function(position) {
748 this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
749 return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
751 finish: function() {
752 this.element.setStyle(Object.extend(this.oldStyle, {
753 backgroundColor: this.options.restorecolor
754 }));
758 Effect.ScrollTo = Class.create();
759 Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
760 initialize: function(element) {
761 this.element = $(element);
762 this.start(arguments[1] || {});
764 setup: function() {
765 Position.prepare();
766 var offsets = Position.cumulativeOffset(this.element);
767 if(this.options.offset) offsets[1] += this.options.offset;
768 var max = window.innerHeight ?
769 window.height - window.innerHeight :
770 document.body.scrollHeight -
771 (document.documentElement.clientHeight ?
772 document.documentElement.clientHeight : document.body.clientHeight);
773 this.scrollStart = Position.deltaY;
774 this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
776 update: function(position) {
777 Position.prepare();
778 window.scrollTo(Position.deltaX,
779 this.scrollStart + (position*this.delta));
783 /* ------------- combination effects ------------- */
785 Effect.Fade = function(element) {
786 element = $(element);
787 var oldOpacity = element.getInlineOpacity();
788 var options = Object.extend({
789 from: element.getOpacity() || 1.0,
790 to: 0.0,
791 afterFinishInternal: function(effect) {
792 if(effect.options.to!=0) return;
793 effect.element.hide().setStyle({opacity: oldOpacity});
794 }}, arguments[1] || {});
795 return new Effect.Opacity(element,options);
798 Effect.Appear = function(element) {
799 element = $(element);
800 var options = Object.extend({
801 from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
802 to: 1.0,
803 // force Safari to render floated elements properly
804 afterFinishInternal: function(effect) {
805 effect.element.forceRerendering();
807 beforeSetup: function(effect) {
808 effect.element.setOpacity(effect.options.from).show();
809 }}, arguments[1] || {});
810 return new Effect.Opacity(element,options);
813 Effect.Puff = function(element) {
814 element = $(element);
815 var oldStyle = {
816 opacity: element.getInlineOpacity(),
817 position: element.getStyle('position'),
818 top: element.style.top,
819 left: element.style.left,
820 width: element.style.width,
821 height: element.style.height
823 return new Effect.Parallel(
824 [ new Effect.Scale(element, 200,
825 { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
826 new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
827 Object.extend({ duration: 1.0,
828 beforeSetupInternal: function(effect) {
829 Position.absolutize(effect.effects[0].element)
831 afterFinishInternal: function(effect) {
832 effect.effects[0].element.hide().setStyle(oldStyle); }
833 }, arguments[1] || {})
837 Effect.BlindUp = function(element) {
838 element = $(element);
839 element.makeClipping();
840 return new Effect.Scale(element, 0,
841 Object.extend({ scaleContent: false,
842 scaleX: false,
843 restoreAfterFinish: true,
844 afterFinishInternal: function(effect) {
845 effect.element.hide().undoClipping();
847 }, arguments[1] || {})
851 Effect.BlindDown = function(element) {
852 element = $(element);
853 var elementDimensions = element.getDimensions();
854 return new Effect.Scale(element, 100, Object.extend({
855 scaleContent: false,
856 scaleX: false,
857 scaleFrom: 0,
858 scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
859 restoreAfterFinish: true,
860 afterSetup: function(effect) {
861 effect.element.makeClipping().setStyle({height: '0px'}).show();
863 afterFinishInternal: function(effect) {
864 effect.element.undoClipping();
866 }, arguments[1] || {}));
869 Effect.SwitchOff = function(element) {
870 element = $(element);
871 var oldOpacity = element.getInlineOpacity();
872 return new Effect.Appear(element, Object.extend({
873 duration: 0.4,
874 from: 0,
875 transition: Effect.Transitions.flicker,
876 afterFinishInternal: function(effect) {
877 new Effect.Scale(effect.element, 1, {
878 duration: 0.3, scaleFromCenter: true,
879 scaleX: false, scaleContent: false, restoreAfterFinish: true,
880 beforeSetup: function(effect) {
881 effect.element.makePositioned().makeClipping();
883 afterFinishInternal: function(effect) {
884 effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
888 }, arguments[1] || {}));
891 Effect.DropOut = function(element) {
892 element = $(element);
893 var oldStyle = {
894 top: element.getStyle('top'),
895 left: element.getStyle('left'),
896 opacity: element.getInlineOpacity() };
897 return new Effect.Parallel(
898 [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
899 new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
900 Object.extend(
901 { duration: 0.5,
902 beforeSetup: function(effect) {
903 effect.effects[0].element.makePositioned();
905 afterFinishInternal: function(effect) {
906 effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
908 }, arguments[1] || {}));
911 Effect.Shake = function(element) {
912 element = $(element);
913 var oldStyle = {
914 top: element.getStyle('top'),
915 left: element.getStyle('left') };
916 return new Effect.Move(element,
917 { x: 20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
918 new Effect.Move(effect.element,
919 { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
920 new Effect.Move(effect.element,
921 { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
922 new Effect.Move(effect.element,
923 { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
924 new Effect.Move(effect.element,
925 { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
926 new Effect.Move(effect.element,
927 { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
928 effect.element.undoPositioned().setStyle(oldStyle);
929 }}) }}) }}) }}) }}) }});
932 Effect.SlideDown = function(element) {
933 element = $(element).cleanWhitespace();
934 // SlideDown need to have the content of the element wrapped in a container element with fixed height!
935 var oldInnerBottom = element.down().getStyle('bottom');
936 var elementDimensions = element.getDimensions();
937 return new Effect.Scale(element, 100, Object.extend({
938 scaleContent: false,
939 scaleX: false,
940 scaleFrom: window.opera ? 0 : 1,
941 scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
942 restoreAfterFinish: true,
943 afterSetup: function(effect) {
944 effect.element.makePositioned();
945 effect.element.down().makePositioned();
946 if(window.opera) effect.element.setStyle({top: ''});
947 effect.element.makeClipping().setStyle({height: '0px'}).show();
949 afterUpdateInternal: function(effect) {
950 effect.element.down().setStyle({bottom:
951 (effect.dims[0] - effect.element.clientHeight) + 'px' });
953 afterFinishInternal: function(effect) {
954 effect.element.undoClipping().undoPositioned();
955 effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
956 }, arguments[1] || {})
960 Effect.SlideUp = function(element) {
961 element = $(element).cleanWhitespace();
962 var oldInnerBottom = element.down().getStyle('bottom');
963 return new Effect.Scale(element, window.opera ? 0 : 1,
964 Object.extend({ scaleContent: false,
965 scaleX: false,
966 scaleMode: 'box',
967 scaleFrom: 100,
968 restoreAfterFinish: true,
969 beforeStartInternal: function(effect) {
970 effect.element.makePositioned();
971 effect.element.down().makePositioned();
972 if(window.opera) effect.element.setStyle({top: ''});
973 effect.element.makeClipping().show();
975 afterUpdateInternal: function(effect) {
976 effect.element.down().setStyle({bottom:
977 (effect.dims[0] - effect.element.clientHeight) + 'px' });
979 afterFinishInternal: function(effect) {
980 effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom});
981 effect.element.down().undoPositioned();
983 }, arguments[1] || {})
987 // Bug in opera makes the TD containing this element expand for a instance after finish
988 Effect.Squish = function(element) {
989 return new Effect.Scale(element, window.opera ? 1 : 0, {
990 restoreAfterFinish: true,
991 beforeSetup: function(effect) {
992 effect.element.makeClipping();
994 afterFinishInternal: function(effect) {
995 effect.element.hide().undoClipping();
1000 Effect.Grow = function(element) {
1001 element = $(element);
1002 var options = Object.extend({
1003 direction: 'center',
1004 moveTransition: Effect.Transitions.sinoidal,
1005 scaleTransition: Effect.Transitions.sinoidal,
1006 opacityTransition: Effect.Transitions.full
1007 }, arguments[1] || {});
1008 var oldStyle = {
1009 top: element.style.top,
1010 left: element.style.left,
1011 height: element.style.height,
1012 width: element.style.width,
1013 opacity: element.getInlineOpacity() };
1015 var dims = element.getDimensions();
1016 var initialMoveX, initialMoveY;
1017 var moveX, moveY;
1019 switch (options.direction) {
1020 case 'top-left':
1021 initialMoveX = initialMoveY = moveX = moveY = 0;
1022 break;
1023 case 'top-right':
1024 initialMoveX = dims.width;
1025 initialMoveY = moveY = 0;
1026 moveX = -dims.width;
1027 break;
1028 case 'bottom-left':
1029 initialMoveX = moveX = 0;
1030 initialMoveY = dims.height;
1031 moveY = -dims.height;
1032 break;
1033 case 'bottom-right':
1034 initialMoveX = dims.width;
1035 initialMoveY = dims.height;
1036 moveX = -dims.width;
1037 moveY = -dims.height;
1038 break;
1039 case 'center':
1040 initialMoveX = dims.width / 2;
1041 initialMoveY = dims.height / 2;
1042 moveX = -dims.width / 2;
1043 moveY = -dims.height / 2;
1044 break;
1047 return new Effect.Move(element, {
1048 x: initialMoveX,
1049 y: initialMoveY,
1050 duration: 0.01,
1051 beforeSetup: function(effect) {
1052 effect.element.hide().makeClipping().makePositioned();
1054 afterFinishInternal: function(effect) {
1055 new Effect.Parallel(
1056 [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
1057 new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
1058 new Effect.Scale(effect.element, 100, {
1059 scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
1060 sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
1061 ], Object.extend({
1062 beforeSetup: function(effect) {
1063 effect.effects[0].element.setStyle({height: '0px'}).show();
1065 afterFinishInternal: function(effect) {
1066 effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
1068 }, options)
1074 Effect.Shrink = function(element) {
1075 element = $(element);
1076 var options = Object.extend({
1077 direction: 'center',
1078 moveTransition: Effect.Transitions.sinoidal,
1079 scaleTransition: Effect.Transitions.sinoidal,
1080 opacityTransition: Effect.Transitions.none
1081 }, arguments[1] || {});
1082 var oldStyle = {
1083 top: element.style.top,
1084 left: element.style.left,
1085 height: element.style.height,
1086 width: element.style.width,
1087 opacity: element.getInlineOpacity() };
1089 var dims = element.getDimensions();
1090 var moveX, moveY;
1092 switch (options.direction) {
1093 case 'top-left':
1094 moveX = moveY = 0;
1095 break;
1096 case 'top-right':
1097 moveX = dims.width;
1098 moveY = 0;
1099 break;
1100 case 'bottom-left':
1101 moveX = 0;
1102 moveY = dims.height;
1103 break;
1104 case 'bottom-right':
1105 moveX = dims.width;
1106 moveY = dims.height;
1107 break;
1108 case 'center':
1109 moveX = dims.width / 2;
1110 moveY = dims.height / 2;
1111 break;
1114 return new Effect.Parallel(
1115 [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
1116 new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
1117 new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
1118 ], Object.extend({
1119 beforeStartInternal: function(effect) {
1120 effect.effects[0].element.makePositioned().makeClipping();
1122 afterFinishInternal: function(effect) {
1123 effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
1124 }, options)
1128 Effect.Pulsate = function(element) {
1129 element = $(element);
1130 var options = arguments[1] || {};
1131 var oldOpacity = element.getInlineOpacity();
1132 var transition = options.transition || Effect.Transitions.sinoidal;
1133 var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
1134 reverser.bind(transition);
1135 return new Effect.Opacity(element,
1136 Object.extend(Object.extend({ duration: 2.0, from: 0,
1137 afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
1138 }, options), {transition: reverser}));
1141 Effect.Fold = function(element) {
1142 element = $(element);
1143 var oldStyle = {
1144 top: element.style.top,
1145 left: element.style.left,
1146 width: element.style.width,
1147 height: element.style.height };
1148 element.makeClipping();
1149 return new Effect.Scale(element, 5, Object.extend({
1150 scaleContent: false,
1151 scaleX: false,
1152 afterFinishInternal: function(effect) {
1153 new Effect.Scale(element, 1, {
1154 scaleContent: false,
1155 scaleY: false,
1156 afterFinishInternal: function(effect) {
1157 effect.element.hide().undoClipping().setStyle(oldStyle);
1158 } });
1159 }}, arguments[1] || {}));
1162 Effect.Morph = Class.create();
1163 Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), {
1164 initialize: function(element) {
1165 this.element = $(element);
1166 if(!this.element) throw(Effect._elementDoesNotExistError);
1167 var options = Object.extend({
1168 style: {}
1169 }, arguments[1] || {});
1170 if (typeof options.style == 'string') {
1171 if(options.style.indexOf(':') == -1) {
1172 var cssText = '', selector = '.' + options.style;
1173 $A(document.styleSheets).reverse().each(function(styleSheet) {
1174 if (styleSheet.cssRules) cssRules = styleSheet.cssRules;
1175 else if (styleSheet.rules) cssRules = styleSheet.rules;
1176 $A(cssRules).reverse().each(function(rule) {
1177 if (selector == rule.selectorText) {
1178 cssText = rule.style.cssText;
1179 throw $break;
1182 if (cssText) throw $break;
1184 this.style = cssText.parseStyle();
1185 options.afterFinishInternal = function(effect){
1186 effect.element.addClassName(effect.options.style);
1187 effect.transforms.each(function(transform) {
1188 if(transform.style != 'opacity')
1189 effect.element.style[transform.style] = '';
1192 } else this.style = options.style.parseStyle();
1193 } else this.style = $H(options.style)
1194 this.start(options);
1196 setup: function(){
1197 function parseColor(color){
1198 if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
1199 color = color.parseColor();
1200 return $R(0,2).map(function(i){
1201 return parseInt( color.slice(i*2+1,i*2+3), 16 )
1204 this.transforms = this.style.map(function(pair){
1205 var property = pair[0], value = pair[1], unit = null;
1207 if(value.parseColor('#zzzzzz') != '#zzzzzz') {
1208 value = value.parseColor();
1209 unit = 'color';
1210 } else if(property == 'opacity') {
1211 value = parseFloat(value);
1212 if(Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
1213 this.element.setStyle({zoom: 1});
1214 } else if(Element.CSS_LENGTH.test(value)) {
1215 var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
1216 value = parseFloat(components[1]);
1217 unit = (components.length == 3) ? components[2] : null;
1220 var originalValue = this.element.getStyle(property);
1221 return {
1222 style: property.camelize(),
1223 originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
1224 targetValue: unit=='color' ? parseColor(value) : value,
1225 unit: unit
1227 }.bind(this)).reject(function(transform){
1228 return (
1229 (transform.originalValue == transform.targetValue) ||
1231 transform.unit != 'color' &&
1232 (isNaN(transform.originalValue) || isNaN(transform.targetValue))
1237 update: function(position) {
1238 var style = {}, transform, i = this.transforms.length;
1239 while(i--)
1240 style[(transform = this.transforms[i]).style] =
1241 transform.unit=='color' ? '#'+
1242 (Math.round(transform.originalValue[0]+
1243 (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
1244 (Math.round(transform.originalValue[1]+
1245 (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
1246 (Math.round(transform.originalValue[2]+
1247 (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
1248 transform.originalValue + Math.round(
1249 ((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit;
1250 this.element.setStyle(style, true);
1254 Effect.Transform = Class.create();
1255 Object.extend(Effect.Transform.prototype, {
1256 initialize: function(tracks){
1257 this.tracks = [];
1258 this.options = arguments[1] || {};
1259 this.addTracks(tracks);
1261 addTracks: function(tracks){
1262 tracks.each(function(track){
1263 var data = $H(track).values().first();
1264 this.tracks.push($H({
1265 ids: $H(track).keys().first(),
1266 effect: Effect.Morph,
1267 options: { style: data }
1268 }));
1269 }.bind(this));
1270 return this;
1272 play: function(){
1273 return new Effect.Parallel(
1274 this.tracks.map(function(track){
1275 var elements = [$(track.ids) || $$(track.ids)].flatten();
1276 return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) });
1277 }).flatten(),
1278 this.options
1283 Element.CSS_PROPERTIES = $w(
1284 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
1285 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
1286 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
1287 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
1288 'fontSize fontWeight height left letterSpacing lineHeight ' +
1289 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
1290 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
1291 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
1292 'right textIndent top width wordSpacing zIndex');
1294 Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
1296 String.prototype.parseStyle = function(){
1297 var element = document.createElement('div');
1298 element.innerHTML = '<div style="' + this + '"></div>';
1299 var style = element.childNodes[0].style, styleRules = $H();
1301 Element.CSS_PROPERTIES.each(function(property){
1302 if(style[property]) styleRules[property] = style[property];
1304 if(Prototype.Browser.IE && this.indexOf('opacity') > -1) {
1305 styleRules.opacity = this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1];
1307 return styleRules;
1310 Element.morph = function(element, style) {
1311 new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {}));
1312 return element;
1315 ['getInlineOpacity','forceRerendering','setContentZoom',
1316 'collectTextNodes','collectTextNodesIgnoreClass','morph'].each(
1317 function(f) { Element.Methods[f] = Element[f]; }
1320 Element.Methods.visualEffect = function(element, effect, options) {
1321 s = effect.dasherize().camelize();
1322 effect_class = s.charAt(0).toUpperCase() + s.substring(1);
1323 new Effect[effect_class](element, options);
1324 return $(element);
1327 Element.addMethods();
1329 var Droppables = {
1330 drops: [],
1332 remove: function(element) {
1333 this.drops = this.drops.reject(function(d) { return d.element==$(element) });
1336 add: function(element) {
1337 element = $(element);
1338 var options = Object.extend({
1339 greedy: true,
1340 hoverclass: null,
1341 tree: false
1342 }, arguments[1] || {});
1344 // cache containers
1345 if(options.containment) {
1346 options._containers = [];
1347 var containment = options.containment;
1348 if((typeof containment == 'object') &&
1349 (containment.constructor == Array)) {
1350 containment.each( function(c) { options._containers.push($(c)) });
1351 } else {
1352 options._containers.push($(containment));
1356 if(options.accept) options.accept = [options.accept].flatten();
1358 Element.makePositioned(element); // fix IE
1359 options.element = element;
1361 this.drops.push(options);
1364 findDeepestChild: function(drops) {
1365 deepest = drops[0];
1367 for (i = 1; i < drops.length; ++i)
1368 if (Element.isParent(drops[i].element, deepest.element))
1369 deepest = drops[i];
1371 return deepest;
1374 isContained: function(element, drop) {
1375 var containmentNode;
1376 if(drop.tree) {
1377 containmentNode = element.treeNode;
1378 } else {
1379 containmentNode = element.parentNode;
1381 return drop._containers.detect(function(c) { return containmentNode == c });
1384 isAffected: function(point, element, drop) {
1385 return (
1386 (drop.element!=element) &&
1387 ((!drop._containers) ||
1388 this.isContained(element, drop)) &&
1389 ((!drop.accept) ||
1390 (Element.classNames(element).detect(
1391 function(v) { return drop.accept.include(v) } ) )) &&
1392 Position.within(drop.element, point[0], point[1]) );
1395 deactivate: function(drop) {
1396 if(drop.hoverclass)
1397 Element.removeClassName(drop.element, drop.hoverclass);
1398 this.last_active = null;
1401 activate: function(drop) {
1402 if(drop.hoverclass)
1403 Element.addClassName(drop.element, drop.hoverclass);
1404 this.last_active = drop;
1407 show: function(point, element) {
1408 if(!this.drops.length) return;
1409 var affected = [];
1411 if(this.last_active) this.deactivate(this.last_active);
1412 this.drops.each( function(drop) {
1413 if(Droppables.isAffected(point, element, drop))
1414 affected.push(drop);
1417 if(affected.length>0) {
1418 drop = Droppables.findDeepestChild(affected);
1419 Position.within(drop.element, point[0], point[1]);
1420 if(drop.onHover)
1421 drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
1423 Droppables.activate(drop);
1427 fire: function(event, element) {
1428 if(!this.last_active) return;
1429 Position.prepare();
1431 if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
1432 if (this.last_active.onDrop) {
1433 this.last_active.onDrop(element, this.last_active.element, event);
1434 return true;
1438 reset: function() {
1439 if(this.last_active)
1440 this.deactivate(this.last_active);
1444 var Draggables = {
1445 drags: [],
1446 observers: [],
1448 register: function(draggable) {
1449 if(this.drags.length == 0) {
1450 this.eventMouseUp = this.endDrag.bindAsEventListener(this);
1451 this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
1452 this.eventKeypress = this.keyPress.bindAsEventListener(this);
1454 Event.observe(document, "mouseup", this.eventMouseUp);
1455 Event.observe(document, "mousemove", this.eventMouseMove);
1456 Event.observe(document, "keypress", this.eventKeypress);
1458 this.drags.push(draggable);
1461 unregister: function(draggable) {
1462 this.drags = this.drags.reject(function(d) { return d==draggable });
1463 if(this.drags.length == 0) {
1464 Event.stopObserving(document, "mouseup", this.eventMouseUp);
1465 Event.stopObserving(document, "mousemove", this.eventMouseMove);
1466 Event.stopObserving(document, "keypress", this.eventKeypress);
1470 activate: function(draggable) {
1471 if(draggable.options.delay) {
1472 this._timeout = setTimeout(function() {
1473 Draggables._timeout = null;
1474 window.focus();
1475 Draggables.activeDraggable = draggable;
1476 }.bind(this), draggable.options.delay);
1477 } else {
1478 window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
1479 this.activeDraggable = draggable;
1483 deactivate: function() {
1484 this.activeDraggable = null;
1487 updateDrag: function(event) {
1488 if(!this.activeDraggable) return;
1489 var pointer = [Event.pointerX(event), Event.pointerY(event)];
1490 // Mozilla-based browsers fire successive mousemove events with
1491 // the same coordinates, prevent needless redrawing (moz bug?)
1492 if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
1493 this._lastPointer = pointer;
1495 this.activeDraggable.updateDrag(event, pointer);
1498 endDrag: function(event) {
1499 if(this._timeout) {
1500 clearTimeout(this._timeout);
1501 this._timeout = null;
1503 if(!this.activeDraggable) return;
1504 this._lastPointer = null;
1505 this.activeDraggable.endDrag(event);
1506 this.activeDraggable = null;
1509 keyPress: function(event) {
1510 if(this.activeDraggable)
1511 this.activeDraggable.keyPress(event);
1514 addObserver: function(observer) {
1515 this.observers.push(observer);
1516 this._cacheObserverCallbacks();
1519 removeObserver: function(element) { // element instead of observer fixes mem leaks
1520 this.observers = this.observers.reject( function(o) { return o.element==element });
1521 this._cacheObserverCallbacks();
1524 notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
1525 if(this[eventName+'Count'] > 0)
1526 this.observers.each( function(o) {
1527 if(o[eventName]) o[eventName](eventName, draggable, event);
1529 if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
1532 _cacheObserverCallbacks: function() {
1533 ['onStart','onEnd','onDrag'].each( function(eventName) {
1534 Draggables[eventName+'Count'] = Draggables.observers.select(
1535 function(o) { return o[eventName]; }
1536 ).length;
1541 /*--------------------------------------------------------------------------*/
1543 var Draggable = Class.create();
1544 Draggable._dragging = {};
1546 Draggable.prototype = {
1547 initialize: function(element) {
1548 var defaults = {
1549 handle: false,
1550 reverteffect: function(element, top_offset, left_offset) {
1551 var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
1552 new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
1553 queue: {scope:'_draggable', position:'end'}
1556 endeffect: function(element) {
1557 var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0;
1558 new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
1559 queue: {scope:'_draggable', position:'end'},
1560 afterFinish: function(){
1561 Draggable._dragging[element] = false
1563 });
1565 zindex: 1000,
1566 revert: false,
1567 quiet: false,
1568 scroll: false,
1569 scrollSensitivity: 20,
1570 scrollSpeed: 15,
1571 snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
1572 delay: 0
1575 if(!arguments[1] || typeof arguments[1].endeffect == 'undefined')
1576 Object.extend(defaults, {
1577 starteffect: function(element) {
1578 element._opacity = Element.getOpacity(element);
1579 Draggable._dragging[element] = true;
1580 new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
1584 var options = Object.extend(defaults, arguments[1] || {});
1586 this.element = $(element);
1588 if(options.handle && (typeof options.handle == 'string'))
1589 this.handle = this.element.down('.'+options.handle, 0);
1591 if(!this.handle) this.handle = $(options.handle);
1592 if(!this.handle) this.handle = this.element;
1594 if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
1595 options.scroll = $(options.scroll);
1596 this._isScrollChild = Element.childOf(this.element, options.scroll);
1599 Element.makePositioned(this.element); // fix IE
1601 this.delta = this.currentDelta();
1602 this.options = options;
1603 this.dragging = false;
1605 this.eventMouseDown = this.initDrag.bindAsEventListener(this);
1606 Event.observe(this.handle, "mousedown", this.eventMouseDown);
1608 Draggables.register(this);
1611 destroy: function() {
1612 Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
1613 Draggables.unregister(this);
1616 currentDelta: function() {
1617 return([
1618 parseInt(Element.getStyle(this.element,'left') || '0'),
1619 parseInt(Element.getStyle(this.element,'top') || '0')]);
1622 initDrag: function(event) {
1623 if(typeof Draggable._dragging[this.element] != 'undefined' &&
1624 Draggable._dragging[this.element]) return;
1625 if(Event.isLeftClick(event)) {
1626 // abort on form elements, fixes a Firefox issue
1627 var src = Event.element(event);
1628 if((tag_name = src.tagName.toUpperCase()) && (
1629 tag_name=='INPUT' ||
1630 tag_name=='SELECT' ||
1631 tag_name=='OPTION' ||
1632 tag_name=='BUTTON' ||
1633 tag_name=='TEXTAREA')) return;
1635 var pointer = [Event.pointerX(event), Event.pointerY(event)];
1636 var pos = Position.cumulativeOffset(this.element);
1637 this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
1639 Draggables.activate(this);
1640 Event.stop(event);
1644 startDrag: function(event) {
1645 this.dragging = true;
1647 if(this.options.zindex) {
1648 this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
1649 this.element.style.zIndex = this.options.zindex;
1652 if(this.options.ghosting) {
1653 this._clone = this.element.cloneNode(true);
1654 Position.absolutize(this.element);
1655 this.element.parentNode.insertBefore(this._clone, this.element);
1658 if(this.options.scroll) {
1659 if (this.options.scroll == window) {
1660 var where = this._getWindowScroll(this.options.scroll);
1661 this.originalScrollLeft = where.left;
1662 this.originalScrollTop = where.top;
1663 } else {
1664 this.originalScrollLeft = this.options.scroll.scrollLeft;
1665 this.originalScrollTop = this.options.scroll.scrollTop;
1669 Draggables.notify('onStart', this, event);
1671 if(this.options.starteffect) this.options.starteffect(this.element);
1674 updateDrag: function(event, pointer) {
1675 if(!this.dragging) this.startDrag(event);
1677 if(!this.options.quiet){
1678 Position.prepare();
1679 Droppables.show(pointer, this.element);
1682 Draggables.notify('onDrag', this, event);
1684 this.draw(pointer);
1685 if(this.options.change) this.options.change(this);
1687 if(this.options.scroll) {
1688 this.stopScrolling();
1690 var p;
1691 if (this.options.scroll == window) {
1692 with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
1693 } else {
1694 p = Position.page(this.options.scroll);
1695 p[0] += this.options.scroll.scrollLeft + Position.deltaX;
1696 p[1] += this.options.scroll.scrollTop + Position.deltaY;
1697 p.push(p[0]+this.options.scroll.offsetWidth);
1698 p.push(p[1]+this.options.scroll.offsetHeight);
1700 var speed = [0,0];
1701 if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
1702 if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
1703 if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
1704 if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
1705 this.startScrolling(speed);
1708 // fix AppleWebKit rendering
1709 if(Prototype.Browser.WebKit) window.scrollBy(0,0);
1711 Event.stop(event);
1714 finishDrag: function(event, success) {
1715 this.dragging = false;
1717 if(this.options.quiet){
1718 Position.prepare();
1719 var pointer = [Event.pointerX(event), Event.pointerY(event)];
1720 Droppables.show(pointer, this.element);
1723 if(this.options.ghosting) {
1724 Position.relativize(this.element);
1725 Element.remove(this._clone);
1726 this._clone = null;
1729 var dropped = false;
1730 if(success) {
1731 dropped = Droppables.fire(event, this.element);
1732 if (!dropped) dropped = false;
1734 if(dropped && this.options.onDropped) this.options.onDropped(this.element);
1735 Draggables.notify('onEnd', this, event);
1737 var revert = this.options.revert;
1738 if(revert && typeof revert == 'function') revert = revert(this.element);
1740 var d = this.currentDelta();
1741 if(revert && this.options.reverteffect) {
1742 if (dropped == 0 || revert != 'failure')
1743 this.options.reverteffect(this.element,
1744 d[1]-this.delta[1], d[0]-this.delta[0]);
1745 } else {
1746 this.delta = d;
1749 if(this.options.zindex)
1750 this.element.style.zIndex = this.originalZ;
1752 if(this.options.endeffect)
1753 this.options.endeffect(this.element);
1755 Draggables.deactivate(this);
1756 Droppables.reset();
1759 keyPress: function(event) {
1760 if(event.keyCode!=Event.KEY_ESC) return;
1761 this.finishDrag(event, false);
1762 Event.stop(event);
1765 endDrag: function(event) {
1766 if(!this.dragging) return;
1767 this.stopScrolling();
1768 this.finishDrag(event, true);
1769 Event.stop(event);
1772 draw: function(point) {
1773 var pos = Position.cumulativeOffset(this.element);
1774 if(this.options.ghosting) {
1775 var r = Position.realOffset(this.element);
1776 pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
1779 var d = this.currentDelta();
1780 pos[0] -= d[0]; pos[1] -= d[1];
1782 if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
1783 pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
1784 pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
1787 var p = [0,1].map(function(i){
1788 return (point[i]-pos[i]-this.offset[i])
1789 }.bind(this));
1791 if(this.options.snap) {
1792 if(typeof this.options.snap == 'function') {
1793 p = this.options.snap(p[0],p[1],this);
1794 } else {
1795 if(this.options.snap instanceof Array) {
1796 p = p.map( function(v, i) {
1797 return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this))
1798 } else {
1799 p = p.map( function(v) {
1800 return Math.round(v/this.options.snap)*this.options.snap }.bind(this))
1804 var style = this.element.style;
1805 if((!this.options.constraint) || (this.options.constraint=='horizontal'))
1806 style.left = p[0] + "px";
1807 if((!this.options.constraint) || (this.options.constraint=='vertical'))
1808 style.top = p[1] + "px";
1810 if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
1813 stopScrolling: function() {
1814 if(this.scrollInterval) {
1815 clearInterval(this.scrollInterval);
1816 this.scrollInterval = null;
1817 Draggables._lastScrollPointer = null;
1821 startScrolling: function(speed) {
1822 if(!(speed[0] || speed[1])) return;
1823 this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
1824 this.lastScrolled = new Date();
1825 this.scrollInterval = setInterval(this.scroll.bind(this), 10);
1828 scroll: function() {
1829 var current = new Date();
1830 var delta = current - this.lastScrolled;
1831 this.lastScrolled = current;
1832 if(this.options.scroll == window) {
1833 with (this._getWindowScroll(this.options.scroll)) {
1834 if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
1835 var d = delta / 1000;
1836 this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
1839 } else {
1840 this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
1841 this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
1844 Position.prepare();
1845 Droppables.show(Draggables._lastPointer, this.element);
1846 Draggables.notify('onDrag', this);
1847 if (this._isScrollChild) {
1848 Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
1849 Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
1850 Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
1851 if (Draggables._lastScrollPointer[0] < 0)
1852 Draggables._lastScrollPointer[0] = 0;
1853 if (Draggables._lastScrollPointer[1] < 0)
1854 Draggables._lastScrollPointer[1] = 0;
1855 this.draw(Draggables._lastScrollPointer);
1858 if(this.options.change) this.options.change(this);
1861 _getWindowScroll: function(w) {
1862 var T, L, W, H;
1863 with (w.document) {
1864 if (w.document.documentElement && documentElement.scrollTop) {
1865 T = documentElement.scrollTop;
1866 L = documentElement.scrollLeft;
1867 } else if (w.document.body) {
1868 T = body.scrollTop;
1869 L = body.scrollLeft;
1871 if (w.innerWidth) {
1872 W = w.innerWidth;
1873 H = w.innerHeight;
1874 } else if (w.document.documentElement && documentElement.clientWidth) {
1875 W = documentElement.clientWidth;
1876 H = documentElement.clientHeight;
1877 } else {
1878 W = body.offsetWidth;
1879 H = body.offsetHeight
1882 return { top: T, left: L, width: W, height: H };
1886 /*--------------------------------------------------------------------------*/
1888 var SortableObserver = Class.create();
1889 SortableObserver.prototype = {
1890 initialize: function(element, observer) {
1891 this.element = $(element);
1892 this.observer = observer;
1893 this.lastValue = Sortable.serialize(this.element);
1896 onStart: function() {
1897 this.lastValue = Sortable.serialize(this.element);
1900 onEnd: function() {
1901 Sortable.unmark();
1902 if(this.lastValue != Sortable.serialize(this.element))
1903 this.observer(this.element)
1907 var Sortable = {
1908 SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
1910 sortables: {},
1912 _findRootElement: function(element) {
1913 while (element.tagName.toUpperCase() != "BODY") {
1914 if(element.id && Sortable.sortables[element.id]) return element;
1915 element = element.parentNode;
1919 options: function(element) {
1920 element = Sortable._findRootElement($(element));
1921 if(!element) return;
1922 return Sortable.sortables[element.id];
1925 destroy: function(element){
1926 var s = Sortable.options(element);
1928 if(s) {
1929 Draggables.removeObserver(s.element);
1930 s.droppables.each(function(d){ Droppables.remove(d) });
1931 s.draggables.invoke('destroy');
1933 delete Sortable.sortables[s.element.id];
1937 create: function(element) {
1938 element = $(element);
1939 var options = Object.extend({
1940 element: element,
1941 tag: 'li', // assumes li children, override with tag: 'tagname'
1942 dropOnEmpty: false,
1943 tree: false,
1944 treeTag: 'ul',
1945 overlap: 'vertical', // one of 'vertical', 'horizontal'
1946 constraint: 'vertical', // one of 'vertical', 'horizontal', false
1947 containment: element, // also takes array of elements (or id's); or false
1948 handle: false, // or a CSS class
1949 only: false,
1950 delay: 0,
1951 hoverclass: null,
1952 ghosting: false,
1953 quiet: false,
1954 scroll: false,
1955 scrollSensitivity: 20,
1956 scrollSpeed: 15,
1957 format: this.SERIALIZE_RULE,
1959 // these take arrays of elements or ids and can be
1960 // used for better initialization performance
1961 elements: false,
1962 handles: false,
1964 onChange: Prototype.emptyFunction,
1965 onUpdate: Prototype.emptyFunction
1966 }, arguments[1] || {});
1968 // clear any old sortable with same element
1969 this.destroy(element);
1971 // build options for the draggables
1972 var options_for_draggable = {
1973 revert: true,
1974 quiet: options.quiet,
1975 scroll: options.scroll,
1976 scrollSpeed: options.scrollSpeed,
1977 scrollSensitivity: options.scrollSensitivity,
1978 delay: options.delay,
1979 ghosting: options.ghosting,
1980 constraint: options.constraint,
1981 handle: options.handle };
1983 if(options.starteffect)
1984 options_for_draggable.starteffect = options.starteffect;
1986 if(options.reverteffect)
1987 options_for_draggable.reverteffect = options.reverteffect;
1988 else
1989 if(options.ghosting) options_for_draggable.reverteffect = function(element) {
1990 element.style.top = 0;
1991 element.style.left = 0;
1994 if(options.endeffect)
1995 options_for_draggable.endeffect = options.endeffect;
1997 if(options.zindex)
1998 options_for_draggable.zindex = options.zindex;
2000 // build options for the droppables
2001 var options_for_droppable = {
2002 overlap: options.overlap,
2003 containment: options.containment,
2004 tree: options.tree,
2005 hoverclass: options.hoverclass,
2006 onHover: Sortable.onHover
2009 var options_for_tree = {
2010 onHover: Sortable.onEmptyHover,
2011 overlap: options.overlap,
2012 containment: options.containment,
2013 hoverclass: options.hoverclass
2016 // fix for gecko engine
2017 Element.cleanWhitespace(element);
2019 options.draggables = [];
2020 options.droppables = [];
2022 // drop on empty handling
2023 if(options.dropOnEmpty || options.tree) {
2024 Droppables.add(element, options_for_tree);
2025 options.droppables.push(element);
2028 (options.elements || this.findElements(element, options) || []).each( function(e,i) {
2029 var handle = options.handles ? $(options.handles[i]) :
2030 (options.handle ? $(e).getElementsByClassName(options.handle)[0] : e);
2031 options.draggables.push(
2032 new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
2033 Droppables.add(e, options_for_droppable);
2034 if(options.tree) e.treeNode = element;
2035 options.droppables.push(e);
2038 if(options.tree) {
2039 (Sortable.findTreeElements(element, options) || []).each( function(e) {
2040 Droppables.add(e, options_for_tree);
2041 e.treeNode = element;
2042 options.droppables.push(e);
2046 // keep reference
2047 this.sortables[element.id] = options;
2049 // for onupdate
2050 Draggables.addObserver(new SortableObserver(element, options.onUpdate));
2054 // return all suitable-for-sortable elements in a guaranteed order
2055 findElements: function(element, options) {
2056 return Element.findChildren(
2057 element, options.only, options.tree ? true : false, options.tag);
2060 findTreeElements: function(element, options) {
2061 return Element.findChildren(
2062 element, options.only, options.tree ? true : false, options.treeTag);
2065 onHover: function(element, dropon, overlap) {
2066 if(Element.isParent(dropon, element)) return;
2068 if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
2069 return;
2070 } else if(overlap>0.5) {
2071 Sortable.mark(dropon, 'before');
2072 if(dropon.previousSibling != element) {
2073 var oldParentNode = element.parentNode;
2074 element.style.visibility = "hidden"; // fix gecko rendering
2075 dropon.parentNode.insertBefore(element, dropon);
2076 if(dropon.parentNode!=oldParentNode)
2077 Sortable.options(oldParentNode).onChange(element);
2078 Sortable.options(dropon.parentNode).onChange(element);
2080 } else {
2081 Sortable.mark(dropon, 'after');
2082 var nextElement = dropon.nextSibling || null;
2083 if(nextElement != element) {
2084 var oldParentNode = element.parentNode;
2085 element.style.visibility = "hidden"; // fix gecko rendering
2086 dropon.parentNode.insertBefore(element, nextElement);
2087 if(dropon.parentNode!=oldParentNode)
2088 Sortable.options(oldParentNode).onChange(element);
2089 Sortable.options(dropon.parentNode).onChange(element);
2094 onEmptyHover: function(element, dropon, overlap) {
2095 var oldParentNode = element.parentNode;
2096 var droponOptions = Sortable.options(dropon);
2098 if(!Element.isParent(dropon, element)) {
2099 var index;
2101 var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
2102 var child = null;
2104 if(children) {
2105 var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
2107 for (index = 0; index < children.length; index += 1) {
2108 if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
2109 offset -= Element.offsetSize (children[index], droponOptions.overlap);
2110 } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
2111 child = index + 1 < children.length ? children[index + 1] : null;
2112 break;
2113 } else {
2114 child = children[index];
2115 break;
2120 dropon.insertBefore(element, child);
2122 Sortable.options(oldParentNode).onChange(element);
2123 droponOptions.onChange(element);
2127 unmark: function() {
2128 if(Sortable._marker) Sortable._marker.hide();
2131 mark: function(dropon, position) {
2132 // mark on ghosting only
2133 var sortable = Sortable.options(dropon.parentNode);
2134 if(sortable && !sortable.ghosting) return;
2136 if(!Sortable._marker) {
2137 Sortable._marker =
2138 ($('dropmarker') || Element.extend(document.createElement('DIV'))).
2139 hide().addClassName('dropmarker').setStyle({position:'absolute'});
2140 document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
2142 var offsets = Position.cumulativeOffset(dropon);
2143 Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
2145 if(position=='after')
2146 if(sortable.overlap == 'horizontal')
2147 Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
2148 else
2149 Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
2151 Sortable._marker.show();
2154 _tree: function(element, options, parent) {
2155 var children = Sortable.findElements(element, options) || [];
2157 for (var i = 0; i < children.length; ++i) {
2158 var match = children[i].id.match(options.format);
2160 if (!match) continue;
2162 var child = {
2163 id: encodeURIComponent(match ? match[1] : null),
2164 element: element,
2165 parent: parent,
2166 children: [],
2167 position: parent.children.length,
2168 container: $(children[i]).down(options.treeTag)
2171 /* Get the element containing the children and recurse over it */
2172 if (child.container)
2173 this._tree(child.container, options, child)
2175 parent.children.push (child);
2178 return parent;
2181 tree: function(element) {
2182 element = $(element);
2183 var sortableOptions = this.options(element);
2184 var options = Object.extend({
2185 tag: sortableOptions.tag,
2186 treeTag: sortableOptions.treeTag,
2187 only: sortableOptions.only,
2188 name: element.id,
2189 format: sortableOptions.format
2190 }, arguments[1] || {});
2192 var root = {
2193 id: null,
2194 parent: null,
2195 children: [],
2196 container: element,
2197 position: 0
2200 return Sortable._tree(element, options, root);
2203 /* Construct a [i] index for a particular node */
2204 _constructIndex: function(node) {
2205 var index = '';
2206 do {
2207 if (node.id) index = '[' + node.position + ']' + index;
2208 } while ((node = node.parent) != null);
2209 return index;
2212 sequence: function(element) {
2213 element = $(element);
2214 var options = Object.extend(this.options(element), arguments[1] || {});
2216 return $(this.findElements(element, options) || []).map( function(item) {
2217 return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
2221 setSequence: function(element, new_sequence) {
2222 element = $(element);
2223 var options = Object.extend(this.options(element), arguments[2] || {});
2225 var nodeMap = {};
2226 this.findElements(element, options).each( function(n) {
2227 if (n.id.match(options.format))
2228 nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
2229 n.parentNode.removeChild(n);
2232 new_sequence.each(function(ident) {
2233 var n = nodeMap[ident];
2234 if (n) {
2235 n[1].appendChild(n[0]);
2236 delete nodeMap[ident];
2241 serialize: function(element) {
2242 element = $(element);
2243 var options = Object.extend(Sortable.options(element), arguments[1] || {});
2244 var name = encodeURIComponent(
2245 (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
2247 if (options.tree) {
2248 return Sortable.tree(element, arguments[1]).children.map( function (item) {
2249 return [name + Sortable._constructIndex(item) + "[id]=" +
2250 encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
2251 }).flatten().join('&');
2252 } else {
2253 return Sortable.sequence(element, arguments[1]).map( function(item) {
2254 return name + "[]=" + encodeURIComponent(item);
2255 }).join('&');
2260 // Returns true if child is contained within element
2261 Element.isParent = function(child, element) {
2262 if (!child.parentNode || child == element) return false;
2263 if (child.parentNode == element) return true;
2264 return Element.isParent(child.parentNode, element);
2267 Element.findChildren = function(element, only, recursive, tagName) {
2268 if(!element.hasChildNodes()) return null;
2269 tagName = tagName.toUpperCase();
2270 if(only) only = [only].flatten();
2271 var elements = [];
2272 $A(element.childNodes).each( function(e) {
2273 if(e.tagName && e.tagName.toUpperCase()==tagName &&
2274 (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
2275 elements.push(e);
2276 if(recursive) {
2277 var grandchildren = Element.findChildren(e, only, recursive, tagName);
2278 if(grandchildren) elements.push(grandchildren);
2282 return (elements.length>0 ? elements.flatten() : []);
2285 Element.offsetSize = function (element, type) {
2286 return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
2290 // Autocompleter.Base handles all the autocompletion functionality
2291 // that's independent of the data source for autocompletion. This
2292 // includes drawing the autocompletion menu, observing keyboard
2293 // and mouse events, and similar.
2295 // Specific autocompleters need to provide, at the very least,
2296 // a getUpdatedChoices function that will be invoked every time
2297 // the text inside the monitored textbox changes. This method
2298 // should get the text for which to provide autocompletion by
2299 // invoking this.getToken(), NOT by directly accessing
2300 // this.element.value. This is to allow incremental tokenized
2301 // autocompletion. Specific auto-completion logic (AJAX, etc)
2302 // belongs in getUpdatedChoices.
2304 // Tokenized incremental autocompletion is enabled automatically
2305 // when an autocompleter is instantiated with the 'tokens' option
2306 // in the options parameter, e.g.:
2307 // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
2308 // will incrementally autocomplete with a comma as the token.
2309 // Additionally, ',' in the above example can be replaced with
2310 // a token array, e.g. { tokens: [',', '\n'] } which
2311 // enables autocompletion on multiple tokens. This is most
2312 // useful when one of the tokens is \n (a newline), as it
2313 // allows smart autocompletion after linebreaks.
2315 if(typeof Effect == 'undefined')
2316 throw("controls.js requires including script.aculo.us' effects.js library");
2318 var Autocompleter = {}
2319 Autocompleter.Base = function() {};
2320 Autocompleter.Base.prototype = {
2321 baseInitialize: function(element, update, options) {
2322 element = $(element)
2323 this.element = element;
2324 this.update = $(update);
2325 this.hasFocus = false;
2326 this.changed = false;
2327 this.active = false;
2328 this.index = 0;
2329 this.entryCount = 0;
2331 if(this.setOptions)
2332 this.setOptions(options);
2333 else
2334 this.options = options || {};
2336 this.options.paramName = this.options.paramName || this.element.name;
2337 this.options.tokens = this.options.tokens || [];
2338 this.options.frequency = this.options.frequency || 0.4;
2339 this.options.minChars = this.options.minChars || 1;
2340 this.options.onShow = this.options.onShow ||
2341 function(element, update){
2342 if(!update.style.position || update.style.position=='absolute') {
2343 update.style.position = 'absolute';
2344 Position.clone(element, update, {
2345 setHeight: false,
2346 offsetTop: element.offsetHeight
2349 Effect.Appear(update,{duration:0.15});
2351 this.options.onHide = this.options.onHide ||
2352 function(element, update){ new Effect.Fade(update,{duration:0.15}) };
2354 if(typeof(this.options.tokens) == 'string')
2355 this.options.tokens = new Array(this.options.tokens);
2357 this.observer = null;
2359 this.element.setAttribute('autocomplete','off');
2361 Element.hide(this.update);
2363 Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
2364 Event.observe(this.element, 'keypress', this.onKeyPress.bindAsEventListener(this));
2366 // Turn autocomplete back on when the user leaves the page, so that the
2367 // field's value will be remembered on Mozilla-based browsers.
2368 Event.observe(window, 'beforeunload', function(){
2369 element.setAttribute('autocomplete', 'on');
2373 show: function() {
2374 if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
2375 if(!this.iefix &&
2376 (Prototype.Browser.IE) &&
2377 (Element.getStyle(this.update, 'position')=='absolute')) {
2378 new Insertion.After(this.update,
2379 '<iframe id="' + this.update.id + '_iefix" '+
2380 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
2381 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
2382 this.iefix = $(this.update.id+'_iefix');
2384 if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
2387 fixIEOverlapping: function() {
2388 Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
2389 this.iefix.style.zIndex = 1;
2390 this.update.style.zIndex = 2;
2391 Element.show(this.iefix);
2394 hide: function() {
2395 this.stopIndicator();
2396 if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
2397 if(this.iefix) Element.hide(this.iefix);
2400 startIndicator: function() {
2401 if(this.options.indicator) Element.show(this.options.indicator);
2404 stopIndicator: function() {
2405 if(this.options.indicator) Element.hide(this.options.indicator);
2408 onKeyPress: function(event) {
2409 if(this.active)
2410 switch(event.keyCode) {
2411 case Event.KEY_TAB:
2412 case Event.KEY_RETURN:
2413 this.selectEntry();
2414 Event.stop(event);
2415 case Event.KEY_ESC:
2416 this.hide();
2417 this.active = false;
2418 Event.stop(event);
2419 return;
2420 case Event.KEY_LEFT:
2421 case Event.KEY_RIGHT:
2422 return;
2423 case Event.KEY_UP:
2424 this.markPrevious();
2425 this.render();
2426 if(Prototype.Browser.WebKit) Event.stop(event);
2427 return;
2428 case Event.KEY_DOWN:
2429 this.markNext();
2430 this.render();
2431 if(Prototype.Browser.WebKit) Event.stop(event);
2432 return;
2434 else
2435 if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
2436 (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
2438 this.changed = true;
2439 this.hasFocus = true;
2441 if(this.observer) clearTimeout(this.observer);
2442 this.observer =
2443 setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
2446 activate: function() {
2447 this.changed = false;
2448 this.hasFocus = true;
2449 this.getUpdatedChoices();
2452 onHover: function(event) {
2453 var element = Event.findElement(event, 'LI');
2454 if(this.index != element.autocompleteIndex)
2456 this.index = element.autocompleteIndex;
2457 this.render();
2459 Event.stop(event);
2462 onClick: function(event) {
2463 var element = Event.findElement(event, 'LI');
2464 this.index = element.autocompleteIndex;
2465 this.selectEntry();
2466 this.hide();
2469 onBlur: function(event) {
2470 // needed to make click events working
2471 setTimeout(this.hide.bind(this), 250);
2472 this.hasFocus = false;
2473 this.active = false;
2476 render: function() {
2477 if(this.entryCount > 0) {
2478 for (var i = 0; i < this.entryCount; i++)
2479 this.index==i ?
2480 Element.addClassName(this.getEntry(i),"selected") :
2481 Element.removeClassName(this.getEntry(i),"selected");
2482 if(this.hasFocus) {
2483 this.show();
2484 this.active = true;
2486 } else {
2487 this.active = false;
2488 this.hide();
2492 markPrevious: function() {
2493 if(this.index > 0) this.index--
2494 else this.index = this.entryCount-1;
2495 this.getEntry(this.index).scrollIntoView(true);
2498 markNext: function() {
2499 if(this.index < this.entryCount-1) this.index++
2500 else this.index = 0;
2501 this.getEntry(this.index).scrollIntoView(false);
2504 getEntry: function(index) {
2505 return this.update.firstChild.childNodes[index];
2508 getCurrentEntry: function() {
2509 return this.getEntry(this.index);
2512 selectEntry: function() {
2513 this.active = false;
2514 this.updateElement(this.getCurrentEntry());
2517 updateElement: function(selectedElement) {
2518 if (this.options.updateElement) {
2519 this.options.updateElement(selectedElement);
2520 return;
2522 var value = '';
2523 if (this.options.select) {
2524 var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
2525 if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
2526 } else
2527 value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
2529 var lastTokenPos = this.findLastToken();
2530 if (lastTokenPos != -1) {
2531 var newValue = this.element.value.substr(0, lastTokenPos + 1);
2532 var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
2533 if (whitespace)
2534 newValue += whitespace[0];
2535 this.element.value = newValue + value;
2536 } else {
2537 this.element.value = value;
2539 this.element.focus();
2541 if (this.options.afterUpdateElement)
2542 this.options.afterUpdateElement(this.element, selectedElement);
2545 updateChoices: function(choices) {
2546 if(!this.changed && this.hasFocus) {
2547 this.update.innerHTML = choices;
2548 Element.cleanWhitespace(this.update);
2549 Element.cleanWhitespace(this.update.down());
2551 if(this.update.firstChild && this.update.down().childNodes) {
2552 this.entryCount =
2553 this.update.down().childNodes.length;
2554 for (var i = 0; i < this.entryCount; i++) {
2555 var entry = this.getEntry(i);
2556 entry.autocompleteIndex = i;
2557 this.addObservers(entry);
2559 } else {
2560 this.entryCount = 0;
2563 this.stopIndicator();
2564 this.index = 0;
2566 if(this.entryCount==1 && this.options.autoSelect) {
2567 this.selectEntry();
2568 this.hide();
2569 } else {
2570 this.render();
2575 addObservers: function(element) {
2576 Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
2577 Event.observe(element, "click", this.onClick.bindAsEventListener(this));
2580 onObserverEvent: function() {
2581 this.changed = false;
2582 if(this.getToken().length>=this.options.minChars) {
2583 this.getUpdatedChoices();
2584 } else {
2585 this.active = false;
2586 this.hide();
2590 getToken: function() {
2591 var tokenPos = this.findLastToken();
2592 if (tokenPos != -1)
2593 var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,'');
2594 else
2595 var ret = this.element.value;
2597 return /\n/.test(ret) ? '' : ret;
2600 findLastToken: function() {
2601 var lastTokenPos = -1;
2603 for (var i=0; i<this.options.tokens.length; i++) {
2604 var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
2605 if (thisTokenPos > lastTokenPos)
2606 lastTokenPos = thisTokenPos;
2608 return lastTokenPos;
2612 Ajax.Autocompleter = Class.create();
2613 Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {
2614 initialize: function(element, update, url, options) {
2615 this.baseInitialize(element, update, options);
2616 this.options.asynchronous = true;
2617 this.options.onComplete = this.onComplete.bind(this);
2618 this.options.defaultParams = this.options.parameters || null;
2619 this.url = url;
2622 getUpdatedChoices: function() {
2623 this.startIndicator();
2625 var entry = encodeURIComponent(this.options.paramName) + '=' +
2626 encodeURIComponent(this.getToken());
2628 this.options.parameters = this.options.callback ?
2629 this.options.callback(this.element, entry) : entry;
2631 if(this.options.defaultParams)
2632 this.options.parameters += '&' + this.options.defaultParams;
2634 new Ajax.Request(this.url, this.options);
2637 onComplete: function(request) {
2638 this.updateChoices(request.responseText);
2643 // The local array autocompleter. Used when you'd prefer to
2644 // inject an array of autocompletion options into the page, rather
2645 // than sending out Ajax queries, which can be quite slow sometimes.
2647 // The constructor takes four parameters. The first two are, as usual,
2648 // the id of the monitored textbox, and id of the autocompletion menu.
2649 // The third is the array you want to autocomplete from, and the fourth
2650 // is the options block.
2652 // Extra local autocompletion options:
2653 // - choices - How many autocompletion choices to offer
2655 // - partialSearch - If false, the autocompleter will match entered
2656 // text only at the beginning of strings in the
2657 // autocomplete array. Defaults to true, which will
2658 // match text at the beginning of any *word* in the
2659 // strings in the autocomplete array. If you want to
2660 // search anywhere in the string, additionally set
2661 // the option fullSearch to true (default: off).
2663 // - fullSsearch - Search anywhere in autocomplete array strings.
2665 // - partialChars - How many characters to enter before triggering
2666 // a partial match (unlike minChars, which defines
2667 // how many characters are required to do any match
2668 // at all). Defaults to 2.
2670 // - ignoreCase - Whether to ignore case when autocompleting.
2671 // Defaults to true.
2673 // It's possible to pass in a custom function as the 'selector'
2674 // option, if you prefer to write your own autocompletion logic.
2675 // In that case, the other options above will not apply unless
2676 // you support them.
2678 Autocompleter.Local = Class.create();
2679 Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), {
2680 initialize: function(element, update, array, options) {
2681 this.baseInitialize(element, update, options);
2682 this.options.array = array;
2685 getUpdatedChoices: function() {
2686 this.updateChoices(this.options.selector(this));
2689 setOptions: function(options) {
2690 this.options = Object.extend({
2691 choices: 10,
2692 partialSearch: true,
2693 partialChars: 2,
2694 ignoreCase: true,
2695 fullSearch: false,
2696 selector: function(instance) {
2697 var ret = []; // Beginning matches
2698 var partial = []; // Inside matches
2699 var entry = instance.getToken();
2700 var count = 0;
2702 for (var i = 0; i < instance.options.array.length &&
2703 ret.length < instance.options.choices ; i++) {
2705 var elem = instance.options.array[i];
2706 var foundPos = instance.options.ignoreCase ?
2707 elem.toLowerCase().indexOf(entry.toLowerCase()) :
2708 elem.indexOf(entry);
2710 while (foundPos != -1) {
2711 if (foundPos == 0 && elem.length != entry.length) {
2712 ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
2713 elem.substr(entry.length) + "</li>");
2714 break;
2715 } else if (entry.length >= instance.options.partialChars &&
2716 instance.options.partialSearch && foundPos != -1) {
2717 if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
2718 partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
2719 elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
2720 foundPos + entry.length) + "</li>");
2721 break;
2725 foundPos = instance.options.ignoreCase ?
2726 elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
2727 elem.indexOf(entry, foundPos + 1);
2731 if (partial.length)
2732 ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
2733 return "<ul>" + ret.join('') + "</ul>";
2735 }, options || {});
2739 // AJAX in-place editor
2741 // see documentation on http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor
2743 // Use this if you notice weird scrolling problems on some browsers,
2744 // the DOM might be a bit confused when this gets called so do this
2745 // waits 1 ms (with setTimeout) until it does the activation
2746 Field.scrollFreeActivate = function(field) {
2747 setTimeout(function() {
2748 Field.activate(field);
2749 }, 1);
2752 Ajax.InPlaceEditor = Class.create();
2753 Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99";
2754 Ajax.InPlaceEditor.prototype = {
2755 initialize: function(element, url, options) {
2756 this.url = url;
2757 this.element = $(element);
2759 this.options = Object.extend({
2760 paramName: "value",
2761 okButton: true,
2762 okLink: false,
2763 okText: "ok",
2764 cancelButton: false,
2765 cancelLink: true,
2766 cancelText: "cancel",
2767 textBeforeControls: '',
2768 textBetweenControls: '',
2769 textAfterControls: '',
2770 savingText: "Saving...",
2771 clickToEditText: "Click to edit",
2772 okText: "ok",
2773 rows: 1,
2774 onComplete: function(transport, element) {
2775 new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
2777 onFailure: function(transport) {
2778 alert("Error communicating with the server: " + transport.responseText.stripTags());
2780 callback: function(form) {
2781 return Form.serialize(form);
2783 handleLineBreaks: true,
2784 loadingText: 'Loading...',
2785 savingClassName: 'inplaceeditor-saving',
2786 loadingClassName: 'inplaceeditor-loading',
2787 formClassName: 'inplaceeditor-form',
2788 highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
2789 highlightendcolor: "#FFFFFF",
2790 externalControl: null,
2791 submitOnBlur: false,
2792 ajaxOptions: {},
2793 evalScripts: false
2794 }, options || {});
2796 if(!this.options.formId && this.element.id) {
2797 this.options.formId = this.element.id + "-inplaceeditor";
2798 if ($(this.options.formId)) {
2799 // there's already a form with that name, don't specify an id
2800 this.options.formId = null;
2804 if (this.options.externalControl) {
2805 this.options.externalControl = $(this.options.externalControl);
2808 this.originalBackground = Element.getStyle(this.element, 'background-color');
2809 if (!this.originalBackground) {
2810 this.originalBackground = "transparent";
2813 this.element.title = this.options.clickToEditText;
2815 this.onclickListener = this.enterEditMode.bindAsEventListener(this);
2816 this.mouseoverListener = this.enterHover.bindAsEventListener(this);
2817 this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
2818 Event.observe(this.element, 'click', this.onclickListener);
2819 Event.observe(this.element, 'mouseover', this.mouseoverListener);
2820 Event.observe(this.element, 'mouseout', this.mouseoutListener);
2821 if (this.options.externalControl) {
2822 Event.observe(this.options.externalControl, 'click', this.onclickListener);
2823 Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
2824 Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
2827 enterEditMode: function(evt) {
2828 if (this.saving) return;
2829 if (this.editing) return;
2830 this.editing = true;
2831 this.onEnterEditMode();
2832 if (this.options.externalControl) {
2833 Element.hide(this.options.externalControl);
2835 Element.hide(this.element);
2836 this.createForm();
2837 this.element.parentNode.insertBefore(this.form, this.element);
2838 if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField);
2839 // stop the event to avoid a page refresh in Safari
2840 if (evt) {
2841 Event.stop(evt);
2843 return false;
2845 createForm: function() {
2846 this.form = document.createElement("form");
2847 this.form.id = this.options.formId;
2848 Element.addClassName(this.form, this.options.formClassName)
2849 this.form.onsubmit = this.onSubmit.bind(this);
2851 this.createEditField();
2853 if (this.options.textarea) {
2854 var br = document.createElement("br");
2855 this.form.appendChild(br);
2858 if (this.options.textBeforeControls)
2859 this.form.appendChild(document.createTextNode(this.options.textBeforeControls));
2861 if (this.options.okButton) {
2862 var okButton = document.createElement("input");
2863 okButton.type = "submit";
2864 okButton.value = this.options.okText;
2865 okButton.className = 'editor_ok_button';
2866 this.form.appendChild(okButton);
2869 if (this.options.okLink) {
2870 var okLink = document.createElement("a");
2871 okLink.href = "#";
2872 okLink.appendChild(document.createTextNode(this.options.okText));
2873 okLink.onclick = this.onSubmit.bind(this);
2874 okLink.className = 'editor_ok_link';
2875 this.form.appendChild(okLink);
2878 if (this.options.textBetweenControls &&
2879 (this.options.okLink || this.options.okButton) &&
2880 (this.options.cancelLink || this.options.cancelButton))
2881 this.form.appendChild(document.createTextNode(this.options.textBetweenControls));
2883 if (this.options.cancelButton) {
2884 var cancelButton = document.createElement("input");
2885 cancelButton.type = "submit";
2886 cancelButton.value = this.options.cancelText;
2887 cancelButton.onclick = this.onclickCancel.bind(this);
2888 cancelButton.className = 'editor_cancel_button';
2889 this.form.appendChild(cancelButton);
2892 if (this.options.cancelLink) {
2893 var cancelLink = document.createElement("a");
2894 cancelLink.href = "#";
2895 cancelLink.appendChild(document.createTextNode(this.options.cancelText));
2896 cancelLink.onclick = this.onclickCancel.bind(this);
2897 cancelLink.className = 'editor_cancel editor_cancel_link';
2898 this.form.appendChild(cancelLink);
2901 if (this.options.textAfterControls)
2902 this.form.appendChild(document.createTextNode(this.options.textAfterControls));
2904 hasHTMLLineBreaks: function(string) {
2905 if (!this.options.handleLineBreaks) return false;
2906 return string.match(/<br/i) || string.match(/<p>/i);
2908 convertHTMLLineBreaks: function(string) {
2909 return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
2911 createEditField: function() {
2912 var text;
2913 if(this.options.loadTextURL) {
2914 text = this.options.loadingText;
2915 } else {
2916 text = this.getText();
2919 var obj = this;
2921 if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
2922 this.options.textarea = false;
2923 var textField = document.createElement("input");
2924 textField.obj = this;
2925 textField.type = "text";
2926 textField.name = this.options.paramName;
2927 textField.value = text;
2928 textField.style.backgroundColor = this.options.highlightcolor;
2929 textField.className = 'editor_field';
2930 var size = this.options.size || this.options.cols || 0;
2931 if (size != 0) textField.size = size;
2932 if (this.options.submitOnBlur)
2933 textField.onblur = this.onSubmit.bind(this);
2934 this.editField = textField;
2935 } else {
2936 this.options.textarea = true;
2937 var textArea = document.createElement("textarea");
2938 textArea.obj = this;
2939 textArea.name = this.options.paramName;
2940 textArea.value = this.convertHTMLLineBreaks(text);
2941 textArea.rows = this.options.rows;
2942 textArea.cols = this.options.cols || 40;
2943 textArea.className = 'editor_field';
2944 if (this.options.submitOnBlur)
2945 textArea.onblur = this.onSubmit.bind(this);
2946 this.editField = textArea;
2949 if(this.options.loadTextURL) {
2950 this.loadExternalText();
2952 this.form.appendChild(this.editField);
2954 getText: function() {
2955 return this.element.innerHTML;
2957 loadExternalText: function() {
2958 Element.addClassName(this.form, this.options.loadingClassName);
2959 this.editField.disabled = true;
2960 new Ajax.Request(
2961 this.options.loadTextURL,
2962 Object.extend({
2963 asynchronous: true,
2964 onComplete: this.onLoadedExternalText.bind(this)
2965 }, this.options.ajaxOptions)
2968 onLoadedExternalText: function(transport) {
2969 Element.removeClassName(this.form, this.options.loadingClassName);
2970 this.editField.disabled = false;
2971 this.editField.value = transport.responseText.stripTags();
2972 Field.scrollFreeActivate(this.editField);
2974 onclickCancel: function() {
2975 this.onComplete();
2976 this.leaveEditMode();
2977 return false;
2979 onFailure: function(transport) {
2980 this.options.onFailure(transport);
2981 if (this.oldInnerHTML) {
2982 this.element.innerHTML = this.oldInnerHTML;
2983 this.oldInnerHTML = null;
2985 return false;
2987 onSubmit: function() {
2988 // onLoading resets these so we need to save them away for the Ajax call
2989 var form = this.form;
2990 var value = this.editField.value;
2992 // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
2993 // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
2994 // to be displayed indefinitely
2995 this.onLoading();
2997 if (this.options.evalScripts) {
2998 new Ajax.Request(
2999 this.url, Object.extend({
3000 parameters: this.options.callback(form, value),
3001 onComplete: this.onComplete.bind(this),
3002 onFailure: this.onFailure.bind(this),
3003 asynchronous:true,
3004 evalScripts:true
3005 }, this.options.ajaxOptions));
3006 } else {
3007 new Ajax.Updater(
3008 { success: this.element,
3009 // don't update on failure (this could be an option)
3010 failure: null },
3011 this.url, Object.extend({
3012 parameters: this.options.callback(form, value),
3013 onComplete: this.onComplete.bind(this),
3014 onFailure: this.onFailure.bind(this)
3015 }, this.options.ajaxOptions));
3017 // stop the event to avoid a page refresh in Safari
3018 if (arguments.length > 1) {
3019 Event.stop(arguments[0]);
3021 return false;
3023 onLoading: function() {
3024 this.saving = true;
3025 this.removeForm();
3026 this.leaveHover();
3027 this.showSaving();
3029 showSaving: function() {
3030 this.oldInnerHTML = this.element.innerHTML;
3031 this.element.innerHTML = this.options.savingText;
3032 Element.addClassName(this.element, this.options.savingClassName);
3033 this.element.style.backgroundColor = this.originalBackground;
3034 Element.show(this.element);
3036 removeForm: function() {
3037 if(this.form) {
3038 if (this.form.parentNode) Element.remove(this.form);
3039 this.form = null;
3042 enterHover: function() {
3043 if (this.saving) return;
3044 this.element.style.backgroundColor = this.options.highlightcolor;
3045 if (this.effect) {
3046 this.effect.cancel();
3048 Element.addClassName(this.element, this.options.hoverClassName)
3050 leaveHover: function() {
3051 if (this.options.backgroundColor) {
3052 this.element.style.backgroundColor = this.oldBackground;
3054 Element.removeClassName(this.element, this.options.hoverClassName)
3055 if (this.saving) return;
3056 this.effect = new Effect.Highlight(this.element, {
3057 startcolor: this.options.highlightcolor,
3058 endcolor: this.options.highlightendcolor,
3059 restorecolor: this.originalBackground
3062 leaveEditMode: function() {
3063 Element.removeClassName(this.element, this.options.savingClassName);
3064 this.removeForm();
3065 this.leaveHover();
3066 this.element.style.backgroundColor = this.originalBackground;
3067 Element.show(this.element);
3068 if (this.options.externalControl) {
3069 Element.show(this.options.externalControl);
3071 this.editing = false;
3072 this.saving = false;
3073 this.oldInnerHTML = null;
3074 this.onLeaveEditMode();
3076 onComplete: function(transport) {
3077 this.leaveEditMode();
3078 this.options.onComplete.bind(this)(transport, this.element);
3080 onEnterEditMode: function() {},
3081 onLeaveEditMode: function() {},
3082 dispose: function() {
3083 if (this.oldInnerHTML) {
3084 this.element.innerHTML = this.oldInnerHTML;
3086 this.leaveEditMode();
3087 Event.stopObserving(this.element, 'click', this.onclickListener);
3088 Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
3089 Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
3090 if (this.options.externalControl) {
3091 Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
3092 Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
3093 Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
3098 Ajax.InPlaceCollectionEditor = Class.create();
3099 Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype);
3100 Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
3101 createEditField: function() {
3102 if (!this.cached_selectTag) {
3103 var selectTag = document.createElement("select");
3104 var collection = this.options.collection || [];
3105 var optionTag;
3106 collection.each(function(e,i) {
3107 optionTag = document.createElement("option");
3108 optionTag.value = (e instanceof Array) ? e[0] : e;
3109 if((typeof this.options.value == 'undefined') &&
3110 ((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true;
3111 if(this.options.value==optionTag.value) optionTag.selected = true;
3112 optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
3113 selectTag.appendChild(optionTag);
3114 }.bind(this));
3115 this.cached_selectTag = selectTag;
3118 this.editField = this.cached_selectTag;
3119 if(this.options.loadTextURL) this.loadExternalText();
3120 this.form.appendChild(this.editField);
3121 this.options.callback = function(form, value) {
3122 return "value=" + encodeURIComponent(value);
3127 // Delayed observer, like Form.Element.Observer,
3128 // but waits for delay after last key input
3129 // Ideal for live-search fields
3131 Form.Element.DelayedObserver = Class.create();
3132 Form.Element.DelayedObserver.prototype = {
3133 initialize: function(element, delay, callback) {
3134 this.delay = delay || 0.5;
3135 this.element = $(element);
3136 this.callback = callback;
3137 this.timer = null;
3138 this.lastValue = $F(this.element);
3139 Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
3141 delayedListener: function(event) {
3142 if(this.lastValue == $F(this.element)) return;
3143 if(this.timer) clearTimeout(this.timer);
3144 this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
3145 this.lastValue = $F(this.element);
3147 onTimerEvent: function() {
3148 this.timer = null;
3149 this.callback(this.element, $F(this.element));
3154 if(!Control) var Control = {};
3155 Control.Slider = Class.create();
3157 // options:
3158 // axis: 'vertical', or 'horizontal' (default)
3160 // callbacks:
3161 // onChange(value)
3162 // onSlide(value)
3163 Control.Slider.prototype = {
3164 initialize: function(handle, track, options) {
3165 var slider = this;
3167 if(handle instanceof Array) {
3168 this.handles = handle.collect( function(e) { return $(e) });
3169 } else {
3170 this.handles = [$(handle)];
3173 this.track = $(track);
3174 this.options = options || {};
3176 this.axis = this.options.axis || 'horizontal';
3177 this.increment = this.options.increment || 1;
3178 this.step = parseInt(this.options.step || '1');
3179 this.range = this.options.range || $R(0,1);
3181 this.value = 0; // assure backwards compat
3182 this.values = this.handles.map( function() { return 0 });
3183 this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
3184 this.options.startSpan = $(this.options.startSpan || null);
3185 this.options.endSpan = $(this.options.endSpan || null);
3187 this.restricted = this.options.restricted || false;
3189 this.maximum = this.options.maximum || this.range.end;
3190 this.minimum = this.options.minimum || this.range.start;
3192 // Will be used to align the handle onto the track, if necessary
3193 this.alignX = parseInt(this.options.alignX || '0');
3194 this.alignY = parseInt(this.options.alignY || '0');
3196 this.trackLength = this.maximumOffset() - this.minimumOffset();
3198 this.handleLength = this.isVertical() ?
3199 (this.handles[0].offsetHeight != 0 ?
3200 this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) :
3201 (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth :
3202 this.handles[0].style.width.replace(/px$/,""));
3204 this.active = false;
3205 this.dragging = false;
3206 this.disabled = false;
3208 if(this.options.disabled) this.setDisabled();
3210 // Allowed values array
3211 this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
3212 if(this.allowedValues) {
3213 this.minimum = this.allowedValues.min();
3214 this.maximum = this.allowedValues.max();
3217 this.eventMouseDown = this.startDrag.bindAsEventListener(this);
3218 this.eventMouseUp = this.endDrag.bindAsEventListener(this);
3219 this.eventMouseMove = this.update.bindAsEventListener(this);
3221 // Initialize handles in reverse (make sure first handle is active)
3222 this.handles.each( function(h,i) {
3223 i = slider.handles.length-1-i;
3224 slider.setValue(parseFloat(
3225 (slider.options.sliderValue instanceof Array ?
3226 slider.options.sliderValue[i] : slider.options.sliderValue) ||
3227 slider.range.start), i);
3228 Element.makePositioned(h); // fix IE
3229 Event.observe(h, "mousedown", slider.eventMouseDown);
3232 Event.observe(this.track, "mousedown", this.eventMouseDown);
3233 Event.observe(document, "mouseup", this.eventMouseUp);
3234 Event.observe(document, "mousemove", this.eventMouseMove);
3236 this.initialized = true;
3238 dispose: function() {
3239 var slider = this;
3240 Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
3241 Event.stopObserving(document, "mouseup", this.eventMouseUp);
3242 Event.stopObserving(document, "mousemove", this.eventMouseMove);
3243 this.handles.each( function(h) {
3244 Event.stopObserving(h, "mousedown", slider.eventMouseDown);
3247 setDisabled: function(){
3248 this.disabled = true;
3250 setEnabled: function(){
3251 this.disabled = false;
3253 getNearestValue: function(value){
3254 if(this.allowedValues){
3255 if(value >= this.allowedValues.max()) return(this.allowedValues.max());
3256 if(value <= this.allowedValues.min()) return(this.allowedValues.min());
3258 var offset = Math.abs(this.allowedValues[0] - value);
3259 var newValue = this.allowedValues[0];
3260 this.allowedValues.each( function(v) {
3261 var currentOffset = Math.abs(v - value);
3262 if(currentOffset <= offset){
3263 newValue = v;
3264 offset = currentOffset;
3267 return newValue;
3269 if(value > this.range.end) return this.range.end;
3270 if(value < this.range.start) return this.range.start;
3271 return value;
3273 setValue: function(sliderValue, handleIdx){
3274 if(!this.active) {
3275 this.activeHandleIdx = handleIdx || 0;
3276 this.activeHandle = this.handles[this.activeHandleIdx];
3277 this.updateStyles();
3279 handleIdx = handleIdx || this.activeHandleIdx || 0;
3280 if(this.initialized && this.restricted) {
3281 if((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
3282 sliderValue = this.values[handleIdx-1];
3283 if((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
3284 sliderValue = this.values[handleIdx+1];
3286 sliderValue = this.getNearestValue(sliderValue);
3287 this.values[handleIdx] = sliderValue;
3288 this.value = this.values[0]; // assure backwards compat
3290 this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] =
3291 this.translateToPx(sliderValue);
3293 this.drawSpans();
3294 if(!this.dragging || !this.event) this.updateFinished();
3296 setValueBy: function(delta, handleIdx) {
3297 this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta,
3298 handleIdx || this.activeHandleIdx || 0);
3300 translateToPx: function(value) {
3301 return Math.round(
3302 ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) *
3303 (value - this.range.start)) + "px";
3305 translateToValue: function(offset) {
3306 return ((offset/(this.trackLength-this.handleLength) *
3307 (this.range.end-this.range.start)) + this.range.start);
3309 getRange: function(range) {
3310 var v = this.values.sortBy(Prototype.K);
3311 range = range || 0;
3312 return $R(v[range],v[range+1]);
3314 minimumOffset: function(){
3315 return(this.isVertical() ? this.alignY : this.alignX);
3317 maximumOffset: function(){
3318 return(this.isVertical() ?
3319 (this.track.offsetHeight != 0 ? this.track.offsetHeight :
3320 this.track.style.height.replace(/px$/,"")) - this.alignY :
3321 (this.track.offsetWidth != 0 ? this.track.offsetWidth :
3322 this.track.style.width.replace(/px$/,"")) - this.alignY);
3324 isVertical: function(){
3325 return (this.axis == 'vertical');
3327 drawSpans: function() {
3328 var slider = this;
3329 if(this.spans)
3330 $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
3331 if(this.options.startSpan)
3332 this.setSpan(this.options.startSpan,
3333 $R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
3334 if(this.options.endSpan)
3335 this.setSpan(this.options.endSpan,
3336 $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
3338 setSpan: function(span, range) {
3339 if(this.isVertical()) {
3340 span.style.top = this.translateToPx(range.start);
3341 span.style.height = this.translateToPx(range.end - range.start + this.range.start);
3342 } else {
3343 span.style.left = this.translateToPx(range.start);
3344 span.style.width = this.translateToPx(range.end - range.start + this.range.start);
3347 updateStyles: function() {
3348 this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
3349 Element.addClassName(this.activeHandle, 'selected');
3351 startDrag: function(event) {
3352 if(Event.isLeftClick(event)) {
3353 if(!this.disabled){
3354 this.active = true;
3356 var handle = Event.element(event);
3357 var pointer = [Event.pointerX(event), Event.pointerY(event)];
3358 var track = handle;
3359 if(track==this.track) {
3360 var offsets = Position.cumulativeOffset(this.track);
3361 this.event = event;
3362 this.setValue(this.translateToValue(
3363 (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
3365 var offsets = Position.cumulativeOffset(this.activeHandle);
3366 this.offsetX = (pointer[0] - offsets[0]);
3367 this.offsetY = (pointer[1] - offsets[1]);
3368 } else {
3369 // find the handle (prevents issues with Safari)
3370 while((this.handles.indexOf(handle) == -1) && handle.parentNode)
3371 handle = handle.parentNode;
3373 if(this.handles.indexOf(handle)!=-1) {
3374 this.activeHandle = handle;
3375 this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
3376 this.updateStyles();
3378 var offsets = Position.cumulativeOffset(this.activeHandle);
3379 this.offsetX = (pointer[0] - offsets[0]);
3380 this.offsetY = (pointer[1] - offsets[1]);
3384 Event.stop(event);
3387 update: function(event) {
3388 if(this.active) {
3389 if(!this.dragging) this.dragging = true;
3390 this.draw(event);
3391 if(Prototype.Browser.WebKit) window.scrollBy(0,0);
3392 Event.stop(event);
3395 draw: function(event) {
3396 var pointer = [Event.pointerX(event), Event.pointerY(event)];
3397 var offsets = Position.cumulativeOffset(this.track);
3398 pointer[0] -= this.offsetX + offsets[0];
3399 pointer[1] -= this.offsetY + offsets[1];
3400 this.event = event;
3401 this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
3402 if(this.initialized && this.options.onSlide)
3403 this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
3405 endDrag: function(event) {
3406 if(this.active && this.dragging) {
3407 this.finishDrag(event, true);
3408 Event.stop(event);
3410 this.active = false;
3411 this.dragging = false;
3413 finishDrag: function(event, success) {
3414 this.active = false;
3415 this.dragging = false;
3416 this.updateFinished();
3418 updateFinished: function() {
3419 if(this.initialized && this.options.onChange)
3420 this.options.onChange(this.values.length>1 ? this.values : this.value, this);
3421 this.event = null;
3425 Sound = {
3426 tracks: {},
3427 _enabled: true,
3428 template:
3429 new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'),
3430 enable: function(){
3431 Sound._enabled = true;
3433 disable: function(){
3434 Sound._enabled = false;
3436 play: function(url){
3437 if(!Sound._enabled) return;
3438 var options = Object.extend({
3439 track: 'global', url: url, replace: false
3440 }, arguments[1] || {});
3442 if(options.replace && this.tracks[options.track]) {
3443 $R(0, this.tracks[options.track].id).each(function(id){
3444 var sound = $('sound_'+options.track+'_'+id);
3445 sound.Stop && sound.Stop();
3446 sound.remove();
3448 this.tracks[options.track] = null;
3451 if(!this.tracks[options.track])
3452 this.tracks[options.track] = { id: 0 }
3453 else
3454 this.tracks[options.track].id++;
3456 options.id = this.tracks[options.track].id;
3457 if (Prototype.Browser.IE) {
3458 var sound = document.createElement('bgsound');
3459 sound.setAttribute('id','sound_'+options.track+'_'+options.id);
3460 sound.setAttribute('src',options.url);
3461 sound.setAttribute('loop','1');
3462 sound.setAttribute('autostart','true');
3463 $$('body')[0].appendChild(sound);
3465 else
3466 new Insertion.Bottom($$('body')[0], Sound.template.evaluate(options));
3470 if(Prototype.Browser.Gecko && navigator.userAgent.indexOf("Win") > 0){
3471 if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('QuickTime') != -1 }))
3472 Sound.template = new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>')
3473 else
3474 Sound.play = function(){}
3478 </value>
3479 </data>
3480 </root>