prototype.js 51.6 KB
Newer Older
S
Sam Stephenson 已提交
1
/*  Prototype JavaScript framework, version 1.5.0_pre0
2 3
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
S
Sam Stephenson 已提交
4 5 6 7
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/
8

9
var Prototype = {
S
Sam Stephenson 已提交
10
  Version: '1.5.0_pre0',
11
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
S
Sam Stephenson 已提交
12

13 14
  emptyFunction: function() {},
  K: function(x) {return x}
15 16
}

17
var Class = {
18
  create: function() {
S
Sam Stephenson 已提交
19
    return function() {
20 21 22 23 24
      this.initialize.apply(this, arguments);
    }
  }
}

25
var Abstract = new Object();
26

27 28 29
Object.extend = function(destination, source) {
  for (property in source) {
    destination[property] = source[property];
30
  }
31 32 33
  return destination;
}

34 35 36 37 38 39 40 41 42 43 44
Object.inspect = function(object) {
  try {
    if (object == undefined) return 'undefined';
    if (object == null) return 'null';
    return object.inspect ? object.inspect() : object.toString();
  } catch (e) {
    if (e instanceof RangeError) return '...';
    throw e;
  }
}

S
Sam Stephenson 已提交
45 46
Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
47
  return function() {
S
Sam Stephenson 已提交
48
    return __method.apply(object, args.concat($A(arguments)));
49 50 51 52
  }
}

Function.prototype.bindAsEventListener = function(object) {
53
  var __method = this;
54
  return function(event) {
55
    return __method.call(object, event || window.event);
56 57 58
  }
}

59 60 61 62 63 64 65 66 67 68
Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },
S
Sam Stephenson 已提交
69

70 71 72 73 74
  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});
75 76

var Try = {
77 78
  these: function() {
    var returnValue;
79

80 81 82 83 84 85 86
    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }
87

88 89 90 91
    return returnValue;
  }
}

S
Sam Stephenson 已提交
92
/*--------------------------------------------------------------------------*/
93

S
Sam Stephenson 已提交
94 95 96 97 98 99
var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;
100

S
Sam Stephenson 已提交
101 102
    this.registerCallback();
  },
103

S
Sam Stephenson 已提交
104
  registerCallback: function() {
105
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
S
Sam Stephenson 已提交
106
  },
107

S
Sam Stephenson 已提交
108 109
  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
S
Sam Stephenson 已提交
110
      try {
S
Sam Stephenson 已提交
111
        this.currentlyExecuting = true;
S
Sam Stephenson 已提交
112 113
        this.callback();
      } finally {
S
Sam Stephenson 已提交
114 115
        this.currentlyExecuting = false;
      }
116 117
    }
  }
118 119 120 121 122 123
}

/*--------------------------------------------------------------------------*/

function $() {
  var elements = new Array();
124

125
  for (var i = 0; i < arguments.length; i++) {
126 127 128 129
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

S
Sam Stephenson 已提交
130
    if (arguments.length == 1)
131
      return element;
132

133 134
    elements.push(element);
  }
135

136 137
  return elements;
}
138
Object.extend(String.prototype, {
S
Sam Stephenson 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += (replacement(match) || '').toString();
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

181 182 183 184
  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(eval);
  },

S
Sam Stephenson 已提交
201 202 203 204 205 206 207
  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

208
  unescapeHTML: function() {
S
Sam Stephenson 已提交
209 210
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
211
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
212
  },
S
Sam Stephenson 已提交
213

214 215 216 217 218 219 220 221
  toQueryParams: function() {
    var pairs = this.match(/^\??(.*)$/)[1].split('&');
    return pairs.inject({}, function(params, pairString) {
      var pair = pairString.split('=');
      params[pair[0]] = pair[1];
      return params;
    });
  },
S
Sam Stephenson 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

  toArray: function() {
    return this.split('');
  },

  camelize: function() {
    var oStringList = this.split('-');
    if (oStringList.length == 1) return oStringList[0];

    var camelizedString = this.indexOf('-') == 0
      ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
      : oStringList[0];

    for (var i = 1, len = oStringList.length; i < len; i++) {
      var s = oStringList[i];
      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    }

    return camelizedString;
  },

243
  inspect: function() {
S
Sam Stephenson 已提交
244
    return "'" + this.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') + "'";
245 246 247
  }
});

S
Sam Stephenson 已提交
248 249 250 251 252 253
String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

254 255
String.prototype.parseQuery = String.prototype.toQueryParams;

S
Sam Stephenson 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + (object[match[3]] || '').toString();
    });
  }
}

273 274
var $break    = new Object();
var $continue = new Object();
275 276 277 278 279 280 281 282 283

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
284
          if (e != $continue) throw e;
285 286 287
        }
      });
    } catch (e) {
288
      if (e != $break) throw e;
289 290
    }
  },
S
Sam Stephenson 已提交
291

292 293 294
  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
295 296
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
297 298 299
    });
    return result;
  },
S
Sam Stephenson 已提交
300

301 302 303
  any: function(iterator) {
    var result = true;
    this.each(function(value, index) {
304
      if (result = !!(iterator || Prototype.K)(value, index))
305
        throw $break;
306 307 308
    });
    return result;
  },
S
Sam Stephenson 已提交
309

310 311 312 313 314 315 316
  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },
S
Sam Stephenson 已提交
317

318 319 320 321 322
  detect: function (iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
323
        throw $break;
324 325 326 327
      }
    });
    return result;
  },
S
Sam Stephenson 已提交
328

329 330 331 332 333 334 335 336
  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },
S
Sam Stephenson 已提交
337

338 339 340 341 342 343 344 345 346
  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },
S
Sam Stephenson 已提交
347

348 349 350 351 352
  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
353
        throw $break;
354 355 356 357
      }
    });
    return found;
  },
S
Sam Stephenson 已提交
358

359 360 361 362 363 364
  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },
S
Sam Stephenson 已提交
365

366 367 368 369 370 371
  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.collect(function(value) {
      return value[method].apply(value, args);
    });
  },
S
Sam Stephenson 已提交
372

373 374 375 376 377 378 379 380 381
  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (value >= (result || value))
        result = value;
    });
    return result;
  },
S
Sam Stephenson 已提交
382

383 384 385 386 387 388 389 390 391
  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (value <= (result || value))
        result = value;
    });
    return result;
  },
S
Sam Stephenson 已提交
392

393 394 395
  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
S
Sam Stephenson 已提交
396
      ((iterator || Prototype.K)(value, index) ?
397 398 399 400
        trues : falses).push(value);
    });
    return [trues, falses];
  },
S
Sam Stephenson 已提交
401

402 403 404 405 406 407 408
  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },
S
Sam Stephenson 已提交
409

410 411 412 413 414 415 416 417
  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },
S
Sam Stephenson 已提交
418

419 420 421 422 423 424 425 426
  sortBy: function(iterator) {
    return this.collect(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },
S
Sam Stephenson 已提交
427

428 429 430
  toArray: function() {
    return this.collect(Prototype.K);
  },
S
Sam Stephenson 已提交
431

432 433 434 435 436 437 438 439 440 441
  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      iterator(value = collections.pluck(index));
      return value;
    });
442
  },
S
Sam Stephenson 已提交
443

444 445
  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
446
  }
447 448 449 450 451 452 453 454
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
455
});
456
var $A = Array.from = function(iterable) {
S
Sam Stephenson 已提交
457
  if (!iterable) return [];
458 459 460 461 462 463 464 465 466 467
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

468 469
Object.extend(Array.prototype, Enumerable);

470 471
Array.prototype._reverse = Array.prototype.reverse;

472 473 474 475 476
Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0; i < this.length; i++)
      iterator(this[i]);
  },
S
Sam Stephenson 已提交
477

478 479 480 481 482
  clear: function() {
    this.length = 0;
    return this;
  },

483 484 485
  first: function() {
    return this[0];
  },
S
Sam Stephenson 已提交
486

487 488
  last: function() {
    return this[this.length - 1];
489
  },
S
Sam Stephenson 已提交
490

491 492 493 494 495
  compact: function() {
    return this.select(function(value) {
      return value != undefined || value != null;
    });
  },
S
Sam Stephenson 已提交
496

497 498 499 500 501 502
  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value.constructor == Array ?
        value.flatten() : [value]);
    });
  },
S
Sam Stephenson 已提交
503

504 505 506 507 508 509
  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },
S
Sam Stephenson 已提交
510 511 512 513

  indexOf: function(object) {
    for (var i = 0; i < this.length; i++)
      if (this[i] == object) return i;
514
    return -1;
S
Sam Stephenson 已提交
515 516
  },

517 518
  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
S
Sam Stephenson 已提交
519 520
  },

S
Sam Stephenson 已提交
521 522 523 524 525 526 527 528
  shift: function() {
    var result = this[0];
    for (var i = 0; i < this.length - 1; i++)
      this[i] = this[i + 1];
    this.length--;
    return result;
  },

529 530
  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
531 532
  }
});
533 534 535 536 537
var Hash = {
  _each: function(iterator) {
    for (key in this) {
      var value = this[key];
      if (typeof value == 'function') continue;
S
Sam Stephenson 已提交
538

539 540 541 542 543 544
      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },
S
Sam Stephenson 已提交
545

546 547 548
  keys: function() {
    return this.pluck('key');
  },
S
Sam Stephenson 已提交
549

550 551 552
  values: function() {
    return this.pluck('value');
  },
S
Sam Stephenson 已提交
553

554 555 556 557 558 559
  merge: function(hash) {
    return $H(hash).inject($H(this), function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },
S
Sam Stephenson 已提交
560

561 562 563 564 565
  toQueryString: function() {
    return this.map(function(pair) {
      return pair.map(encodeURIComponent).join('=');
    }).join('&');
  },
S
Sam Stephenson 已提交
566

567 568 569 570 571 572 573 574 575 576 577 578 579
  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
}

function $H(object) {
  var hash = Object.extend({}, object || {});
  Object.extend(hash, Enumerable);
  Object.extend(hash, Hash);
  return hash;
}
580 581 582
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
583 584 585 586 587
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },
S
Sam Stephenson 已提交
588

589 590 591 592 593 594 595
  _each: function(iterator) {
    var value = this.start;
    do {
      iterator(value);
      value = value.succ();
    } while (this.include(value));
  },
S
Sam Stephenson 已提交
596

597
  include: function(value) {
S
Sam Stephenson 已提交
598
    if (value < this.start)
599 600 601 602 603 604 605 606
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
607
  return new ObjectRange(start, end, exclusive);
608 609
}

610
var Ajax = {
611 612 613 614 615 616
  getTransport: function() {
    return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false;
617
  },
S
Sam Stephenson 已提交
618

619
  activeRequestCount: 0
620 621
}

622 623
Ajax.Responders = {
  responders: [],
S
Sam Stephenson 已提交
624

625 626 627 628 629 630 631 632
  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responderToAdd) {
    if (!this.include(responderToAdd))
      this.responders.push(responderToAdd);
  },
S
Sam Stephenson 已提交
633

634 635 636
  unregister: function(responderToRemove) {
    this.responders = this.responders.without(responderToRemove);
  },
S
Sam Stephenson 已提交
637

638 639 640 641 642
  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (responder[callback] && typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
643
        } catch (e) {}
644 645 646 647 648 649 650 651 652 653 654
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
S
Sam Stephenson 已提交
655

656 657 658 659 660
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

661 662 663 664 665 666
Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
667
      parameters:   ''
668 669
    }
    Object.extend(this.options, options || {});
670 671 672 673
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
S
Sam Stephenson 已提交
674
        || this.transport.status == 0
675 676 677 678 679
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
680 681 682 683
  }
}

Ajax.Request = Class.create();
S
Sam Stephenson 已提交
684
Ajax.Request.Events =
685 686
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

687
Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
688 689 690
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
691 692
    this.request(url);
  },
693

694
  request: function(url) {
695 696 697
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

698
    try {
699
      this.url = url;
S
Sam Stephenson 已提交
700 701
      if (this.options.method == 'get' && parameters.length > 0)
        this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;
S
Sam Stephenson 已提交
702

703
      Ajax.Responders.dispatch('onCreate', this, this.transport);
S
Sam Stephenson 已提交
704 705

      this.transport.open(this.options.method, this.url,
S
Sam Stephenson 已提交
706
        this.options.asynchronous);
707

708
      if (this.options.asynchronous) {
709
        this.transport.onreadystatechange = this.onStateChange.bind(this);
710 711
        setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
      }
712

713 714
      this.setRequestHeaders();

715 716
      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);
717

718
    } catch (e) {
719
      this.dispatchException(e);
720
    }
721
  },
722

723
  setRequestHeaders: function() {
S
Sam Stephenson 已提交
724
    var requestHeaders =
725 726 727
      ['X-Requested-With', 'XMLHttpRequest',
       'X-Prototype-Version', Prototype.Version];

728
    if (this.options.method == 'post') {
S
Sam Stephenson 已提交
729
      requestHeaders.push('Content-type',
730 731 732 733
        'application/x-www-form-urlencoded');

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
S
Sam Stephenson 已提交
734
       * header. See Mozilla Bugzilla #246651.
735 736 737
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
738
    }
739 740 741

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);
742

743
    for (var i = 0; i < requestHeaders.length; i += 2)
744
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
745
  },
746

747
  onStateChange: function() {
748 749 750 751
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },
S
Sam Stephenson 已提交
752

753 754 755 756 757 758
  header: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) {}
  },

759 760
  evalJSON: function() {
    try {
761 762 763 764 765 766 767
      return eval(this.header('X-JSON'));
    } catch (e) {}
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
768
    } catch (e) {
769
      this.dispatchException(e);
770 771
    }
  },
772

773 774
  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];
775
    var transport = this.transport, json = this.evalJSON();
776

777 778 779 780 781 782 783 784 785
    if (event == 'Complete') {
      try {
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

786
      if ((this.header('Content-type') || '').match(/^text\/javascript/i))
787 788
        this.evalResponse();
    }
789

790 791 792 793 794 795
    try {
      (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + event, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }
S
Sam Stephenson 已提交
796 797 798 799

    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
800 801 802 803 804
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
805 806 807 808
  }
});

Ajax.Updater = Class.create();
S
Sam Stephenson 已提交
809

810
Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
811
  initialize: function(container, url, options) {
812 813
    this.containers = {
      success: container.success ? $(container.success) : $(container),
814 815
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
816
    }
817 818

    this.transport = Ajax.getTransport();
819
    this.setOptions(options);
820 821

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
822
    this.options.onComplete = (function(transport, object) {
823
      this.updateContent();
824
      onComplete(transport, object);
825 826 827
    }).bind(this);

    this.request(url);
828
  },
829

830
  updateContent: function() {
831
    var receiver = this.responseIsSuccess() ?
832
      this.containers.success : this.containers.failure;
833
    var response = this.transport.responseText;
834

835 836
    if (!this.options.evalScripts)
      response = response.stripScripts();
837

838
    if (receiver) {
839
      if (this.options.insertion) {
840
        new this.options.insertion(receiver, response);
841
      } else {
842
        Element.update(receiver, response);
843
      }
844
    }
845

846
    if (this.responseIsSuccess()) {
S
Sam Stephenson 已提交
847
      if (this.onComplete)
848
        setTimeout(this.onComplete.bind(this), 10);
849
    }
850 851 852 853
  }
});

Ajax.PeriodicalUpdater = Class.create();
854
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
855 856 857 858 859
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
S
Sam Stephenson 已提交
860
    this.decay = (this.options.decay || 1);
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.onComplete = undefined;
    clearTimeout(this.timer);
S
Sam Stephenson 已提交
877
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
878 879 880 881
  },

  updateComplete: function(request) {
    if (this.options.decay) {
S
Sam Stephenson 已提交
882
      this.decay = (request.responseText == this.lastText ?
883 884 885
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
886
    }
S
Sam Stephenson 已提交
887
    this.timer = setTimeout(this.onTimerEvent.bind(this),
888 889 890 891 892
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
893 894
  }
});
895
document.getElementsByClassName = function(className, parentElement) {
S
Sam Stephenson 已提交
896
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
897
  return $A(children).inject([], function(elements, child) {
S
Sam Stephenson 已提交
898
    if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
899 900 901
      elements.push(child);
    return elements;
  });
902 903 904 905 906 907 908 909
}

/*--------------------------------------------------------------------------*/

if (!window.Element) {
  var Element = new Object();
}

910
Object.extend(Element, {
911 912 913
  visible: function(element) {
    return $(element).style.display != 'none';
  },
S
Sam Stephenson 已提交
914

915 916 917
  toggle: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
S
Sam Stephenson 已提交
918
      Element[Element.visible(element) ? 'hide' : 'show'](element);
919 920 921 922 923 924 925 926 927
    }
  },

  hide: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = 'none';
    }
  },
S
Sam Stephenson 已提交
928

929 930 931 932 933 934 935 936 937 938 939
  show: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = '';
    }
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
  },
S
Sam Stephenson 已提交
940

941 942 943 944 945
  update: function(element, html) {
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
  },

946 947
  getHeight: function(element) {
    element = $(element);
S
Sam Stephenson 已提交
948
    return element.offsetHeight;
949
  },
S
Sam Stephenson 已提交
950

951 952 953
  classNames: function(element) {
    return new Element.ClassNames(element);
  },
954 955

  hasClassName: function(element, className) {
956 957
    if (!(element = $(element))) return;
    return Element.classNames(element).include(className);
958 959 960
  },

  addClassName: function(element, className) {
961 962
    if (!(element = $(element))) return;
    return Element.classNames(element).add(className);
963 964 965
  },

  removeClassName: function(element, className) {
966 967
    if (!(element = $(element))) return;
    return Element.classNames(element).remove(className);
968
  },
S
Sam Stephenson 已提交
969

970 971
  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
972
    element = $(element);
973 974
    for (var i = 0; i < element.childNodes.length; i++) {
      var node = element.childNodes[i];
S
Sam Stephenson 已提交
975
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
976
        Element.remove(node);
977
    }
978
  },
S
Sam Stephenson 已提交
979

980 981 982
  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },
S
Sam Stephenson 已提交
983

S
Sam Stephenson 已提交
984 985 986 987 988 989 990
  childOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

991 992 993 994 995
  scrollTo: function(element) {
    element = $(element);
    var x = element.x ? element.x : element.offsetLeft,
        y = element.y ? element.y : element.offsetTop;
    window.scrollTo(x, y);
S
Sam Stephenson 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  },

  getStyle: function(element, style) {
    element = $(element);
    var value = element.style[style.camelize()];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css.getPropertyValue(style) : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style.camelize()];
      }
    }

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';

    return value == 'auto' ? null : value;
  },

1016 1017 1018 1019 1020 1021
  setStyle: function(element, style) {
    element = $(element);
    for (name in style)
      element.style[name.camelize()] = style[name];
  },

S
Sam Stephenson 已提交
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
  getDimensions: function(element) {
    element = $(element);
    if (Element.getStyle(element, 'display') != 'none')
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = '';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = 'none';
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element._overflow = element.style.overflow;
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
  },

  undoClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element.style.overflow = element._overflow;
    element._overflow = undefined;
1083 1084 1085
  }
});

1086 1087 1088
var Toggle = new Object();
Toggle.display = Element.toggle;

1089 1090
/*--------------------------------------------------------------------------*/

1091 1092 1093 1094 1095 1096 1097
Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
1098
    this.content = content.stripScripts();
S
Sam Stephenson 已提交
1099

1100
    if (this.adjacency && this.element.insertAdjacentHTML) {
1101 1102 1103 1104
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        if (this.element.tagName.toLowerCase() == 'tbody') {
S
Sam Stephenson 已提交
1105
          this.insertContent(this.contentFromAnonymousTable());
1106 1107 1108 1109
        } else {
          throw e;
        }
      }
1110 1111 1112
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
S
Sam Stephenson 已提交
1113
      this.insertContent([this.range.createContextualFragment(this.content)]);
1114
    }
1115 1116

    setTimeout(function() {content.evalScripts()}, 10);
1117
  },
S
Sam Stephenson 已提交
1118

1119 1120 1121
  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
S
Sam Stephenson 已提交
1122
    return $A(div.childNodes[0].childNodes[0].childNodes);
1123 1124 1125 1126 1127 1128
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
1129
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
1130 1131 1132
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },
S
Sam Stephenson 已提交
1133 1134 1135 1136 1137

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
1138 1139 1140 1141
  }
});

Insertion.Top = Class.create();
1142
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
1143 1144 1145 1146
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },
S
Sam Stephenson 已提交
1147 1148

  insertContent: function(fragments) {
1149
    fragments.reverse(false).each((function(fragment) {
S
Sam Stephenson 已提交
1150 1151
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
1152 1153 1154 1155
  }
});

Insertion.Bottom = Class.create();
1156
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
1157 1158 1159 1160
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },
S
Sam Stephenson 已提交
1161 1162 1163 1164 1165

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
1166 1167 1168 1169
  }
});

Insertion.After = Class.create();
1170
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
1171 1172 1173
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },
S
Sam Stephenson 已提交
1174 1175 1176 1177 1178 1179

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
1180 1181 1182
  }
});

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },
S
Sam Stephenson 已提交
1196

1197 1198 1199
  set: function(className) {
    this.element.className = className;
  },
S
Sam Stephenson 已提交
1200

1201 1202 1203 1204
  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set(this.toArray().concat(classNameToAdd).join(' '));
  },
S
Sam Stephenson 已提交
1205

1206 1207 1208 1209
  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set(this.select(function(className) {
      return className != classNameToRemove;
1210
    }).join(' '));
1211
  },
S
Sam Stephenson 已提交
1212

1213 1214 1215 1216 1217 1218
  toString: function() {
    return this.toArray().join(' ');
  }
}

Object.extend(Element.ClassNames.prototype, Enumerable);
S
Sam Stephenson 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
var Selector = Class.create();
Selector.prototype = {
  initialize: function(expression) {
    this.params = {classNames: []};
    this.expression = expression.toString().strip();
    this.parseExpression();
    this.compileMatcher();
  },

  parseExpression: function() {
    function abort(message) { throw 'Parse error in selector: ' + message; }

    if (this.expression == '')  abort('empty expression');
    if (this.expression == '*') return this.params.wildcard = true;

    var params = this.params, expr = this.expression, match, modifier, clause, rest;
    while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
      modifier = match[1], clause = match[2], rest = match[3];
      switch (modifier) {
        case '#':       params.id = clause; break;
        case '.':       params.classNames.push(clause); break;
        case undefined: params.tagName = clause.toUpperCase(); break;
        default:        abort(expr.inspect());
      }
      expr = rest;
    }

    if (expr.length > 0) abort(expr.inspect());
  },

  buildMatchExpression: function() {
    var params = this.params, conditions = [], clause;

    if (params.wildcard)
      return 'true';

    if (clause = params.id)
      conditions.push('element.id == ' + clause.inspect());
    if (clause = params.tagName)
      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    if ((clause = params.classNames).length > 0)
      for (var i = 0; i < clause.length; i++)
        conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');

    return conditions.join(' && ');
  },

  compileMatcher: function() {
    this.match = eval('function(element) { if (!element.tagName) return false; \
      return ' + this.buildMatchExpression() + ' }');
  },

  findElements: function(scope) {
    var element;

    if (element = $(this.params.id))
      if (this.match(element))
        if (!scope || Element.childOf(element, scope))
          return [element];

    scope = (scope || document).getElementsByTagName(this.params.tagName || '*');

    var results = [];
    for (var i = 0; i < scope.length; i++)
      if (this.match(element = scope[i]))
        results.push(element);

    return results;
  },

  toString: function() {
    return this.expression;
  }
}

function $$() {
  return $A(arguments).map(function(expression) {
    return expression.strip().split(/\s+/).inject([null], function(results, expr) {
      var selector = new Selector(expr);
      return results.map(selector.findElements.bind(selector)).flatten();
    });
  }).flatten();
}
1302
var Field = {
1303
  clear: function() {
1304
    for (var i = 0; i < arguments.length; i++)
1305 1306 1307
      $(arguments[i]).value = '';
  },

1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
  // Pass the field id or element as the first parameter and optionally a triggering delay in micro-seconds as the second.
  // The delay is useful when the focus is part of effects that won't finish instantly since they prevent the focus from
  // taking hold. Set the delay to right after the effect finishes and the focus will work.
  focus: function() {
    element = $(arguments[0]);
    delay   = arguments[1];
    
    if (delay) {
      setTimeout(function() { $(element).focus(); }, delay)
    } else {
      $(element).focus();
    }
1320
  },
S
Sam Stephenson 已提交
1321

1322
  present: function() {
1323
    for (var i = 0; i < arguments.length; i++)
1324 1325
      if ($(arguments[i]).value == '') return false;
    return true;
S
Sam Stephenson 已提交
1326
  },
S
Sam Stephenson 已提交
1327

S
Sam Stephenson 已提交
1328 1329 1330
  select: function(element) {
    $(element).select();
  },
S
Sam Stephenson 已提交
1331

S
Sam Stephenson 已提交
1332
  activate: function(element) {
1333 1334 1335 1336
    element = $(element);
    element.focus();
    if (element.select)
      element.select();
1337 1338 1339 1340 1341
  }
}

/*--------------------------------------------------------------------------*/

1342
var Form = {
1343 1344 1345
  serialize: function(form) {
    var elements = Form.getElements($(form));
    var queryComponents = new Array();
S
Sam Stephenson 已提交
1346

1347 1348 1349 1350 1351
    for (var i = 0; i < elements.length; i++) {
      var queryComponent = Form.Element.serialize(elements[i]);
      if (queryComponent)
        queryComponents.push(queryComponent);
    }
S
Sam Stephenson 已提交
1352

1353 1354
    return queryComponents.join('&');
  },
S
Sam Stephenson 已提交
1355

1356
  getElements: function(form) {
S
Sam Stephenson 已提交
1357
    form = $(form);
1358 1359 1360 1361 1362 1363 1364 1365
    var elements = new Array();

    for (tagName in Form.Element.Serializers) {
      var tagElements = form.getElementsByTagName(tagName);
      for (var j = 0; j < tagElements.length; j++)
        elements.push(tagElements[j]);
    }
    return elements;
S
Sam Stephenson 已提交
1366
  },
S
Sam Stephenson 已提交
1367

1368
  getInputs: function(form, typeName, name) {
S
Sam Stephenson 已提交
1369
    form = $(form);
1370
    var inputs = form.getElementsByTagName('input');
S
Sam Stephenson 已提交
1371

1372 1373
    if (!typeName && !name)
      return inputs;
S
Sam Stephenson 已提交
1374

1375 1376 1377 1378
    var matchingInputs = new Array();
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) ||
S
Sam Stephenson 已提交
1379
          (name && input.name != name))
1380 1381 1382 1383 1384 1385 1386
        continue;
      matchingInputs.push(input);
    }

    return matchingInputs;
  },

S
Sam Stephenson 已提交
1387 1388 1389 1390 1391
  disable: function(form) {
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.blur();
1392
      element.disabled = 'true';
S
Sam Stephenson 已提交
1393 1394 1395
    }
  },

1396 1397 1398 1399 1400 1401 1402 1403
  enable: function(form) {
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.disabled = '';
    }
  },

1404 1405 1406 1407 1408 1409 1410
  findFirstElement: function(form) {
    return Form.getElements(form).find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

S
Sam Stephenson 已提交
1411
  focusFirstElement: function(form) {
1412
    Field.activate(Form.findFirstElement(form));
S
Sam Stephenson 已提交
1413 1414 1415 1416
  },

  reset: function(form) {
    $(form).reset();
1417 1418 1419 1420 1421
  }
}

Form.Element = {
  serialize: function(element) {
S
Sam Stephenson 已提交
1422
    element = $(element);
1423 1424
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);
S
Sam Stephenson 已提交
1425

S
Sam Stephenson 已提交
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
    if (parameter) {
      var key = encodeURIComponent(parameter[0]);
      if (key.length == 0) return;

      if (parameter[1].constructor != Array)
        parameter[1] = [parameter[1]];

      return parameter[1].map(function(value) {
        return key + '=' + encodeURIComponent(value);
      }).join('&');
    }
1437
  },
S
Sam Stephenson 已提交
1438

1439
  getValue: function(element) {
S
Sam Stephenson 已提交
1440
    element = $(element);
1441 1442
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);
S
Sam Stephenson 已提交
1443 1444

    if (parameter)
1445 1446 1447 1448 1449 1450 1451
      return parameter[1];
  }
}

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
1452 1453 1454 1455 1456
      case 'submit':
      case 'hidden':
      case 'password':
      case 'text':
        return Form.Element.Serializers.textarea(element);
S
Sam Stephenson 已提交
1457
      case 'checkbox':
1458 1459 1460
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
    }
1461
    return false;
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
  },

  inputSelector: function(element) {
    if (element.checked)
      return [element.name, element.value];
  },

  textarea: function(element) {
    return [element.name, element.value];
  },
S
Sam Stephenson 已提交
1472

1473
  select: function(element) {
S
Sam Stephenson 已提交
1474
    return Form.Element.Serializers[element.type == 'select-one' ?
1475 1476
      'selectOne' : 'selectMany'](element);
  },
S
Sam Stephenson 已提交
1477

1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
  selectOne: function(element) {
    var value = '', opt, index = element.selectedIndex;
    if (index >= 0) {
      opt = element.options[index];
      value = opt.value;
      if (!value && !('value' in opt))
        value = opt.text;
    }
    return [element.name, value];
  },
S
Sam Stephenson 已提交
1488

1489 1490 1491 1492 1493 1494 1495 1496 1497
  selectMany: function(element) {
    var value = new Array();
    for (var i = 0; i < element.length; i++) {
      var opt = element.options[i];
      if (opt.selected) {
        var optValue = opt.value;
        if (!optValue && !('value' in opt))
          optValue = opt.text;
        value.push(optValue);
1498 1499 1500
      }
    }
    return [element.name, value];
1501 1502 1503 1504 1505
  }
}

/*--------------------------------------------------------------------------*/

S
Sam Stephenson 已提交
1506 1507 1508 1509
var $F = Form.Element.getValue;

/*--------------------------------------------------------------------------*/

1510 1511 1512 1513 1514 1515
Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;
S
Sam Stephenson 已提交
1516

1517 1518 1519
    this.lastValue = this.getValue();
    this.registerCallback();
  },
S
Sam Stephenson 已提交
1520

1521
  registerCallback: function() {
1522
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
1523
  },
S
Sam Stephenson 已提交
1524

1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
  onTimerEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
1535
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
1536 1537 1538 1539 1540 1541
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
1542
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
1543 1544 1545 1546 1547
  getValue: function() {
    return Form.serialize(this.element);
  }
});

S
Sam Stephenson 已提交
1548 1549
/*--------------------------------------------------------------------------*/

1550 1551
Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
1552 1553 1554 1555
  initialize: function() {
    this.element  = $(arguments[0]);
    this.callback = arguments[1];
    this.trigger  = arguments[2];
S
Sam Stephenson 已提交
1556

1557 1558 1559 1560
    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
1561
      this.registerCallback(this.element, this.trigger);
1562
  },
S
Sam Stephenson 已提交
1563

1564 1565 1566 1567 1568
  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
1569 1570
    }
  },
S
Sam Stephenson 已提交
1571

1572 1573 1574
  registerFormCallbacks: function() {
    var elements = Form.getElements(this.element);
    for (var i = 0; i < elements.length; i++)
1575
      this.registerCallback(elements[i], this.trigger);
1576
  },
S
Sam Stephenson 已提交
1577

1578 1579 1580 1581
  registerCallback: function(element, trigger) {
    if (trigger && element.type) {
      Event.observe(element, trigger, this.onElementEvent.bind(this));
    } else if (element.type) {
1582
      switch (element.type.toLowerCase()) {
S
Sam Stephenson 已提交
1583
        case 'checkbox':
1584
        case 'radio':
1585
          Event.observe(element, 'click', this.onElementEvent.bind(this));
1586 1587 1588 1589 1590 1591
          break;
        case 'password':
        case 'text':
        case 'textarea':
        case 'select-one':
        case 'select-multiple':
1592
          Event.observe(element, 'change', this.onElementEvent.bind(this));
1593 1594
          break;
      }
S
Sam Stephenson 已提交
1595
    }
1596
  }
1597
}
1598

1599
Form.Element.EventObserver = Class.create();
1600
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
1601 1602
  getValue: function() {
    return Form.Element.getValue(this.element);
1603 1604 1605
  }
});

1606
Form.EventObserver = Class.create();
1607
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
1608 1609
  getValue: function() {
    return Form.serialize(this.element);
1610 1611
  }
});
1612
if (!window.Event) {
1613
  var Event = new Object();
1614
}
1615

1616
Object.extend(Event, {
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,

  element: function(event) {
1628
    return event.target || event.srcElement;
1629
  },
1630

1631 1632 1633 1634
  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },
1635

1636
  pointerX: function(event) {
S
Sam Stephenson 已提交
1637
    return event.pageX || (event.clientX +
1638
      (document.documentElement.scrollLeft || document.body.scrollLeft));
1639
  },
1640

1641
  pointerY: function(event) {
S
Sam Stephenson 已提交
1642
    return event.pageY || (event.clientY +
1643
      (document.documentElement.scrollTop || document.body.scrollTop));
1644 1645 1646
  },

  stop: function(event) {
S
Sam Stephenson 已提交
1647 1648 1649
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
1650
    } else {
1651
      event.returnValue = false;
1652
      event.cancelBubble = true;
1653
    }
1654 1655 1656
  },

  // find the first node with the given tagName, starting from the
1657
  // node the event was triggered on; traverses the DOM upwards
1658
  findElement: function(event, tagName) {
1659
    var element = Event.element(event);
S
Sam Stephenson 已提交
1660 1661
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
1662
      element = element.parentNode;
1663 1664
    return element;
  },
1665

S
Sam Stephenson 已提交
1666
  observers: false,
S
Sam Stephenson 已提交
1667

S
Sam Stephenson 已提交
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },
S
Sam Stephenson 已提交
1678

S
Sam Stephenson 已提交
1679 1680 1681 1682 1683 1684 1685 1686 1687
  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0; i < Event.observers.length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

S
Sam Stephenson 已提交
1688
  observe: function(element, name, observer, useCapture) {
1689
    var element = $(element);
S
Sam Stephenson 已提交
1690
    useCapture = useCapture || false;
S
Sam Stephenson 已提交
1691

S
Sam Stephenson 已提交
1692
    if (name == 'keypress' &&
1693
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
S
Sam Stephenson 已提交
1694 1695
        || element.attachEvent))
      name = 'keydown';
S
Sam Stephenson 已提交
1696

S
Sam Stephenson 已提交
1697
    this._observeAndCache(element, name, observer, useCapture);
S
Sam Stephenson 已提交
1698 1699 1700 1701 1702
  },

  stopObserving: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;
S
Sam Stephenson 已提交
1703

S
Sam Stephenson 已提交
1704
    if (name == 'keypress' &&
1705
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
S
Sam Stephenson 已提交
1706 1707
        || element.detachEvent))
      name = 'keydown';
S
Sam Stephenson 已提交
1708

S
Sam Stephenson 已提交
1709 1710 1711 1712
    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      element.detachEvent('on' + name, observer);
S
Sam Stephenson 已提交
1713
    }
1714 1715
  }
});
1716

S
Sam Stephenson 已提交
1717 1718
/* prevent memory leaks in IE */
Event.observe(window, 'unload', Event.unloadCache, false);
1719
var Position = {
1720 1721 1722
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
S
Sam Stephenson 已提交
1723
  includeScrollOffsets: false,
1724

1725 1726
  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
1727
  prepare: function() {
S
Sam Stephenson 已提交
1728 1729 1730
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
1731
                || 0;
S
Sam Stephenson 已提交
1732 1733 1734
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
1735 1736 1737 1738 1739
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
1740
    do {
1741
      valueT += element.scrollTop  || 0;
S
Sam Stephenson 已提交
1742
      valueL += element.scrollLeft || 0;
1743
      element = element.parentNode;
1744
    } while (element);
1745 1746
    return [valueL, valueT];
  },
1747 1748 1749

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
1750
    do {
1751
      valueT += element.offsetTop  || 0;
1752 1753
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
1754
    } while (element);
1755 1756
    return [valueL, valueT];
  },
1757

S
Sam Stephenson 已提交
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

1783 1784
  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
1785 1786
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
1787 1788
    this.xcomp = x;
    this.ycomp = y;
1789
    this.offset = this.cumulativeOffset(element);
1790

1791 1792
    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
S
Sam Stephenson 已提交
1793
            x >= this.offset[0] &&
1794
            x <  this.offset[0] + element.offsetWidth);
1795
  },
1796 1797 1798

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);
1799

1800 1801
    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
1802 1803 1804 1805
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
S
Sam Stephenson 已提交
1806
            this.xcomp >= this.offset[0] &&
1807
            this.xcomp <  this.offset[0] + element.offsetWidth);
1808
  },
1809

1810
  // within must be called directly before
S
Sam Stephenson 已提交
1811 1812 1813 1814
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
1815 1816
        element.offsetHeight;
    if (mode == 'horizontal')
S
Sam Stephenson 已提交
1817
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
1818
        element.offsetWidth;
1819
  },
1820

1821
  clone: function(source, target) {
1822 1823
    source = $(source);
    target = $(target);
1824 1825 1826 1827
    target.style.position = 'absolute';
    var offsets = this.cumulativeOffset(source);
    target.style.top    = offsets[1] + 'px';
    target.style.left   = offsets[0] + 'px';
1828 1829
    target.style.width  = source.offsetWidth + 'px';
    target.style.height = source.offsetHeight + 'px';
S
Sam Stephenson 已提交
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent==document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      valueT -= element.scrollTop  || 0;
      valueL -= element.scrollLeft || 0;
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';;
    element.style.left   = left + 'px';;
    element.style.width  = width + 'px';;
    element.style.height = height + 'px';;
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
1929
  }
1930
}
S
Sam Stephenson 已提交
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}