/*
 * EasyGUI XP 1.0.293
 * Copyright(c) 2006-2008 Gaetan Lauff <glauff@plansoft.de>.
 * 
 * This code is licensed under BSD license. Use it as you wish, 
 * but keep the copyright intact.
 * 
 * ========================================================
 * 
 * Prototype JavaScript framework, version 1.6.0.2
 * (c) 2005-2008 Sam Stephenson
 * 
 * ========================================================
 * 
 * script.aculo.us scriptaculous.js v1.8.1
 * Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
 * 
 * ========================================================
 */

BUILD = true;


var Prototype = {
  Version: '1.6.0.2',

  Browser: {
    IE:     !!(window.attachEvent && !window.opera),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
    MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
  },

  BrowserFeatures: {
    XPath: !!document.evaluate,
    ElementExtensions: !!window.HTMLElement,
    SpecificElementExtensions:
      document.createElement('div').__proto__ &&
      document.createElement('div').__proto__ !==
        document.createElement('form').__proto__
  },

  ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
  JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,

  emptyFunction: function() { },
  K: function(x) { return x }
};

if (Prototype.Browser.MobileSafari)
  Prototype.BrowserFeatures.SpecificElementExtensions = false;



var Class = {
  create: function() {
    var parent = null, properties = $A(arguments);
    if (Object.isFunction(properties[0]))
      parent = properties.shift();

    function klass() {
      this.initialize.apply(this, arguments);
    }

    Object.extend(klass, Class.Methods);
    klass.superclass = parent;
    klass.subclasses = [];

    if (parent) {
      var subclass = function() { };
      subclass.prototype = parent.prototype;
      klass.prototype = new subclass;
      parent.subclasses.push(klass);
    }

    for (var i = 0; i < properties.length; i++)
      klass.addMethods(properties[i]);

    if (!klass.prototype.initialize)
      klass.prototype.initialize = Prototype.emptyFunction;

    klass.prototype.constructor = klass;

    return klass;
  }
};

Class.Methods = {
  addMethods: function(source) {
    var ancestor   = this.superclass && this.superclass.prototype;
    var properties = Object.keys(source);

    if (!Object.keys({ toString: true }).length)
      properties.push("toString", "valueOf");

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && Object.isFunction(value) &&
          value.argumentNames().first() == "$super") {
        var method = value, value = Object.extend((function(m) {
          return function() { return ancestor[m].apply(this, arguments) };
        })(property).wrap(method), {
          valueOf:  function() { return method },
          toString: function() { return method.toString() }
        });
      }
      this.prototype[property] = value;
    }

    return this;
  }
};

var Abstract = { };

Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (Object.isUndefined(object)) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : String(object);
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  toJSON: function(object) {
    var type = typeof object;
    switch (type) {
      case 'undefined':
      case 'function':
      case 'unknown': return;
      case 'boolean': return object.toString();
    }

    if (object === null) return 'null';
    if (object.toJSON) return object.toJSON();
    if (Object.isElement(object)) return;

    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (!Object.isUndefined(value))
        results.push(property.toJSON() + ': ' + value);
    }

    return '{' + results.join(', ') + '}';
  },

  toQueryString: function(object) {
    return $H(object).toQueryString();
  },

  toHTML: function(object) {
    return object && object.toHTML ? object.toHTML() : String.interpret(object);
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({ }, object);
  },

  isElement: function(object) {
    return object && object.nodeType == 1;
  },

  isArray: function(object) {
    return object != null && typeof object == "object" &&
      'splice' in object && 'join' in object;
  },

  isHash: function(object) {
    return object instanceof Hash;
  },

  isFunction: function(object) {
    return typeof object == "function";
  },

  isString: function(object) {
    return typeof object == "string";
  },

  isNumber: function(object) {
    return typeof object == "number";
  },

  isUndefined: function(object) {
    return typeof object == "undefined";
  }
});

Object.extend(Function.prototype, {
  argumentNames: function() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
    return names.length == 1 && !names[0] ? [] : names;
  },

  bind: function() {
    if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
    var __method = this, args = $A(arguments), object = args.shift();
    return function() {
      return __method.apply(object, args.concat($A(arguments)));
    }
  },

  bindAsEventListener: function() {
    var __method = this, args = $A(arguments), object = args.shift();
    return function(event) {
      return __method.apply(object, [event || window.event].concat(args));
    }
  },

  curry: function() {
    if (!arguments.length) return this;
    var __method = this, args = $A(arguments);
    return function() {
      return __method.apply(this, args.concat($A(arguments)));
    }
  },

  delay: function() {
    var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  },

  wrap: function(wrapper) {
    var __method = this;
    return function() {
      return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
    }
  },

  methodize: function() {
    if (this._methodized) return this._methodized;
    var __method = this;
    return this._methodized = function() {
      return __method.apply(null, [this].concat($A(arguments)));
    };
  }
});

Function.prototype.defer = Function.prototype.delay.curry(0.01);

Date.prototype.toJSON = function() {
  return '"' + this.getUTCFullYear() + '-' +
    (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
    this.getUTCDate().toPaddedString(2) + 'T' +
    this.getUTCHours().toPaddedString(2) + ':' +
    this.getUTCMinutes().toPaddedString(2) + ':' +
    this.getUTCSeconds().toPaddedString(2) + 'Z"';
};

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) { }
    }

    return returnValue;
  }
};

RegExp.prototype.match = RegExp.prototype.test;

RegExp.escape = function(str) {
  return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};



var PeriodicalExecuter = Class.create({
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  execute: function() {
    this.callback(this);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.execute();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
});
Object.extend(String, {
  interpret: function(value) {
    return value == null ? '' : String(value);
  },
  specialChar: {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '\\': '\\\\'
  }
});

Object.extend(String.prototype, {
  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 += String.interpret(replacement(match));
        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 = Object.isUndefined(count) ? 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 String(this);
  },

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

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

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

  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(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var self = arguments.callee;
    self.text.data = this;
    return self.div.innerHTML;
  },

  unescapeHTML: function() {
    var div = new Element('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return { };

    return match[1].split(separator || '&').inject({ }, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = value;
      }
      return hash;
    });
  },

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

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  times: function(count) {
    return count < 1 ? '' : new Array(count + 1).join(this);
  },

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

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function() {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
      var character = String.specialChar[match[0]];
      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
    });
    if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
    return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  },

  toJSON: function() {
    return this.inspect(true);
  },

  unfilterJSON: function(filter) {
    return this.sub(filter || Prototype.JSONFilter, '#{1}');
  },

  isJSON: function() {
    var str = this;
    if (str.blank()) return false;
    str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  },

  evalJSON: function(sanitize) {
    var json = this.unfilterJSON();
    try {
      if (!sanitize || json.isJSON()) return eval('(' + json + ')');
    } catch (e) { }
    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  },

  include: function(pattern) {
    return this.indexOf(pattern) > -1;
  },

  startsWith: function(pattern) {
    return this.indexOf(pattern) === 0;
  },

  endsWith: function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
  },

  empty: function() {
    return this == '';
  },

  blank: function() {
    return /^\s*$/.test(this);
  },

  interpolate: function(object, pattern) {
    return new Template(this, pattern).evaluate(object);
  }
});

if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
  escapeHTML: function() {
    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  },
  unescapeHTML: function() {
    return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (Object.isFunction(replacement)) return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
};

String.prototype.parseQuery = String.prototype.toQueryParams;

Object.extend(String.prototype.escapeHTML, {
  div:  document.createElement('div'),
  text: document.createTextNode('')
});

with (String.prototype.escapeHTML) div.appendChild(text);

var Template = Class.create({
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    if (Object.isFunction(object.toTemplateReplacements))
      object = object.toTemplateReplacements();

    return this.template.gsub(this.pattern, function(match) {
      if (object == null) return '';

      var before = match[1] || '';
      if (before == '\\') return match[2];

      var ctx = object, expr = match[3];
      var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
      match = pattern.exec(expr);
      if (match == null) return before;

      while (match != null) {
        var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
        ctx = ctx[comp];
        if (null == ctx || '' == match[3]) break;
        expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
        match = pattern.exec(expr);
      }

      return before + String.interpret(ctx);
    });
  }
});
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;

var $break = { };

var Enumerable = {
  each: function(iterator, context) {
    var index = 0;
    iterator = iterator.bind(context);
    try {
      this._each(function(value) {
        iterator(value, index++);
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.collect(iterator, context);
  },

  all: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result = true;
    this.each(function(value, index) {
      result = result && !!iterator(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result = false;
    this.each(function(value, index) {
      if (result = !!iterator(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function(iterator, context) {
    iterator = iterator.bind(context);
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator, context) {
    iterator = iterator.bind(context);
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(filter, iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var results = [];

    if (Object.isString(filter))
      filter = new RegExp(filter);

    this.each(function(value, index) {
      if (filter.match(value))
        results.push(iterator(value, index));
    });
    return results;
  },

  include: function(object) {
    if (Object.isFunction(this.indexOf))
      if (this.indexOf(object) != -1) return true;

    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = Object.isUndefined(fillWith) ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator, context) {
    iterator = iterator.bind(context);
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result;
    this.each(function(value, index) {
      value = iterator(value, index);
      if (result == null || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result;
    this.each(function(value, index) {
      value = iterator(value, index);
      if (result == null || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var trues = [], falses = [];
    this.each(function(value, index) {
      (iterator(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator, context) {
    iterator = iterator.bind(context);
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator, context) {
    iterator = iterator.bind(context);
    return this.map(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');
  },

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

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (Object.isFunction(args.last()))
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
};

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  filter:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray,
  every:   Enumerable.all,
  some:    Enumerable.any
});
function $A(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

if (Prototype.Browser.WebKit) {
  $A = function(iterable) {
    if (!iterable) return [];
    if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
        iterable.toArray) return iterable.toArray();
    var length = iterable.length || 0, results = new Array(length);
    while (length--) results[length] = iterable[length];
    return results;
  };
}

Array.from = $A;

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(Object.isArray(value) ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function(sorted) {
    return this.inject([], function(array, value, index) {
      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
        array.push(value);
      return array;
    });
  },

  intersect: function(array) {
    return this.uniq().findAll(function(item) {
      return array.detect(function(value) { return item === value });
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  },

  toJSON: function() {
    var results = [];
    this.each(function(object) {
      var value = Object.toJSON(object);
      if (!Object.isUndefined(value)) results.push(value);
    });
    return '[' + results.join(', ') + ']';
  }
});

// use native browser JS 1.6 implementation if available
if (Object.isFunction(Array.prototype.forEach))
  Array.prototype._each = Array.prototype.forEach;

if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
};

if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
  i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
  var n = this.slice(0, i).reverse().indexOf(item);
  return (n < 0) ? n : i - n - 1;
};

Array.prototype.toArray = Array.prototype.clone;

function $w(string) {
  if (!Object.isString(string)) return [];
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

if (Prototype.Browser.Opera){
  Array.prototype.concat = function() {
    var array = [];
    for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
    for (var i = 0, length = arguments.length; i < length; i++) {
      if (Object.isArray(arguments[i])) {
        for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  };
}
Object.extend(Number.prototype, {
  toColorPart: function() {
    return this.toPaddedString(2, 16);
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  },

  toPaddedString: function(length, radix) {
    var string = this.toString(radix || 10);
    return '0'.times(length - string.length) + string;
  },

  toJSON: function() {
    return isFinite(this) ? this.toString() : 'null';
  }
});

$w('abs round ceil floor').each(function(method){
  Number.prototype[method] = Math[method].methodize();
});
function $H(object) {
  return new Hash(object);
};

var Hash = Class.create(Enumerable, (function() {

  function toQueryPair(key, value) {
    if (Object.isUndefined(value)) return key;
    return key + '=' + encodeURIComponent(String.interpret(value));
  }

  return {
    initialize: function(object) {
      this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
    },

    _each: function(iterator) {
      for (var key in this._object) {
        var value = this._object[key], pair = [key, value];
        pair.key = key;
        pair.value = value;
        iterator(pair);
      }
    },

    set: function(key, value) {
      return this._object[key] = value;
    },

    get: function(key) {
      return this._object[key];
    },

    unset: function(key) {
      var value = this._object[key];
      delete this._object[key];
      return value;
    },

    toObject: function() {
      return Object.clone(this._object);
    },

    keys: function() {
      return this.pluck('key');
    },

    values: function() {
      return this.pluck('value');
    },

    index: function(value) {
      var match = this.detect(function(pair) {
        return pair.value === value;
      });
      return match && match.key;
    },

    merge: function(object) {
      return this.clone().update(object);
    },

    update: function(object) {
      return new Hash(object).inject(this, function(result, pair) {
        result.set(pair.key, pair.value);
        return result;
      });
    },

    toQueryString: function() {
      return this.map(function(pair) {
        var key = encodeURIComponent(pair.key), values = pair.value;

        if (values && typeof values == 'object') {
          if (Object.isArray(values))
            return values.map(toQueryPair.curry(key)).join('&');
        }
        return toQueryPair(key, values);
      }).join('&');
    },

    inspect: function() {
      return '#<Hash:{' + this.map(function(pair) {
        return pair.map(Object.inspect).join(': ');
      }).join(', ') + '}>';
    },

    toJSON: function() {
      return Object.toJSON(this.toObject());
    },

    clone: function() {
      return new Hash(this);
    }
  }
})());

Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
Hash.from = $H;
var ObjectRange = Class.create(Enumerable, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

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

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
};

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responder) {
    if (!this.include(responder))
      this.responders.push(responder);
  },

  unregister: function(responder) {
    this.responders = this.responders.without(responder);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (Object.isFunction(responder[callback])) {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) { }
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate:   function() { Ajax.activeRequestCount++ },
  onComplete: function() { Ajax.activeRequestCount-- }
});

Ajax.Base = Class.create({
  initialize: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   '',
      evalJSON:     true,
      evalJS:       true
    };
    Object.extend(this.options, options || { });

    this.options.method = this.options.method.toLowerCase();

    if (Object.isString(this.options.parameters))
      this.options.parameters = this.options.parameters.toQueryParams();
    else if (Object.isHash(this.options.parameters))
      this.options.parameters = this.options.parameters.toObject();
  }
});

Ajax.Request = Class.create(Ajax.Base, {
  _complete: false,

  initialize: function($super, url, options) {
    $super(options);
    this.transport = Ajax.getTransport();
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = Object.clone(this.options.parameters);

    if (!['get', 'post'].include(this.method)) {
      // simulate other verbs over post
      params['_method'] = this.method;
      this.method = 'post';
    }

    this.parameters = params;

    if (params = Object.toQueryString(params)) {
      // when GET, append parameters to URL
      if (this.method == 'get')
        this.url += (this.url.include('?') ? '&' : '?') + params;
      else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
        params += '&_=';
    }

    try {
      var response = new Ajax.Response(this);
      if (this.options.onCreate) this.options.onCreate(response);
      Ajax.Responders.dispatch('onCreate', this, response);

      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      this.body = this.method == 'post' ? (this.options.postBody || params) : null;
      this.transport.send(this.body);

      
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    }
    catch (e) {
      this.dispatchException(e);
    }
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },

  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-Prototype-Version': Prototype.Version,
      'Accept': 'text/javascript, text/html, application/xml, text/xml, *
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }

    // user-defined headers
    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

      if (Object.isFunction(extras.push))
        for (var i = 0, length = extras.length; i < length; i += 2)
          headers[extras[i]] = extras[i+1];
      else
        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
    }

    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },

  success: function() {
    var status = this.getStatus();
    return !status || (status >= 200 && status < 300);
  },

  getStatus: function() {
    try {
      return this.transport.status || 0;
    } catch (e) { return 0 }
  },

  respondToReadyState: function(readyState) {
    var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + response.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(response, response.headerJSON);
      } catch (e) {
        this.dispatchException(e);
      }

      var contentType = response.getHeader('Content-type');
      if (this.options.evalJS == 'force'
          || (this.options.evalJS && this.isSameOrigin() && contentType
          && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
        this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
      Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  isSameOrigin: function() {
    var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
    return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
      protocol: location.protocol,
      domain: document.domain,
      port: location.port ? ':' + location.port : ''
    }));
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name) || null;
    } catch (e) { return null }
  },

  evalResponse: function() {
    try {
      return eval((this.transport.responseText || '').unfilterJSON());
    } catch (e) {
      this.dispatchException(e);
    }
  },

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

Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Response = Class.create({
  initialize: function(request){
    this.request = request;
    var transport  = this.transport  = request.transport,
        readyState = this.readyState = transport.readyState;

    if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
      this.status       = this.getStatus();
      this.statusText   = this.getStatusText();
      this.responseText = String.interpret(transport.responseText);
      this.headerJSON   = this._getHeaderJSON();
    }

    if(readyState == 4) {
      var xml = transport.responseXML;
      this.responseXML  = Object.isUndefined(xml) ? null : xml;
      this.responseJSON = this._getResponseJSON();
    }
  },

  status:      0,
  statusText: '',

  getStatus: Ajax.Request.prototype.getStatus,

  getStatusText: function() {
    try {
      return this.transport.statusText || '';
    } catch (e) { return '' }
  },

  getHeader: Ajax.Request.prototype.getHeader,

  getAllHeaders: function() {
    try {
      return this.getAllResponseHeaders();
    } catch (e) { return null }
  },

  getResponseHeader: function(name) {
    return this.transport.getResponseHeader(name);
  },

  getAllResponseHeaders: function() {
    return this.transport.getAllResponseHeaders();
  },

  _getHeaderJSON: function() {
    var json = this.getHeader('X-JSON');
    if (!json) return null;
    json = decodeURIComponent(escape(json));
    try {
      return json.evalJSON(this.request.options.sanitizeJSON ||
        !this.request.isSameOrigin());
    } catch (e) {
      this.request.dispatchException(e);
    }
  },

  _getResponseJSON: function() {
    var options = this.request.options;
    if (!options.evalJSON || (options.evalJSON != 'force' &&
      !(this.getHeader('Content-type') || '').include('application/json')) ||
        this.responseText.blank())
          return null;
    try {
      return this.responseText.evalJSON(options.sanitizeJSON ||
        !this.request.isSameOrigin());
    } catch (e) {
      this.request.dispatchException(e);
    }
  }
});

Ajax.Updater = Class.create(Ajax.Request, {
  initialize: function($super, container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    };

    options = Object.clone(options);
    var onComplete = options.onComplete;
    options.onComplete = (function(response, json) {
      this.updateContent(response.responseText);
      if (Object.isFunction(onComplete)) onComplete(response, json);
    }).bind(this);

    $super(url, options);
  },

  updateContent: function(responseText) {
    var receiver = this.container[this.success() ? 'success' : 'failure'],
        options = this.options;

    if (!options.evalScripts) responseText = responseText.stripScripts();

    if (receiver = $(receiver)) {
      if (options.insertion) {
        if (Object.isString(options.insertion)) {
          var insertion = { }; insertion[options.insertion] = responseText;
          receiver.insert(insertion);
        }
        else options.insertion(receiver, responseText);
      }
      else receiver.update(responseText);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
  initialize: function($super, container, url, options) {
    $super(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    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.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(response) {
    if (this.options.decay) {
      this.decay = (response.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = response.responseText;
    }
    this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

if (Prototype.BrowserFeatures.XPath) {
  document._getElementsByXPath = function(expression, parentElement) {
    var results = [];
    var query = document.evaluate(expression, $(parentElement) || document,
      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
      results.push(Element.extend(query.snapshotItem(i)));
    return results;
  };
}



if (!window.Node) var Node = { };

if (!Node.ELEMENT_NODE) {
  // DOM level 2 ECMAScript Language Binding
  Object.extend(Node, {
    ELEMENT_NODE: 1,
    ATTRIBUTE_NODE: 2,
    TEXT_NODE: 3,
    CDATA_SECTION_NODE: 4,
    ENTITY_REFERENCE_NODE: 5,
    ENTITY_NODE: 6,
    PROCESSING_INSTRUCTION_NODE: 7,
    COMMENT_NODE: 8,
    DOCUMENT_NODE: 9,
    DOCUMENT_TYPE_NODE: 10,
    DOCUMENT_FRAGMENT_NODE: 11,
    NOTATION_NODE: 12
  });
}

(function() {
  var element = this.Element;
  this.Element = function(tagName, attributes) {
    attributes = attributes || { };
    tagName = tagName.toLowerCase();
    var cache = Element.cache;
    if (Prototype.Browser.IE && attributes.name) {
      tagName = '<' + tagName + ' name="' + attributes.name + '">';
      delete attributes.name;
      return Element.writeAttribute(document.createElement(tagName), attributes);
    }
    if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
    return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
  };
  Object.extend(this.Element, element || { });
}).call(window);

Element.cache = { };

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, content) {
    element = $(element);
    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) return element.update().insert(content);
    content = Object.toHTML(content);
    element.innerHTML = content.stripScripts();
    content.evalScripts.bind(content).defer();
    return element;
  },

  replace: function(element, content) {
    element = $(element);
    if (content && content.toElement) content = content.toElement();
    else if (!Object.isElement(content)) {
      content = Object.toHTML(content);
      var range = element.ownerDocument.createRange();
      range.selectNode(element);
      content.evalScripts.bind(content).defer();
      content = range.createContextualFragment(content.stripScripts());
    }
    element.parentNode.replaceChild(content, element);
    return element;
  },

  insert: function(element, insertions) {
    element = $(element);

    if (Object.isString(insertions) || Object.isNumber(insertions) ||
        Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
          insertions = {bottom:insertions};

    var content, insert, tagName, childNodes;

    for (var position in insertions) {
      content  = insertions[position];
      position = position.toLowerCase();
      insert = Element._insertionTranslations[position];

      if (content && content.toElement) content = content.toElement();
      if (Object.isElement(content)) {
        insert(element, content);
        continue;
      }

      content = Object.toHTML(content);

      tagName = ((position == 'before' || position == 'after')
        ? element.parentNode : element).tagName.toUpperCase();

      childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());

      if (position == 'top' || position == 'after') childNodes.reverse();
      childNodes.each(insert.curry(element));

      content.evalScripts.bind(content).defer();
    }

    return element;
  },

  wrap: function(element, wrapper, attributes) {
    element = $(element);
    if (Object.isElement(wrapper))
      $(wrapper).writeAttribute(attributes || { });
    else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
    else wrapper = new Element('div', wrapper);
    if (element.parentNode)
      element.parentNode.replaceChild(wrapper, element);
    wrapper.appendChild(element);
    return wrapper;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    return $(element).select("*");
  },

  firstDescendant: function(element) {
    element = $(element).firstChild;
    while (element && element.nodeType != 1) element = element.nextSibling;
    return $(element);
  },

  immediateDescendants: function(element) {
    if (!(element = $(element).firstChild)) return [];
    while (element && element.nodeType != 1) element = element.nextSibling;
    if (element) return [element].concat($(element).nextSiblings());
    return [];
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    if (Object.isString(selector))
      selector = new Selector(selector);
    return selector.match($(element));
  },

  up: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(element.parentNode);
    var ancestors = element.ancestors();
    return Object.isNumber(expression) ? ancestors[expression] :
      Selector.findElement(ancestors, expression, index);
  },

  down: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return element.firstDescendant();
    return Object.isNumber(expression) ? element.descendants()[expression] :
      element.select(expression)[index || 0];
  },

  previous: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
    var previousSiblings = element.previousSiblings();
    return Object.isNumber(expression) ? previousSiblings[expression] :
      Selector.findElement(previousSiblings, expression, index);
  },

  next: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
    var nextSiblings = element.nextSiblings();
    return Object.isNumber(expression) ? nextSiblings[expression] :
      Selector.findElement(nextSiblings, expression, index);
  },

  select: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  adjacent: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element.parentNode, args).without(element);
  },

  identify: function(element) {
    element = $(element);
    var id = element.readAttribute('id'), self = arguments.callee;
    if (id) return id;
    do { id = 'anonymous_element_' + self.counter++ } while ($(id));
    element.writeAttribute('id', id);
    return id;
  },

  readAttribute: function(element, name) {
    element = $(element);
    if (Prototype.Browser.IE) {
      var t = Element._attributeTranslations.read;
      if (t.values[name]) return t.values[name](element, name);
      if (t.names[name]) name = t.names[name];
      if (name.include(':')) {
        return (!element.attributes || !element.attributes[name]) ? null :
         element.attributes[name].value;
      }
    }
    return element.getAttribute(name);
  },

  writeAttribute: function(element, name, value) {
    element = $(element);
    var attributes = { }, t = Element._attributeTranslations.write;

    if (typeof name == 'object') attributes = name;
    else attributes[name] = Object.isUndefined(value) ? true : value;

    for (var attr in attributes) {
      name = t.names[attr] || attr;
      value = attributes[attr];
      if (t.values[attr]) name = t.values[attr](element, value);
      if (value === false || value === null)
        element.removeAttribute(name);
      else if (value === true)
        element.setAttribute(name, name);
      else element.setAttribute(name, value);
    }
    return element;
  },

  getHeight: function(element) {
    return $(element).getDimensions().height;
  },

  getWidth: function(element) {
    return $(element).getDimensions().width;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    var elementClassName = element.className;
    return (elementClassName.length > 0 && (elementClassName == className ||
      new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    if (!element.hasClassName(className))
      element.className += (element.className ? ' ' : '') + className;
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    element.className = element.className.replace(
      new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
    return element;
  },

  toggleClassName: function(element, className) {
    if (!(element = $(element))) return;
    return element[element.hasClassName(className) ?
      'removeClassName' : 'addClassName'](className);
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.blank();
  },

  descendantOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    var originalAncestor = ancestor;

    if (element.compareDocumentPosition)
      return (element.compareDocumentPosition(ancestor) & 8) === 8;

    if (element.sourceIndex && !Prototype.Browser.Opera) {
      var e = element.sourceIndex, a = ancestor.sourceIndex,
       nextAncestor = ancestor.nextSibling;
      if (!nextAncestor) {
        do { ancestor = ancestor.parentNode; }
        while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
      }
      if (nextAncestor && nextAncestor.sourceIndex)
       return (e > a && e < nextAncestor.sourceIndex);
    }

    while (element = element.parentNode)
      if (element == originalAncestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var pos = element.cumulativeOffset();
    window.scrollTo(pos[0], pos[1]);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    style = style == 'float' ? 'cssFloat' : style.camelize();
    var value = element.style[style];
    if (!value) {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    }
    if (style == 'opacity') return value ? parseFloat(value) : 1.0;
    return value == 'auto' ? null : value;
  },

  getOpacity: function(element) {
    return $(element).getStyle('opacity');
  },

  setStyle: function(element, styles) {
    element = $(element);
    var elementStyle = element.style, match;
    if (Object.isString(styles)) {
      element.style.cssText += ';' + styles;
      return styles.include('opacity') ?
        element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
    }
    for (var property in styles)
      if (property == 'opacity') element.setOpacity(styles[property]);
      else
        elementStyle[(property == 'float' || property == 'cssFloat') ?
          (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
            property] = styles[property];

    return element;
  },

  setOpacity: function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    var display = $(element).getStyle('display');
    if (display != 'none' && display != null) // Safari bug
      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;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = originalDisplay;
    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;
      }
    }
    return element;
  },

  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 = '';
    }
    return element;
  },

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

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return element;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if (element.tagName == 'BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p !== 'static') break;
      }
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  absolutize: function(element) {
    element = $(element);
    if (element.getStyle('position') == 'absolute') return;
    // Position.prepare(); // To be done manually by Scripty when it needs it.

    var offsets = element.positionedOffset();
    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';
    return element;
  },

  relativize: function(element) {
    element = $(element);
    if (element.getStyle('position') == 'relative') return;
    // Position.prepare(); // To be done manually by Scripty when it needs it.

    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;
    return element;
  },

  cumulativeScrollOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  getOffsetParent: 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);
  },

  viewportOffset: 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 &&
        Element.getStyle(element, 'position') == 'absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return Element._returnOffset(valueL, valueT);
  },

  clonePosition: function(element, source) {
    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 = source.viewportOffset();

    // find coordinate system to use
    element = $(element);
    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(element, 'position') == 'absolute') {
      parent = element.getOffsetParent();
      delta = parent.viewportOffset();
    }

    // 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)   element.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if (options.setTop)    element.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if (options.setWidth)  element.style.width = source.offsetWidth + 'px';
    if (options.setHeight) element.style.height = source.offsetHeight + 'px';
    return element;
  }
};

Element.Methods.identify.counter = 1;

Object.extend(Element.Methods, {
  getElementsBySelector: Element.Methods.select,
  childElements: Element.Methods.immediateDescendants
});

Element._attributeTranslations = {
  write: {
    names: {
      className: 'class',
      htmlFor:   'for'
    },
    values: { }
  }
};

if (Prototype.Browser.Opera) {
  Element.Methods.getStyle = Element.Methods.getStyle.wrap(
    function(proceed, element, style) {
      switch (style) {
        case 'left': case 'top': case 'right': case 'bottom':
          if (proceed(element, 'position') === 'static') return null;
        case 'height': case 'width':
          // returns '0px' for hidden elements; we want it to return null
          if (!Element.visible(element)) return null;

          // returns the border-box dimensions rather than the content-box
          // dimensions, so we subtract padding and borders from the value
          var dim = parseInt(proceed(element, style), 10);

          if (dim !== element['offset' + style.capitalize()])
            return dim + 'px';

          var properties;
          if (style === 'height') {
            properties = ['border-top-width', 'padding-top',
             'padding-bottom', 'border-bottom-width'];
          }
          else {
            properties = ['border-left-width', 'padding-left',
             'padding-right', 'border-right-width'];
          }
          return properties.inject(dim, function(memo, property) {
            var val = proceed(element, property);
            return val === null ? memo : memo - parseInt(val, 10);
          }) + 'px';
        default: return proceed(element, style);
      }
    }
  );

  Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
    function(proceed, element, attribute) {
      if (attribute === 'title') return element.title;
      return proceed(element, attribute);
    }
  );
}

else if (Prototype.Browser.IE) {
  // IE doesn't report offsets correctly for static elements, so we change them
  // to "relative" to get the values, then change them back.
  Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
    function(proceed, element) {
      element = $(element);
      var position = element.getStyle('position');
      if (position !== 'static') return proceed(element);
      element.setStyle({ position: 'relative' });
      var value = proceed(element);
      element.setStyle({ position: position });
      return value;
    }
  );

  $w('positionedOffset viewportOffset').each(function(method) {
    Element.Methods[method] = Element.Methods[method].wrap(
      function(proceed, element) {
        element = $(element);
        var position = element.getStyle('position');
        if (position !== 'static') return proceed(element);
        // Trigger hasLayout on the offset parent so that IE6 reports
        // accurate offsetTop and offsetLeft values for position: fixed.
        var offsetParent = element.getOffsetParent();
        if (offsetParent && offsetParent.getStyle('position') === 'fixed')
          offsetParent.setStyle({ zoom: 1 });
        element.setStyle({ position: 'relative' });
        var value = proceed(element);
        element.setStyle({ position: position });
        return value;
      }
    );
  });

  Element.Methods.getStyle = function(element, style) {
    element = $(element);
    style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
    var value = element.style[style];
    if (!value && element.currentStyle) value = element.currentStyle[style];

    if (style == 'opacity') {
      if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
        if (value[1]) return parseFloat(value[1]) / 100;
      return 1.0;
    }

    if (value == 'auto') {
      if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
        return element['offset' + style.capitalize()] + 'px';
      return null;
    }
    return value;
  };

  Element.Methods.setOpacity = function(element, value) {
    function stripAlpha(filter){
      return filter.replace(/alpha\([^\)]*\)/gi,'');
    }
    element = $(element);
    var currentStyle = element.currentStyle;
    if ((currentStyle && !currentStyle.hasLayout) ||
      (!currentStyle && element.style.zoom == 'normal'))
        element.style.zoom = 1;

    var filter = element.getStyle('filter'), style = element.style;
    if (value == 1 || value === '') {
      (filter = stripAlpha(filter)) ?
        style.filter = filter : style.removeAttribute('filter');
      return element;
    } else if (value < 0.00001) value = 0;
    style.filter = stripAlpha(filter) +
      'alpha(opacity=' + (value * 100) + ')';
    return element;
  };

  Element._attributeTranslations = {
    read: {
      names: {
        'class': 'className',
        'for':   'htmlFor'
      },
      values: {
        _getAttr: function(element, attribute) {
          return element.getAttribute(attribute, 2);
        },
        _getAttrNode: function(element, attribute) {
          var node = element.getAttributeNode(attribute);
          return node ? node.value : "";
        },
        _getEv: function(element, attribute) {
          attribute = element.getAttribute(attribute);
          return attribute ? attribute.toString().slice(23, -2) : null;
        },
        _flag: function(element, attribute) {
          return $(element).hasAttribute(attribute) ? attribute : null;
        },
        style: function(element) {
          return element.style.cssText.toLowerCase();
        },
        title: function(element) {
          return element.title;
        }
      }
    }
  };

  Element._attributeTranslations.write = {
    names: Object.extend({
      cellpadding: 'cellPadding',
      cellspacing: 'cellSpacing'
    }, Element._attributeTranslations.read.names),
    values: {
      checked: function(element, value) {
        element.checked = !!value;
      },

      style: function(element, value) {
        element.style.cssText = value ? value : '';
      }
    }
  };

  Element._attributeTranslations.has = {};

  $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
      'encType maxLength readOnly longDesc').each(function(attr) {
    Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
    Element._attributeTranslations.has[attr.toLowerCase()] = attr;
  });

  (function(v) {
    Object.extend(v, {
      href:        v._getAttr,
      src:         v._getAttr,
      type:        v._getAttr,
      action:      v._getAttrNode,
      disabled:    v._flag,
      checked:     v._flag,
      readonly:    v._flag,
      multiple:    v._flag,
      onload:      v._getEv,
      onunload:    v._getEv,
      onclick:     v._getEv,
      ondblclick:  v._getEv,
      onmousedown: v._getEv,
      onmouseup:   v._getEv,
      onmouseover: v._getEv,
      onmousemove: v._getEv,
      onmouseout:  v._getEv,
      onfocus:     v._getEv,
      onblur:      v._getEv,
      onkeypress:  v._getEv,
      onkeydown:   v._getEv,
      onkeyup:     v._getEv,
      onsubmit:    v._getEv,
      onreset:     v._getEv,
      onselect:    v._getEv,
      onchange:    v._getEv
    });
  })(Element._attributeTranslations.read.values);
}

else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1) ? 0.999999 :
      (value === '') ? '' : (value < 0.00001) ? 0 : value;
    return element;
  };
}

else if (Prototype.Browser.WebKit) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;

    if (value == 1)
      if(element.tagName == 'IMG' && element.width) {
        element.width++; element.width--;
      } else try {
        var n = document.createTextNode(' ');
        element.appendChild(n);
        element.removeChild(n);
      } catch (e) { }

    return element;
  };

  // Safari returns margins on body which is incorrect if the child is absolutely
  // positioned.  For performance reasons, redefine Element#cumulativeOffset for
  // KHTML/WebKit only.
  Element.Methods.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 Element._returnOffset(valueL, valueT);
  };
}

if (Prototype.Browser.IE || Prototype.Browser.Opera) {
  // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
  Element.Methods.update = function(element, content) {
    element = $(element);

    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) return element.update().insert(content);

    content = Object.toHTML(content);
    var tagName = element.tagName.toUpperCase();

    if (tagName in Element._insertionTranslations.tags) {
      $A(element.childNodes).each(function(node) { element.removeChild(node) });
      Element._getContentFromAnonymousElement(tagName, content.stripScripts())
        .each(function(node) { element.appendChild(node) });
    }
    else element.innerHTML = content.stripScripts();

    content.evalScripts.bind(content).defer();
    return element;
  };
}

if ('outerHTML' in document.createElement('div')) {
  Element.Methods.replace = function(element, content) {
    element = $(element);

    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) {
      element.parentNode.replaceChild(content, element);
      return element;
    }

    content = Object.toHTML(content);
    var parent = element.parentNode, tagName = parent.tagName.toUpperCase();

    if (Element._insertionTranslations.tags[tagName]) {
      var nextSibling = element.next();
      var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
      parent.removeChild(element);
      if (nextSibling)
        fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
      else
        fragments.each(function(node) { parent.appendChild(node) });
    }
    else element.outerHTML = content.stripScripts();

    content.evalScripts.bind(content).defer();
    return element;
  };
}

Element._returnOffset = function(l, t) {
  var result = [l, t];
  result.left = l;
  result.top = t;
  return result;
};

Element._getContentFromAnonymousElement = function(tagName, html) {
  var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
  if (t) {
    div.innerHTML = t[0] + html + t[1];
    t[2].times(function() { div = div.firstChild });
  } else div.innerHTML = html;
  return $A(div.childNodes);
};

Element._insertionTranslations = {
  before: function(element, node) {
    element.parentNode.insertBefore(node, element);
  },
  top: function(element, node) {
    element.insertBefore(node, element.firstChild);
  },
  bottom: function(element, node) {
    element.appendChild(node);
  },
  after: function(element, node) {
    element.parentNode.insertBefore(node, element.nextSibling);
  },
  tags: {
    TABLE:  ['<table>',                '</table>',                   1],
    TBODY:  ['<table><tbody>',         '</tbody></table>',           2],
    TR:     ['<table><tbody><tr>',     '</tr></tbody></table>',      3],
    TD:     ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
    SELECT: ['<select>',               '</select>',                  1]
  }
};

(function() {
  Object.extend(this.tags, {
    THEAD: this.tags.TBODY,
    TFOOT: this.tags.TBODY,
    TH:    this.tags.TD
  });
}).call(Element._insertionTranslations);

Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    attribute = Element._attributeTranslations.has[attribute] || attribute;
    var node = $(element).getAttributeNode(attribute);
    return node && node.specified;
  }
};

Element.Methods.ByTag = { };

Object.extend(Element, Element.Methods);

if (!Prototype.BrowserFeatures.ElementExtensions &&
    document.createElement('div').__proto__) {
  window.HTMLElement = { };
  window.HTMLElement.prototype = document.createElement('div').__proto__;
  Prototype.BrowserFeatures.ElementExtensions = true;
}

Element.extend = (function() {
  if (Prototype.BrowserFeatures.SpecificElementExtensions)
    return Prototype.K;

  var Methods = { }, ByTag = Element.Methods.ByTag;

  var extend = Object.extend(function(element) {
    if (!element || element._extendedByPrototype ||
        element.nodeType != 1 || element == window) return element;

    var methods = Object.clone(Methods),
      tagName = element.tagName, property, value;

    // extend methods for specific tags
    if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);

    for (property in methods) {
      value = methods[property];
      if (Object.isFunction(value) && !(property in element))
        element[property] = value.methodize();
    }

    element._extendedByPrototype = Prototype.emptyFunction;
    return element;

  }, {
    refresh: function() {
      // extend methods for all tags (Safari doesn't need this)
      if (!Prototype.BrowserFeatures.ElementExtensions) {
        Object.extend(Methods, Element.Methods);
        Object.extend(Methods, Element.Methods.Simulated);
      }
    }
  });

  extend.refresh();
  return extend;
})();

Element.hasAttribute = function(element, attribute) {
  if (element.hasAttribute) return element.hasAttribute(attribute);
  return Element.Methods.Simulated.hasAttribute(element, attribute);
};

Element.addMethods = function(methods) {
  var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;

  if (!methods) {
    Object.extend(Form, Form.Methods);
    Object.extend(Form.Element, Form.Element.Methods);
    Object.extend(Element.Methods.ByTag, {
      "FORM":     Object.clone(Form.Methods),
      "INPUT":    Object.clone(Form.Element.Methods),
      "SELECT":   Object.clone(Form.Element.Methods),
      "TEXTAREA": Object.clone(Form.Element.Methods)
    });
  }

  if (arguments.length == 2) {
    var tagName = methods;
    methods = arguments[1];
  }

  if (!tagName) Object.extend(Element.Methods, methods || { });
  else {
    if (Object.isArray(tagName)) tagName.each(extend);
    else extend(tagName);
  }

  function extend(tagName) {
    tagName = tagName.toUpperCase();
    if (!Element.Methods.ByTag[tagName])
      Element.Methods.ByTag[tagName] = { };
    Object.extend(Element.Methods.ByTag[tagName], methods);
  }

  function copy(methods, destination, onlyIfAbsent) {
    onlyIfAbsent = onlyIfAbsent || false;
    for (var property in methods) {
      var value = methods[property];
      if (!Object.isFunction(value)) continue;
      if (!onlyIfAbsent || !(property in destination))
        destination[property] = value.methodize();
    }
  }

  function findDOMClass(tagName) {
    var klass;
    var trans = {
      "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
      "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
      "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
      "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
      "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
      "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
      "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
      "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
      "FrameSet", "IFRAME": "IFrame"
    };
    if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName.capitalize() + 'Element';
    if (window[klass]) return window[klass];

    window[klass] = { };
    window[klass].prototype = document.createElement(tagName).__proto__;
    return window[klass];
  }

  if (F.ElementExtensions) {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  }

  if (F.SpecificElementExtensions) {
    for (var tag in Element.Methods.ByTag) {
      var klass = findDOMClass(tag);
      if (Object.isUndefined(klass)) continue;
      copy(T[tag], klass.prototype);
    }
  }

  Object.extend(Element, Element.Methods);
  delete Element.ByTag;

  if (Element.extend.refresh) Element.extend.refresh();
  Element.cache = { };
};

document.viewport = {
  getDimensions: function() {
    var dimensions = { };
    var B = Prototype.Browser;
    $w('width height').each(function(d) {
      var D = d.capitalize();
      dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
        (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
    });
    return dimensions;
  },

  getWidth: function() {
    return this.getDimensions().width;
  },

  getHeight: function() {
    return this.getDimensions().height;
  },

  getScrollOffsets: function() {
    return Element._returnOffset(
      window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
      window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
  }
};


var Selector = Class.create({
  initialize: function(expression) {
    this.expression = expression.strip();
    this.compileMatcher();
  },

  shouldUseXPath: function() {
    if (!Prototype.BrowserFeatures.XPath) return false;

    var e = this.expression;

    // Safari 3 chokes on :*-of-type and :empty
    if (Prototype.Browser.WebKit &&
     (e.include("-of-type") || e.include(":empty")))
      return false;

    // XPath can't do namespaced attributes, nor can it read
    // the "checked" property from DOM nodes
    if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
      return false;

    return true;
  },

  compileMatcher: function() {
    if (this.shouldUseXPath())
      return this.compileXPathMatcher();

    var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
        c = Selector.criteria, le, p, m;

    if (Selector._cache[e]) {
      this.matcher = Selector._cache[e];
      return;
    }

    this.matcher = ["this.matcher = function(root) {",
                    "var r = root, h = Selector.handlers, c = false, n;"];

    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        p = ps[i];
        if (m = e.match(p)) {
          this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
    	      new Template(c[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.matcher.push("return h.unique(n);\n}");
    eval(this.matcher.join('\n'));
    Selector._cache[this.expression] = this.matcher;
  },

  compileXPathMatcher: function() {
    var e = this.expression, ps = Selector.patterns,
        x = Selector.xpath, le, m;

    if (Selector._cache[e]) {
      this.xpath = Selector._cache[e]; return;
    }

    this.matcher = ['./,
    child:        /^\s*>\s*/,
    adjacent:     /^\s*\+\s*/,
    descendant:   /^\s/,

    // selectors follow
    tagName:      /^\s*(\*|[\w\-]+)(\b|$)?/,
    id:           /^#([\w\-\*]+)(\b|$)/,
    className:    /^\.([\w\-\*]+)(\b|$)/,
    pseudo:
/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
    attrPresence: /^\[([\w]+)\]/,
    attr:         /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^"'][^\]]*?)))?\]/
  },

  // for Selector.match and Element#match
  assertions: {
    tagName: function(element, matches) {
      return matches[1].toUpperCase() == element.tagName.toUpperCase();
    },

    className: function(element, matches) {
      return Element.hasClassName(element, matches[1]);
    },

    id: function(element, matches) {
      return element.id === matches[1];
    },

    attrPresence: function(element, matches) {
      return Element.hasAttribute(element, matches[1]);
    },

    attr: function(element, matches) {
      var nodeValue = Element.readAttribute(element, matches[1]);
      return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
    }
  },

  handlers: {
    // UTILITY FUNCTIONS
    // joins two collections
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        a.push(node);
      return a;
    },

    // marks an array of nodes for counting
    mark: function(nodes) {
      var _true = Prototype.emptyFunction;
      for (var i = 0, node; node = nodes[i]; i++)
        node._countedByPrototype = _true;
      return nodes;
    },

    unmark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._countedByPrototype = undefined;
      return nodes;
    },

    // mark each child node with its position (for nth calls)
    // "ofType" flag indicates whether we're indexing for nth-of-type
    // rather than nth-child
    index: function(parentNode, reverse, ofType) {
      parentNode._countedByPrototype = Prototype.emptyFunction;
      if (reverse) {
        for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
          var node = nodes[i];
          if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
        }
      } else {
        for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
          if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
      }
    },

    // filters out duplicates and extends all nodes
    unique: function(nodes) {
      if (nodes.length == 0) return nodes;
      var results = [], n;
      for (var i = 0, l = nodes.length; i < l; i++)
        if (!(n = nodes[i])._countedByPrototype) {
          n._countedByPrototype = Prototype.emptyFunction;
          results.push(Element.extend(n));
        }
      return Selector.handlers.unmark(results);
    },

    // COMBINATOR FUNCTIONS
    descendant: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, node.getElementsByTagName('*'));
      return results;
    },

    child: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        for (var j = 0, child; child = node.childNodes[j]; j++)
          if (child.nodeType == 1 && child.tagName != '!') results.push(child);
      }
      return results;
    },

    adjacent: function(nodes) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        var next = this.nextElementSibling(node);
        if (next) results.push(next);
      }
      return results;
    },

    laterSibling: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, Element.nextSiblings(node));
      return results;
    },

    nextElementSibling: function(node) {
      while (node = node.nextSibling)
	      if (node.nodeType == 1) return node;
      return null;
    },

    previousElementSibling: function(node) {
      while (node = node.previousSibling)
        if (node.nodeType == 1) return node;
      return null;
    },

    // TOKEN FUNCTIONS
    tagName: function(nodes, root, tagName, combinator) {
      var uTagName = tagName.toUpperCase();
      var results = [], h = Selector.handlers;
      if (nodes) {
        if (combinator) {
          // fastlane for ordinary descendant combinators
          if (combinator == "descendant") {
            for (var i = 0, node; node = nodes[i]; i++)
              h.concat(results, node.getElementsByTagName(tagName));
            return results;
          } else nodes = this[combinator](nodes);
          if (tagName == "*") return nodes;
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.tagName.toUpperCase() === uTagName) results.push(node);
        return results;
      } else return root.getElementsByTagName(tagName);
    },

    id: function(nodes, root, id, combinator) {
      var targetNode = $(id), h = Selector.handlers;
      if (!targetNode) return [];
      if (!nodes && root == document) return [targetNode];
      if (nodes) {
        if (combinator) {
          if (combinator == 'child') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (targetNode.parentNode == node) return [targetNode];
          } else if (combinator == 'descendant') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Element.descendantOf(targetNode, node)) return [targetNode];
          } else if (combinator == 'adjacent') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Selector.handlers.previousElementSibling(targetNode) == node)
                return [targetNode];
          } else nodes = h[combinator](nodes);
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node == targetNode) return [targetNode];
        return [];
      }
      return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
    },

    className: function(nodes, root, className, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      return Selector.handlers.byClassName(nodes, root, className);
    },

    byClassName: function(nodes, root, className) {
      if (!nodes) nodes = Selector.handlers.descendant([root]);
      var needle = ' ' + className + ' ';
      for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
        nodeClassName = node.className;
        if (nodeClassName.length == 0) continue;
        if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
          results.push(node);
      }
      return results;
    },

    attrPresence: function(nodes, root, attr, combinator) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      if (nodes && combinator) nodes = this[combinator](nodes);
      var results = [];
      for (var i = 0, node; node = nodes[i]; i++)
        if (Element.hasAttribute(node, attr)) results.push(node);
      return results;
    },

    attr: function(nodes, root, attr, value, operator, combinator) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      if (nodes && combinator) nodes = this[combinator](nodes);
      var handler = Selector.operators[operator], results = [];
      for (var i = 0, node; node = nodes[i]; i++) {
        var nodeValue = Element.readAttribute(node, attr);
        if (nodeValue === null) continue;
        if (handler(nodeValue, value)) results.push(node);
      }
      return results;
    },

    pseudo: function(nodes, name, value, root, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      if (!nodes) nodes = root.getElementsByTagName("*");
      return Selector.pseudos[name](nodes, value, root);
    }
  },

  pseudos: {
    'first-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.previousElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'last-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.nextElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'only-child': function(nodes, value, root) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
          results.push(node);
      return results;
    },
    'nth-child':        function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root);
    },
    'nth-last-child':   function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true);
    },
    'nth-of-type':      function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, false, true);
    },
    'nth-last-of-type': function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true, true);
    },
    'first-of-type':    function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, false, true);
    },
    'last-of-type':     function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, true, true);
    },
    'only-of-type':     function(nodes, formula, root) {
      var p = Selector.pseudos;
      return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
    },

    // handles the an+b logic
    getIndices: function(a, b, total) {
      if (a == 0) return b > 0 ? [b] : [];
      return $R(1, total).inject([], function(memo, i) {
        if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
        return memo;
      });
    },

    // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
    nth: function(nodes, formula, root, reverse, ofType) {
      if (nodes.length == 0) return [];
      if (formula == 'even') formula = '2n+0';
      if (formula == 'odd')  formula = '2n+1';
      var h = Selector.handlers, results = [], indexed = [], m;
      h.mark(nodes);
      for (var i = 0, node; node = nodes[i]; i++) {
        if (!node.parentNode._countedByPrototype) {
          h.index(node.parentNode, reverse, ofType);
          indexed.push(node.parentNode);
        }
      }
      if (formula.match(/^\d+$/)) { // just a number
        formula = Number(formula);
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.nodeIndex == formula) results.push(node);
      } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
        if (m[1] == "-") m[1] = -1;
        var a = m[1] ? Number(m[1]) : 1;
        var b = m[2] ? Number(m[2]) : 0;
        var indices = Selector.pseudos.getIndices(a, b, nodes.length);
        for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
          for (var j = 0; j < l; j++)
            if (node.nodeIndex == indices[j]) results.push(node);
        }
      }
      h.unmark(nodes);
      h.unmark(indexed);
      return results;
    },

    'empty': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        // IE treats comments as element nodes
        if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
        results.push(node);
      }
      return results;
    },

    'not': function(nodes, selector, root) {
      var h = Selector.handlers, selectorType, m;
      var exclusions = new Selector(selector).findElements(root);
      h.mark(exclusions);
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node._countedByPrototype) results.push(node);
      h.unmark(exclusions);
      return results;
    },

    'enabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node.disabled) results.push(node);
      return results;
    },

    'disabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.disabled) results.push(node);
      return results;
    },

    'checked': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.checked) results.push(node);
      return results;
    }
  },

  operators: {
    '=':  function(nv, v) { return nv == v; },
    '!=': function(nv, v) { return nv != v; },
    '^=': function(nv, v) { return nv.startsWith(v); },
    '$=': function(nv, v) { return nv.endsWith(v); },
    '*=': function(nv, v) { return nv.include(v); },
    '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
    '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
  },

  split: function(expression) {
    var expressions = [];
    expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
      expressions.push(m[1].strip());
    });
    return expressions;
  },

  matchElements: function(elements, expression) {
    var matches = $$(expression), h = Selector.handlers;
    h.mark(matches);
    for (var i = 0, results = [], element; element = elements[i]; i++)
      if (element._countedByPrototype) results.push(element);
    h.unmark(matches);
    return results;
  },

  findElement: function(elements, expression, index) {
    if (Object.isNumber(expression)) {
      index = expression; expression = false;
    }
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    expressions = Selector.split(expressions.join(','));
    var results = [], h = Selector.handlers;
    for (var i = 0, l = expressions.length, selector; i < l; i++) {
      selector = new Selector(expressions[i].strip());
      h.concat(results, selector.findElements(element));
    }
    return (l > 1) ? h.unique(results) : results;
  }
});

if (Prototype.Browser.IE) {
  Object.extend(Selector.handlers, {
    // IE returns comment nodes on getElementsByTagName("*").
    // Filter them out.
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        if (node.tagName !== "!") a.push(node);
      return a;
    },

    // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
    unmark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node.removeAttribute('_countedByPrototype');
      return nodes;
    }
  });
}

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  },

  serializeElements: function(elements, options) {
    if (typeof options != 'object') options = { hash: !!options };
    else if (Object.isUndefined(options.hash)) options.hash = true;
    var key, value, submitted = false, submit = options.submit;

    var data = elements.inject({ }, function(result, element) {
      if (!element.disabled && element.name) {
        key = element.name; value = $(element).getValue();
        if (value != null && (element.type != 'submit' || (!submitted &&
            submit !== false && (!submit || key == submit) && (submitted = true)))) {
          if (key in result) {
            // a key is already present; construct an array of values
            if (!Object.isArray(result[key])) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

    return options.hash ? data : Object.toQueryString(data);
  }
};

Form.Methods = {
  serialize: function(form, options) {
    return Form.serializeElements(Form.getElements(form), options);
  },

  getElements: function(form) {
    return $A($(form).getElementsByTagName('*')).inject([],
      function(elements, child) {
        if (Form.Element.Serializers[child.tagName.toLowerCase()])
          elements.push(Element.extend(child));
        return elements;
      }
    );
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name) return $A(inputs).map(Element.extend);

    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) || (name && input.name != name))
        continue;
      matchingInputs.push(Element.extend(input));
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('disable');
    return form;
  },

  enable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('enable');
    return form;
  },

  findFirstElement: function(form) {
    var elements = $(form).getElements().findAll(function(element) {
      return 'hidden' != element.type && !element.disabled;
    });
    var firstByIndex = elements.findAll(function(element) {
      return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
    }).sortBy(function(element) { return element.tabIndex }).first();

    return firstByIndex ? firstByIndex : elements.find(function(element) {
      return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    form.findFirstElement().activate();
    return form;
  },

  request: function(form, options) {
    form = $(form), options = Object.clone(options || { });

    var params = options.parameters, action = form.readAttribute('action') || '';
    if (action.blank()) action = window.location.href;
    options.parameters = form.serialize(true);

    if (params) {
      if (Object.isString(params)) params = params.toQueryParams();
      Object.extend(options.parameters, params);
    }

    if (form.hasAttribute('method') && !options.method)
      options.method = form.method;

    return new Ajax.Request(action, options);
  }
};



Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
};

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    if (!element.disabled && element.name) {
      var value = element.getValue();
      if (value != undefined) {
        var pair = { };
        pair[element.name] = value;
        return Object.toQueryString(pair);
      }
    }
    return '';
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    return Form.Element.Serializers[method](element);
  },

  setValue: function(element, value) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    Form.Element.Serializers[method](element, value);
    return element;
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    try {
      element.focus();
      if (element.select && (element.tagName.toLowerCase() != 'input' ||
          !['button', 'reset', 'submit'].include(element.type)))
        element.select();
    } catch (e) { }
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = true;
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.disabled = false;
    return element;
  }
};



var Field = Form.Element;
var $F = Form.Element.Methods.getValue;



Form.Element.Serializers = {
  input: function(element, value) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element, value);
      default:
        return Form.Element.Serializers.textarea(element, value);
    }
  },

  inputSelector: function(element, value) {
    if (Object.isUndefined(value)) return element.checked ? element.value : null;
    else element.checked = !!value;
  },

  textarea: function(element, value) {
    if (Object.isUndefined(value)) return element.value;
    else element.value = value;
  },

  select: function(element, index) {
    if (Object.isUndefined(index))
      return this[element.type == 'select-one' ?
        'selectOne' : 'selectMany'](element);
    else {
      var opt, value, single = !Object.isArray(index);
      for (var i = 0, length = element.length; i < length; i++) {
        opt = element.options[i];
        value = this.optionValue(opt);
        if (single) {
          if (value == index) {
            opt.selected = true;
            return;
          }
        }
        else opt.selected = index.include(value);
      }
    }
  },

  selectOne: function(element) {
    var index = element.selectedIndex;
    return index >= 0 ? this.optionValue(element.options[index]) : null;
  },

  selectMany: function(element) {
    var values, length = element.length;
    if (!length) return null;

    for (var i = 0, values = []; i < length; i++) {
      var opt = element.options[i];
      if (opt.selected) values.push(this.optionValue(opt));
    }
    return values;
  },

  optionValue: function(opt) {
    // extend element because hasAttribute may not be native
    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
};



Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
  initialize: function($super, element, frequency, callback) {
    $super(callback, frequency);
    this.element   = $(element);
    this.lastValue = this.getValue();
  },

  execute: function() {
    var value = this.getValue();
    if (Object.isString(this.lastValue) && Object.isString(value) ?
        this.lastValue != value : String(this.lastValue) != String(value)) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
});

Form.Element.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
    return Form.serialize(this.element);
  }
});



Abstract.EventObserver = Class.create({
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    Form.getElements(this.element).each(this.registerCallback, this);
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
});

Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create(Abstract.EventObserver, {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) var Event = { };

Object.extend(Event, {
  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,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,
  KEY_INSERT:   45,

  cache: { },

  relatedTarget: function(event) {
    var element;
    switch(event.type) {
      case 'mouseover': element = event.fromElement; break;
      case 'mouseout':  element = event.toElement;   break;
      default: return null;
    }
    return Element.extend(element);
  }
});

Event.Methods = (function() {
  var isButton;

  if (Prototype.Browser.IE) {
    var buttonMap = { 0: 1, 1: 4, 2: 2 };
    isButton = function(event, code) {
      return event.button == buttonMap[code];
    };

  } else if (Prototype.Browser.WebKit) {
    isButton = function(event, code) {
      switch (code) {
        case 0: return event.which == 1 && !event.metaKey;
        case 1: return event.which == 1 && event.metaKey;
        default: return false;
      }
    };

  } else {
    isButton = function(event, code) {
      return event.which ? (event.which === code + 1) : (event.button === code);
    };
  }

  return {
    isLeftClick:   function(event) { return isButton(event, 0) },
    isMiddleClick: function(event) { return isButton(event, 1) },
    isRightClick:  function(event) { return isButton(event, 2) },

    element: function(event) {
      var node = Event.extend(event).target;
      return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
    },

    findElement: function(event, expression) {
      var element = Event.element(event);
      if (!expression) return element;
      var elements = [element].concat(element.ancestors());
      return Selector.findElement(elements, expression, 0);
    },

    pointer: function(event) {
      return {
        x: event.pageX || (event.clientX +
          (document.documentElement.scrollLeft || document.body.scrollLeft)),
        y: event.pageY || (event.clientY +
          (document.documentElement.scrollTop || document.body.scrollTop))
      };
    },

    pointerX: function(event) { return Event.pointer(event).x },
    pointerY: function(event) { return Event.pointer(event).y },

    stop: function(event) {
      Event.extend(event);
      event.preventDefault();
      event.stopPropagation();
      event.stopped = true;
    }
  };
})();

Event.extend = (function() {
  var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
    m[name] = Event.Methods[name].methodize();
    return m;
  });

  if (Prototype.Browser.IE) {
    Object.extend(methods, {
      stopPropagation: function() { this.cancelBubble = true },
      preventDefault:  function() { this.returnValue = false },
      inspect: function() { return "[object Event]" }
    });

    return function(event) {
      if (!event) return false;
      if (event._extendedByPrototype) return event;

      event._extendedByPrototype = Prototype.emptyFunction;
      var pointer = Event.pointer(event);
      Object.extend(event, {
        target: event.srcElement,
        relatedTarget: Event.relatedTarget(event),
        pageX:  pointer.x,
        pageY:  pointer.y
      });
      return Object.extend(event, methods);
    };

  } else {
    Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
    Object.extend(Event.prototype, methods);
    return Prototype.K;
  }
})();

Object.extend(Event, (function() {
  var cache = Event.cache;

  function getEventID(element) {
    if (element._prototypeEventID) return element._prototypeEventID[0];
    arguments.callee.id = arguments.callee.id || 1;
    return element._prototypeEventID = [++arguments.callee.id];
  }

  function getDOMEventName(eventName) {
    if (eventName && eventName.include(':')) return "dataavailable";
    return eventName;
  }

  function getCacheForID(id) {
    return cache[id] = cache[id] || { };
  }

  function getWrappersForEventName(id, eventName) {
    var c = getCacheForID(id);
    return c[eventName] = c[eventName] || [];
  }

  function createWrapper(element, eventName, handler) {
    var id = getEventID(element);
    var c = getWrappersForEventName(id, eventName);
    if (c.pluck("handler").include(handler)) return false;

    var wrapper = function(event) {
      if (!Event || !Event.extend ||
        (event.eventName && event.eventName != eventName))
          return false;

      Event.extend(event);
      handler.call(element, event);
    };

    wrapper.handler = handler;
    c.push(wrapper);
    return wrapper;
  }

  function findWrapper(id, eventName, handler) {
    var c = getWrappersForEventName(id, eventName);
    return c.find(function(wrapper) { return wrapper.handler == handler });
  }

  function destroyWrapper(id, eventName, handler) {
    var c = getCacheForID(id);
    if (!c[eventName]) return false;
    c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
  }

  function destroyCache() {
    for (var id in cache)
      for (var eventName in cache[id])
        cache[id][eventName] = null;
  }

  if (window.attachEvent) {
    window.attachEvent("onunload", destroyCache);
  }

  return {
    observe: function(element, eventName, handler) {
      element = $(element);
      var name = getDOMEventName(eventName);

      var wrapper = createWrapper(element, eventName, handler);
      if (!wrapper) return element;

      if (element.addEventListener) {
        element.addEventListener(name, wrapper, false);
      } else {
        element.attachEvent("on" + name, wrapper);
      }

      return element;
    },

    stopObserving: function(element, eventName, handler) {
      element = $(element);
      var id = getEventID(element), name = getDOMEventName(eventName);

      if (!handler && eventName) {
        getWrappersForEventName(id, eventName).each(function(wrapper) {
          element.stopObserving(eventName, wrapper.handler);
        });
        return element;

      } else if (!eventName) {
        Object.keys(getCacheForID(id)).each(function(eventName) {
          element.stopObserving(eventName);
        });
        return element;
      }

      var wrapper = findWrapper(id, eventName, handler);
      if (!wrapper) return element;

      if (element.removeEventListener) {
        element.removeEventListener(name, wrapper, false);
      } else {
        element.detachEvent("on" + name, wrapper);
      }

      destroyWrapper(id, eventName, handler);

      return element;
    },

    fire: function(element, eventName, memo) {
      element = $(element);
      if (element == document && document.createEvent && !element.dispatchEvent)
        element = document.documentElement;

      var event;
      if (document.createEvent) {
        event = document.createEvent("HTMLEvents");
        event.initEvent("dataavailable", true, true);
      } else {
        event = document.createEventObject();
        event.eventType = "ondataavailable";
      }

      event.eventName = eventName;
      event.memo = memo || { };

      if (document.createEvent) {
        element.dispatchEvent(event);
      } else {
        element.fireEvent(event.eventType, event);
      }

      return Event.extend(event);
    }
  };
})());

Object.extend(Event, Event.Methods);

Element.addMethods({
  fire:          Event.fire,
  observe:       Event.observe,
  stopObserving: Event.stopObserving
});

Object.extend(document, {
  fire:          Element.Methods.fire.methodize(),
  observe:       Element.Methods.observe.methodize(),
  stopObserving: Element.Methods.stopObserving.methodize(),
  loaded:        false
});

(function() {
  

  var timer;

  function fireContentLoadedEvent() {
    if (document.loaded) return;
    if (timer) window.clearInterval(timer);
    document.fire("dom:loaded");
    document.loaded = true;
  }

  if (document.addEventListener) {
    if (Prototype.Browser.WebKit) {
      timer = window.setInterval(function() {
        if (/loaded|complete/.test(document.readyState))
          fireContentLoadedEvent();
      }, 0);

      Event.observe(window, "load", fireContentLoadedEvent);

    } else {
      document.addEventListener("DOMContentLoaded",
        fireContentLoadedEvent, false);
    }

  } else {
    document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
    $("__onDOMContentLoaded").onreadystatechange = function() {
      if (this.readyState == "complete") {
        this.onreadystatechange = null;
        fireContentLoadedEvent();
      }
    };
  }
})();


Hash.toQueryString = Object.toQueryString;

var Toggle = { display: Element.toggle };

Element.Methods.childOf = Element.Methods.descendantOf;

var Insertion = {
  Before: function(element, content) {
    return Element.insert(element, {before:content});
  },

  Top: function(element, content) {
    return Element.insert(element, {top:content});
  },

  Bottom: function(element, content) {
    return Element.insert(element, {bottom:content});
  },

  After: function(element, content) {
    return Element.insert(element, {after:content});
  }
};

var $continue = new Error('"throw $continue" is deprecated, use "return" instead');

// This should be moved to script.aculo.us; notice the deprecated methods
// further below, that map to the newer Element methods.
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = Element.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = Element.cumulativeScrollOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = Element.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  // Deprecation layer -- use newer Element methods now (1.5.2).

  cumulativeOffset: Element.Methods.cumulativeOffset,

  positionedOffset: Element.Methods.positionedOffset,

  absolutize: function(element) {
    Position.prepare();
    return Element.absolutize(element);
  },

  relativize: function(element) {
    Position.prepare();
    return Element.relativize(element);
  },

  realOffset: Element.Methods.cumulativeScrollOffset,

  offsetParent: Element.Methods.getOffsetParent,

  page: Element.Methods.viewportOffset,

  clone: function(source, target, options) {
    options = options || { };
    return Element.clonePosition(target, source, options);
  }
};



if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
  function iter(name) {
    return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
  }

  instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
  function(element, className) {
    className = className.toString().strip();
    var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
    return cond ? document._getElementsByXPath('./

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);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set($A(this).concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set($A(this).without(classNameToRemove).join(' '));
  },

  toString: function() {
    return $A(this).join(' ');
  }
};

Object.extend(Element.ClassNames.prototype, Enumerable);



Element.addMethods();
// script.aculo.us scriptaculous.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Scriptaculous = {
  Version: '1.8.1',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
  },
  REQUIRED_PROTOTYPE: '1.6.0',
	
  load: function() {
    function convertVersionString(versionString){
      var r = versionString.split('.');
      return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
    }
 
    if((typeof Prototype=='undefined') || 
       (typeof Element == 'undefined') || 
       (typeof Element.Methods=='undefined') ||
       (convertVersionString(Prototype.Version) < 
        convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
       throw("script.aculo.us requires the Prototype JavaScript framework >= " +
        Scriptaculous.REQUIRED_PROTOTYPE);
    
    $A(document.getElementsByTagName("script")).findAll( function(s) {
      return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
    }).each( function(s) {
      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
       function(include) { Scriptaculous.require(path+include+'.js') });
    });
  }
}

Scriptaculous.load();
// script.aculo.us builder.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Builder = {
  NODEMAP: {
    AREA: 'map',
    CAPTION: 'table',
    COL: 'table',
    COLGROUP: 'table',
    LEGEND: 'fieldset',
    OPTGROUP: 'select',
    OPTION: 'select',
    PARAM: 'object',
    TBODY: 'table',
    TD: 'table',
    TFOOT: 'table',
    TH: 'table',
    THEAD: 'table',
    TR: 'table'
  },
  // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
  //       due to a Firefox bug
  node: function(elementName) {
    elementName = elementName.toUpperCase();
    
    // try innerHTML approach
    var parentTag = this.NODEMAP[elementName] || 'div';
    var parentElement = document.createElement(parentTag);
    try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
      parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
    } catch(e) {}
    var element = parentElement.firstChild || null;
      
    // see if browser added wrapping tags
    if(element && (element.tagName.toUpperCase() != elementName))
      element = element.getElementsByTagName(elementName)[0];
    
    // fallback to createElement approach
    if(!element) element = document.createElement(elementName);
    
    // abort if nothing could be created
    if(!element) return;

    // attributes (or text)
    if(arguments[1])
      if(this._isStringOrNumber(arguments[1]) ||
        (arguments[1] instanceof Array) ||
        arguments[1].tagName) {
          this._children(element, arguments[1]);
        } else {
          var attrs = this._attributes(arguments[1]);
          if(attrs.length) {
            try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
              parentElement.innerHTML = "<" +elementName + " " +
                attrs + "></" + elementName + ">";
            } catch(e) {}
            element = parentElement.firstChild || null;
            // workaround firefox 1.0.X bug
            if(!element) {
              element = document.createElement(elementName);
              for(attr in arguments[1]) 
                element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
            }
            if(element.tagName.toUpperCase() != elementName)
              element = parentElement.getElementsByTagName(elementName)[0];
          }
        } 

    // text, or array of children
    if(arguments[2])
      this._children(element, arguments[2]);

     return element;
  },
  _text: function(text) {
     return document.createTextNode(text);
  },

  ATTR_MAP: {
    'className': 'class',
    'htmlFor': 'for'
  },

  _attributes: function(attributes) {
    var attrs = [];
    for(attribute in attributes)
      attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
          '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"');
    return attrs.join(" ");
  },
  _children: function(element, children) {
    if(children.tagName) {
      element.appendChild(children);
      return;
    }
    if(typeof children=='object') { // array can hold nodes and text
      children.flatten().each( function(e) {
        if(typeof e=='object')
          element.appendChild(e)
        else
          if(Builder._isStringOrNumber(e))
            element.appendChild(Builder._text(e));
      });
    } else
      if(Builder._isStringOrNumber(children))
        element.appendChild(Builder._text(children));
  },
  _isStringOrNumber: function(param) {
    return(typeof param=='string' || typeof param=='number');
  },
  build: function(html) {
    var element = this.node('div');
    $(element).update(html.strip());
    return element.down();
  },
  dump: function(scope) { 
    if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope 
  
    var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
      "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
      "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
      "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
      "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
      "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
  
    tags.each( function(tag){ 
      scope[tag] = function() { 
        return Builder.node.apply(Builder, [tag].concat($A(arguments)));  
      } 
    });
  }
}

// script.aculo.us effects.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/ 

// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
  var color = '#';
  if (this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if (this.slice(0,1) == '#') {  
      if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if (this.length==7) color = this.toLowerCase();  
    }  
  }  
  return (color.length==7 ? color : (arguments[0] || this));  
};



Element.collectTextNodes = function(element) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
};

Element.collectTextNodesIgnoreClass = function(element, className) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
        Element.collectTextNodesIgnoreClass(node, className) : ''));
  }).flatten().join('');
};

Element.setContentZoom = function(element, percent) {
  element = $(element);  
  element.setStyle({fontSize: (percent/100) + 'em'});   
  if (Prototype.Browser.WebKit) window.scrollBy(0,0);
  return element;
};

Element.getInlineOpacity = function(element){
  return $(element).style.opacity || '';
};

Element.forceRerendering = function(element) {
  try {
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    element.removeChild(n);
  } catch(e) { }
};



var Effect = {
  _elementDoesNotExistError: {
    name: 'ElementDoesNotExistError',
    message: 'The specified DOM element does not exist, but is required for this effect to operate'
  },
  Transitions: {
    linear: Prototype.K,
    sinoidal: function(pos) {
      return (-Math.cos(pos*Math.PI)/2) + 0.5;
    },
    reverse: function(pos) {
      return 1-pos;
    },
    flicker: function(pos) {
      var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
      return pos > 1 ? 1 : pos;
    },
    wobble: function(pos) {
      return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
    },
    pulse: function(pos, pulses) { 
      pulses = pulses || 5; 
      return (
        ((pos % (1/pulses)) * pulses).round() == 0 ? 
              ((pos * pulses * 2) - (pos * pulses * 2).floor()) : 
          1 - ((pos * pulses * 2) - (pos * pulses * 2).floor())
        );
    },
    spring: function(pos) { 
      return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); 
    },
    none: function(pos) {
      return 0;
    },
    full: function(pos) {
      return 1;
    }
  },
  DefaultOptions: {
    duration:   1.0,   // seconds
    fps:        100,   // 100= assume 66fps max.
    sync:       false, // true for combining
    from:       0.0,
    to:         1.0,
    delay:      0.0,
    queue:      'parallel'
  },
  tagifyText: function(element) {
    var tagifyStyle = 'position:relative';
    if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
    
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if (child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            new Element('span', {style: tagifyStyle}).update(
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if (((typeof element == 'object') || 
        Object.isFunction(element)) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || { });
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
    }, arguments[2] || { });
    Effect[element.visible() ? 
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;



Effect.ScopedQueue = Class.create(Enumerable, {
  initialize: function() {
    this.effects  = [];
    this.interval = null;    
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    var position = Object.isString(effect.options.queue) ? 
      effect.options.queue : effect.options.queue.position;
    
    switch(position) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'with-last':
        timestamp = this.effects.pluck('startOn').max() || timestamp;
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;

    if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);
    
    if (!this.interval)
      this.interval = setInterval(this.loop.bind(this), 15);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if (this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    for(var i=0, len=this.effects.length;i<len;i++) 
      this.effects[i] && this.effects[i].loop(timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if (!Object.isString(queueName)) return queueName;
    
    return this.instances.get(queueName) ||
      this.instances.set(queueName, new Effect.ScopedQueue());
  }
};
Effect.Queue = Effect.Queues.get('global');

Effect.Base = Class.create({
  position: null,
  start: function(options) {
    function codeForEvent(options,eventName){
      return (
        (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
        (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
      );
    }
    if (options && options.transition === false) options.transition = Effect.Transitions.linear;
    this.options      = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn+(this.options.duration*1000);
    this.fromToDelta  = this.options.to-this.options.from;
    this.totalTime    = this.finishOn-this.startOn;
    this.totalFrames  = this.options.fps*this.options.duration;
    
    eval('this.render = function(pos){ '+
      'if (this.state=="idle"){this.state="running";'+
      codeForEvent(this.options,'beforeSetup')+
      (this.setup ? 'this.setup();':'')+ 
      codeForEvent(this.options,'afterSetup')+
      '};if (this.state=="running"){'+
      'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
      'this.position=pos;'+
      codeForEvent(this.options,'beforeUpdate')+
      (this.update ? 'this.update(pos);':'')+
      codeForEvent(this.options,'afterUpdate')+
      '}}');
    
    this.event('beforeStart');
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ? 
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if (timePos >= this.startOn) {
      if (timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if (this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / this.totalTime,
          frame = (pos * this.totalFrames).round();
      if (frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  cancel: function() {
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ? 
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if (this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    var data = $H();
    for(property in this)
      if (!Object.isFunction(this[property])) data.set(property, this[property]);
    return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
});

Effect.Parallel = Class.create(Effect.Base, {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if (effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Tween = Class.create(Effect.Base, {
  initialize: function(object, from, to) {
    object = Object.isString(object) ? $(object) : object;
    var args = $A(arguments), method = args.last(), 
      options = args.length == 5 ? args[3] : null;
    this.method = Object.isFunction(method) ? method.bind(object) :
      Object.isFunction(object[method]) ? object[method].bind(object) : 
      function(value) { object[method] = value };
    this.start(Object.extend({ from: from, to: to }, options || { }));
  },
  update: function(position) {
    this.method(position);
  }
});

Effect.Event = Class.create(Effect.Base, {
  initialize: function() {
    this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
  },
  update: Prototype.emptyFunction
});

Effect.Opacity = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    // make this work on IE on elements without 'layout'
    if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
      this.element.setStyle({zoom: 1});
    var options = Object.extend({
      from: this.element.getOpacity() || 0.0,
      to:   1.0
    }, arguments[1] || { });
    this.start(options);
  },
  update: function(position) {
    this.element.setOpacity(position);
  }
});

Effect.Move = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || { });
    this.start(options);
  },
  setup: function() {
    this.element.makePositioned();
    this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
    this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
    if (this.options.mode == 'absolute') {
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
  },
  update: function(position) {
    this.element.setStyle({
      left: (this.options.x  * position + this.originalLeft).round() + 'px',
      top:  (this.options.y  * position + this.originalTop).round()  + 'px'
    });
  }
});

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

Effect.Scale = Class.create(Effect.Base, {
  initialize: function(element, percent) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or { } with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || { });
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = this.element.getStyle('position');
    
    this.originalStyle = { };
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = this.element.getStyle('font-size') || '100%';
    ['em','px','%','pt'].each( function(fontSizeType) {
      if (fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if (this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if (/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if (!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if (this.options.scaleContent && this.fontSize)
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = { };
    if (this.options.scaleX) d.width = width.round() + 'px';
    if (this.options.scaleY) d.height = height.round() + 'px';
    if (this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if (this.elementPositioning == 'absolute') {
        if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if (this.options.scaleY) d.top = -topd + 'px';
        if (this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    this.element.setStyle(d);
  }
});

Effect.Highlight = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if (this.element.getStyle('display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = { };
    if (!this.options.keepBackgroundImage) {
      this.oldStyle.backgroundImage = this.element.getStyle('background-image');
      this.element.setStyle({backgroundImage: 'none'});
    }
    if (!this.options.endcolor)
      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
    if (!this.options.restorecolor)
      this.options.restorecolor = this.element.getStyle('background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle(Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = function(element) {
  var options = arguments[1] || { },
    scrollOffsets = document.viewport.getScrollOffsets(),
    elementOffsets = $(element).cumulativeOffset(),
    max = (window.height || document.body.scrollHeight) - document.viewport.getHeight();  

  if (options.offset) elementOffsets[1] += options.offset;

  return new Effect.Tween(null,
    scrollOffsets.top,
    elementOffsets[1] > max ? max : elementOffsets[1],
    options,
    function(p){ scrollTo(scrollOffsets.left, p.round()) }
  );
};



Effect.Fade = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  var options = Object.extend({
    from: element.getOpacity() || 1.0,
    to:   0.0,
    afterFinishInternal: function(effect) { 
      if (effect.options.to!=0) return;
      effect.element.hide().setStyle({opacity: oldOpacity}); 
    }
  }, arguments[1] || { });
  return new Effect.Opacity(element,options);
};

Effect.Appear = function(element) {
  element = $(element);
  var options = Object.extend({
  from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
  to:   1.0,
  // force Safari to render floated elements properly
  afterFinishInternal: function(effect) {
    effect.element.forceRerendering();
  },
  beforeSetup: function(effect) {
    effect.element.setOpacity(effect.options.from).show(); 
  }}, arguments[1] || { });
  return new Effect.Opacity(element,options);
};

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = { 
    opacity: element.getInlineOpacity(), 
    position: element.getStyle('position'),
    top:  element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height
  };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
      beforeSetupInternal: function(effect) {
        Position.absolutize(effect.effects[0].element)
      },
      afterFinishInternal: function(effect) {
         effect.effects[0].element.hide().setStyle(oldStyle); }
     }, arguments[1] || { })
   );
};

Effect.BlindUp = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      } 
    }, arguments[1] || { })
  );
};

Effect.BlindDown = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  return new Effect.Appear(element, Object.extend({
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) { 
          effect.element.makePositioned().makeClipping();
        },
        afterFinishInternal: function(effect) {
          effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
        }
      })
    }
  }, arguments[1] || { }));
};

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left'),
    opacity: element.getInlineOpacity() };
  return new Effect.Parallel(
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) {
          effect.effects[0].element.makePositioned(); 
        },
        afterFinishInternal: function(effect) {
          effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
        } 
      }, arguments[1] || { }));
};

Effect.Shake = function(element) {
  element = $(element);
  var options = Object.extend({
    distance: 20,
    duration: 0.5
  }, arguments[1] || {});
  var distance = parseFloat(options.distance);
  var split = parseFloat(options.duration) / 10.0;
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left') };
    return new Effect.Move(element,
      { x:  distance, y: 0, duration: split, afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
        effect.element.undoPositioned().setStyle(oldStyle);
  }}) }}) }}) }}) }}) }});
};

Effect.SlideDown = function(element) {
  element = $(element).cleanWhitespace();
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: window.opera ? 0 : 1,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if (window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); 
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
    }, arguments[1] || { })
  );
};

Effect.SlideUp = function(element) {
  element = $(element).cleanWhitespace();
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, window.opera ? 0 : 1,
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if (window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().show();
    },  
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' });
    },
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
    }
   }, arguments[1] || { })
  );
};

// Bug in opera makes the TD containing this element expand for a instance after finish 
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, { 
    restoreAfterFinish: true,
    beforeSetup: function(effect) {
      effect.element.makeClipping(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping(); 
    }
  });
};

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || { });
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();    
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }
  
  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
    duration: 0.01, 
    beforeSetup: function(effect) {
      effect.element.hide().makeClipping().makePositioned();
    },
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) {
               effect.effects[0].element.setStyle({height: '0px'}).show(); 
             },
             afterFinishInternal: function(effect) {
               effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); 
             }
           }, options)
      )
    }
  });
};

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || { });
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':  
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }
  
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({            
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned().makeClipping(); 
         },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
       }, options)
  );
};

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || { };
  var oldOpacity = element.getInlineOpacity();
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
  reverser.bind(transition);
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 2.0, from: 0,
      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
    }, options), {transition: reverser}));
};

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  element.makeClipping();
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping().setStyle(oldStyle);
      } });
  }}, arguments[1] || { }));
};

Effect.Morph = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      style: { }
    }, arguments[1] || { });
    
    if (!Object.isString(options.style)) this.style = $H(options.style);
    else {
      if (options.style.include(':'))
        this.style = options.style.parseStyle();
      else {
        this.element.addClassName(options.style);
        this.style = $H(this.element.getStyles());
        this.element.removeClassName(options.style);
        var css = this.element.getStyles();
        this.style = this.style.reject(function(style) {
          return style.value == css[style.key];
        });
        options.afterFinishInternal = function(effect) {
          effect.element.addClassName(effect.options.style);
          effect.transforms.each(function(transform) {
            effect.element.style[transform.style] = '';
          });
        }
      }
    }
    this.start(options);
  },
  
  setup: function(){
    function parseColor(color){
      if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
      color = color.parseColor();
      return $R(0,2).map(function(i){
        return parseInt( color.slice(i*2+1,i*2+3), 16 ) 
      });
    }
    this.transforms = this.style.map(function(pair){
      var property = pair[0], value = pair[1], unit = null;

      if (value.parseColor('#zzzzzz') != '#zzzzzz') {
        value = value.parseColor();
        unit  = 'color';
      } else if (property == 'opacity') {
        value = parseFloat(value);
        if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
          this.element.setStyle({zoom: 1});
      } else if (Element.CSS_LENGTH.test(value)) {
          var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
          value = parseFloat(components[1]);
          unit = (components.length == 3) ? components[2] : null;
      }

      var originalValue = this.element.getStyle(property);
      return { 
        style: property.camelize(), 
        originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), 
        targetValue: unit=='color' ? parseColor(value) : value,
        unit: unit
      };
    }.bind(this)).reject(function(transform){
      return (
        (transform.originalValue == transform.targetValue) ||
        (
          transform.unit != 'color' &&
          (isNaN(transform.originalValue) || isNaN(transform.targetValue))
        )
      )
    });
  },
  update: function(position) {
    var style = { }, transform, i = this.transforms.length;
    while(i--)
      style[(transform = this.transforms[i]).style] = 
        transform.unit=='color' ? '#'+
          (Math.round(transform.originalValue[0]+
            (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
          (Math.round(transform.originalValue[1]+
            (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
          (Math.round(transform.originalValue[2]+
            (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
        (transform.originalValue +
          (transform.targetValue - transform.originalValue) * position).toFixed(3) + 
            (transform.unit === null ? '' : transform.unit);
    this.element.setStyle(style, true);
  }
});

Effect.Transform = Class.create({
  initialize: function(tracks){
    this.tracks  = [];
    this.options = arguments[1] || { };
    this.addTracks(tracks);
  },
  addTracks: function(tracks){
    tracks.each(function(track){
      track = $H(track);
      var data = track.values().first();
      this.tracks.push($H({
        ids:     track.keys().first(),
        effect:  Effect.Morph,
        options: { style: data }
      }));
    }.bind(this));
    return this;
  },
  play: function(){
    return new Effect.Parallel(
      this.tracks.map(function(track){
        var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
        var elements = [$(ids) || $$(ids)].flatten();
        return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
      }).flatten(),
      this.options
    );
  }
});

Element.CSS_PROPERTIES = $w(
  'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 
  'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
  'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
  'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
  'fontSize fontWeight height left letterSpacing lineHeight ' +
  'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
  'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
  'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
  'right textIndent top width wordSpacing zIndex');
  
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;

String.__parseStyleElement = document.createElement('div');
String.prototype.parseStyle = function(){
  var style, styleRules = $H();
  if (Prototype.Browser.WebKit)
    style = new Element('div',{style:this}).style;
  else {
    String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
    style = String.__parseStyleElement.childNodes[0].style;
  }
  
  Element.CSS_PROPERTIES.each(function(property){
    if (style[property]) styleRules.set(property, style[property]); 
  });
  
  if (Prototype.Browser.IE && this.include('opacity'))
    styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);

  return styleRules;
};

if (document.defaultView && document.defaultView.getComputedStyle) {
  Element.getStyles = function(element) {
    var css = document.defaultView.getComputedStyle($(element), null);
    return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
      styles[property] = css[property];
      return styles;
    });
  };
} else {
  Element.getStyles = function(element) {
    element = $(element);
    var css = element.currentStyle, styles;
    styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
      results[property] = css[property];
      return results;
    });
    if (!styles.opacity) styles.opacity = element.getOpacity();
    return styles;
  };
};

Effect.Methods = {
  morph: function(element, style) {
    element = $(element);
    new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
    return element;
  },
  visualEffect: function(element, effect, options) {
    element = $(element)
    var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
    new Effect[klass](element, options);
    return element;
  },
  highlight: function(element, options) {
    element = $(element);
    new Effect.Highlight(element, options);
    return element;
  }
};

$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
  'pulsate shake puff squish switchOff dropOut').each(
  function(effect) { 
    Effect.Methods[effect] = function(element, options){
      element = $(element);
      Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
      return element;
    }
  }
);

$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( 
  function(f) { Effect.Methods[f] = Element[f]; }
);

Element.addMethods(Effect.Methods);

// script.aculo.us dragdrop.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

if(Object.isUndefined(Effect))
  throw("dragdrop.js requires including script.aculo.us' effects.js library");

var Droppables = {
  drops: [],

  remove: function(element) {
    this.drops = this.drops.reject(function(d) { return d.element==$(element) });
  },

  add: function(element) {
    element = $(element);
    var options = Object.extend({
      greedy:     true,
      hoverclass: null,
      tree:       false
    }, arguments[1] || { });

    // cache containers
    if(options.containment) {
      options._containers = [];
      var containment = options.containment;
      if(Object.isArray(containment)) {
        containment.each( function(c) { options._containers.push($(c)) });
      } else {
        options._containers.push($(containment));
      }
    }
    
    if(options.accept) options.accept = [options.accept].flatten();

    Element.makePositioned(element); // fix IE
    options.element = element;

    this.drops.push(options);
  },
  
  findDeepestChild: function(drops) {
    deepest = drops[0];
      
    for (i = 1; i < drops.length; ++i)
      if (Element.isParent(drops[i].element, deepest.element))
        deepest = drops[i];
    
    return deepest;
  },

  isContained: function(element, drop) {
    var containmentNode;
    if(drop.tree) {
      containmentNode = element.treeNode; 
    } else {
      containmentNode = element.parentNode;
    }
    return drop._containers.detect(function(c) { return containmentNode == c });
  },
  
  isAffected: function(point, element, drop) {
    return (
      (drop.element!=element) &&
      ((!drop._containers) ||
        this.isContained(element, drop)) &&
      ((!drop.accept) ||
        (Element.classNames(element).detect( 
          function(v) { return drop.accept.include(v) } ) )) &&
      Position.within(drop.element, point[0], point[1]) );
  },

  deactivate: function(drop) {
    if(drop.hoverclass)
      Element.removeClassName(drop.element, drop.hoverclass);
    this.last_active = null;
  },

  activate: function(drop) {
    if(drop.hoverclass)
      Element.addClassName(drop.element, drop.hoverclass);
    this.last_active = drop;
  },

  show: function(point, element) {
    if(!this.drops.length) return;
    var drop, affected = [];
    
    this.drops.each( function(drop) {
      if(Droppables.isAffected(point, element, drop))
        affected.push(drop);
    });
        
    if(affected.length>0)
      drop = Droppables.findDeepestChild(affected);

    if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
    if (drop) {
      Position.within(drop.element, point[0], point[1]);
      if(drop.onHover)
        drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
      
      if (drop != this.last_active) Droppables.activate(drop);
    }
  },

  fire: function(event, element) {
    if(!this.last_active) return;
    Position.prepare();

    if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
      if (this.last_active.onDrop) {
        this.last_active.onDrop(element, this.last_active.element, event); 
        return true; 
      }
  },

  reset: function() {
    if(this.last_active)
      this.deactivate(this.last_active);
  }
}

var Draggables = {
  drags: [],
  observers: [],
  
  register: function(draggable) {
    if(this.drags.length == 0) {
      this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
      this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
      this.eventKeypress  = this.keyPress.bindAsEventListener(this);
      
      Event.observe(document, "mouseup", this.eventMouseUp);
      Event.observe(document, "mousemove", this.eventMouseMove);
      Event.observe(document, "keypress", this.eventKeypress);
    }
    this.drags.push(draggable);
  },
  
  unregister: function(draggable) {
    this.drags = this.drags.reject(function(d) { return d==draggable });
    if(this.drags.length == 0) {
      Event.stopObserving(document, "mouseup", this.eventMouseUp);
      Event.stopObserving(document, "mousemove", this.eventMouseMove);
      Event.stopObserving(document, "keypress", this.eventKeypress);
    }
  },
  
  activate: function(draggable) {
    if(draggable.options.delay) { 
      this._timeout = setTimeout(function() { 
        Draggables._timeout = null; 
        window.focus(); 
        Draggables.activeDraggable = draggable; 
      }.bind(this), draggable.options.delay); 
    } else {
      window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
      this.activeDraggable = draggable;
    }
  },
  
  deactivate: function() {
    this.activeDraggable = null;
  },
  
  updateDrag: function(event) {
    if(!this.activeDraggable) return;
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    // Mozilla-based browsers fire successive mousemove events with
    // the same coordinates, prevent needless redrawing (moz bug?)
    if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
    this._lastPointer = pointer;
    
    this.activeDraggable.updateDrag(event, pointer);
  },
  
  endDrag: function(event) {
    if(this._timeout) { 
      clearTimeout(this._timeout); 
      this._timeout = null; 
    }
    if(!this.activeDraggable) return;
    this._lastPointer = null;
    this.activeDraggable.endDrag(event);
    this.activeDraggable = null;
  },
  
  keyPress: function(event) {
    if(this.activeDraggable)
      this.activeDraggable.keyPress(event);
  },
  
  addObserver: function(observer) {
    this.observers.push(observer);
    this._cacheObserverCallbacks();
  },
  
  removeObserver: function(element) {  // element instead of observer fixes mem leaks
    this.observers = this.observers.reject( function(o) { return o.element==element });
    this._cacheObserverCallbacks();
  },
  
  notify: function(eventName, draggable, event) {  // 'onStart', 'onEnd', 'onDrag'
    if(this[eventName+'Count'] > 0)
      this.observers.each( function(o) {
        if(o[eventName]) o[eventName](eventName, draggable, event);
      });
    if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
  },
  
  _cacheObserverCallbacks: function() {
    ['onStart','onEnd','onDrag'].each( function(eventName) {
      Draggables[eventName+'Count'] = Draggables.observers.select(
        function(o) { return o[eventName]; }
      ).length;
    });
  }
}



var Draggable = Class.create({
  initialize: function(element) {
    var defaults = {
      handle: false,
      reverteffect: function(element, top_offset, left_offset) {
        var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
        new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
          queue: {scope:'_draggable', position:'end'}
        });
      },
      endeffect: function(element) {
        var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
        new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, 
          queue: {scope:'_draggable', position:'end'},
          afterFinish: function(){ 
            Draggable._dragging[element] = false 
          }
        }); 
      },
      zindex: 1000,
      revert: false,
      quiet: false,
      scroll: false,
      scrollSensitivity: 20,
      scrollSpeed: 15,
      snap: false,  // false, or xy or [x,y] or function(x,y){ return [x,y] }
      delay: 0
    };
    
    if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
      Object.extend(defaults, {
        starteffect: function(element) {
          element._opacity = Element.getOpacity(element);
          Draggable._dragging[element] = true;
          new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); 
        }
      });
    
    var options = Object.extend(defaults, arguments[1] || { });

    this.element = $(element);
    
    if(options.handle && Object.isString(options.handle))
      this.handle = this.element.down('.'+options.handle, 0);
    
    if(!this.handle) this.handle = $(options.handle);
    if(!this.handle) this.handle = this.element;
    
    if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
      options.scroll = $(options.scroll);
      this._isScrollChild = Element.childOf(this.element, options.scroll);
    }

    Element.makePositioned(this.element); // fix IE    

    this.options  = options;
    this.dragging = false;   

    this.eventMouseDown = this.initDrag.bindAsEventListener(this);
    Event.observe(this.handle, "mousedown", this.eventMouseDown);
    
    Draggables.register(this);
  },
  
  destroy: function() {
    Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
    Draggables.unregister(this);
  },
  
  currentDelta: function() {
    return([
      parseInt(Element.getStyle(this.element,'left') || '0'),
      parseInt(Element.getStyle(this.element,'top') || '0')]);
  },
  
  initDrag: function(event) {
    if(!Object.isUndefined(Draggable._dragging[this.element]) &&
      Draggable._dragging[this.element]) return;
    if(Event.isLeftClick(event)) {    
      // abort on form elements, fixes a Firefox issue
      var src = Event.element(event);
      if((tag_name = src.tagName.toUpperCase()) && (
        tag_name=='INPUT' ||
        tag_name=='SELECT' ||
        tag_name=='OPTION' ||
        tag_name=='BUTTON' ||
        tag_name=='TEXTAREA')) return;
        
      var pointer = [Event.pointerX(event), Event.pointerY(event)];
      var pos     = Position.cumulativeOffset(this.element);
      this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
      
      Draggables.activate(this);
      Event.stop(event);
    }
  },
  
  startDrag: function(event) {
    this.dragging = true;
    if(!this.delta)
      this.delta = this.currentDelta();
    
    if(this.options.zindex) {
      this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
      this.element.style.zIndex = this.options.zindex;
    }
    
    if(this.options.ghosting) {
      this._clone = this.element.cloneNode(true);
      this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
      if (!this.element._originallyAbsolute)
        Position.absolutize(this.element);
      this.element.parentNode.insertBefore(this._clone, this.element);
    }
    
    if(this.options.scroll) {
      if (this.options.scroll == window) {
        var where = this._getWindowScroll(this.options.scroll);
        this.originalScrollLeft = where.left;
        this.originalScrollTop = where.top;
      } else {
        this.originalScrollLeft = this.options.scroll.scrollLeft;
        this.originalScrollTop = this.options.scroll.scrollTop;
      }
    }
    
    Draggables.notify('onStart', this, event);
        
    if(this.options.starteffect) this.options.starteffect(this.element);
  },
  
  updateDrag: function(event, pointer) {
    if(!this.dragging) this.startDrag(event);
    
    if(!this.options.quiet){
      Position.prepare();
      Droppables.show(pointer, this.element);
    }
    
    Draggables.notify('onDrag', this, event);
    
    this.draw(pointer);
    if(this.options.change) this.options.change(this);
    
    if(this.options.scroll) {
      this.stopScrolling();
      
      var p;
      if (this.options.scroll == window) {
        with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
      } else {
        p = Position.page(this.options.scroll);
        p[0] += this.options.scroll.scrollLeft + Position.deltaX;
        p[1] += this.options.scroll.scrollTop + Position.deltaY;
        p.push(p[0]+this.options.scroll.offsetWidth);
        p.push(p[1]+this.options.scroll.offsetHeight);
      }
      var speed = [0,0];
      if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
      if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
      if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
      if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
      this.startScrolling(speed);
    }
    
    // fix AppleWebKit rendering
    if(Prototype.Browser.WebKit) window.scrollBy(0,0);
    
    Event.stop(event);
  },
  
  finishDrag: function(event, success) {
    this.dragging = false;
    
    if(this.options.quiet){
      Position.prepare();
      var pointer = [Event.pointerX(event), Event.pointerY(event)];
      Droppables.show(pointer, this.element);
    }

    if(this.options.ghosting) {
      if (!this.element._originallyAbsolute)
        Position.relativize(this.element);
      delete this.element._originallyAbsolute;
      Element.remove(this._clone);
      this._clone = null;
    }

    var dropped = false; 
    if(success) { 
      dropped = Droppables.fire(event, this.element); 
      if (!dropped) dropped = false; 
    }
    if(dropped && this.options.onDropped) this.options.onDropped(this.element);
    Draggables.notify('onEnd', this, event);

    var revert = this.options.revert;
    if(revert && Object.isFunction(revert)) revert = revert(this.element);
    
    var d = this.currentDelta();
    if(revert && this.options.reverteffect) {
      if (dropped == 0 || revert != 'failure')
        this.options.reverteffect(this.element,
          d[1]-this.delta[1], d[0]-this.delta[0]);
    } else {
      this.delta = d;
    }

    if(this.options.zindex)
      this.element.style.zIndex = this.originalZ;

    if(this.options.endeffect) 
      this.options.endeffect(this.element);
      
    Draggables.deactivate(this);
    Droppables.reset();
  },
  
  keyPress: function(event) {
    if(event.keyCode!=Event.KEY_ESC) return;
    this.finishDrag(event, false);
    Event.stop(event);
  },
  
  endDrag: function(event) {
    if(!this.dragging) return;
    this.stopScrolling();
    this.finishDrag(event, true);
    Event.stop(event);
  },
  
  draw: function(point) {
    var pos = Position.cumulativeOffset(this.element);
    if(this.options.ghosting) {
      var r   = Position.realOffset(this.element);
      pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
    }
    
    var d = this.currentDelta();
    pos[0] -= d[0]; pos[1] -= d[1];
    
    if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
      pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
      pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
    }
    
    var p = [0,1].map(function(i){ 
      return (point[i]-pos[i]-this.offset[i]) 
    }.bind(this));
    
    if(this.options.snap) {
      if(Object.isFunction(this.options.snap)) {
        p = this.options.snap(p[0],p[1],this);
      } else {
      if(Object.isArray(this.options.snap)) {
        p = p.map( function(v, i) {
          return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this))
      } else {
        p = p.map( function(v) {
          return (v/this.options.snap).round()*this.options.snap }.bind(this))
      }
    }}
    
    var style = this.element.style;
    if((!this.options.constraint) || (this.options.constraint=='horizontal'))
      style.left = p[0] + "px";
    if((!this.options.constraint) || (this.options.constraint=='vertical'))
      style.top  = p[1] + "px";
    
    if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
  },
  
  stopScrolling: function() {
    if(this.scrollInterval) {
      clearInterval(this.scrollInterval);
      this.scrollInterval = null;
      Draggables._lastScrollPointer = null;
    }
  },
  
  startScrolling: function(speed) {
    if(!(speed[0] || speed[1])) return;
    this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
    this.lastScrolled = new Date();
    this.scrollInterval = setInterval(this.scroll.bind(this), 10);
  },
  
  scroll: function() {
    var current = new Date();
    var delta = current - this.lastScrolled;
    this.lastScrolled = current;
    if(this.options.scroll == window) {
      with (this._getWindowScroll(this.options.scroll)) {
        if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
          var d = delta / 1000;
          this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
        }
      }
    } else {
      this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
      this.options.scroll.scrollTop  += this.scrollSpeed[1] * delta / 1000;
    }
    
    Position.prepare();
    Droppables.show(Draggables._lastPointer, this.element);
    Draggables.notify('onDrag', this);
    if (this._isScrollChild) {
      Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
      Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
      Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
      if (Draggables._lastScrollPointer[0] < 0)
        Draggables._lastScrollPointer[0] = 0;
      if (Draggables._lastScrollPointer[1] < 0)
        Draggables._lastScrollPointer[1] = 0;
      this.draw(Draggables._lastScrollPointer);
    }
    
    if(this.options.change) this.options.change(this);
  },
  
  _getWindowScroll: function(w) {
    var T, L, W, H;
    with (w.document) {
      if (w.document.documentElement && documentElement.scrollTop) {
        T = documentElement.scrollTop;
        L = documentElement.scrollLeft;
      } else if (w.document.body) {
        T = body.scrollTop;
        L = body.scrollLeft;
      }
      if (w.innerWidth) {
        W = w.innerWidth;
        H = w.innerHeight;
      } else if (w.document.documentElement && documentElement.clientWidth) {
        W = documentElement.clientWidth;
        H = documentElement.clientHeight;
      } else {
        W = body.offsetWidth;
        H = body.offsetHeight
      }
    }
    return { top: T, left: L, width: W, height: H };
  }
});

Draggable._dragging = { };



var SortableObserver = Class.create({
  initialize: function(element, observer) {
    this.element   = $(element);
    this.observer  = observer;
    this.lastValue = Sortable.serialize(this.element);
  },
  
  onStart: function() {
    this.lastValue = Sortable.serialize(this.element);
  },
  
  onEnd: function() {
    Sortable.unmark();
    if(this.lastValue != Sortable.serialize(this.element))
      this.observer(this.element)
  }
});

var Sortable = {
  SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
  
  sortables: { },
  
  _findRootElement: function(element) {
    while (element.tagName.toUpperCase() != "BODY") {  
      if(element.id && Sortable.sortables[element.id]) return element;
      element = element.parentNode;
    }
  },

  options: function(element) {
    element = Sortable._findRootElement($(element));
    if(!element) return;
    return Sortable.sortables[element.id];
  },
  
  destroy: function(element){
    var s = Sortable.options(element);
    
    if(s) {
      Draggables.removeObserver(s.element);
      s.droppables.each(function(d){ Droppables.remove(d) });
      s.draggables.invoke('destroy');
      
      delete Sortable.sortables[s.element.id];
    }
  },

  create: function(element) {
    element = $(element);
    var options = Object.extend({ 
      element:     element,
      tag:         'li',       // assumes li children, override with tag: 'tagname'
      dropOnEmpty: false,
      tree:        false,
      treeTag:     'ul',
      overlap:     'vertical', // one of 'vertical', 'horizontal'
      constraint:  'vertical', // one of 'vertical', 'horizontal', false
      containment: element,    // also takes array of elements (or id's); or false
      handle:      false,      // or a CSS class
      only:        false,
      delay:       0,
      hoverclass:  null,
      ghosting:    false,
      quiet:       false, 
      scroll:      false,
      scrollSensitivity: 20,
      scrollSpeed: 15,
      format:      this.SERIALIZE_RULE,
      
      // these take arrays of elements or ids and can be 
      // used for better initialization performance
      elements:    false,
      handles:     false,
      
      onChange:    Prototype.emptyFunction,
      onUpdate:    Prototype.emptyFunction
    }, arguments[1] || { });

    // clear any old sortable with same element
    this.destroy(element);

    // build options for the draggables
    var options_for_draggable = {
      revert:      true,
      quiet:       options.quiet,
      scroll:      options.scroll,
      scrollSpeed: options.scrollSpeed,
      scrollSensitivity: options.scrollSensitivity,
      delay:       options.delay,
      ghosting:    options.ghosting,
      constraint:  options.constraint,
      handle:      options.handle };

    if(options.starteffect)
      options_for_draggable.starteffect = options.starteffect;

    if(options.reverteffect)
      options_for_draggable.reverteffect = options.reverteffect;
    else
      if(options.ghosting) options_for_draggable.reverteffect = function(element) {
        element.style.top  = 0;
        element.style.left = 0;
      };

    if(options.endeffect)
      options_for_draggable.endeffect = options.endeffect;

    if(options.zindex)
      options_for_draggable.zindex = options.zindex;

    // build options for the droppables  
    var options_for_droppable = {
      overlap:     options.overlap,
      containment: options.containment,
      tree:        options.tree,
      hoverclass:  options.hoverclass,
      onHover:     Sortable.onHover
    }
    
    var options_for_tree = {
      onHover:      Sortable.onEmptyHover,
      overlap:      options.overlap,
      containment:  options.containment,
      hoverclass:   options.hoverclass
    }

    // fix for gecko engine
    Element.cleanWhitespace(element); 

    options.draggables = [];
    options.droppables = [];

    // drop on empty handling
    if(options.dropOnEmpty || options.tree) {
      Droppables.add(element, options_for_tree);
      options.droppables.push(element);
    }

    (options.elements || this.findElements(element, options) || []).each( function(e,i) {
      var handle = options.handles ? $(options.handles[i]) :
        (options.handle ? $(e).select('.' + options.handle)[0] : e); 
      options.draggables.push(
        new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
      Droppables.add(e, options_for_droppable);
      if(options.tree) e.treeNode = element;
      options.droppables.push(e);      
    });
    
    if(options.tree) {
      (Sortable.findTreeElements(element, options) || []).each( function(e) {
        Droppables.add(e, options_for_tree);
        e.treeNode = element;
        options.droppables.push(e);
      });
    }

    // keep reference
    this.sortables[element.id] = options;

    // for onupdate
    Draggables.addObserver(new SortableObserver(element, options.onUpdate));

  },

  // return all suitable-for-sortable elements in a guaranteed order
  findElements: function(element, options) {
    return Element.findChildren(
      element, options.only, options.tree ? true : false, options.tag);
  },
  
  findTreeElements: function(element, options) {
    return Element.findChildren(
      element, options.only, options.tree ? true : false, options.treeTag);
  },

  onHover: function(element, dropon, overlap) {
    if(Element.isParent(dropon, element)) return;

    if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
      return;
    } else if(overlap>0.5) {
      Sortable.mark(dropon, 'before');
      if(dropon.previousSibling != element) {
        var oldParentNode = element.parentNode;
        element.style.visibility = "hidden"; // fix gecko rendering
        dropon.parentNode.insertBefore(element, dropon);
        if(dropon.parentNode!=oldParentNode) 
          Sortable.options(oldParentNode).onChange(element);
        Sortable.options(dropon.parentNode).onChange(element);
      }
    } else {
      Sortable.mark(dropon, 'after');
      var nextElement = dropon.nextSibling || null;
      if(nextElement != element) {
        var oldParentNode = element.parentNode;
        element.style.visibility = "hidden"; // fix gecko rendering
        dropon.parentNode.insertBefore(element, nextElement);
        if(dropon.parentNode!=oldParentNode) 
          Sortable.options(oldParentNode).onChange(element);
        Sortable.options(dropon.parentNode).onChange(element);
      }
    }
  },
  
  onEmptyHover: function(element, dropon, overlap) {
    var oldParentNode = element.parentNode;
    var droponOptions = Sortable.options(dropon);
        
    if(!Element.isParent(dropon, element)) {
      var index;
      
      var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
      var child = null;
            
      if(children) {
        var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
        
        for (index = 0; index < children.length; index += 1) {
          if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
            offset -= Element.offsetSize (children[index], droponOptions.overlap);
          } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
            child = index + 1 < children.length ? children[index + 1] : null;
            break;
          } else {
            child = children[index];
            break;
          }
        }
      }
      
      dropon.insertBefore(element, child);
      
      Sortable.options(oldParentNode).onChange(element);
      droponOptions.onChange(element);
    }
  },

  unmark: function() {
    if(Sortable._marker) Sortable._marker.hide();
  },

  mark: function(dropon, position) {
    // mark on ghosting only
    var sortable = Sortable.options(dropon.parentNode);
    if(sortable && !sortable.ghosting) return; 

    if(!Sortable._marker) {
      Sortable._marker = 
        ($('dropmarker') || Element.extend(document.createElement('DIV'))).
          hide().addClassName('dropmarker').setStyle({position:'absolute'});
      document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
    }    
    var offsets = Position.cumulativeOffset(dropon);
    Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
    
    if(position=='after')
      if(sortable.overlap == 'horizontal') 
        Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
      else
        Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
    
    Sortable._marker.show();
  },
  
  _tree: function(element, options, parent) {
    var children = Sortable.findElements(element, options) || [];
  
    for (var i = 0; i < children.length; ++i) {
      var match = children[i].id.match(options.format);

      if (!match) continue;
      
      var child = {
        id: encodeURIComponent(match ? match[1] : null),
        element: element,
        parent: parent,
        children: [],
        position: parent.children.length,
        container: $(children[i]).down(options.treeTag)
      }
      
      
      if (child.container)
        this._tree(child.container, options, child)
      
      parent.children.push (child);
    }

    return parent; 
  },

  tree: function(element) {
    element = $(element);
    var sortableOptions = this.options(element);
    var options = Object.extend({
      tag: sortableOptions.tag,
      treeTag: sortableOptions.treeTag,
      only: sortableOptions.only,
      name: element.id,
      format: sortableOptions.format
    }, arguments[1] || { });
    
    var root = {
      id: null,
      parent: null,
      children: [],
      container: element,
      position: 0
    }
    
    return Sortable._tree(element, options, root);
  },

  
  _constructIndex: function(node) {
    var index = '';
    do {
      if (node.id) index = '[' + node.position + ']' + index;
    } while ((node = node.parent) != null);
    return index;
  },

  sequence: function(element) {
    element = $(element);
    var options = Object.extend(this.options(element), arguments[1] || { });
    
    return $(this.findElements(element, options) || []).map( function(item) {
      return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
    });
  },

  setSequence: function(element, new_sequence) {
    element = $(element);
    var options = Object.extend(this.options(element), arguments[2] || { });
    
    var nodeMap = { };
    this.findElements(element, options).each( function(n) {
        if (n.id.match(options.format))
            nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
        n.parentNode.removeChild(n);
    });
   
    new_sequence.each(function(ident) {
      var n = nodeMap[ident];
      if (n) {
        n[1].appendChild(n[0]);
        delete nodeMap[ident];
      }
    });
  },
  
  serialize: function(element) {
    element = $(element);
    var options = Object.extend(Sortable.options(element), arguments[1] || { });
    var name = encodeURIComponent(
      (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
    
    if (options.tree) {
      return Sortable.tree(element, arguments[1]).children.map( function (item) {
        return [name + Sortable._constructIndex(item) + "[id]=" + 
                encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
      }).flatten().join('&');
    } else {
      return Sortable.sequence(element, arguments[1]).map( function(item) {
        return name + "[]=" + encodeURIComponent(item);
      }).join('&');
    }
  }
}

// Returns true if child is contained within element
Element.isParent = function(child, element) {
  if (!child.parentNode || child == element) return false;
  if (child.parentNode == element) return true;
  return Element.isParent(child.parentNode, element);
}

Element.findChildren = function(element, only, recursive, tagName) {   
  if(!element.hasChildNodes()) return null;
  tagName = tagName.toUpperCase();
  if(only) only = [only].flatten();
  var elements = [];
  $A(element.childNodes).each( function(e) {
    if(e.tagName && e.tagName.toUpperCase()==tagName &&
      (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
        elements.push(e);
    if(recursive) {
      var grandchildren = Element.findChildren(e, only, recursive, tagName);
      if(grandchildren) elements.push(grandchildren);
    }
  });

  return (elements.length>0 ? elements.flatten() : []);
}

Element.offsetSize = function (element, type) {
  return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
}

// script.aculo.us controls.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
//           (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
// Contributors:
//  Richard Livsey
//  Rahul Bhargava
//  Rob Wills
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

// Autocompleter.Base handles all the autocompletion functionality 
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
// Specific autocompleters need to provide, at the very least, 
// a getUpdatedChoices function that will be invoked every time
// the text inside the monitored textbox changes. This method 
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
// autocompletion. Specific auto-completion logic (AJAX, etc)
// belongs in getUpdatedChoices.
//
// Tokenized incremental autocompletion is enabled automatically
// when an autocompleter is instantiated with the 'tokens' option
// in the options parameter, e.g.:
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
// enables autocompletion on multiple tokens. This is most 
// useful when one of the tokens is \n (a newline), as it 
// allows smart autocompletion after linebreaks.

if(typeof Effect == 'undefined')
  throw("controls.js requires including script.aculo.us' effects.js library");

var Autocompleter = { }
Autocompleter.Base = Class.create({
  baseInitialize: function(element, update, options) {
    element          = $(element)
    this.element     = element; 
    this.update      = $(update);  
    this.hasFocus    = false; 
    this.changed     = false; 
    this.active      = false; 
    this.index       = 0;     
    this.entryCount  = 0;
    this.oldElementValue = this.element.value;

    if(this.setOptions)
      this.setOptions(options);
    else
      this.options = options || { };

    this.options.paramName    = this.options.paramName || this.element.name;
    this.options.tokens       = this.options.tokens || [];
    this.options.frequency    = this.options.frequency || 0.4;
    this.options.minChars     = this.options.minChars || 1;
    this.options.onShow       = this.options.onShow || 
      function(element, update){ 
        if(!update.style.position || update.style.position=='absolute') {
          update.style.position = 'absolute';
          Position.clone(element, update, {
            setHeight: false, 
            offsetTop: element.offsetHeight
          });
        }
        Effect.Appear(update,{duration:0.15});
      };
    this.options.onHide = this.options.onHide || 
      function(element, update){ new Effect.Fade(update,{duration:0.15}) };

    if(typeof(this.options.tokens) == 'string') 
      this.options.tokens = new Array(this.options.tokens);
    // Force carriage returns as token delimiters anyway
    if (!this.options.tokens.include('\n'))
      this.options.tokens.push('\n');

    this.observer = null;
    
    this.element.setAttribute('autocomplete','off');

    Element.hide(this.update);

    Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
    Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
  },

  show: function() {
    if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
    if(!this.iefix && 
      (Prototype.Browser.IE) &&
      (Element.getStyle(this.update, 'position')=='absolute')) {
      new Insertion.After(this.update, 
       '<iframe id="' + this.update.id + '_iefix" '+
       'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
       'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
      this.iefix = $(this.update.id+'_iefix');
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
  },
  
  fixIEOverlapping: function() {
    Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
    this.iefix.style.zIndex = 1;
    this.update.style.zIndex = 2;
    Element.show(this.iefix);
  },

  hide: function() {
    this.stopIndicator();
    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
    if(this.iefix) Element.hide(this.iefix);
  },

  startIndicator: function() {
    if(this.options.indicator) Element.show(this.options.indicator);
  },

  stopIndicator: function() {
    if(this.options.indicator) Element.hide(this.options.indicator);
  },

  onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         Event.stop(event);
         return;
      }
     else 
       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 
         (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer = 
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },

  activate: function() {
    this.changed = false;
    this.hasFocus = true;
    this.getUpdatedChoices();
  },

  onHover: function(event) {
    var element = Event.findElement(event, 'LI');
    if(this.index != element.autocompleteIndex) 
    {
        this.index = element.autocompleteIndex;
        this.render();
    }
    Event.stop(event);
  },
  
  onClick: function(event) {
    var element = Event.findElement(event, 'LI');
    this.index = element.autocompleteIndex;
    this.selectEntry();
    this.hide();
  },
  
  onBlur: function(event) {
    // needed to make click events working
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
    this.active = false;     
  }, 
  
  render: function() {
    if(this.entryCount > 0) {
      for (var i = 0; i < this.entryCount; i++)
        this.index==i ? 
          Element.addClassName(this.getEntry(i),"selected") : 
          Element.removeClassName(this.getEntry(i),"selected");
      if(this.hasFocus) { 
        this.show();
        this.active = true;
      }
    } else {
      this.active = false;
      this.hide();
    }
  },
  
  markPrevious: function() {
    if(this.index > 0) this.index--
      else this.index = this.entryCount-1;
    this.getEntry(this.index).scrollIntoView(true);
  },
  
  markNext: function() {
    if(this.index < this.entryCount-1) this.index++
      else this.index = 0;
    this.getEntry(this.index).scrollIntoView(false);
  },
  
  getEntry: function(index) {
    return this.update.firstChild.childNodes[index];
  },
  
  getCurrentEntry: function() {
    return this.getEntry(this.index);
  },
  
  selectEntry: function() {
    this.active = false;
    this.updateElement(this.getCurrentEntry());
  },

  updateElement: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
    
    var bounds = this.getTokenBounds();
    if (bounds[0] != -1) {
      var newValue = this.element.value.substr(0, bounds[0]);
      var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value + this.element.value.substr(bounds[1]);
    } else {
      this.element.value = value;
    }
    this.oldElementValue = this.element.value;
    this.element.focus();
    
    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());

      if(this.update.firstChild && this.update.down().childNodes) {
        this.entryCount = 
          this.update.down().childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else { 
        this.entryCount = 0;
      }

      this.stopIndicator();
      this.index = 0;
      
      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
    }
  },

  addObservers: function(element) {
    Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
    Event.observe(element, "click", this.onClick.bindAsEventListener(this));
  },

  onObserverEvent: function() {
    this.changed = false;   
    this.tokenBounds = null;
    if(this.getToken().length>=this.options.minChars) {
      this.getUpdatedChoices();
    } else {
      this.active = false;
      this.hide();
    }
    this.oldElementValue = this.element.value;
  },

  getToken: function() {
    var bounds = this.getTokenBounds();
    return this.element.value.substring(bounds[0], bounds[1]).strip();
  },

  getTokenBounds: function() {
    if (null != this.tokenBounds) return this.tokenBounds;
    var value = this.element.value;
    if (value.strip().empty()) return [-1, 0];
    var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
    var offset = (diff == this.oldElementValue.length ? 1 : 0);
    var prevTokenPos = -1, nextTokenPos = value.length;
    var tp;
    for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
      tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
      if (tp > prevTokenPos) prevTokenPos = tp;
      tp = value.indexOf(this.options.tokens[index], diff + offset);
      if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
    }
    return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
  }
});

Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
  var boundary = Math.min(newS.length, oldS.length);
  for (var index = 0; index < boundary; ++index)
    if (newS[index] != oldS[index])
      return index;
  return boundary;
};

Ajax.Autocompleter = Class.create(Autocompleter.Base, {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
  },

  getUpdatedChoices: function() {
    this.startIndicator();
    
    var entry = encodeURIComponent(this.options.paramName) + '=' + 
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams) 
      this.options.parameters += '&' + this.options.defaultParams;
    
    new Ajax.Request(this.url, this.options);
  },

  onComplete: function(request) {
    this.updateChoices(request.responseText);
  }
});

// The local array autocompleter. Used when you'd prefer to
// inject an array of autocompletion options into the page, rather
// than sending out Ajax queries, which can be quite slow sometimes.
//
// The constructor takes four parameters. The first two are, as usual,
// the id of the monitored textbox, and id of the autocompletion menu.
// The third is the array you want to autocomplete from, and the fourth
// is the options block.
//
// Extra local autocompletion options:
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
//                    text only at the beginning of strings in the 
//                    autocomplete array. Defaults to true, which will
//                    match text at the beginning of any *word* in the
//                    strings in the autocomplete array. If you want to
//                    search anywhere in the string, additionally set
//                    the option fullSearch to true (default: off).
//
// - fullSsearch - Search anywhere in autocomplete array strings.
//
// - partialChars - How many characters to enter before triggering
//                   a partial match (unlike minChars, which defines
//                   how many characters are required to do any match
//                   at all). Defaults to 2.
//
// - ignoreCase - Whether to ignore case when autocompleting.
//                 Defaults to true.
//
// It's possible to pass in a custom function as the 'selector' 
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.

Autocompleter.Local = Class.create(Autocompleter.Base, {
  initialize: function(element, update, array, options) {
    this.baseInitialize(element, update, options);
    this.options.array = array;
  },

  getUpdatedChoices: function() {
    this.updateChoices(this.options.selector(this));
  },

  setOptions: function(options) {
    this.options = Object.extend({
      choices: 10,
      partialSearch: true,
      partialChars: 2,
      ignoreCase: true,
      fullSearch: false,
      selector: function(instance) {
        var ret       = []; // Beginning matches
        var partial   = []; // Inside matches
        var entry     = instance.getToken();
        var count     = 0;

        for (var i = 0; i < instance.options.array.length &&  
          ret.length < instance.options.choices ; i++) { 

          var elem = instance.options.array[i];
          var foundPos = instance.options.ignoreCase ? 
            elem.toLowerCase().indexOf(entry.toLowerCase()) : 
            elem.indexOf(entry);

          while (foundPos != -1) {
            if (foundPos == 0 && elem.length != entry.length) { 
              ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" + 
                elem.substr(entry.length) + "</li>");
              break;
            } else if (entry.length >= instance.options.partialChars && 
              instance.options.partialSearch && foundPos != -1) {
              if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
                partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
                  elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
                  foundPos + entry.length) + "</li>");
                break;
              }
            }

            foundPos = instance.options.ignoreCase ? 
              elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
              elem.indexOf(entry, foundPos + 1);

          }
        }
        if (partial.length)
          ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
        return "<ul>" + ret.join('') + "</ul>";
      }
    }, options || { });
  }
});

// AJAX in-place editor and collection editor
// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).

// Use this if you notice weird scrolling problems on some browsers,
// the DOM might be a bit confused when this gets called so do this
// waits 1 ms (with setTimeout) until it does the activation
Field.scrollFreeActivate = function(field) {
  setTimeout(function() {
    Field.activate(field);
  }, 1);
}

Ajax.InPlaceEditor = Class.create({
  initialize: function(element, url, options) {
    this.url = url;
    this.element = element = $(element);
    this.prepareOptions();
    this._controls = { };
    arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
    Object.extend(this.options, options || { });
    if (!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + '-inplaceeditor';
      if ($(this.options.formId))
        this.options.formId = '';
    }
    if (this.options.externalControl)
      this.options.externalControl = $(this.options.externalControl);
    if (!this.options.externalControl)
      this.options.externalControlOnly = false;
    this._originalBackground = this.element.getStyle('background-color') || 'transparent';
    this.element.title = this.options.clickToEditText;
    this._boundCancelHandler = this.handleFormCancellation.bind(this);
    this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
    this._boundFailureHandler = this.handleAJAXFailure.bind(this);
    this._boundSubmitHandler = this.handleFormSubmission.bind(this);
    this._boundWrapperHandler = this.wrapUp.bind(this);
    this.registerListeners();
  },
  checkForEscapeOrReturn: function(e) {
    if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
    if (Event.KEY_ESC == e.keyCode)
      this.handleFormCancellation(e);
    else if (Event.KEY_RETURN == e.keyCode)
      this.handleFormSubmission(e);
  },
  createControl: function(mode, handler, extraClasses) {
    var control = this.options[mode + 'Control'];
    var text = this.options[mode + 'Text'];
    if ('button' == control) {
      var btn = document.createElement('input');
      btn.type = 'submit';
      btn.value = text;
      btn.className = 'editor_' + mode + '_button';
      if ('cancel' == mode)
        btn.onclick = this._boundCancelHandler;
      this._form.appendChild(btn);
      this._controls[mode] = btn;
    } else if ('link' == control) {
      var link = document.createElement('a');
      link.href = '#';
      link.appendChild(document.createTextNode(text));
      link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
      link.className = 'editor_' + mode + '_link';
      if (extraClasses)
        link.className += ' ' + extraClasses;
      this._form.appendChild(link);
      this._controls[mode] = link;
    }
  },
  createEditField: function() {
    var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
    var fld;
    if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
      fld = document.createElement('input');
      fld.type = 'text';
      var size = this.options.size || this.options.cols || 0;
      if (0 < size) fld.size = size;
    } else {
      fld = document.createElement('textarea');
      fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
      fld.cols = this.options.cols || 40;
    }
    fld.name = this.options.paramName;
    fld.value = text; // No HTML breaks conversion anymore
    fld.className = 'editor_field';
    if (this.options.submitOnBlur)
      fld.onblur = this._boundSubmitHandler;
    this._controls.editor = fld;
    if (this.options.loadTextURL)
      this.loadExternalText();
    this._form.appendChild(this._controls.editor);
  },
  createForm: function() {
    var ipe = this;
    function addText(mode, condition) {
      var text = ipe.options['text' + mode + 'Controls'];
      if (!text || condition === false) return;
      ipe._form.appendChild(document.createTextNode(text));
    };
    this._form = $(document.createElement('form'));
    this._form.id = this.options.formId;
    this._form.addClassName(this.options.formClassName);
    this._form.onsubmit = this._boundSubmitHandler;
    this.createEditField();
    if ('textarea' == this._controls.editor.tagName.toLowerCase())
      this._form.appendChild(document.createElement('br'));
    if (this.options.onFormCustomization)
      this.options.onFormCustomization(this, this._form);
    addText('Before', this.options.okControl || this.options.cancelControl);
    this.createControl('ok', this._boundSubmitHandler);
    addText('Between', this.options.okControl && this.options.cancelControl);
    this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
    addText('After', this.options.okControl || this.options.cancelControl);
  },
  destroy: function() {
    if (this._oldInnerHTML)
      this.element.innerHTML = this._oldInnerHTML;
    this.leaveEditMode();
    this.unregisterListeners();
  },
  enterEditMode: function(e) {
    if (this._saving || this._editing) return;
    this._editing = true;
    this.triggerCallback('onEnterEditMode');
    if (this.options.externalControl)
      this.options.externalControl.hide();
    this.element.hide();
    this.createForm();
    this.element.parentNode.insertBefore(this._form, this.element);
    if (!this.options.loadTextURL)
      this.postProcessEditField();
    if (e) Event.stop(e);
  },
  enterHover: function(e) {
    if (this.options.hoverClassName)
      this.element.addClassName(this.options.hoverClassName);
    if (this._saving) return;
    this.triggerCallback('onEnterHover');
  },
  getText: function() {
    return this.element.innerHTML;
  },
  handleAJAXFailure: function(transport) {
    this.triggerCallback('onFailure', transport);
    if (this._oldInnerHTML) {
      this.element.innerHTML = this._oldInnerHTML;
      this._oldInnerHTML = null;
    }
  },
  handleFormCancellation: function(e) {
    this.wrapUp();
    if (e) Event.stop(e);
  },
  handleFormSubmission: function(e) {
    var form = this._form;
    var value = $F(this._controls.editor);
    this.prepareSubmission();
    var params = this.options.callback(form, value) || '';
    if (Object.isString(params))
      params = params.toQueryParams();
    params.editorId = this.element.id;
    if (this.options.htmlResponse) {
      var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
      Object.extend(options, {
        parameters: params,
        onComplete: this._boundWrapperHandler,
        onFailure: this._boundFailureHandler
      });
      new Ajax.Updater({ success: this.element }, this.url, options);
    } else {
      var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
      Object.extend(options, {
        parameters: params,
        onComplete: this._boundWrapperHandler,
        onFailure: this._boundFailureHandler
      });
      new Ajax.Request(this.url, options);
    }
    if (e) Event.stop(e);
  },
  leaveEditMode: function() {
    this.element.removeClassName(this.options.savingClassName);
    this.removeForm();
    this.leaveHover();
    this.element.style.backgroundColor = this._originalBackground;
    this.element.show();
    if (this.options.externalControl)
      this.options.externalControl.show();
    this._saving = false;
    this._editing = false;
    this._oldInnerHTML = null;
    this.triggerCallback('onLeaveEditMode');
  },
  leaveHover: function(e) {
    if (this.options.hoverClassName)
      this.element.removeClassName(this.options.hoverClassName);
    if (this._saving) return;
    this.triggerCallback('onLeaveHover');
  },
  loadExternalText: function() {
    this._form.addClassName(this.options.loadingClassName);
    this._controls.editor.disabled = true;
    var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
    Object.extend(options, {
      parameters: 'editorId=' + encodeURIComponent(this.element.id),
      onComplete: Prototype.emptyFunction,
      onSuccess: function(transport) {
        this._form.removeClassName(this.options.loadingClassName);
        var text = transport.responseText;
        if (this.options.stripLoadedTextTags)
          text = text.stripTags();
        this._controls.editor.value = text;
        this._controls.editor.disabled = false;
        this.postProcessEditField();
      }.bind(this),
      onFailure: this._boundFailureHandler
    });
    new Ajax.Request(this.options.loadTextURL, options);
  },
  postProcessEditField: function() {
    var fpc = this.options.fieldPostCreation;
    if (fpc)
      $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
  },
  prepareOptions: function() {
    this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
    Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
    [this._extraDefaultOptions].flatten().compact().each(function(defs) {
      Object.extend(this.options, defs);
    }.bind(this));
  },
  prepareSubmission: function() {
    this._saving = true;
    this.removeForm();
    this.leaveHover();
    this.showSaving();
  },
  registerListeners: function() {
    this._listeners = { };
    var listener;
    $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
      listener = this[pair.value].bind(this);
      this._listeners[pair.key] = listener;
      if (!this.options.externalControlOnly)
        this.element.observe(pair.key, listener);
      if (this.options.externalControl)
        this.options.externalControl.observe(pair.key, listener);
    }.bind(this));
  },
  removeForm: function() {
    if (!this._form) return;
    this._form.remove();
    this._form = null;
    this._controls = { };
  },
  showSaving: function() {
    this._oldInnerHTML = this.element.innerHTML;
    this.element.innerHTML = this.options.savingText;
    this.element.addClassName(this.options.savingClassName);
    this.element.style.backgroundColor = this._originalBackground;
    this.element.show();
  },
  triggerCallback: function(cbName, arg) {
    if ('function' == typeof this.options[cbName]) {
      this.options[cbName](this, arg);
    }
  },
  unregisterListeners: function() {
    $H(this._listeners).each(function(pair) {
      if (!this.options.externalControlOnly)
        this.element.stopObserving(pair.key, pair.value);
      if (this.options.externalControl)
        this.options.externalControl.stopObserving(pair.key, pair.value);
    }.bind(this));
  },
  wrapUp: function(transport) {
    this.leaveEditMode();
    // Can't use triggerCallback due to backward compatibility: requires
    // binding + direct element
    this._boundComplete(transport, this.element);
  }
});

Object.extend(Ajax.InPlaceEditor.prototype, {
  dispose: Ajax.InPlaceEditor.prototype.destroy
});

Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
  initialize: function($super, element, url, options) {
    this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
    $super(element, url, options);
  },

  createEditField: function() {
    var list = document.createElement('select');
    list.name = this.options.paramName;
    list.size = 1;
    this._controls.editor = list;
    this._collection = this.options.collection || [];
    if (this.options.loadCollectionURL)
      this.loadCollection();
    else
      this.checkForExternalText();
    this._form.appendChild(this._controls.editor);
  },

  loadCollection: function() {
    this._form.addClassName(this.options.loadingClassName);
    this.showLoadingText(this.options.loadingCollectionText);
    var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
    Object.extend(options, {
      parameters: 'editorId=' + encodeURIComponent(this.element.id),
      onComplete: Prototype.emptyFunction,
      onSuccess: function(transport) {
        var js = transport.responseText.strip();
        if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
          throw 'Server returned an invalid collection representation.';
        this._collection = eval(js);
        this.checkForExternalText();
      }.bind(this),
      onFailure: this.onFailure
    });
    new Ajax.Request(this.options.loadCollectionURL, options);
  },

  showLoadingText: function(text) {
    this._controls.editor.disabled = true;
    var tempOption = this._controls.editor.firstChild;
    if (!tempOption) {
      tempOption = document.createElement('option');
      tempOption.value = '';
      this._controls.editor.appendChild(tempOption);
      tempOption.selected = true;
    }
    tempOption.update((text || '').stripScripts().stripTags());
  },

  checkForExternalText: function() {
    this._text = this.getText();
    if (this.options.loadTextURL)
      this.loadExternalText();
    else
      this.buildOptionList();
  },

  loadExternalText: function() {
    this.showLoadingText(this.options.loadingText);
    var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
    Object.extend(options, {
      parameters: 'editorId=' + encodeURIComponent(this.element.id),
      onComplete: Prototype.emptyFunction,
      onSuccess: function(transport) {
        this._text = transport.responseText.strip();
        this.buildOptionList();
      }.bind(this),
      onFailure: this.onFailure
    });
    new Ajax.Request(this.options.loadTextURL, options);
  },

  buildOptionList: function() {
    this._form.removeClassName(this.options.loadingClassName);
    this._collection = this._collection.map(function(entry) {
      return 2 === entry.length ? entry : [entry, entry].flatten();
    });
    var marker = ('value' in this.options) ? this.options.value : this._text;
    var textFound = this._collection.any(function(entry) {
      return entry[0] == marker;
    }.bind(this));
    this._controls.editor.update('');
    var option;
    this._collection.each(function(entry, index) {
      option = document.createElement('option');
      option.value = entry[0];
      option.selected = textFound ? entry[0] == marker : 0 == index;
      option.appendChild(document.createTextNode(entry[1]));
      this._controls.editor.appendChild(option);
    }.bind(this));
    this._controls.editor.disabled = false;
    Field.scrollFreeActivate(this._controls.editor);
  }
});

//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
//**** This only  exists for a while,  in order to  let ****
//**** users adapt to  the new API.  Read up on the new ****
//**** API and convert your code to it ASAP!            ****

Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
  if (!options) return;
  function fallback(name, expr) {
    if (name in options || expr === undefined) return;
    options[name] = expr;
  };
  fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
    options.cancelLink == options.cancelButton == false ? false : undefined)));
  fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
    options.okLink == options.okButton == false ? false : undefined)));
  fallback('highlightColor', options.highlightcolor);
  fallback('highlightEndColor', options.highlightendcolor);
};

Object.extend(Ajax.InPlaceEditor, {
  DefaultOptions: {
    ajaxOptions: { },
    autoRows: 3,                                // Use when multi-line w/ rows == 1
    cancelControl: 'link',                      // 'link'|'button'|false
    cancelText: 'cancel',
    clickToEditText: 'Click to edit',
    externalControl: null,                      // id|elt
    externalControlOnly: false,
    fieldPostCreation: 'activate',              // 'activate'|'focus'|false
    formClassName: 'inplaceeditor-form',
    formId: null,                               // id|elt
    highlightColor: '#ffff99',
    highlightEndColor: '#ffffff',
    hoverClassName: '',
    htmlResponse: true,
    loadingClassName: 'inplaceeditor-loading',
    loadingText: 'Loading...',
    okControl: 'button',                        // 'link'|'button'|false
    okText: 'ok',
    paramName: 'value',
    rows: 1,                                    // If 1 and multi-line, uses autoRows
    savingClassName: 'inplaceeditor-saving',
    savingText: 'Saving...',
    size: 0,
    stripLoadedTextTags: false,
    submitOnBlur: false,
    textAfterControls: '',
    textBeforeControls: '',
    textBetweenControls: ''
  },
  DefaultCallbacks: {
    callback: function(form) {
      return Form.serialize(form);
    },
    onComplete: function(transport, element) {
      // For backward compatibility, this one is bound to the IPE, and passes
      // the element directly.  It was too often customized, so we don't break it.
      new Effect.Highlight(element, {
        startcolor: this.options.highlightColor, keepBackgroundImage: true });
    },
    onEnterEditMode: null,
    onEnterHover: function(ipe) {
      ipe.element.style.backgroundColor = ipe.options.highlightColor;
      if (ipe._effect)
        ipe._effect.cancel();
    },
    onFailure: function(transport, ipe) {
      alert('Error communication with the server: ' + transport.responseText.stripTags());
    },
    onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
    onLeaveEditMode: null,
    onLeaveHover: function(ipe) {
      ipe._effect = new Effect.Highlight(ipe.element, {
        startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
        restorecolor: ipe._originalBackground, keepBackgroundImage: true
      });
    }
  },
  Listeners: {
    click: 'enterEditMode',
    keydown: 'checkForEscapeOrReturn',
    mouseover: 'enterHover',
    mouseout: 'leaveHover'
  }
});

Ajax.InPlaceCollectionEditor.DefaultOptions = {
  loadingCollectionText: 'Loading options...'
};

// Delayed observer, like Form.Element.Observer, 
// but waits for delay after last key input
// Ideal for live-search fields

Form.Element.DelayedObserver = Class.create({
  initialize: function(element, delay, callback) {
    this.delay     = delay || 0.5;
    this.element   = $(element);
    this.callback  = callback;
    this.timer     = null;
    this.lastValue = $F(this.element); 
    Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
  },
  delayedListener: function(event) {
    if(this.lastValue == $F(this.element)) return;
    if(this.timer) clearTimeout(this.timer);
    this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
    this.lastValue = $F(this.element);
  },
  onTimerEvent: function() {
    this.timer = null;
    this.callback(this.element, $F(this.element));
  }
});

// script.aculo.us slider.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Marty Haught, Thomas Fuchs 
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

if (!Control) var Control = { };

// options:
//  axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
//  onChange(value)
//  onSlide(value)
Control.Slider = Class.create({
  initialize: function(handle, track, options) {
    var slider = this;
    
    if (Object.isArray(handle)) {
      this.handles = handle.collect( function(e) { return $(e) });
    } else {
      this.handles = [$(handle)];
    }
    
    this.track   = $(track);
    this.options = options || { };

    this.axis      = this.options.axis || 'horizontal';
    this.increment = this.options.increment || 1;
    this.step      = parseInt(this.options.step || '1');
    this.range     = this.options.range || $R(0,1);
    
    this.value     = 0; // assure backwards compat
    this.values    = this.handles.map( function() { return 0 });
    this.spans     = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
    this.options.startSpan = $(this.options.startSpan || null);
    this.options.endSpan   = $(this.options.endSpan || null);

    this.restricted = this.options.restricted || false;

    this.maximum   = this.options.maximum || this.range.end;
    this.minimum   = this.options.minimum || this.range.start;

    // Will be used to align the handle onto the track, if necessary
    this.alignX = parseInt(this.options.alignX || '0');
    this.alignY = parseInt(this.options.alignY || '0');
    
    this.trackLength = this.maximumOffset() - this.minimumOffset();

    this.handleLength = this.isVertical() ? 
      (this.handles[0].offsetHeight != 0 ? 
        this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : 
      (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : 
        this.handles[0].style.width.replace(/px$/,""));

    this.active   = false;
    this.dragging = false;
    this.disabled = false;

    if (this.options.disabled) this.setDisabled();

    // Allowed values array
    this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
    if (this.allowedValues) {
      this.minimum = this.allowedValues.min();
      this.maximum = this.allowedValues.max();
    }

    this.eventMouseDown = this.startDrag.bindAsEventListener(this);
    this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
    this.eventMouseMove = this.update.bindAsEventListener(this);

    // Initialize handles in reverse (make sure first handle is active)
    this.handles.each( function(h,i) {
      i = slider.handles.length-1-i;
      slider.setValue(parseFloat(
        (Object.isArray(slider.options.sliderValue) ? 
          slider.options.sliderValue[i] : slider.options.sliderValue) || 
         slider.range.start), i);
      h.makePositioned().observe("mousedown", slider.eventMouseDown);
    });
    
    this.track.observe("mousedown", this.eventMouseDown);
    document.observe("mouseup", this.eventMouseUp);
    document.observe("mousemove", this.eventMouseMove);
    
    this.initialized = true;
  },
  dispose: function() {
    var slider = this;    
    Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
    Event.stopObserving(document, "mouseup", this.eventMouseUp);
    Event.stopObserving(document, "mousemove", this.eventMouseMove);
    this.handles.each( function(h) {
      Event.stopObserving(h, "mousedown", slider.eventMouseDown);
    });
  },
  setDisabled: function(){
    this.disabled = true;
  },
  setEnabled: function(){
    this.disabled = false;
  },  
  getNearestValue: function(value){
    if (this.allowedValues){
      if (value >= this.allowedValues.max()) return(this.allowedValues.max());
      if (value <= this.allowedValues.min()) return(this.allowedValues.min());
      
      var offset = Math.abs(this.allowedValues[0] - value);
      var newValue = this.allowedValues[0];
      this.allowedValues.each( function(v) {
        var currentOffset = Math.abs(v - value);
        if (currentOffset <= offset){
          newValue = v;
          offset = currentOffset;
        } 
      });
      return newValue;
    }
    if (value > this.range.end) return this.range.end;
    if (value < this.range.start) return this.range.start;
    return value;
  },
  setValue: function(sliderValue, handleIdx){
    if (!this.active) {
      this.activeHandleIdx = handleIdx || 0;
      this.activeHandle    = this.handles[this.activeHandleIdx];
      this.updateStyles();
    }
    handleIdx = handleIdx || this.activeHandleIdx || 0;
    if (this.initialized && this.restricted) {
      if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
        sliderValue = this.values[handleIdx-1];
      if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
        sliderValue = this.values[handleIdx+1];
    }
    sliderValue = this.getNearestValue(sliderValue);
    this.values[handleIdx] = sliderValue;
    this.value = this.values[0]; // assure backwards compat
    
    this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = 
      this.translateToPx(sliderValue);
    
    this.drawSpans();
    if (!this.dragging || !this.event) this.updateFinished();
  },
  setValueBy: function(delta, handleIdx) {
    this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, 
      handleIdx || this.activeHandleIdx || 0);
  },
  translateToPx: function(value) {
    return Math.round(
      ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * 
      (value - this.range.start)) + "px";
  },
  translateToValue: function(offset) {
    return ((offset/(this.trackLength-this.handleLength) * 
      (this.range.end-this.range.start)) + this.range.start);
  },
  getRange: function(range) {
    var v = this.values.sortBy(Prototype.K); 
    range = range || 0;
    return $R(v[range],v[range+1]);
  },
  minimumOffset: function(){
    return(this.isVertical() ? this.alignY : this.alignX);
  },
  maximumOffset: function(){
    return(this.isVertical() ? 
      (this.track.offsetHeight != 0 ? this.track.offsetHeight :
        this.track.style.height.replace(/px$/,"")) - this.alignY : 
      (this.track.offsetWidth != 0 ? this.track.offsetWidth : 
        this.track.style.width.replace(/px$/,"")) - this.alignX);
  },  
  isVertical:  function(){
    return (this.axis == 'vertical');
  },
  drawSpans: function() {
    var slider = this;
    if (this.spans)
      $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
    if (this.options.startSpan)
      this.setSpan(this.options.startSpan,
        $R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
    if (this.options.endSpan)
      this.setSpan(this.options.endSpan, 
        $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
  },
  setSpan: function(span, range) {
    if (this.isVertical()) {
      span.style.top = this.translateToPx(range.start);
      span.style.height = this.translateToPx(range.end - range.start + this.range.start);
    } else {
      span.style.left = this.translateToPx(range.start);
      span.style.width = this.translateToPx(range.end - range.start + this.range.start);
    }
  },
  updateStyles: function() {
    this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
    Element.addClassName(this.activeHandle, 'selected');
  },
  startDrag: function(event) {
    if (Event.isLeftClick(event)) {
      if (!this.disabled){
        this.active = true;
        
        var handle = Event.element(event);
        var pointer  = [Event.pointerX(event), Event.pointerY(event)];
        var track = handle;
        if (track==this.track) {
          var offsets  = Position.cumulativeOffset(this.track); 
          this.event = event;
          this.setValue(this.translateToValue( 
           (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
          ));
          var offsets  = Position.cumulativeOffset(this.activeHandle);
          this.offsetX = (pointer[0] - offsets[0]);
          this.offsetY = (pointer[1] - offsets[1]);
        } else {
          // find the handle (prevents issues with Safari)
          while((this.handles.indexOf(handle) == -1) && handle.parentNode) 
            handle = handle.parentNode;
            
          if (this.handles.indexOf(handle)!=-1) {
            this.activeHandle    = handle;
            this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
            this.updateStyles();
            
            var offsets  = Position.cumulativeOffset(this.activeHandle);
            this.offsetX = (pointer[0] - offsets[0]);
            this.offsetY = (pointer[1] - offsets[1]);
          }
        }
      }
      Event.stop(event);
    }
  },
  update: function(event) {
   if (this.active) {
      if (!this.dragging) this.dragging = true;
      this.draw(event);
      if (Prototype.Browser.WebKit) window.scrollBy(0,0);
      Event.stop(event);
   }
  },
  draw: function(event) {
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    var offsets = Position.cumulativeOffset(this.track);
    pointer[0] -= this.offsetX + offsets[0];
    pointer[1] -= this.offsetY + offsets[1];
    this.event = event;
    this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
    if (this.initialized && this.options.onSlide)
      this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
  },
  endDrag: function(event) {
    if (this.active && this.dragging) {
      this.finishDrag(event, true);
      Event.stop(event);
    }
    this.active = false;
    this.dragging = false;
  },  
  finishDrag: function(event, success) {
    this.active = false;
    this.dragging = false;
    this.updateFinished();
  },
  updateFinished: function() {
    if (this.initialized && this.options.onChange) 
      this.options.onChange(this.values.length>1 ? this.values : this.value, this);
    this.event = null;
  }
});

// script.aculo.us sound.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Based on code created by Jules Gravinese (http://www.webveteran.com/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

Sound = {
  tracks: {},
  _enabled: true,
  template:
    new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'),
  enable: function(){
    Sound._enabled = true;
  },
  disable: function(){
    Sound._enabled = false;
  },
  play: function(url){
    if(!Sound._enabled) return;
    var options = Object.extend({
      track: 'global', url: url, replace: false
    }, arguments[1] || {});
    
    if(options.replace && this.tracks[options.track]) {
      $R(0, this.tracks[options.track].id).each(function(id){
        var sound = $('sound_'+options.track+'_'+id);
        sound.Stop && sound.Stop();
        sound.remove();
      })
      this.tracks[options.track] = null;
    }
      
    if(!this.tracks[options.track])
      this.tracks[options.track] = { id: 0 }
    else
      this.tracks[options.track].id++;
      
    options.id = this.tracks[options.track].id;
    $$('body')[0].insert( 
      Prototype.Browser.IE ? new Element('bgsound',{
        id: 'sound_'+options.track+'_'+options.id,
        src: options.url, loop: 1, autostart: true
      }) : Sound.template.evaluate(options));
  }
};

if(Prototype.Browser.Gecko && navigator.userAgent.indexOf("Win") > 0){
  if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('QuickTime') != -1 }))
    Sound.template = new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>')
  else
    Sound.play = function(){}
}

// script.aculo.us unittest.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
//           (c) 2005-2007 Michael Schuerig (http://www.schuerig.de/michael/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

// experimental, Firefox-only
Event.simulateMouse = function(element, eventName) {
  var options = Object.extend({
    pointerX: 0,
    pointerY: 0,
    buttons:  0,
    ctrlKey:  false,
    altKey:   false,
    shiftKey: false,
    metaKey:  false
  }, arguments[2] || {});
  var oEvent = document.createEvent("MouseEvents");
  oEvent.initMouseEvent(eventName, true, true, document.defaultView, 
    options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY, 
    options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));
  
  if(this.mark) Element.remove(this.mark);
  this.mark = document.createElement('div');
  this.mark.appendChild(document.createTextNode(" "));
  document.body.appendChild(this.mark);
  this.mark.style.position = 'absolute';
  this.mark.style.top = options.pointerY + "px";
  this.mark.style.left = options.pointerX + "px";
  this.mark.style.width = "5px";
  this.mark.style.height = "5px;";
  this.mark.style.borderTop = "1px solid red;"
  this.mark.style.borderLeft = "1px solid red;"
  
  if(this.step)
    alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));
  
  $(element).dispatchEvent(oEvent);
};

// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
// You need to downgrade to 1.0.4 for now to get this working
// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
Event.simulateKey = function(element, eventName) {
  var options = Object.extend({
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    keyCode: 0,
    charCode: 0
  }, arguments[2] || {});

  var oEvent = document.createEvent("KeyEvents");
  oEvent.initKeyEvent(eventName, true, true, window, 
    options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
    options.keyCode, options.charCode );
  $(element).dispatchEvent(oEvent);
};

Event.simulateKeys = function(element, command) {
  for(var i=0; i<command.length; i++) {
    Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
  }
};

var Test = {}
Test.Unit = {};

// security exception workaround
Test.Unit.inspect = Object.inspect;

Test.Unit.Logger = Class.create();
Test.Unit.Logger.prototype = {
  initialize: function(log) {
    this.log = $(log);
    if (this.log) {
      this._createLogTable();
    }
  },
  start: function(testName) {
    if (!this.log) return;
    this.testName = testName;
    this.lastLogLine = document.createElement('tr');
    this.statusCell = document.createElement('td');
    this.nameCell = document.createElement('td');
    this.nameCell.className = "nameCell";
    this.nameCell.appendChild(document.createTextNode(testName));
    this.messageCell = document.createElement('td');
    this.lastLogLine.appendChild(this.statusCell);
    this.lastLogLine.appendChild(this.nameCell);
    this.lastLogLine.appendChild(this.messageCell);
    this.loglines.appendChild(this.lastLogLine);
  },
  finish: function(status, summary) {
    if (!this.log) return;
    this.lastLogLine.className = status;
    this.statusCell.innerHTML = status;
    this.messageCell.innerHTML = this._toHTML(summary);
    this.addLinksToResults();
  },
  message: function(message) {
    if (!this.log) return;
    this.messageCell.innerHTML = this._toHTML(message);
  },
  summary: function(summary) {
    if (!this.log) return;
    this.logsummary.innerHTML = this._toHTML(summary);
  },
  _createLogTable: function() {
    this.log.innerHTML =
    '<div id="logsummary"></div>' +
    '<table id="logtable">' +
    '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
    '<tbody id="loglines"></tbody>' +
    '</table>';
    this.logsummary = $('logsummary')
    this.loglines = $('loglines');
  },
  _toHTML: function(txt) {
    return txt.escapeHTML().replace(/\n/g,"<br/>");
  },
  addLinksToResults: function(){ 
    $$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
      td.title = "Run only this test"
      Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
    });
    $$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
      td.title = "Run all tests"
      Event.observe(td, 'click', function(){ window.location.search = "";});
    });
  }
}

Test.Unit.Runner = Class.create();
Test.Unit.Runner.prototype = {
  initialize: function(testcases) {
    this.options = Object.extend({
      testLog: 'testlog'
    }, arguments[1] || {});
    this.options.resultsURL = this.parseResultsURLQueryParameter();
    this.options.tests      = this.parseTestsQueryParameter();
    if (this.options.testLog) {
      this.options.testLog = $(this.options.testLog) || null;
    }
    if(this.options.tests) {
      this.tests = [];
      for(var i = 0; i < this.options.tests.length; i++) {
        if(/^test/.test(this.options.tests[i])) {
          this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
        }
      }
    } else {
      if (this.options.test) {
        this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
      } else {
        this.tests = [];
        for(var testcase in testcases) {
          if(/^test/.test(testcase)) {
            this.tests.push(
               new Test.Unit.Testcase(
                 this.options.context ? ' -> ' + this.options.titles[testcase] : testcase, 
                 testcases[testcase], testcases["setup"], testcases["teardown"]
               ));
          }
        }
      }
    }
    this.currentTest = 0;
    this.logger = new Test.Unit.Logger(this.options.testLog);
    setTimeout(this.runTests.bind(this), 1000);
  },
  parseResultsURLQueryParameter: function() {
    return window.location.search.parseQuery()["resultsURL"];
  },
  parseTestsQueryParameter: function(){
    if (window.location.search.parseQuery()["tests"]){
        return window.location.search.parseQuery()["tests"].split(',');
    };
  },
  // Returns:
  //  "ERROR" if there was an error,
  //  "FAILURE" if there was a failure, or
  //  "SUCCESS" if there was neither
  getResult: function() {
    var hasFailure = false;
    for(var i=0;i<this.tests.length;i++) {
      if (this.tests[i].errors > 0) {
        return "ERROR";
      }
      if (this.tests[i].failures > 0) {
        hasFailure = true;
      }
    }
    if (hasFailure) {
      return "FAILURE";
    } else {
      return "SUCCESS";
    }
  },
  postResults: function() {
    if (this.options.resultsURL) {
      new Ajax.Request(this.options.resultsURL, 
        { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
    }
  },
  runTests: function() {
    var test = this.tests[this.currentTest];
    if (!test) {
      // finished!
      this.postResults();
      this.logger.summary(this.summary());
      return;
    }
    if(!test.isWaiting) {
      this.logger.start(test.name);
    }
    test.run();
    if(test.isWaiting) {
      this.logger.message("Waiting for " + test.timeToWait + "ms");
      setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
    } else {
      this.logger.finish(test.status(), test.summary());
      this.currentTest++;
      // tail recursive, hopefully the browser will skip the stackframe
      this.runTests();
    }
  },
  summary: function() {
    var assertions = 0;
    var failures = 0;
    var errors = 0;
    var messages = [];
    for(var i=0;i<this.tests.length;i++) {
      assertions +=   this.tests[i].assertions;
      failures   +=   this.tests[i].failures;
      errors     +=   this.tests[i].errors;
    }
    return (
      (this.options.context ? this.options.context + ': ': '') + 
      this.tests.length + " tests, " + 
      assertions + " assertions, " + 
      failures   + " failures, " +
      errors     + " errors");
  }
}

Test.Unit.Assertions = Class.create();
Test.Unit.Assertions.prototype = {
  initialize: function() {
    this.assertions = 0;
    this.failures   = 0;
    this.errors     = 0;
    this.messages   = [];
  },
  summary: function() {
    return (
      this.assertions + " assertions, " + 
      this.failures   + " failures, " +
      this.errors     + " errors" + "\n" +
      this.messages.join("\n"));
  },
  pass: function() {
    this.assertions++;
  },
  fail: function(message) {
    this.failures++;
    this.messages.push("Failure: " + message);
  },
  info: function(message) {
    this.messages.push("Info: " + message);
  },
  error: function(error) {
    this.errors++;
    this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
  },
  status: function() {
    if (this.failures > 0) return 'failed';
    if (this.errors > 0) return 'error';
    return 'passed';
  },
  assert: function(expression) {
    var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
    try { expression ? this.pass() : 
      this.fail(message); }
    catch(e) { this.error(e); }
  },
  assertEqual: function(expected, actual) {
    var message = arguments[2] || "assertEqual";
    try { (expected == actual) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) + 
        '", actual "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertInspect: function(expected, actual) {
    var message = arguments[2] || "assertInspect";
    try { (expected == actual.inspect()) ? this.pass() :
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) + 
        '", actual "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertEnumEqual: function(expected, actual) {
    var message = arguments[2] || "assertEnumEqual";
    try { $A(expected).length == $A(actual).length && 
      expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
        this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) + 
          ', actual ' + Test.Unit.inspect(actual)); }
    catch(e) { this.error(e); }
  },
  assertNotEqual: function(expected, actual) {
    var message = arguments[2] || "assertNotEqual";
    try { (expected != actual) ? this.pass() : 
      this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertIdentical: function(expected, actual) { 
    var message = arguments[2] || "assertIdentical"; 
    try { (expected === actual) ? this.pass() : 
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +  
        '", actual "' + Test.Unit.inspect(actual) + '"'); } 
    catch(e) { this.error(e); } 
  },
  assertNotIdentical: function(expected, actual) { 
    var message = arguments[2] || "assertNotIdentical"; 
    try { !(expected === actual) ? this.pass() : 
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +  
        '", actual "' + Test.Unit.inspect(actual) + '"'); } 
    catch(e) { this.error(e); } 
  },
  assertNull: function(obj) {
    var message = arguments[1] || 'assertNull'
    try { (obj==null) ? this.pass() : 
      this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
    catch(e) { this.error(e); }
  },
  assertMatch: function(expected, actual) {
    var message = arguments[2] || 'assertMatch';
    var regex = new RegExp(expected);
    try { (regex.exec(actual)) ? this.pass() :
      this.fail(message + ' : regex: "' +  Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
    catch(e) { this.error(e); }
  },
  assertHidden: function(element) {
    var message = arguments[1] || 'assertHidden';
    this.assertEqual("none", element.style.display, message);
  },
  assertNotNull: function(object) {
    var message = arguments[1] || 'assertNotNull';
    this.assert(object != null, message);
  },
  assertType: function(expected, actual) {
    var message = arguments[2] || 'assertType';
    try { 
      (actual.constructor == expected) ? this.pass() : 
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +  
        '", actual "' + (actual.constructor) + '"'); }
    catch(e) { this.error(e); }
  },
  assertNotOfType: function(expected, actual) {
    var message = arguments[2] || 'assertNotOfType';
    try { 
      (actual.constructor != expected) ? this.pass() : 
      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +  
        '", actual "' + (actual.constructor) + '"'); }
    catch(e) { this.error(e); }
  },
  assertInstanceOf: function(expected, actual) {
    var message = arguments[2] || 'assertInstanceOf';
    try { 
      (actual instanceof expected) ? this.pass() : 
      this.fail(message + ": object was not an instance of the expected type"); }
    catch(e) { this.error(e); } 
  },
  assertNotInstanceOf: function(expected, actual) {
    var message = arguments[2] || 'assertNotInstanceOf';
    try { 
      !(actual instanceof expected) ? this.pass() : 
      this.fail(message + ": object was an instance of the not expected type"); }
    catch(e) { this.error(e); } 
  },
  assertRespondsTo: function(method, obj) {
    var message = arguments[2] || 'assertRespondsTo';
    try {
      (obj[method] && typeof obj[method] == 'function') ? this.pass() : 
      this.fail(message + ": object doesn't respond to [" + method + "]"); }
    catch(e) { this.error(e); }
  },
  assertReturnsTrue: function(method, obj) {
    var message = arguments[2] || 'assertReturnsTrue';
    try {
      var m = obj[method];
      if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
      m() ? this.pass() : 
      this.fail(message + ": method returned false"); }
    catch(e) { this.error(e); }
  },
  assertReturnsFalse: function(method, obj) {
    var message = arguments[2] || 'assertReturnsFalse';
    try {
      var m = obj[method];
      if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
      !m() ? this.pass() : 
      this.fail(message + ": method returned true"); }
    catch(e) { this.error(e); }
  },
  assertRaise: function(exceptionName, method) {
    var message = arguments[2] || 'assertRaise';
    try { 
      method();
      this.fail(message + ": exception expected but none was raised"); }
    catch(e) {
      ((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e); 
    }
  },
  assertElementsMatch: function() {
    var expressions = $A(arguments), elements = $A(expressions.shift());
    if (elements.length != expressions.length) {
      this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
      return false;
    }
    elements.zip(expressions).all(function(pair, index) {
      var element = $(pair.first()), expression = pair.last();
      if (element.match(expression)) return true;
      this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
    }.bind(this)) && this.pass();
  },
  assertElementMatches: function(element, expression) {
    this.assertElementsMatch([element], expression);
  },
  benchmark: function(operation, iterations) {
    var startAt = new Date();
    (iterations || 1).times(operation);
    var timeTaken = ((new Date())-startAt);
    this.info((arguments[2] || 'Operation') + ' finished ' + 
       iterations + ' iterations in ' + (timeTaken/1000)+'s' );
    return timeTaken;
  },
  _isVisible: function(element) {
    element = $(element);
    if(!element.parentNode) return true;
    this.assertNotNull(element);
    if(element.style && Element.getStyle(element, 'display') == 'none')
      return false;
    
    return this._isVisible(element.parentNode);
  },
  assertNotVisible: function(element) {
    this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
  },
  assertVisible: function(element) {
    this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
  },
  benchmark: function(operation, iterations) {
    var startAt = new Date();
    (iterations || 1).times(operation);
    var timeTaken = ((new Date())-startAt);
    this.info((arguments[2] || 'Operation') + ' finished ' + 
       iterations + ' iterations in ' + (timeTaken/1000)+'s' );
    return timeTaken;
  }
}

Test.Unit.Testcase = Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
  initialize: function(name, test, setup, teardown) {
    Test.Unit.Assertions.prototype.initialize.bind(this)();
    this.name           = name;
    
    if(typeof test == 'string') {
      test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
      test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
      this.test = function() {
        eval('with(this){'+test+'}');
      }
    } else {
      this.test = test || function() {};
    }
    
    this.setup          = setup || function() {};
    this.teardown       = teardown || function() {};
    this.isWaiting      = false;
    this.timeToWait     = 1000;
  },
  wait: function(time, nextPart) {
    this.isWaiting = true;
    this.test = nextPart;
    this.timeToWait = time;
  },
  run: function() {
    try {
      try {
        if (!this.isWaiting) this.setup.bind(this)();
        this.isWaiting = false;
        this.test.bind(this)();
      } finally {
        if(!this.isWaiting) {
          this.teardown.bind(this)();
        }
      }
    }
    catch(e) { this.error(e); }
  }
});

// *EXPERIMENTAL* BDD-style testing to please non-technical folk
// This draws many ideas from RSpec http://rspec.rubyforge.org/

Test.setupBDDExtensionMethods = function(){
  var METHODMAP = {
    shouldEqual:     'assertEqual',
    shouldNotEqual:  'assertNotEqual',
    shouldEqualEnum: 'assertEnumEqual',
    shouldBeA:       'assertType',
    shouldNotBeA:    'assertNotOfType',
    shouldBeAn:      'assertType',
    shouldNotBeAn:   'assertNotOfType',
    shouldBeNull:    'assertNull',
    shouldNotBeNull: 'assertNotNull',
    
    shouldBe:        'assertReturnsTrue',
    shouldNotBe:     'assertReturnsFalse',
    shouldRespondTo: 'assertRespondsTo'
  };
  var makeAssertion = function(assertion, args, object) { 
   	this[assertion].apply(this,(args || []).concat([object]));
  }
  
  Test.BDDMethods = {};   
  $H(METHODMAP).each(function(pair) { 
    Test.BDDMethods[pair.key] = function() { 
       var args = $A(arguments); 
       var scope = args.shift(); 
       makeAssertion.apply(scope, [pair.value, args, this]); }; 
  });
  
  [Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each(
    function(p){ Object.extend(p, Test.BDDMethods) }
  );
}

Test.context = function(name, spec, log){
  Test.setupBDDExtensionMethods();
  
  var compiledSpec = {};
  var titles = {};
  for(specName in spec) {
    switch(specName){
      case "setup":
      case "teardown":
        compiledSpec[specName] = spec[specName];
        break;
      default:
        var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
        var body = spec[specName].toString().split('\n').slice(1);
        if(/^\{/.test(body[0])) body = body.slice(1);
        body.pop();
        body = body.map(function(statement){ 
          return statement.strip()
        });
        compiledSpec[testName] = body.join('\n');
        titles[testName] = specName;
    }
  }
  new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
};

function $GE( obj ) {
	return Element.getElement( obj );
}

function navigate( evt )
{
	var element = $GE( evt );
	
	var id 			= Element.getParentAttributeValue(element, 'id' );
	var href 		= Element.getParentAttributeValue(element, 'url' );
	var target 		= Element.getParentAttributeValue(element, 'target', '_self');
	var submitField	= Element.getParentAttributeValue(element, 'submitfield' );
	var targetDlg 	= Element.getParentAttributeValue(element, 'targetdlg' );
	
	if (targetDlg) {
		Form.Element.setValue('EK_TARGET', targetDlg);
	}
	
	if (submitField) {
		Form.Element.setValue(submitField, id);
	}
	
	if (!href) {	
		ekSubmit( id, target);
	} else {
		href = href.urldecode();
		
		if (href.indexOf('javascript:') != -1) {
			if (href.indexOf('ekSubmit(') != -1 ) {
				if (href.indexOf('this') != -1) {
					ekSubmit( element );
				} else {
					ekSubmit( id, target);
				}
			} else {
				code = href.substring(11, href.length) + ";";
				code = code.ltrim();
				eval(code);
			}
		} else {
			if ( href.indexOf('http:') != -1 && href.indexOf('void') == -1 && href.indexOf('#') == -1 ) {
				window.open(href, target);
			}
			
			if (href.indexOf('ekSubmit(') != -1) {
				if (href.indexOf('this') != -1) {
					ekSubmit( element );
				} else {
					ekSubmit(id, target);
				}
			} else {
				code = href.ltrim();
				eval(code);
			}
		}
	}

	return false;
}


function ekSubmit( evt, target, timeout)
{
	if (evt == null)
		throw new Error ('ekSubmit: No Submitevent set !');
		
	var form 		= document.forms[0];
	var action 		= null;
	var targetDlg 	= $F('DLG_ID');
	var element 	= null;
	
	var proceed 	= ( target == 'easygui_proceed' );
	var upload 		= ( target == 'easygui_upload' );
	
	var target = ( target == null || target == 'undefined' || target == 'easygui_proceed' || target == 'easygui_upload' ) ? '_self' : target;
	
	if ( typeof document.body.isubmit != "undefined" ) {
		return;
	}
	// @@@Hack
	if ( self != top && target == "_self" ) {
		document.body.isubmit = true;
	}
	
	if (typeof(evt) == 'object' ) {
		element = $GE( evt );
		evt = ( !element.id ) ? Element.getParentAttributeValue( element, 'id') : element.id;
	}
	
	if ( element = $GE( evt ) ) {
		var validate	= Element.getAttributeValue( element, 'validateform', false);
	
		if ( validate )
			if (!Form.validate( document.forms[0] ) )
				return false;
			
		target 		= Element.getAttributeValue( element, 'target', target );
		action		= Element.getAttributeValue( element, 'action', '' );
		targetDlg 	= Element.getAttributeValue( element, 'targetdlg', '');
		submitevt	= element.id;
	}
	
	var ajax 	= ( target == 'easygui_ajax' );
	var remote	= ( target == 'isyiframe' );
	
	if ( proceed )
		action = '';
		
	form.EK_TARGET.value 	= targetDlg;
	form.EK_REQUEST.value 	= 'false';
	form.EK_NOSTACK.value 	= 'false';
	form.EKSUBMITEVENT.value= evt;
	form.EK_ACTION.value 	= action;
	
	if ( DEBUG ) {
		alert( "--EKSUBMIT--\r\nin targetwin: " + target + 
				"\r\n validate: " + validate + 
				"\r\najax: " + ajax +
				"\r\naction: " + $F('EK_ACTION') + 
				"\r\ntargetdlg: " + $F('EK_TARGET') + 
				"\r\nevt: " + $F('EKSUBMITEVENT') + 
				"\r\nvalues: " + Form.serialize( form ) );
	}
	
	sleep(timeout);
	
	if ( remote ) {
		form.EK_NOSTACK.value = 'true';
	}
	
	if ( upload ) {
		form.EK_REQUEST.value = 'iframe';
		form.target = 'isyajax';
		form.submit();
		return;
	}
	
	if ( ajax ) {
		if ( Ajax.getTransport() ) {
			form.EK_REQUEST.value = 'ajax';
			this.params = '__eksubmit_values__=' + Form.serialize( document.forms[0] );
			var ajax = new Ajax.Request( document.forms[0].action, { postBody: this.params, onComplete: onComplete } );
			return;
		} else {
			form.EK_REQUEST.value = 'iframe';
			target = 'isyajax';
		}
	}
	
	var subForm = document.createElement('form');
	
	subForm.name 	= 'easygui_submit';
	subForm.method 	= 'post';
	subForm.action 	= document.forms[0].action;
	
	subForm.target 	= target;
	document.body.appendChild( subForm );

	if (DEBUG) {
		var timer = new JS_Timer();
		timer.startTimer();
	}
	
	var submitValues = Form.serialize( form );
	submitValues = submitValues.replace(/_EK_WIDGET_VALUE/g, '' );
	
	Form.insertHidden( "__eksubmit_values__", submitValues , subForm.name );
	
	if (DEBUG) {
		alert(timer.stopTimer());
	}
	
	subForm.submit();
	document.body.removeChild(subForm);
}


function ekRemoteSubmit( element ) 
{
	ekSubmit( element, 'isyiframe' );
	dialog.enable();
}


function ekRequest( element )
{
	ekSubmit( element, 'easygui_ajax' );
	dialog.enable();
}

function ekProceed( element )
{
	ekSubmit( element, 'easygui_proceed' );
	dialog.enable();
}

function ekConfirm( element, msg, request )
{
	if (msg == null) {
		ok = window.confirm('Are you sure ?');
	} else {
		msg = dialog.getMessage( msg );
		ok = window.confirm( msg );
	}
	
	if (ok) {
		if ( request ) {
			ekRequest( element );
		} else {
			ekSubmit( element );
		}
	}
	
	return false;
}

function ekUpload( element )
{
	ekSubmit( element, 'easygui_upload' );
	dialog.enable();
}


function getVersion() {
	return $F( $('IDC_EASYGUI_VERSION') );
}


function getBuild() {
	return $F( $('IDC_EASYGUI_BUILD') );
}



function componentShow( element )
{
	Element._show( element );
}


function componentHide( element )
{
	Element._hide( element );
}


function componentDisable( id )
{
	dialog[id].disable();
}


function componentEnable( id )
{
	dialog[id].enable();
}


function addEvent(obj, evType, fn, useCapture)
{
	Event.observe(obj, evType, fn, useCapture);
}


function removeEvent(obj, evType, fn, useCapture)
{
	Event.stopObserving( obj, evType, fn, useCapture);
}


function makeHandcursor( element )
{
	if (is.nav6up) {
   		element.style.cursor = 'pointer';
	} else {
    	element.style.cursor = 'hand';
	}
}


function makeWaitcursor(element)
{
   	element.style.cursor = 'wait';
}


function makeDefaultcursor(element) 
{
	element.style.cursor = 'default';
}


function createNewHiddenFormField(id, value) 
{
	Form.insertHidden(id, value);
}


function initCombobox( id ) 
{
	dialog[id].setOptionList();
}


function openFolder( element ) 
{
	focusItem( element );
}


function sortColumn(evt) 
{
	sortTable( evt );
}


function scrollToTableElement( id ) 
{
	scrollIntoView( id );
}

 
function getColumnFrom(element) 
{
	var element = Element.getParentElementByTagName( element, 'TD', true );
	return element.id
}


function getRowFrom( element ) 
{
	var element = Element.getParentElementByTagName( element, 'TR', true );
	return element.id
}


function getTableFrom(element) 
{
	var element = Element.getParentElementByTagName( element, 'TABLE', true );
	return element.tableid;
}

function getRowNumFrom(obj) 
{
	var rowid	= getRowFrom(obj);
	var tableid	= getTableFrom(obj);
	
	return rowid.substr(tableid.length+1, rowid.length - tableid.length - 1);
}


function getElementFrom( element ) 
{
	return $GE( element );
}


function ekSubmitInIframe() 
{
	callToServer('isycat');
}


function ekSubmitInNewWindow(element, width, height)
{
	if (width == null) {
		width = 800;
	}
	
	if (height == null) {
		height = 600;
	}
	
	if (typeof(element) == "string") {
    	var winId = element;
    } else {
    	var winId = element.id;
    }
    
	var win = window.open("about:blank", winId + "_win" ,"width=" + width + " height=" + height + " toolbar=no");
	dialog.winRegistry.registerWindow(new guiWindow(winId + "_win", win));
	
	ekSubmit(element, winId + "_win");
}


function showContentInNewWindow(element) 
{
	var newWindowUrl 		= "about:blank";
	var newWindowName 		= "newWindow";
	var newWindowHeight 	= 600;
	var newWindowWidth 		= 800;
	var newWindowToolbar 	= "yes";
	var newWindowMenuBar 	= "no";
	
	if (element.getAttribute('docref')) {
		newWindowUrl 		= element.getAttribute('docref');
	}
   	
   	if(element.getAttribute('newwindowname')) {
   		newWindowName 		= element.getAttribute('newwindowname');
   		newWindowName		= newWindowName.replace(/(\s+|-)/g, '_');
   	}
    
    if (element.getAttribute('newwindowwidth')) {
    	newWindowWidth 		= element.getAttribute('newwindowwidth');
    }
         
    if (element.getAttribute('newwindowheight')) {
    	newWindowHeight 	= element.getAttribute('newwindowheight');
    }
         
    if (element.getAttribute('newwindowtoolbar')) {
    	newWindowToolbar 	= element.getAttribute('newwindowtoolbar');
    }
    
    if (element.getAttribute('newwindowmenubar')) {
    	newWindowMenuBar 	= element.getAttribute('newwindowmenubar');
    }

    var newWindowAttributes = "menubar="+newWindowMenuBar+" toolbar="+newWindowToolbar+" width="+newWindowWidth+" height="+newWindowHeight;
    window.open(newWindowUrl, newWindowName, newWindowAttributes);
}


function flipImage (evt) 
{
	var element = $GE(evt);
	
	var overimg = element.getAttribute('mouseoverimage' );
	
	if ( typeof (overimg) == "undefined" ) {
		return;
	}
	
    var imagesrc 			= element.src;
    element.src 			= overimg;
    element.setAttribute( 'mouseoverimage', imagesrc );
}

function confirmDelete( element, msg )
{
	ekConfirm( element, msg );
}

function navigate2(element)
{
	navigate(element);
}
//<--
// Ultimate client-side JavaScript client sniff. Version 3.03
// (C) Netscape Communications 1999.  Permission granted to reuse and distribute.
// Revised 17 May 99 to add is.nav5up and is.ie5up (see below).
// Revised 21 Nov 00 to add is.gecko and is.ie5_5 Also Changed is.nav5 and is.nav5up to is.nav6 and is.nav6up
// Revised 22 Feb 01 to correct Javascript Detection for IE 5.x, Opera 4, 
//                      correct Opera 5 detection
//                      add support for winME and win2k
//                      synch with browser-type-oo.js
// Revised 26 Mar 01 to correct Opera detection
// Revised 02 Oct 01 to add IE6 detection

// Everything you always wanted to know about your JavaScript client
// but were afraid to ask ... "Is" is the constructor function for "is" object,
// which has properties indicating:
// (1) browser vendor:
//     is.nav, is.ie, is.opera, is.hotjava, is.webtv, is.TVNavigator, is.AOLTV
// (2) browser version number:
//     is.major (integer indicating major version number: 2, 3, 4 ...)
//     is.minor (float   indicating full  version number: 2.02, 3.01, 4.04 ...)
// (3) browser vendor AND major version number
//     is.nav2, is.nav3, is.nav4, is.nav4up, is.nav6, is.nav6up, is.gecko, is.ie3, 
//     is.ie4, is.ie4up, is.ie5, is.ie5up, is.ie5_5, is.ie5_5up, is.ie6, is.ie6up, is.hotjava3, is.hotjava3up
// (4) JavaScript version number:
//     is.js (float indicating full JavaScript version number: 1, 1.1, 1.2 ...)
// (5) OS platform and version:
//     is.win, is.win16, is.win32, is.win31, is.win95, is.winnt, is.win98, is.winme, is.win2k
//     is.os2
//     is.mac, is.mac68k, is.macppc
//     is.unix
//     is.sun, is.sun4, is.sun5, is.suni86
//     is.irix, is.irix5, is.irix6
//     is.hpux, is.hpux9, is.hpux10
//     is.aix, is.aix1, is.aix2, is.aix3, is.aix4
//     is.linux, is.sco, is.unixware, is.mpras, is.reliant
//     is.dec, is.sinix, is.freebsd, is.bsd
//     is.vms
//
// See http://www.it97.de/JavaScript/JS_tutorial/bstat/navobj.html and
// http://www.it97.de/JavaScript/JS_tutorial/bstat/Browseraol.html
// for detailed lists of userAgent strings.
//
// Note: you don't want your Nav4 or IE4 code to "turn off" or
// stop working when Nav5 and IE5 (or later) are released, so
// in conditional code forks, use is.nav4up ("Nav4 or greater")
// and is.ie4up ("IE4 or greater") instead of is.nav4 or is.ie4
// to check version in code which you want to work on future
// versions.
function Is ()
{   // convert all characters to lowercase to simplify testing
    var agt=navigator.userAgent.toLowerCase();
    // *** BROWSER VERSION ***
    // Note: On IE5, these return 4, so use is.ie5up to detect IE5.

    this.major = parseInt(navigator.appVersion);
    this.minor = parseFloat(navigator.appVersion);

    // Note: Opera and WebTV spoof Navigator.  We do strict client detection.
    // If you want to allow spoofing, take out the tests for opera and webtv.
    this.nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
    this.nav2 = (this.nav && (this.major == 2));
    this.nav3 = (this.nav && (this.major == 3));
    this.nav4 = (this.nav && (this.major == 4));
    this.nav4up = (this.nav && (this.major >= 4));
    this.navonly      = (this.nav && ((agt.indexOf(";nav") != -1) ||
                          (agt.indexOf("; nav") != -1)) );
    this.nav6 = (this.nav && (this.major == 5));
    this.nav6up = (this.nav && (this.major >= 5));
    this.gecko = (agt.indexOf('gecko') != -1);


    this.ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    this.ie3    = (this.ie && (this.major < 4));
    this.ie4    = (this.ie && (this.major == 4) && (agt.indexOf("msie 4")!=-1) );
    this.ie4up  = (this.ie  && (this.major >= 4));
    this.ie5    = (this.ie && (this.major == 4) && (agt.indexOf("msie 5.0")!=-1) );
    this.ie5_5  = (this.ie && (this.major == 4) && (agt.indexOf("msie 5.5") !=-1));
    this.ie5up  = (this.ie  && !this.ie3 && !this.ie4);
    this.ie5_5up =(this.ie && !this.ie3 && !this.ie4 && !this.ie5);
    this.ie6    = (this.ie && (this.major == 4) && (agt.indexOf("msie 6.")!=-1) );
    this.ie6up  = (this.ie  && !this.ie3 && !this.ie4 && !this.ie5 && !this.ie5_5);

    // KNOWN BUG: On AOL4, returns false if IE3 is embedded browser
    // or if this is the first browser window opened.  Thus the
    // variables is.aol, is.aol3, and is.aol4 aren't 100% reliable.
    this.aol   = (agt.indexOf("aol") != -1);
    this.aol3  = (this.aol && this.ie3);
    this.aol4  = (this.aol && this.ie4);
    this.aol5  = (agt.indexOf("aol 5") != -1);
    this.aol6  = (agt.indexOf("aol 6") != -1);

    this.opera = (agt.indexOf("opera") != -1);
    this.opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
    this.opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
    this.opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
    this.opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
    this.opera5up = (this.opera && !this.opera2 && !this.opera3 && !this.opera4);

    this.webtv = (agt.indexOf("webtv") != -1); 

    this.TVNavigator = ((agt.indexOf("navio") != -1) || (agt.indexOf("navio_aoltv") != -1)); 
    this.AOLTV = this.TVNavigator;

    this.hotjava = (agt.indexOf("hotjava") != -1);
    this.hotjava3 = (this.hotjava && (this.major == 3));
    this.hotjava3up = (this.hotjava && (this.major >= 3));

    // *** JAVASCRIPT VERSION CHECK ***
    if (this.nav2 || this.ie3) this.js = 1.0;
    else if (this.nav3) this.js = 1.1;
    else if (this.opera5up) this.js = 1.3;
    else if (this.opera) this.js = 1.1;
    else if ((this.nav4 && (this.minor <= 4.05)) || this.ie4) this.js = 1.2;
    else if ((this.nav4 && (this.minor > 4.05)) || this.ie5) this.js = 1.3;
    else if (this.hotjava3up) this.js = 1.4;
    else if (this.nav6 || this.gecko) this.js = 1.5;
    // NOTE: In the future, update this code when newer versions of JS
    // are released. For now, we try to provide some upward compatibility
    // so that future versions of Nav and IE will show they are at
    // *least* JS 1.x capable. Always check for JS version compatibility
    // with > or >=.
    else if (this.nav6up) this.js = 1.5;
    // note ie5up on mac is 1.4
    else if (this.ie5up) this.js = 1.3

    // HACK: no idea for other browsers; always check for JS version with > or >=
    else this.js = 0.0;

    // *** PLATFORM ***
    this.win   = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
    // NOTE: On Opera 3.0, the userAgent string includes "Windows 95/NT4" on all
    //        Win32, so you can't distinguish between Win95 and WinNT.
    this.win95 = ((agt.indexOf("win95")!=-1) || (agt.indexOf("windows 95")!=-1));

    // is this a 16 bit compiled version?
    this.win16 = ((agt.indexOf("win16")!=-1) || 
               (agt.indexOf("16bit")!=-1) || (agt.indexOf("windows 3.1")!=-1) || 
               (agt.indexOf("windows 16-bit")!=-1) );  

    this.win31 = ((agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("win16")!=-1) ||
                    (agt.indexOf("windows 16-bit")!=-1));

    // NOTE: Reliable detection of Win98 may not be possible. It appears that:
    //       - On Nav 4.x and before you'll get plain "Windows" in userAgent.
    //       - On Mercury client, the 32-bit version will return "Win98", but
    //         the 16-bit version running on Win98 will still return "Win95".
    this.win98 = ((agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1));
    this.winnt = ((agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1));
    this.win32 = (this.win95 || this.winnt || this.win98 || 
                    ((this.major >= 4) && (navigator.platform == "Win32")) ||
                    (agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1));

    this.winme = ((agt.indexOf("win 9x 4.90")!=-1));
    this.win2k = ((agt.indexOf("windows nt 5.0")!=-1));
	this.winxp = ((agt.indexOf("windows nt 5.1")!=-1));
	
    this.os2   = ((agt.indexOf("os/2")!=-1) || 
                    (navigator.appVersion.indexOf("OS/2")!=-1) ||   
                    (agt.indexOf("ibm-webexplorer")!=-1));

    this.mac    = (agt.indexOf("mac")!=-1);
    // hack ie5 js version for mac
    if (this.mac && this.ie5up) this.js = 1.4;
    this.mac68k = (this.mac && ((agt.indexOf("68k")!=-1) || 
                               (agt.indexOf("68000")!=-1)));
    this.macppc = (this.mac && ((agt.indexOf("ppc")!=-1) || 
                                (agt.indexOf("powerpc")!=-1)));

    this.sun   = (agt.indexOf("sunos")!=-1);
    this.sun4  = (agt.indexOf("sunos 4")!=-1);
    this.sun5  = (agt.indexOf("sunos 5")!=-1);
    this.suni86= (this.sun && (agt.indexOf("i86")!=-1));
    this.irix  = (agt.indexOf("irix") !=-1);    // SGI
    this.irix5 = (agt.indexOf("irix 5") !=-1);
    this.irix6 = ((agt.indexOf("irix 6") !=-1) || (agt.indexOf("irix6") !=-1));
    this.hpux  = (agt.indexOf("hp-ux")!=-1);
    this.hpux9 = (this.hpux && (agt.indexOf("09.")!=-1));
    this.hpux10= (this.hpux && (agt.indexOf("10.")!=-1));
    this.aix   = (agt.indexOf("aix") !=-1);      // IBM
    this.aix1  = (agt.indexOf("aix 1") !=-1);    
    this.aix2  = (agt.indexOf("aix 2") !=-1);    
    this.aix3  = (agt.indexOf("aix 3") !=-1);    
    this.aix4  = (agt.indexOf("aix 4") !=-1);    
    this.linux = (agt.indexOf("inux")!=-1);
    this.sco   = (agt.indexOf("sco")!=-1) || (agt.indexOf("unix_sv")!=-1);
    this.unixware = (agt.indexOf("unix_system_v")!=-1); 
    this.mpras    = (agt.indexOf("ncr")!=-1); 
    this.reliant  = (agt.indexOf("reliantunix")!=-1);
    this.dec   = ((agt.indexOf("dec")!=-1) || (agt.indexOf("osf1")!=-1) || 
                  (agt.indexOf("dec_alpha")!=-1) || (agt.indexOf("alphaserver")!=-1) || 
                  (agt.indexOf("ultrix")!=-1) || (agt.indexOf("alphastation")!=-1)); 
    this.sinix = (agt.indexOf("sinix")!=-1);
    this.freebsd = (agt.indexOf("freebsd")!=-1);
    this.bsd = (agt.indexOf("bsd")!=-1);
    this.unix  = ((agt.indexOf("x11")!=-1) || this.sun || this.irix || this.hpux || 
                 this.sco ||this.unixware || this.mpras || this.reliant || 
                 this.dec || this.sinix || this.aix || this.linux || this.bsd || this.freebsd);

    this.vms   = ((agt.indexOf("vax")!=-1) || (agt.indexOf("openvms")!=-1));
}

var is;
var isIE3Mac = false;
// this section is designed specifically for IE3 for the Mac

if ((navigator.appVersion.indexOf("Mac")!=-1) && (navigator.userAgent.indexOf("MSIE")!=-1) && 
(parseInt(navigator.appVersion)==3))
       isIE3Mac = true;
else   is = new Is();
//EasyGUI.require( 'core/lib/lib.core' );



function EKAT_RESIZE(w,h) {;}
function EKAT_CENTER_WINDOW() {;}


var Dialog = Class.create();

Dialog.prototype = 
{
	
	id: null,
	
	
	widgets: [],
	
	
	width: 0,
	
	
	height: 0,
	
	
	winRegistry: null,
	
	
	initialized: false,
	
	popupsBlocked: false,
	
	
	initialize: function() 
	{
		if(is.ie5_5up){
			try{
				document.execCommand("BackgroundImageCache", false, true);
			}catch(e){}
		}

		if (self != top) {
			try {
				top.dialog.enable();
			} catch( e ) {}
		} else {
			try {   
				if (self.opener) {
					var modal = Element.getAttributeValue( document.body, 'modal' );
				
					if (modal) {
						self.opener.dialog.winRegistry.startModalObserver( self.name );
					} else {
						self.opener.dialog.enable();
					}
				} else {
					$('GUI_DISABLE').style.visibility = 'hidden';
				}
			} catch( e ) {
				
				//alert("Cross site opening !" + document.domain);
			}
		}
	
		Event.observe(document, "keydown", toggleEnterKey, true);
		if ( document.body.getAttribute('allowselect') != "true" )
			Event.observe(document, "selectstart", noSelect, true);
		
		this.id = document.body.id;
		this.winRegistry = new windowRegistry();
		
		Form.insertHidden('DLG_ID', this.id);

		Dialog.setWindowSize();
		
		if (is.ie5up)
			Event.observe( window, "unload", this.destroy.bindAsEventListener(this) );
	},
	
	
	getVersion: function()
	{
		alert( "Client Side System Properties \nEasyGUI: " + EasyGUI.Version + " " + EasyGUI.Build + "\nPrototype: " + Prototype.Version + "\nScriptaculous: " + Scriptaculous.Version );
	},
	
	
	getMessage: function( id )
	{
		var element = $(id);
		
		if ( element ) {
			return Element.getInnerText( element );
		}
		
		return id;
	},
	
	
	init: function()
	{
		//var allElements = document.getElementsByTagName('*');
		var tables 		= [];
		var widgetCons 	= [];
		var tabctrls 	= [];
		
		for (var i=0; i < widgets.length; i++) {
			var widget = widgets[i].split(':');
			var widgetName = '';
			
			for (var j=1; j < widget.length; j++ ) {
				widgetName += (widgetName == "" ) ? widget[j] : ":" + widget[j];
			}
			
			switch( widget[0] ) {
				case 'EasyGUI_table':
					tables[tables.length] = widgetName;
					break;
					
				case 'EasyGUI_TabCtrl':
					tabctrls[tabctrls.length] = widgetName;
					break;
					
				default:
					var widgetConstructor = widget[0] + '(\'' + widgetName + '\')';
					widgetCons[widgetCons.length] = widgetConstructor;
					break;
			}
		}
	
		for ( var i=0; i < tabctrls.length; i++ )
			this.registerWidget( new EasyGUI_TabCtrl( tabctrls[i] ) );
		
		for ( var i=0; i < widgetCons.length; i++ )
			this.registerWidget( eval( 'new ' + widgetCons[i] ) );
		
		for ( var i=0; i < tables.length; i++ ) {
			this.registerWidget( new EasyGUI_table( tables[i] ) );
		}
			
		this.renderWidgets();
		this.finalizeWidgets();
		
		this.initialized = true;
		
		// For nested iframes in iframes
		// very dangerous
		document.body.dialog = this;
	},
	
	
	renderWidgets: function()
	{
		for (var i=0; i < this.widgets.length; i++) {
			var windowname = self.name;
			
			if ( DEBUGTIME ) {
				var timer = new JS_Timer();
				timer.startTimer();
			}
			
			this.widgets[i].render();
			
			if( DEBUGTIME )		
				GUITIME += this.widgets[i].id + ': ' + timer.stopTimer() + "s\r\n";
		}
	},
	
	
	finalizeWidgets: function() 
	{
		for ( var i=0; i < this.widgets.length; i++ )
			this.widgets[i].finalize();
	},
	
	
	destroy: function()
	{
		for (var i=0; i < this.widgets.length; i++) {
			this.widgets[i].destroy();
		}
	},
	
	
	registerWidget: function ( widget )
	{
		this[widget.id] = widget;
		this.widgets.push(widget);
	},
	
	
	getWidget: function( id )
	{
		return (this[id]) ? this[id] : false;
		
	},
	
	
	getWidgets: function()
	{
		return this.widgets;
	},
	
	
	enable: function()
	{
		Element._hide('GUI_DISABLE');
	},
	
	
	disable: function ()
	{
		var disabler = $( 'GUI_DISABLE' ); 
		Element.setDimension( disabler, '100%', Dialog.getInnerHeight() );
		Element._show('GUI_DISABLE');
	}
};



Object.extend( Dialog, {
	
	getInnerWidth: function()
	{
		if (self.innerWidth) {
			return self.innerWidth;
		} else if (document.documentElement && document.documentElement.clientWidth) {
			return document.documentElement.clientWidth;	
		} else if (document.body) {
			return document.body.clientWidth;	
		}
	},
	
	
	getInnerHeight: function() 
	{
		if (self.innerHeight) {
			return self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			return document.documentElement.clientHeight;
		} else if (document.body) {
			return document.body.clientHeight;
		}
	},
	
	
	getPageYOffset: function()
	{
		if (self.pageYOffset) {
			return self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			return document.documentElement.scrollTop;
		} else if (document.body) {
			return document.body.scrollTop;
		}
	},
	
	
	getPageXOffset: function()
	{
		if (self.pageXOffset) {
			return self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollLeft) {
			return document.documentElement.scrollLeft;
		} else if (document.body) {
			return document.body.scrollLeft;
		}
	},
	
	
	getPageHeight: function()
	{
		var test1 = document.body.scrollHeight;
		var test2 = document.body.offsetHeight;
		
		if (test1 > test2) {
			return document.body.scrollHeight;
		} else {
			return document.body.offsetHeight;
		}
	},
	
	
	getPageWidth: function()
	{
		var test1 = document.body.scrollHeight;
		var test2 = document.body.offsetHeight;
		
		if (test1 > test2) {
			return document.body.scrollWidth;
		} else {
			return document.body.offsetWidth;
		}
	},
	
	
	setWindowSize: function()
	{
		var appmode = ( document.forms[0].action == "" ) ? 'ek_internet' : 'ek_cdrom';
		
		var resizeDialog 	= Element.getAttributeValue( document.body, 'resizedialog');
		var centerDialog 	= Element.getAttributeValue( document.body, 'centerdialog' );
		
		var width 	= parseInt( Element.getAttributeValue( document.body, 'dialogwidth' ));
		var height 	= parseInt( Element.getAttributeValue( document.body, 'dialogheight' ));
	
		if (self == top && ( resizeDialog || appmode == 'ek_cdrom') ) {
			try {
				self.resizeTo(width + 10, height + 4);
				width += 4;
			    height +=4;
				var hrefCMD="javascript:void(EKAT_RESIZE("+width+","+height+"))";
				window.location.href=hrefCMD;
			} catch(e) {
				;
			}
		}
		
		if (self == top && centerDialog) {
			if ( appmode != 'ek_cdrom' ) {
				try {
					self.moveTo(((screen.width/2) - (width/2)), ((screen.height/2) - (height/2)));
					var hrefCMD="javascript:void(EKAT_CENTER_WINDOW())";
					window.location.href = hrefCMD;
				} catch(e) {
					;
				}
			}
		}
	},
	
	
	showMessage: function( msgId ) {
		var msg = Element.getInnerText( msgId );
		alert( msg );
		return false;
	},
	
	
	submit: function( id, target, timeout ) 
	{
		ekSubmit( id, target, timeout );
	}
});

Dialog.Style = {
	
	getSheet: function( idx )
	{
		if (!idx) {
			var idx = 1;
		} else {
			if (typeof(idx) == 'string') {
				for (var i=0; i < document.styleSheets.length; i++) {
					if (document.styleSheets[i].title == idx) {
						var idx = i;
					}
				}
			}
		}
		
		return document.styleSheets[idx];
	},
	
	
	getRules: function( idx )
	{
		if (!document.styleSheets) {
			return false;
		}
		
		if (document.styleSheets[idx].cssRules) {
			return document.styleSheets[idx].cssRules;
		} else if (document.styleSheets[idx].rules) {
			return document.styleSheets[idx].rules;
		}
	},
	
	
	getIdx: function( idx )
	{
		if (idx == null) {
			var idx = 1;
		} else {
			if (typeof(idx) == 'string') {
				for (var i=0; i < document.styleSheets.length; i++) {
					if (document.styleSheets[i].title == idx) {
						var idx = i;
					}
				}
			}
		}
				
		return idx;
	},
	
	
	getStyle: function (selector, attribute, idx)
	{
		if (!selector) {
			return false;
		}
		
		var idx 	= Dialog.Style.getIdx( idx );
		var rules 	= Dialog.Style.getRules( idx );
		
		for (var i=0; i < rules.length; i++) {
			if (rules[i].selectorText.indexOf("." + selector) != -1) {
				return rules[i].style[attribute];
			}
		}
				
		return Dialog.Style.getDefaultValue( selector, attribute );
	},
	
	
	ruleExists: function( selector )
	{
		for (var i = (document.styleSheets.length - 1); i > 0; i--) {
			var rules = Dialog.Style.getRules( i );
		
			for (var j=0; j < rules.length; j++) {
				if (rules[j].selectorText.indexOf("." + selector) != -1) {
					return true;
				}
			}
		}
				
		return false;
	},
		
	
	getDefaultValue: function( selector, attribute )
	{
		var rules = Dialog.Style.getRules( 0 );
		
		for (var i=0; i < rules.length; i++) {
			if ("." + selector == rules[i].selectorText) {
				return rules[i].style[attribute];
			}
		}
	
		return false;
	},
	
	
	setProperty: function(property, propertyValue, styleSheet)
	{
		;
	}
};


Error.prototype.getError = function ()
{
	return 	"EasyGUI Exception Handler:\n" + 
			"Exception Type: " + this.name + "\n\n" + 
			this.message;
}


Object.extend( Array.prototype, 
{
	toUserString: function( glue ) {
		var usrStr = '';
		
		for (  var i=0; i < this.length; i++ ) {
			usrStr += this[i] + glue;
		}

		return usrStr;
	},
	
	inArray: function( attribute ) 
	{
		for ( var i=0; i < this.length; i++ ) {
			if ( this[i] == attribute ) {
				return true;
			}
		}
		return false;
	},
	
	keyExists: function( key ) 
	{
		if ( this[key] != null ) {
			return true;
		}
		
		return false;
	},
	
	removeEntry: function( value ) 
	{
		var newArr = new Array();
	 
		for (var i=0; i < this.length; i++) {
			if (this[i] != value) {
				newArr[newArr.length] = this[i];
			}
		}
		
		this.length = newArr.length;
		
		for ( var i=0; i < newArr.length; i++ )
			this[i] = newArr[i];
	}
});



Object.extend( String.prototype, {
	
	
	sprintf: function() {
	   if (!arguments || arguments.length < 1 || !RegExp)
	   {
	      return;
	   }
	   var str = arguments[0];
	   var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
	   var a = b = [], numSubstitutions = 0, numMatches = 0;
	   while (a = re.exec(str))
	   {
	      var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
	      var pPrecision = a[5], pType = a[6], rightPart = a[7];
	
	      numMatches++;
	      if (pType == '%')
	      {
	         subst = '%';
	      }
	      else
	      {
	         numSubstitutions++;
	         if (numSubstitutions >= arguments.length)
	         {
	            alert('Error! Not enough function arguments (' + (arguments.length - 1)
	               + ', excluding the string)\n'
	               + 'for the number of substitution parameters in string ('
	               + numSubstitutions + ' so far).');
	         }
	         var param = arguments[numSubstitutions];
	         var pad = '';
	                if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
	           else if (pPad) pad = pPad;
	         var justifyRight = true;
	                if (pJustify && pJustify === "-") justifyRight = false;
	         var minLength = -1;
	                if (pMinLength) minLength = parseInt(pMinLength);
	         var precision = -1;
	                if (pPrecision && pType == 'f')
	                   precision = parseInt(pPrecision.substring(1));
	         var subst = param;
	         switch (pType)
	         {
	         case 'b':
	            subst = parseInt(param).toString(2);
	            break;
	         case 'c':
	            subst = String.fromCharCode(parseInt(param));
	            break;
	         case 'd':
	            subst = parseInt(param) ? parseInt(param) : 0;
	            break;
	         case 'u':
	            subst = Math.abs(param);
	            break;
	         case 'f':
	            subst = (precision > -1)
	             ? Math.round(parseFloat(param) * Math.pow(10, precision))
	              / Math.pow(10, precision)
	             : parseFloat(param);
	            break;
	         case 'o':
	            subst = parseInt(param).toString(8);
	            break;
	         case 's':
	            subst = param;
	            break;
	         case 'x':
	            subst = ('' + parseInt(param).toString(16)).toLowerCase();
	            break;
	         case 'X':
	            subst = ('' + parseInt(param).toString(16)).toUpperCase();
	            break;
	         }
	         var padLeft = minLength - subst.toString().length;
	         if (padLeft > 0)
	         {
	            var arrTmp = new Array(padLeft+1);
	            var padding = arrTmp.join(pad?pad:" ");
	         }
	         else
	         {
	            var padding = "";
	         }
	      }
	      str = leftpart + padding + subst + rightPart;
	   }
	   return str;
	},
	
	
	ltrim: function( trimchar ) 
	{
		var str = this.valueOf();
		
		while ((str.charAt(0) == " ") || (str.charAt(0) == "\t") || (str.charAt(0) == trimchar) ) 
		{
  			str = str.substring(1, str.length);
		}
		
		return str;
	},
	
	
	rtrim: function( trimchar ) 
	{
		var str = this.valueOf();

		while ((str.charAt(str.length-1) == " " || str.charAt(str.length-1) == "\t" || str.charAt( str.length-1) == trimchar ))
		{
			str = str.substring(0, str.length - 1);
		}
		
		return str;
	},
	
	
	trimright: function( strTrim ) 
	{
		var str = this.valueOf();
		
		if (strTrim.length == 0 || strTrim.length > str.length)
		{
			return str;
		}

		var nDifflen = strTrim.length;
		var nEndPos = str.length - 1;
		
		while (str.lastIndexOf(strTrim, nEndPos) == (nEndPos - nDifflen + 1)) 
		{
			nEndPos -= nDifflen;
		}
		
		str = str.substring(0, nEndPos + 1);
		
		return str;
	},
	
	
	urldecode: function()
	{
		var str = this.valueOf();
		str = str.replace(/%20/g, ' ');
		return str;
	}
});


Object.extend( Element, 
{
	
	getElement: function( evt )
	{
		try {
			if (evt.tagName)
				return $(evt);

			if (typeof evt == 'string')
				return $(evt);
				
			if (window.event)
			  	el = window.event.srcElement;
			else 
				if (evt.type == 'scroll')
					el = evt.currentTarget;
				else
					el = (evt.target.tagName ? evt.target : evt.target.parentNode);
		
			return $(el);
		} catch (e) {
			if (e instanceof Error)
				throw new Error('Element::getElement(): ' + e.name + ' ' + e.message);
		}
	},
	
	
	getDepth: function( node, tagName, ektype )
	{
		var depth = -1;
		
		while (node = Element.getParentElementByTagName( node, tagName)) {
			var nodetype = Element.getAttributeValue(node, 'ektype');
			
			if (nodetype != ektype )
				depth++;
			else
				break;
			
			node = node.parentNode;
		}
		
		return depth;
	},
	
	getPageOffsetTop: function( domElement )
	{
		var y;
	
		y = domElement.offsetTop;
	
		if ( domElement.offsetParent != null ) {
			y +=Element.getPageOffsetTop( domElement.offsetParent );
		}
	
		return y;
	},
	
	
	getPageOffsetLeft: function( domElement )
	{
		var x;
	
		x = domElement.offsetLeft;
		
		if ( domElement.offsetParent != null ) {
			x += Element.getPageOffsetLeft( domElement.offsetParent );
		}
	
		return x;
	},
	
	
	create: function(tagName, id, width, height, left, top)
	{
		try {
			var newElement = document.createElement(tagName);
			newElement.setAttribute( 'id', id );
			
			var width = ( width == null ) ? 100 : width;
			var height = ( height == null ) ? 25 : height;
			
			Element.setDimension( newElement, width, height );
			
			if ( left != null || top != null ) {
				newElement.style.position = "absolute";
				Element.setPosition( newElement, top, left );
			}
		
			return newElement;
		} catch (e) {
			if (e instanceof Error)
				throw new Error('Element::create(): ' + e.name + ' ' + e.message);
		}
	},
	
	
	getIEWidth: function( element )
	{
		var width = parseInt(element.offsetWidth);
		var offset = 0;
		
		
		if (!is.ie5 && !is.ie5_5) {
			var offset = Element.getIEBoxWidthOffset( element );
		}
			
		return width - offset;
	},
	
	
	getIEHeight: function( element )
	{
		var height = parseInt(element.offsetHeight);
		var offset = 0;
		
		
		if (!is.ie5 && !is.ie5_5) {
			var offset = Element.getIEBoxHeightOffset( element );
		}
			
		return height - offset;
	},
	
	
	getIEBoxWidthOffset: function( element )
	{
		var paddingLeft 	= Element.getStyle( element, 'padding-left' );
		var paddingRight 	= Element.getStyle( element, 'padding-right' );
		
		var borderLeft		= Element.getStyle( element, 'border-left-width' );
		var borderRight 	= Element.getStyle( element, 'border-right-width' );
		
		paddingLeft 	= (paddingLeft) ? isNaN(parseInt(paddingLeft)) ? 0 : parseInt(paddingLeft) : 0;
		paddingRight 	= (paddingRight) ? isNaN(parseInt(paddingRight)) ? 0 : parseInt(paddingRight) : 0;
		
		borderLeft 		= (borderLeft) ? isNaN(parseInt(borderLeft)) ? 0 : parseInt(borderLeft) : 0;
		borderRight 	= (borderRight) ? isNaN(parseInt(borderRight)) ? 0 : parseInt(borderRight) : 0;
	
		return borderLeft + borderRight + paddingLeft + paddingRight;
	},
	
	
	getIEBoxHeightOffset: function( element )
	{
		var paddingTop	= Element.getStyle( element, 'padding-top' );
		var paddingBot 	= Element.getStyle( element, 'padding-bottom' );
		
		var borderTop	= Element.getStyle( element, 'border-top-width' );
		var borderBot 	= Element.getStyle( element, 'border-bottom-width' );
		
		paddingTop = (paddingTop) ? isNaN(parseInt(paddingTop)) ? 0 : parseInt(paddingTop) : 0;
		paddingBot = (paddingBot) ? isNaN(parseInt(paddingBot)) ? 0 : parseInt(paddingBot) : 0;
		
		borderTop = (borderTop) ? isNaN(parseInt(borderTop)) ? 0 : parseInt(borderTop) : 0;
		borderBot = (borderBot) ? isNaN(parseInt(borderBot)) ? 0 : parseInt(borderBot) : 0;
		
		return borderTop + borderBot + paddingTop + paddingBot;
	},

	
	getElementsByTagName: function( element, tagName ) 
	{
		return element.getElementsByTagName( tagName );
	},
	
	getAttributeValue: function( element, attribute, defaultValue )
	{
		var attributeValue = element.getAttribute( attribute );
	
		if (!attributeValue) {
			if ( defaultValue != null )
				return defaultValue;
				
			return false;
		}
		
		switch (attributeValue) {
			case 'true':
				attributeValue = true;
				break;
			case 'false':
				attributeValue = false;
				break;
			default:
				break;
		}
	
		return attributeValue;
	},
	
	setDimension: function( element, width, height )
	{
		try {
			var element = $(element);
		
			if (typeof width != 'string')
				width += 'px';
			
			if (typeof height != 'string')
				height += 'px';
			
			element.style.width = width;
			element.style.height = height;
		} catch(e) {
			if (e instanceof Error)
				throw new Error('Element::setDimension(): ' + e.name + ' ' + e.message);
		}
	},
	
	setPosition: function( element, top, left ) 
	{
		try {
			var element = $(element);
			
			if (typeof top != 'string')
				top += 'px';
			
			if (typeof left != 'string')
				left += 'px';
				
			element.style.top = top;
			element.style.left = left;
		} catch (e) {
			if (e instanceof Error)
				throw new Error('Element::setPosition(): ' + e.name + ' ' + e.message);
		}
	},
	
	getChildNodesByTagName: function( element, tagName )
	{
		var cNodes = [];
		var element = $(element);
		
		for (var i=0; i < element.childNodes.length; i++) {
			if (element.childNodes[i].nodeType == 1 && element.childNodes[i].tagName.toLowerCase() == tagName.toLowerCase()) {
				cNodes[cNodes.length] = element.childNodes[i];
			}
		}
				
		return cNodes;
	},
	
	getFirstChildByTagName: function( element, tagName )
	{	
		for (var i=0; i < element.childNodes.length; i++) {
			if (element.childNodes[i].nodeName.toLowerCase() == tagName.toLowerCase()) {
				return element.childNodes[i];
			}
		}
		
		return false;
	},
	
	getFirstChild: function( element )
	{
		for (var i=0; i < element.childNodes.length; i++) {
			if ( element.childNodes[i].nodeType == 1 ) {
				return element.childNodes[i];
			}
		}
		
		return false;
	},
	
	getParentAttributeValue: function(element, attribute, defaultValue)
	{
		while (element != null && element.nodeType != 9 ) {
			if (element.getAttribute( attribute ) ) {
				return element.getAttribute( attribute );
			}
			
			element = element.parentNode;
		}
		
		if ( !isEmptyValue( defaultValue ) ) {
			return defaultValue;
		}
		
		return false;
	},
	
	
	getParentElementByTagName: function( element, tagName, checkelement )
	{
		var tagName = tagName.toLowerCase();
		
		if (checkelement != null && checkelement) {
			if( element.tagName.toLowerCase() == tagName.toLowerCase() ) {
				return element;
			}
		}
			
		while (element != null && element.nodeType != 9) {
	    	if (element.nodeType == 1 && element.tagName.toLowerCase() == tagName.toLowerCase()) {
	    		return element;
	    	}
	      	
	    	element = element.parentNode;
		}
		
		return false;
	},
	
	
	getParentElementByTagNameAndAttribute: function( element, tagName, attribute, checkelement )
	{
		if (element == null) {
			var element = element.parentNode;
		}
		
		var tagName = tagName.toLowerCase();
		
		if (checkelement != null && checkelement) {
			if ( element.tagName.toLowerCase() == tagName.toLowerCase() && element.getAttribute( attribute ) ) {
				return element;
			}
		}
		
		while ( element != null && element.nodeType != 9) {
			if (element.nodeType == 1 && element.tagName.toLowerCase() == tagName.toLowerCase() && element.getAttribute( attribute ) ) {
				return element;
			}
			
			element = element.parentNode;
		}
		
		return false;
	},
	
	
	getParentElementByNodeType: function( element, nodeType, checkelement)
	{	
		while (element != null && element.nodeType != 9) {
	    	if (element.nodeType != null && element.nodeType == nodeType) {
	    		return element;
	    	}
	      	
	    	element = element.parentNode;
		}
		
		return false;
	},
	
	getInnerText: function( element )
	{
		if (typeof(element) == "string")
			var element = $( element );
			
		if (typeof element == "undefined")
			return element;
		
		if (element.innerText)
			return element.innerText;
			
		var text 		= "";
		var childNodes 	= element.childNodes;
		var length 		= element.childNodes.length;
		
		for (var i = 0; i < length; i++) {
			switch (childNodes[i].nodeType) {
				case 1:
					text += Element.getInnerText(childNodes[i]);
					break;
				case 3:
					text += childNodes[i].nodeValue;
					break;
			}
		}
		
		return text;
	},
	
	hasChildNodesWithNodeType: function( element, nodeType )
	{
		if (nodeType == null) {
			var nodeType = 1;
		}
		
		for (var i=0; i < element.childNodes.length; i++) {
			if (element.childNodes[i].nodeType == nodeType) { 
				return true;
			}
		}
			
		return false;
	},
	
	hasChildNodesWithTagName: function( element, tagName )
	{
		for (var i=0; i < element.childNodes.length; i++) {
			if (element.childNodes[i].nodeName == tagName) {
				return true;
			}
		}
				
		return false;
	},
	
	
	
	hasParentWithAttribute: function( element, attribute )
	{
		while ( element != null && element.nodeType != 9 ) {
			if ( element.hasAttribute ) {
				if ( element.hasAttribute( attribute) ) {
					return true;
				}
			} else {
				if ( element.getAttribute( attribute ) != null ) {
					return true;
				}
			}
			
			element = element.parentNode;
		}
		
		return false;
	},
	
	
	hasParentWithAttributeValue: function( element, attribute, value )
	{
		while (element != null && element.nodeType != 9) {
			attributeValue = element.getAttribute( attribute );
			
			if (attributeValue != null && attributeValue == value) {
				return true;
			}
			
			element = element.parentNode;
		}
		
		return false;
	},
	
	
	isChildOf: function( element, type )
	{
		var parentItem = element.parentNode;
		
		while(parentItem != null && parentItem.nodeType != 9) {
			if (parentItem.nodeName == 'DIV' && ( parentItem.getAttribute( 'ektype' ) == type || parentItem.getAttribute( 'ctrltype' ) == type)) {
				return parentItem.id;
			}
			
			parentItem = parentItem.parentNode;
		}
		
		return false;
	},
	
	
	isInTab: function( id )
	{
		var parentItem = $(id).parentNode;
		
		while(parentItem != null && parentItem.nodeType != 9) {
			if (parentItem.nodeName == 'DIV' && parentItem.getAttribute('ctrltype') == 'tabpanel') {
				return parentItem.id;
			}
			
			parentItem = parentItem.parentNode;
		}
		
		return false;
	},
	
	
	isInTable: function( element )
	{
		var parentItem = $(element).parentNode;
	
		while(parentItem != null && parentItem.nodeType != 9 ) {
			if (parentItem.nodeName == 'TABLE' && parentItem.getAttribute('ektype') == 'Table') {
				return parentItem.id;
			}
			
			parentItem = parentItem.parentNode;
		}
		
		return false;
	},
	
	
	allowSelect: function( element )
	{
		var element = $( element );
	
		if (element.onselectstart) {
			Event.observe( element, 'selectstart', Event.stop );
		}
	},
	
	_toggle: function() {
		for (var i = 0; i < arguments.length; i++) {
			var element = $(arguments[i]);
			
			if( element == null ) {
				return;
			}
			
			Element[Element.visible(element) ? 'hide' : 'show'](element);
		}
	},
	
	_hide: function() {
		for (var i = 0; i < arguments.length; i++) {
			var element = $(arguments[i]);
			
			if ( element == null ) {
				return;
			}
			
			if ( dialog && element ) {
				if ( dialog[arguments[i]] ) {
					dialog[element.id].hide();
					return;
				}
			}	 
			
			element.style.visibility = 'hidden';
		}
	},
	
	_show: function() {
		for (var i = 0; i < arguments.length; i++) {
			var element = $(arguments[i]);
			
			if ( element == null ) {
				return;
			}
			
			if ( dialog && element ) {
				if ( dialog[arguments[i]] ) {
					dialog[element.id].show();
					return;
				}
			} 
			
			element.style.visibility = 'visible';
		}
	}
});

if ( is.ie5_5 || is.ie5) {
	document._getElementsByTagName = document.getElementsByTagName;
	document.getElementsByTagName = function ( sTagName )
	{
		if ( sTagName == "*" ) {
			return document.all;
		} else {
			return document._getElementsByTagName( sTagName );
		}
	};
}

Object.extend( Event, 
{
	getModifier: function( evt ) 
	{
		if (window.event)
			evt = window.event;
			
		if ( evt.altKey )
			return 'alt';
			
		if ( evt.ctrlKey ) {
			return 'ctrl';
		}
		
		if ( evt.shiftKey ) {
			return 'shift'
		}
		
		return false;
	}
});

Object.extend( Form, 
{
	
	serializeElements: function(elements, getHash) 
	{
    	var data = elements.inject({}, function(result, element) 
    	{
    		if ( element.name) 
    		{
        		var key = element.name, value = $(element).getValue();
	        	
        		if (value != undefined) 
        		{
	          		if (result[key]) 
	          		{
	            		if (result[key].constructor != Array) result[key] = [result[key]];
	            		{
	            			result[key].push(value);
	            		}
	          		}
	          		else 
	          		{
	          			result[key] = value;
	          		}
	        	}
      		}
      	
      		return result;
    	});

   		return getHash ? data : Hash.toQueryString(data);
  	},
  	
	getHidden: function(form) 
	{
	    var elements = Form.getElements($(form));
	    var queryComponents = new Array();
	
	    for (var i = 0; i < elements.length; i++) {
	      var queryComponent = Form.Element.serialize(elements[i]);
	      if (queryComponent)
	        queryComponents.push(queryComponent);
	    }
	
	    return queryComponents;
  	},
  	
	validate: function(form) 
	{
		var form = $(form);
		var elements = Form.getElements(form);
		
    	for (var i = 0; i < elements.length; i++) {
      		var element = elements[i];
      		
      		if ( !Form.Element.required( element ) || !Form.Element.validate( element ) ) {
      			
      			Field.focus( element );
      			return false;
      		}
    	}
    	
    	return true;
  	},
  	
  	
	getIdx: function( form )
	{
		if (form == null) {
			formIdx = 0;
		}
	
		if ( document.forms.length == 0 ) {
			return false;
		}
			
		for (var i=0; i < document.forms.length; i++) {
			if (document.forms[i].name == form) {
				formIdx = i;
			}
		}
		
		return formIdx;
	},
	
  	
	insertNew: function (type, name, value, form )
	{
		var idx = Form.getIdx( form );
		var form = document.forms[idx];
		
		if (value == null)
			value = '';
		
		if ( form[name] != null ) {
			form[name].value = value;
			return form[name];
		}
		
		var field = Form.Element.getNewInput( name, value, type );
		form.appendChild( field );
		
		return field;
	},
	
	
	insertHidden: function( name, value, form )
	{
		return Form.insertNew( 'hidden', name, value, form );
	}
});

Object.extend( Form.Element,
{
	validate: function( element )
	{
		var element 	= $(element);
		
		var obj 		= new Object();
		obj.validator 	= '';
		
		var rules 		= Element.getAttributeValue( element, 'validationrules' );
		
		if ( rules )
		{
			var obj 	= Util.getJSObject( rules );
		}

		eval( "var validator = new EasyGUI_" + obj.validator + "Validator( obj );" );
	
		if ( !validator )
		{
			eval( "var validator = new " + obj.validator + "( obj );" );
	
			if ( !validator )
			{
				throw new Error('EasyGUI Form Validator: The validator: ' + obj.validator + ' you indicated on Element: ' + element.id + ' is not implemented !');
			}
		}

		return ( validator.validate( element ) );
	},
	
	required: function( element ) 
	{
		var element = $(element);
		
		if ( !Element.getAttributeValue( element, 'required' ) )
		{
			return true;
		}
			
		var value 	= $F(element);
		var valid = false;
		
		var rules 		= Element.getAttributeValue( element, 'validationrules' );
		
		if ( rules )
		{
			var obj 	= Util.getJSObject( rules );
			var custommsg = dialog.getMessage( obj.messages['required'] );
		} 
		else 
		{
			var custommsg = dialog.getMessage( Element.getAttributeValue(element, 'validationerrormsg', '') );			
		}
		
		switch ( element.type ) {	
			case 'checkbox':
				valid = element.checked;
				defaultmsg 	= element.id + " is required to be checked !";
				break;
				
			case 'select-one':
				valid = (element.selectedIndex != 0);
				defaultmsg	= element.id + " You have to make a selection !";
				break;
				
			case 'select-multiple':
				var selectallitems = Element.getAttributeValue( element, 'selectallitems' );
				
				if ( selectallitems ) 
				{
					valid = ( element.options.length > 0 );
				} 
				else 
				{
					valid = ( element.selectedIndex != -1);
				}
				
				defaultmsg = element.id + " You have to make at least one selection !";
				break;
				
			default:
				valid = ( value != '' );
				defaultmsg 	= element.id + " is a required field !";
				break;
		}
		
		if (!valid) 
		{
			var msg = ( custommsg == '' ) ? defaultmsg : custommsg;
			alert( msg );
		}
		
		return valid;
	},
	
	
	setValue: function(field, value, form)
	{
		try 
		{
			if (form == null)
			{
				form = 0;
			}
		
			var form = document.forms[form];
	
			if (form[field] != null)
			{
				form[field].value = value;
			}
		} 
		catch (e) 
		{
			if (e instanceof Error)
			{
				throw new Error('Form::setValue(): ' + e.name + ' ' + e.message);
			}
		}
	},
	
	
	getNewInput: function( name, value, type )
	{
		switch ( type.toLowerCase() ) 
		{
			case 'submit':
			case 'hidden':
			case 'password':
			case 'text':
			case 'checkbox':
			case 'radio':
				break;
				
			default:
				type = 'text';
				break;
		}
		
		try 
		{
			var field 	= document.createElement('input');
		
			field.type 	= type;
			field.id	= name;
			field.name	= name;
			field.value	= value;
		
			return field;
		} 
		catch (e) 
		{
			if (e instanceof Error)
			{
				throw new Error('Form::getNewInput(): ' + e.name + ' ' + e.message);
			}
		}
	},
	
	
	isEmpty: function( element )
	{
		var element = $(element);
		var value 	= $F(element);
		
		return ( value == '' || value == null );
	},

	
	disable: function( element ) 
	{
		$(element).disabled = 'true';
	},
	
	enable: function( element ) 
	{
		$(element).disabled = '';
	}
});

Object.extend( Form.Element.Serializers, 
{
	inputSelector: function(element) 
	{
		if (element.checked) 
		{
			return ( element.value == 'on' || element.value == '' ) ? 'true' : element.value;
		}
			
		return (element.type.toLowerCase() == 'radio') ? "" : 'false';
	},
	
	selectMany: function(element) 
	{
		var value = new Array();
		
		var addremove = element.getAttribute('addremove');
		var selectall = element.getAttribute('selectallitems');
		
		if ( addremove || selectall ) 
		{
			for (var i = 0; i < element.length; i++) 
			{
				var opt = element.options[i];
				var optValue = opt.value;
				
				if ( !optValue && !('value' in opt ) )
				{
					optValue = opt.text;
				}
					
				value.push(optValue);
			}
		} 
		else 
		{
			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);
				}
			}
		}
		
		return value;
	}	
});



function noSelect(evt)
{
	var element = $GE(evt);
	
	if (element.type == "text" || element.nodeName == 'TEXTAREA')
	{
		return true;
	}
	
	return false;
}


function isEmptyValue( value )
{
	switch(value) 
	{
		case 'undefined':
		case null:
		case '0':
		case '':
		case false:
		
			return true;
			break;
	}
	
	return false;
}


function sleep( ms )
{
	if ( !ms ) 
	{
		return;
	}
	
	var d = new Date();
	
	while ( true )	
	{
		var mill = new Date();
		var diff = mill - d;
		
		if( diff > ms) 
		{ 
			break;
		}
	}
}


function toggleEnterKey(evt)
{
	var element = $GE(evt);
	
	var keyCode = 	evt.keyCode ? evt.keyCode :
               		evt.charCode ? evt.charCode :
					evt.which ? evt.which : void 0;
					
	if (element.nodeName != 'INPUT' || (keyCode && keyCode != 13)) 
	{
		return;
	}

	if ( keyCode && window.event && !window.opera ) 
	{
		window.event.keyCode = 9;
		return true;
	} 
	else if (evt.keyCode) 
	{
		
		//return evt.which = 9;
	}
}


function changeKey (textControl, evt, keyChecker) 
{
	var keyCode = 	evt.keyCode ? evt.keyCode :
               		evt.charCode ? evt.charCode :
					evt.which ? evt.which : void 0;
				
  	var key;
  
	if (keyCode)
	{
	  	key = String.fromCharCode(keyCode);
	}

	var keyCheck = keyChecker(keyCode, key);

	if (keyCode && window.event && !window.opera)
	{
	    if (keyCheck.cancelKey)
	    {
	    	return false;
	    } 
	    else if (keyCheck.replaceKey) 
	    {
	    	window.event.keyCode = keyCheck.newKeyCode;
	    	
	      	if (window.event.preventDefault)
	      	{
	      		window.event.preventDefault();
	      	}
	      	
	     	return true;
	    } 
	    else
	    {
	      	return true;
	    }
	  } 
	  else if (typeof textControl.setSelectionRange != 'undefined') 
	  {
	    	if (keyCheck.cancelKey) 
	    	{
	      		if (evt.preventDefault)
	      		{
	        		evt.preventDefault();
	      		}
	      		
	      		return false;
	    	} 
	    	else if (keyCheck.replaceKey) 
	    	{
    			// cancel the key event and insert the newKey for the current selection
	      		if (evt.preventDefault)
	      		{
		  			evt.preventDefault();
	      		}
	      		
	      		var oldSelectionStart = textControl.selectionStart;
	      		var oldSelectionEnd = textControl.selectionEnd;
	      		var selectedText = textControl.value.substring(oldSelectionStart, oldSelectionEnd);
	      		var newText = typeof keyCheck.newKey != 'undefined' ? keyCheck.newKey : String.fromCharCode(keyCheck.newKeyCode);
	      		
	      		textControl.value = textControl.value.substring(0, oldSelectionStart) + newText +
	        						textControl.value.substring(oldSelectionEnd);
	      
	        	textControl.setSelectionRange(oldSelectionStart + newText.length, oldSelectionStart + newText.length);
	      		return false;
	    	} 
	    	else
	    	{
	      		return true;
	    	}
	  } 
	  else if (keyCheck.cancelKey) 
	  {
	    	if (evt.preventDefault)
	    	{
	      		evt.preventDefault();
	    	}
	      		
	    	return false;
	  } 
	  else
	  {
			return true;
	  }
}




function lettersToUpperCase (keyCode, key)
{
	var newKey = key.toUpperCase();
	
  	if (newKey != key)
  	{
    	return { replaceKey: true, newKeyCode: newKey.charCodeAt(), newKey:newKey };
  	}
  	else
  	{
   		return { cancelKey: false };
  	}
}


function digitsToX (keyCode, key)
{
	if ("0123456789".indexOf(key) != -1)
	{
		return { replaceKey: true, newKeyCode: "X".charCodeAt(), newKey: "X" };
	}
	else
	{
		return { cancelKey: false };
	}
}


function cancelDigits (keyCode, key) 
{
 	return { cancelKey: "0123456789".indexOf(key) != -1 };
}



var Util = 
{
	getJSObject: function ( literal ) 
	{
		try 
		{
			eval ( "obj = " + literal + ";" );
			return ( typeof obj != 'number' ) ? obj : false;
		} 
		catch( e ) 
		{
			return false;
		}
	},
	
	getIframe: function() 
	{
		var myframe = document.createElement("IFRAME");
		myframe.frameBorder = 0;
		myframe.scrolling = 'no';
		myframe.src = "javascript: false";
	
		return myframe;
	}
};

var Sort = 
{
	
	compareValues: function(a, b)
	{
		if ( typeof a.value != "undefined" )
		{
			a = a.value;
		}
			
		if ( typeof b.value != "undefined" )
		{
			b = b.value;
		}
			
		if ( a == null || a == 'undefined' || a === false )
		{
			return -1;
		}
		
		if ( b == null || b == 'undefined' || b === false )
		{
			return 1;
		}
	
		var res;
		
		if ( a.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/) || a.match(/^\d\d[\/-]\d\d[\/-]\d\d$/) ) 
		{
			if (a.length == 10) 
			{
		        var date1 = a.substr(6,4) + a.substr(3,2) + a.substr(0,2);
		    } 
		    else 
		    {
		        var year = a.substr(6,2);
		
		        if ( parseInt( year ) < 50 ) 
		        {
		        	year = '20' + year; 
		        } 
		        else 
		        {
		        	year = '19' + year;
		        }
		        
		        date1 = year + a.substr(3,2) + a.substr(0,2);
		    }
		    
		    if (b.length == 10) 
		    {
		        var date2 = b.substr(6,4) + b.substr(3,2) + b.substr(0,2);
		    } 
		    else 
		    {
		        var year = b.substr(6,2);
		        
		        if (parseInt(year) < 50) 
		        {
		        	year = '20' + year;
		        } 
		        else 
		        {
		       		year = '19' + year;
		        }
		       		
		        date2 = year + b.substr(3,2) + b.substr(0,2);
		    }
		    
		    if (date1 == date2)
		    {
		    	res = 0;
		    }
		    	
		    if ( date1 < date2 )
		    {
		    	res = -1;
		    }
	    	
	    	res = 1;
	    
		} 
		else if ( a.match(/^[��$]|EURO/) || a.match(/[\d\.]\s+(EURO|[��$])/) ) 
		{
			//alert(" a before replace: " + a + " b before replace: " + b + "!");
			
			var c = a.replace(/[^0-9.]/g,'');
	    	var d = b.replace(/[^0-9.]/g,'');
			//alert("a has type " + typeof(a) + " and value " + a + "|b has type " + typeof(b) + " and value: " + b);
			    
	    	res = parseFloat(c) - parseFloat(d); 
	    
		} 
		else if (!isNaN( parseInt(a) ) && !isNaN( parseInt(b) ) ) 
		{
			if ( a.indexOf('.') != -1 || a.indexOf(',') != -1 ) 
			{
				
				var c = parseFloat(a);
	    
	    		if (isNaN(c)) 
	    		{
	    			c = 0;
	    		}
	    
	    		var d = parseFloat(b);
	    
	    		if (isNaN(d)) 
	    		{
	    			d = 0;
	    		}
	    	
	    		res = c - d;
			} 
			else 
			{
				
				res = parseInt( a ) - parseInt( b);
			}
		} 
		else 
		{
			
			res = 1;
			
			if ( a == b ) 
			{
	    		res = 0;
			}
	    	
	   		if ( a < b ) 
	   		{
	    		res = -1;
	   		}
		}
		
		if (descend) 
		{
	    	res = res * -1;
		}
	
	    return res;
	}
};

var DateTime = {
	
	isFutureDate: function( dateStr, format)
	{
		var parts 	= DateTime.getParts( dateStr, format );
		
		var day		= DateTime.getPart(parts, 'd', format);
		var month	= DateTime.getPart(parts, 'm', format);
		var year	= DateTime.getPart(parts, 'y', format);
		
		var today = new Date();
		
		if (parseFloat(year) <= 50) {
			year = (parseFloat(year) + 2000).toString(); 
		}
		
		if (parseFloat(year) <= 99) {
			year = (parseFloat(year) + 1900).toString();
		}
		
		var dt = new Date(parseFloat(year), parseFloat(month), parseFloat(day), 0, 0, 0, 0);
		
		var tim1 = dt.getTime();
		var tim2 = today.getTime();
		
		if (tim1 > tim2) {
			return true;
		}
		
		return false;
	},
	
	
	isValidDate: function( dateStr, format )
	{
		var parts 	= DateTime.getParts( dateStr, format );
		
		if ( !parts) {
			return false;
		}
		
		var day		= DateTime.getPart(parts, 'd', format);
		var month	= DateTime.getPart(parts, 'm', format);
		var year	= DateTime.getPart(parts, 'y', format);
		
		if (parseFloat(year) <= 50) {
			year = (parseFloat(year) + 2000).toString(); 
		}
		
		if (parseFloat(year) <= 99) {
			year = (parseFloat(year) + 1900).toString();
		}
		
		var dt = new Date(parseFloat(year), parseFloat(month), parseFloat(day), 0, 0, 0, 0);
		
		if (parseFloat(day) != dt.getDate()) {
			return false;
		}
		
		if (parseFloat(month) != dt.getMonth()) {
			return false; 
		}
		
		return true;
	},
	
	
	getFormat: function( format )
	{
		if (format == null) {
			format = "dmy";
		}
		
		format = format.toLowerCase();
		
		if (format.length != 3) {
	   		format = "dmy";
		}
		   
	   	if ( (format.indexOf("m") == -1) || (format.indexOf("d") == -1) || (format.indexOf("y") == -1) ) {
	      	format = "dmy";
	   	}
	   	
	   	return format;
	},
	
	
	getParts: function(dateStr, format)
	{
		var format = DateTime.getFormat( format );
		
	   	if (format.substring(0, 1) == "y") { // If the year is first
	    	var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/;
	      	var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/;
	   	} else if (format.substring(1, 2) == "y") { // If the year is second
	    	var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/;
	      	var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/;
	   	} else { // The year must be third
	    	var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/;
	      	var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
	   	}
	
	   	if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) {
	   		return false; 
	   	}
	   
	   	var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
	   	return parts;
	},
	
	
	getPart: function(parts, part, format)
	{
		if (part == null) {
			part = 'y';
		}
			
		var part = part.toLowerCase();
		
		if (part != 'm' && part != 'y' && part != 'd') {
			return false;
		}
			
		var format = DateTime.getFormat( format );
		
	   	if (format.substring(0, 1) == part) {
	   		var result = parts[0]; 
	   	} else if (format.substring(1, 2) == part) {
	   		var result = parts[1];
	   	} else {
	   		var result = parts[2];
	   	}
	   	
	   	if ( part == 'm' ) {
	   		return result - 1;
	   	}
	   	
	   	return result;
	},
	
	
	isValidTime: function(hour)
	{
		return /^([01]?[0-9]|[2][0-3])(:[0-5][0-9])?$/.test(hour);
	}
};
function JS_Timer()
{
	// PRIVATE PROPERTIES

    
    this._starttime = '';
    
    this._endtime = '';
    
    this._elapsedtime = '';
   
    
    this.startTimer = function()
    {
        mtime = new Date();
        this._starttime = mtime.getTime();
    };

    
    this.stopTimer = function()
    {
        mtime = new Date();
        this._endtime = mtime.getTime();
        this._setElapsedTime();

        // We are going to assume that when the timer is stopped
        // they will want the elapsed time immediately
        return this.getElapsedTime();
    };

    
    this.restart = function()
    {
        this._endtime = '';
        this._elapsedtime = '';
        
        this.startTimer();      
    };

    
    this.getElapsedTime = function()
    {
        return ( this._elapsedtime / 1000 );
    };

    // PRIVATE METHODS

    
    this._setElapsedTime = function()
    {
        this._elapsedtime = this._endtime - this._starttime;
    };
}

var EasyGUI_Validator = Class.create();

EasyGUI_Validator.prototype = 
{
	initialize: function( obj ) 
	{
		this.rules		= [];
		this.element 	= null;
		this.value		= null;
		this.valid 		= true;
		
		Object.extend( this, obj );
	},
	
	// Check if there's a possibility for sprintf
	
	throwMessage: function( rule )
	{
		if ( this.valid )
		{
			return;
		}
			
		var rule = ( !rule ) ? 'invalid' : rule;
		
		for ( msg in this.messages )
		{
			if ( msg == rule )
			{
				var message = 'No message for ' + rule;
				
				if ( $( this.messages[rule] ) )
				{
					message = dialog.getMessage( this.messages[rule] );
				}
			}
		}
		
		alert( message );
		//alert( message.replace('%d', value) );
	},
	
	validate: function( element ) 
	{
		this.element 	= $( element );
		this.value		= $F( element );
	
		this.valid 		= this.isvalid();
		
		if ( !this.valid )
		{
			this.throwMessage( 'invalid' );
			return this.valid;
		}
		
		var rule = null;
		
		for ( var i=0; i < this.rules.length; i++ )
		{
			var method = this.rules[i][0];
			var value  = this.rules[i][1];
			
			if ( this[method] ) 
			{
				if ( ! (this.valid = this[method].call( this, value ) ) )
				{
					break;
				}
			}
		}
		
		this.throwMessage( method );
		return this.valid;
	},
	
	
	isvalid: function()
	{
		return true;
	},
	
	maxlength: function( value )
	{
		return ( this.value.length < parseFloat( value ) );
	},
	
	minlength: function( value )
	{
		return ( this.value.length > parseInt( value ) );
	},
	
	minvalue: function( value )
	{
		return ( this.value > parseFloat( value.replace( ',','.' ) ) );
	},
	
	maxvalue: function( value )
	{
		return ( this.value < parseFloat( value.replace( ',','.' ) ) );
	},

	range: function( value ) 
	{
		return ( this.value > parseFloat( value.replace(',','.') ) && 
				 this.value < parseFloat( value.replace(',','.') ) );
	}		
}
var EasyGUI_DateValidator = Class.create();

EasyGUI_DateValidator.format = 'dmy';

EasyGUI_DateValidator.messages =
{
	invalid: 	'%d is not a valid date !',
	nofuture:	'Future date is not allowed !',
	before: 	'Date has to be before %d !',
	after: 		'Date has to be after %d !'
}

Object.extend( Object.extend( EasyGUI_DateValidator.prototype, EasyGUI_Validator.prototype ), 
{	
	isvalid: function()
	{
		return DateTime.isValidDate( this.value, this.format );
	},
	
	nofuture: function()
	{
		return !DateTime.isFutureDate( this.value, this.format );
	},
	
	
	before: function( value )
	{
		return true;
	},
	
	
	after: function( value )
	{
		return true;
	}
});
var EasyGUI_AlphaValidator = Class.create();

EasyGUI_AlphaValidator.messages = 
{
	invalid: 'Only alphanumeric values allowed !'
}

Object.extend( Object.extend ( EasyGUI_AlphaValidator.prototype, EasyGUI_Validator.prototype ),
{
	isvalid: function()
	{
		return( !isNaN( value ) && value != '' );
	}
});
var EasyGUI_EmailValidator = Class.create();

EasyGUI_EmailValidator.messages = 
{
	invalid: '%d is not a valid email adress !'
}

Object.extend( Object.extend ( EasyGUI_EmailValidator.prototype, EasyGUI_Validator.prototype ),
{
	isvalid: function()
	{
		return (!this.value.match(/.*\@.*\..*/));
	}
});
var EasyGUI_NumericValidator = Class.create();

EasyGUI_NumericValidator.messages = 
{
	minvalue: 'Only values > %d allowed',
	maxvalue: 'Only values < %d allowed',
	invalid: 'Only numeric values allowed',
	range: 'Value is out of range [%d to %d]'
}

Object.extend( Object.extend ( EasyGUI_NumericValidator.prototype, EasyGUI_Validator.prototype ),
{
	isvalid: function() 
	{
		return ( isNaN( this.value ) );
	}
});
var EasyGUI_TimeValidator = Class.create();

EasyGUI_TimeValidator.messages = 
{
	invalid: '%d is not a valid time !'
}

Object.extend( Object.extend ( EasyGUI_TimeValidator.prototype, EasyGUI_Validator.prototype ),
{
	isvalid: function()
	{
		return DateTime.isValidTime( this.value );
	}
});

function guiWindow(id, obj)
{
	
	this.id = id;
	
	
	this.obj = obj;
	
	
	this.intervalHandler = null;
}

function windowRegistry()
{
	
	this.registry = new Array();
	
	
	this.registerWindow = function(win)
	{
		this.registry.push(win);
	};
	
	
	this.getGuiWindow = function(id)
	{
		for (var i=0; i < this.registry.length; i++) {
			if (this.registry[i] != null) {
				if (this.registry[i].id == id) {
					return this.registry[i];
				}
			}
		}
		
		return false;
	};
	
	
	this.startModalObserver = function(id)
	{
		var observable = this.getGuiWindow(id);
		
		if (!observable) {
			return;
		}
		
		observable.intervalHandler = setInterval("observeModalWindow('" + id + "')", 100);
	};
	
	
	this.removeWindow = function(id)
	{
		for (var i=0; i < this.registry.length; i++) {
			if (this.registry[i] != null && this.registry[i].id == id) {
				this.registry[i] = null;
			}
		}
	};
}


function observeModalWindow(id)
{
	var observable = gui.winRegistry.getGuiWindow(id);

	if (observable.obj.closed == true) {
		clearInterval(observable.intervalHandler);
		gui.winRegistry.removeWindow(id);
		gui.enableDialog();
	}
}


function getWindowName()
{
	return self.name;
}


function getOpener()
{
	if (self.opener == null) return false;	
	return self.opener;
}


function getTopWindow()
{
	if (self.opener == null) return self;
	
	var win = self.opener;
	
	while (win.opener != null) {
		win = win.opener;
	}
	
	return win;
}


var EasyGUI_widget = Class.create();

EasyGUI_widget.prototype = 
{
	
	initialized: false,
	
	
	element: null,
	
	
	widgetElements: [],
	
	
	widget: null,
	
	
	isInTable: false,
	
	
	initialize: function( id )
	{
		this.id = id;
		this.element = $(id);
		this.isInTable = ( Element.isInTable( this.id ) ) ? true : false;
	},
	
	
	setAction: function( action ) 
	{
		this.element.setAttribute( 'action', action );
	},
	
	
	render: function() 
	{
		;
	},
	
	
	update: function()
	{
		;
	},
	
	
	finalize: function() 
	{
		this.initialized = true;
	},
	
	
	destroy: function()
	{
		this.element = null;
		this.widget = null;
	},
	
	
	getClassName: function()
	{
		return this.element.className;
	},
	
	
	getStyleDefinition: function( def )
	{
		return this.element.className + '-' + def;
	},
	
	
	toString: function() 
	{
		return 'object EasyGUI_Widget(' + this.id + ')';
	},
	
	
	getOffsetLeft: function() 
	{
		return parseInt(this.element.offsetLeft);
	},
	
	
	getPageOffsetLeft: function() 
	{
  		return Position.cumulativeOffset( this.element )[0];
	},
	
	
	getOffsetTop: function() 
	{ 
		return parseInt(this.element.offsetTop);
	},
	
	
	getPageOffsetTop: function() 
	{
		return Position.cumulativeOffset( this.element )[1];
	},
	
	
	getOffsetWidth: function() 
	{ 
		return parseInt( this.element.offsetWidth ); 
	},

	
	getOffsetHeight: function() 
	{
		return parseInt( this.element.offsetHeight );
	},
	
	
	getStyleLeft: function() 
	{
		return parseInt( this.element.style.left );
	},
	
	
	getStyleTop: function() 
	{ 
		return parseInt( this.element.style.top );
	},
	
	
	getStyleWidth: function() 
	{ 
		return parseInt( this.element.style.width ); 
	},

	
	getStyleHeight: function() 
	{
		return parseInt( this.element.style.height );
	},
	
	
	moveLeft: function(pixels) 
	{
		this.element.style.left = ( this.getStyleLeft( ) - parseInt( pixels ) ) + 'px';
	},
	
	
	moveRight: function(pixels) 
	{
		this.element.style.left = ( this.getStyleLeft( ) + parseInt( pixels ) ) + 'px';
	},
	
	
	moveUp: function(pixels) 
	{
		this.element.style.top = ( this.getStyleTop() - parseInt( pixels ) ) + 'px';
	},
	
	
	moveDown: function(pixels) 
	{
		this.element.style.top = ( this.getStyleTop() + parseInt(pixels)) + 'px';
	},
	
	
	setPosition: function( top, left ) 
	{
		var top = ( typeof top == 'string' ) ? top : top + 'px';
		var left = ( typeof left == 'string' ) ? left : left + 'px';
		
		this.element.style.top = top;
		this.element.style.left = left;
	},
	
	
	setDimension: function( width, height ) 
	{
		var width = ( typeof width == 'string' ) ? width : width + 'px';
		var height = ( typeof height == 'string' ) ? height : height + 'px';
	
		this.element.style.width = width;
		this.element.style.height = height;
	},
	
	
	disable: function() 
	{ 
		this.element.disabled = true;
	},
	
	
	enable: function() 
	{
		this.element.disabled = false;
	},
	
	
	getValue: function() {
		return $F(this.element);
	},
	
	
	setValue: function( value ) {
		this.element.value = value;
	},
	
	
	
	show: function() 
	{
		this.element.style.visibility = 'visible';
	},
	
	
	hide: function()
	{
		this.element.style.visibility = 'hidden';
	}
};

var EasyGUI_button = Class.create();

Object.extend( Object.extend( EasyGUI_button.prototype, EasyGUI_widget.prototype ),
{
	isPressed: false,
	
	render: function() 
	{
		this.type				= Element.getAttributeValue( this.element, 'type' );
		this.toolbarId 			= Element.getAttributeValue( this.element, 'toolbarid' );
		this.uploadId			= Element.getAttributeValue( this.element, 'uploadid' );
		this.overimg			= Element.getAttributeValue( this.element, 'buttonoverimage' );
		this.pressedimg 		= Element.getAttributeValue( this.element, 'buttonpressedimage' );
		this.inactiveimg 		= Element.getAttributeValue( this.element, 'buttoninactiveimage' );
		
		this.bgimg 				= Element.getStyle( this.element, 'background-image' );
		this.backgroundColor 	= Element.getStyle( this.element, 'background-color' );
		
		Event.observe( this.element, 'mouseover', this.onButtonOver.bindAsEventListener( this ) );
		Event.observe( this.element, 'mouseout', this.onButtonOut.bindAsEventListener( this ) );
		Event.observe( this.element, 'click', this.onButtonClick.bindAsEventListener( this ) );
		
		if ( this.type == 'datepicker' ) {
			this.dateSeparator 		= Element.getAttributeValue( this.element, 'dateseparator' );
			this.dateFormat 		= Element.getAttributeValue( this.element, 'dateformat' );
			this.dateField			= $( Element.getAttributeValue( this.element, 'datetargetfield' ) );
			
			this.actualMonthText	= Element.getAttributeValue( this.element, 'dateactualmonthtext', 'this month' );
			this.closeText			= Element.getAttributeValue( this.element, 'dateclosetext', 'close' );
			
			if ( isEmptyValue(this.element.className) ) {
				this.element.className = 'easygui-dp';
			}
			
			this.dpid = 'EasyGUI_DatePicker';
			this.idpid = 'EasyGUI_DatePickerIframe';
			
			this.element.onclick = function() { return false; };			
			var dateDays = Element.getAttributeValue( this.element, 'datedays' );
			this.dayArrayShort = (!dateDays) ? ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] : Util.getJSObject( dateDays );
			var dateMonths = Element.getAttributeValue( this.element, 'datemonths' );
			this.monthArrayLong = (!dateMonths) ? ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] : Util.getJSObject( dateMonths );
		}
		
		this.reset();
	},
	
	reset: function() {
		if (this.bgimg) {
			this.element.style.backgroundImage = this.bgimg;
		} else {
			if ( this.backgroundColor != '#ece9d8' ) {
				this.element.style.backgroundColor = this.backgroundColor;
			}
		}
		
		this.isPressed = false;
		this.element.blur();
	},
	
	pageMousedown: function( evt )
	{
		if ($( this.dpid ) ) {
			Element.hide( this.dpid );
			Element._hide( this.dpid );
	
			this.setIFrame();
		}
	},
	
	onButtonOver: function( evt ) {
		if ( this.overimg ) {
			this.element.style.backgroundImage = 'url(' + this.overimg + ')';
		}
	},
	
	onButtonOut: function( evt ) {
		if ( this.overimg && !this.isPressed) {
			this.reset();
		} else {
			if (this.pressedimg) {
				this.element.style.backgroundImage = 'url(' + this.pressedimg + ')';
			}
		}
	},
	
	onButtonClick: function( evt ) {
		if ( this.pressedimg ) {
			var allButtons = document.getElementsByTagName('button');
			
			for (var i=0; i < allButtons.length; i++) {
				var button = gui.getWidget( allButtons[i].id );
				
				if ( this.toolbarId && button.toolbarId && this != button) {
					if (this.toolbarId == button.toolbarId) {
						button.reset();
					}
				}
			}
			
			this.isPressed = true;
			this.element.style.backgroundImage = 'url(' + this.pressedimg + ')';
		}
		
		if ( this.type == 'upload' ) {
			ekUpload.call( this, this.element );
		}
			
		if ( this.type == 'submit' ) {
			ekSubmit( this.id );
		}
			
		if ( this.type == 'request' ) {
			ekRequest( this.id );
		}
		
		if ( this.type == 'datepicker') {
			this.drawDatePicker();
		}
	},
	
	drawDatePicker: function() 
	{
		var dt = this.getFieldDate( $F( this.dateField ) );
		
		if (!$( this.dpid ) ) {
			var newNode = document.createElement("div");
			newNode.setAttribute("id", this.dpid);
			newNode.setAttribute("class", this.getStyleDefinition( "div" ) );
			newNode.setAttribute("style", "visibility: hidden;");
			document.body.appendChild(newNode);
		}
		
		var pickerDiv = $( this.dpid);
		pickerDiv.style.position = "absolute";
		pickerDiv.style.left = this.getPageOffsetLeft() + 'px';
		pickerDiv.style.top =  this.getPageOffsetTop() + 'px';
		pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
		pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
		pickerDiv.style.zIndex = 10000;
		
		this.refreshDatePicker(dt.getFullYear(), dt.getMonth(), dt.getDate());
	},
	
	
	refreshDatePicker: function(year, month, day)
	{
		var thisDay = new Date();
		
		if ((month >= 0) && (year > 0)) {
			thisDay = new Date(year, month, 1);
		} else {
			day = thisDay.getDate();
			thisDay.setDate(1);
		}
		
		var crlf = "\r\n";
		
		var TABLE 			= "<table cols=7 class='" + this.getStyleDefinition('table') + "'>" + crlf;
		var xTABLE 			= "</table>" + crlf;
		var TR 				= "<tr class='" + this.getStyleDefinition('row') + "'>";
		var TR_title 		= "<tr class='" + this.getStyleDefinition('title-row') + "'>";
		var TR_days 		= "<tr class='" + this.getStyleDefinition( 'day-row') + "'>";
		var TR_todaybutton 	= "<tr class='" + this.getStyleDefinition( 'today-button-row' ) + "'>";
		var xTR 			= "</tr>" + crlf;
		var TD 				= "<td class='" + this.getStyleDefinition( 'cell') + "' onMouseOut='this.className=\""+ this.getStyleDefinition('cell') + "\";' onMouseOver=' this.className=\"" + this.getStyleDefinition( 'cell-hover') + "\";' ";    // leave this tag open, because we'll be adding an onClick event
		var TD_title 		= "<td colspan=5 class='" + this.getStyleDefinition( 'title-cell') + "'>";
		var TD_buttons 		= "<td class='" + this.getStyleDefinition( 'button-cell' ) + "'>";
		var TD_todaybutton 	= "<td colspan=7 nowrap=\"nowrap\" class='" + this.getStyleDefinition( 'today-button-cell' ) + "'>";
		var TD_days 		= "<td class='" + this.getStyleDefinition( 'day-cell' ) + "'>";
		var TD_selected 	= "<td class='" + this.getStyleDefinition( 'day-hl-cell' ) + "' onMouseOut='this.className=\"" + this.getStyleDefinition( 'day-hl-cell') + "\";' onMouseOver='this.className=\"" + this.getStyleDefinition( 'cell-hover' ) + "\";' ";    // leave this tag open, because we'll be adding an onClick event
		var xTD 			= "</td>" + crlf;
		var DIV_title 		= "<div class='" + this.getStyleDefinition( 'title-text' ) + "'>";
		var DIV_selected 	= "<div class='" + this.getStyleDefinition( 'day-hl' ) + "'>";
		var xDIV 			= "</div>";
		
		var html = TABLE;
		
		html += TR_title;
		html += TD_buttons + this.getButtonCode(thisDay, -1, "&lt;") + xTD;
		html += TD_title + DIV_title + this.monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
		html += TD_buttons + this.getButtonCode(thisDay, 1, "&gt;") + xTD;
		html += xTR;
		
		html += TR_days;
		
		for(i = 0; i < this.dayArrayShort.length; i++) {
			html += TD_days + this.dayArrayShort[i] + xTD;
		}
			
		html += xTR;
		html += TR;
		
		for (i = 0; i < thisDay.getDay(); i++) {
			html += TD + "&nbsp;" + xTD;
		}
		
		// now, the days of the month
		do {
			dayNum = thisDay.getDate();
			TD_onclick = " onclick=\"dialog." + this.id + ".updateDateField('" + this.getDateString(thisDay) + "');\">";
		
			if (dayNum == day) {
				html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
			} else {
				html += TD + TD_onclick + dayNum + xTD;
			}
			
			if (thisDay.getDay() == 6) {
				html += xTR + TR;
			}
			
			thisDay.setDate(thisDay.getDate() + 1);
		} while (thisDay.getDate() > 1)
		
		if (thisDay.getDay() > 0) {
			for (i = 6; i > thisDay.getDay(); i--) {
				html += TD + "&nbsp;" + xTD;
			}
		}
		
		html += xTR;
	
		var today = new Date();
		html += TR_todaybutton + TD_todaybutton;
		html += "<button class='" + this.getStyleDefinition('today-button') + "' onClick='dialog." + this.id + ".refreshDatePicker();'>" + this.actualMonthText + "</button> ";
		html += "<button class='" + this.getStyleDefinition('today-button') + "' onClick='dialog." + this.id + ".updateDateField();'>" + this.closeText + "</button>";
		html += xTD + xTR;
	
		html += xTABLE;
		
		$(this.dpid).innerHTML = html;
		this.setIFrame();
	},
	
	
	updateDateField: function( dateString )
	{
		if (dateString) {
			this.dateField.value = dateString;
		}
		
		Element.hide( this.dpid );
		Element._hide( this.dpid );
	
		this.setIFrame();
		this.dateField.focus();
	},
	
	
	getDateString: function(dateVal)
	{
		var dayString 	= "00" + dateVal.getDate();
		var monthString = "00" + (dateVal.getMonth()+1);
		
		dayString 		= dayString.substring(dayString.length - 2);
		monthString 	= monthString.substring(monthString.length - 2);
		
		switch (this.dateFormat) {
			case "dmy" :
				return dayString + this.dateSeparator + monthString + this.dateSeparator + dateVal.getFullYear();
			case "ymd" :
				return dateVal.getFullYear() + this.dateSeparator + monthString + this.dateSeparator + dayString;
			case "mdy" :
			default :
				return monthString + this.dateSeparator + dayString + this.dateSeparator + dateVal.getFullYear();
		}
	},
	
	
	getButtonCode: function( dateVal, adjust, label )
	{
		var newMonth = (dateVal.getMonth () + adjust) % 12;
		var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
		
		if (newMonth < 0) {
			newMonth += 12;
			newYear += -1;
		}
		
		return "<button class='" + this.getStyleDefinition( 'button' ) + "' onClick='dialog." + this.id + ".refreshDatePicker( " + newYear + ", " + newMonth + ");' style=\"width:20px\">" + label + "</button>";
	},
	
	
	getFieldDate: function(dateString)
	{
		var dateVal;
		var parts;
		var day, month, year;
		
		try {
			parts = DateTime.getParts( dateString, this.dateFormat );
			
			if (parts) {
				var day		= DateTime.getPart(parts, 'd', this.dateFormat);
				var month	= DateTime.getPart(parts, 'm', this.dateFormat);
				var year	= DateTime.getPart(parts, 'y', this.dateFormat);
				
				dateVal = new Date(year, month, day);
			} else if (dateString) {
				dateVal = new Date(dateString);
			} else {
				dateVal = new Date();
			}
		} catch(e) {
			dateVal = new Date();
		}
		
		return dateVal;
	},
	
	
	setIFrame: function()
	{
		if (is.ie5up) {
			var cal = $( this.dpid );
			
			if ( !cal.iframeEl ) {
				cal.iframeEl = cal.parentNode.insertBefore( Util.getIframe(), cal);
			}
			
			Element.setPosition( cal.iframeEl, cal.offsetTop, cal.offsetLeft );
			Element.show( cal.iframeEl );
			
			cal.iframeEl.style.position = 'absolute';
			cal.iframeEl.zIndex = parseInt( cal.style.zIndex ) - 1;
			
			Element.setDimension(cal.iframeEl, cal.clientWidth, cal.clientHeight);
			cal.iframeEl.style.display = cal.style.display;
			cal.iframeEl.style.visibility = cal.style.visibility;
		}
	}
});

var EasyGUI_checkbox = Class.create();

Object.extend( Object.extend( EasyGUI_checkbox.prototype, EasyGUI_widget.prototype ),
{
	checked: false,
	label: '',
	
	render: function()
	{
		this.checked	= Element.getAttributeValue( this.element, 'checked' );
		this.label		= Element.getAttributeValue( this.element, 'label' );
		
		if ( this.checked )
			this.element.checked = 'checked';
			
		//this.element.onfocus = function() { this.blur(); };
		Event.observe(this.element, "focus", this.onFocus.bindAsEventListener(this) );
		this.onclicked = eval( this.element.onclick );
		
		this.element.onclick = null;
		
		Event.observe( this.element, 'click', this.onCheckboxClicked.bindAsEventListener(this) );
	},
	
	onFocus: function( evt )
	{
		var element = $GE(evt);
		element.blur();
	},
	
	show: function()
	{
		if ( this.label )
			$(this.id + '_LABEL').style.visibility = 'visible';
			
		this.element.style.visibility = 'visible';
	},
	
	hide: function()
	{
		if ( this.label )
			$(this.id + '_LABEL').style.visibility = 'hidden';
			
		this.element.style.visibility = 'hidden';
	},
	
	isChecked: function()
	{
		return ( this.element.checked );
	},
	
	
	onCheckboxClicked: function( evt )
	{
		if ( this.onclicked )
			window.setTimeout( this.onclicked, 1 );
	}
});







var EKCombos = {};
var EasyGUI_combobox = Class.create();

Object.extend( Object.extend( EasyGUI_combobox.prototype, EasyGUI_widget.prototype ),
{
	active: false,
	
	bgColor: 'white',
	
	
	textColor: 'black',
	
	
	bgColorHl: 'highlight',
	
	
	leftPos: 0,
	
	
	topPos: 0,
	
	
	itemList: '',
	
	
	selected: null,
	
	
	isEnhanced: false,
	
	
	isAddRemove: false,
	
	
	isInTable: false,
	
	
	addButton: null,
	
	
	removeButton: null,
	
	
	comboButton: null,
	
	
	optionList: null,
	
	
	targetList: null,
	
	
	textDisplay: null,
	
	
	displayTextColIdx: 1,
	textDisplayColumn: null,
	tableId : '',
	
	render: function() 
	{
		var tabCtrl = null;
		
		if ( tabid = Element.isInTab( this.id ) ) {
			tabCtrl = dialog[$( tabid ).getAttribute('widgetid')];
			tabCtrl.switchTab( tabid );
		}
		
		this.bgColor	= Element.getStyle( this.element, 'background-color', this.bgColor );
		this.bgColor 	= (this.bgColor == 'transparent') ? 'white' : this.bgColor;
		
		this.textColor 	= Element.getStyle( this.element, 'color', this.textColor );
		
		this.leftPos 	= this.getPageOffsetLeft();
		this.topPos  	= this.getPageOffsetTop();
	
		var items = Element.getAttributeValue( this.element, 'items' );
	
		if ( items && items.indexOf('=') == -1 && items.indexOf('|') == -1 && items.indexOf('{') == -1 )
			items = items + "=" + items;
		
		this.items = Util.getJSObject( items );
		
		if ( this.items === false ) 
			this.setItemList( items );
		
		this.selected		= Element.getAttributeValue(this.element, 'selected', this.selected );
		
		this.isEnhanced 	= Element.getAttributeValue(this.element, 'enhanced' );
		this.isAddRemove 	= Element.getAttributeValue(this.element, 'addremove' );
		
		this.displayTextColIdx = parseInt( Element.getAttributeValue( this.element, 'displaycol', this.displayTextColIdx - 1));
		
		if ( isEmptyValue(this.element.className) )
			this.element.className = 'easygui-combobox';
			
		if ( this.isInTable ) {
			this.tableId = this.element.up('table[ektype="Table"]' ).readAttribute('tableid');						
			this.table = dialog[this.tableId];
			
			this.isInTable = true;
			this.column		= this.element.up('td');
			
			this.columnId = this.element.parentNode.id;
			this.posTable = document.createElement('table');
			
			this.posTable.cellSpacing = 0;
			this.posTable.cellPadding = 0;
			this.posTable.border = 0;
		
			this.posTr = this.posTable.insertRow(0);
			this.textDisplayColumn = this.posTr.insertCell(0);
			this.comboButtonColumn = this.posTr.insertCell(1);
		}
				
		if (this.isEnhanced) {
			this.createEnhancedCombo();
			Element.hide( this.element );
			Event.observe(document, 'click', this.closeCombo.bindAsEventListener(this), false);
		} else if (this.isAddRemove) {
			this.createAddRemoveBox();
		} else {
			this.setOptionList();

			this.element.style.margin 	= '0px';
			this.element.style.padding 	= '0px';
			
			
		}
	
		if ( tabCtrl != null ) {
			tabCtrl.switchTab( tabCtrl.getSelected() );
		}
	},
	
	setItemList: function( items ) 
	{
		this.items = {};
		
		if ( !items )
			return;
				
		items = items.split('|');
		
		if ( items.length > 0 ) {
			for (var i=0; i < items.length; i++) {
				if ( items[i] == '' )
					continue;
				 
				var option = items[i].split('=');

				if ( option.length == 1 ) {
					option[1] = option[0];
				}
				
				this.items[option[0]] = option[1].split('#');
			}
		}
	},
	
	
	setOptionList: function( obj )
	{
		if ( obj != null ) {
			this.items = obj;
		} else if ( typeof EKCombos[this.id] != "undefined" ) {
			this.items = EKCombos[this.id];
		}
		
		if (this.isEnhanced) 
		{
			this.setEnhancedOptionList( obj );
		} 
		else 
		{
			this.element.options.length = this.items.length;
			var options = "";
			
			if ( typeof this.items == "object" && this.items instanceof Array ) 
			{
				for ( var i=0; i < this.items.length; i++ ) 
				{
					var item = this.items[i];
					
					if ( typeof item.value != "undefined" ) {
						this.element.options[i] = new Option( '', item.value, false, false );
						this.element.options[i].innerHTML = item.text;
						
						if ( this.selected !== false && item.value == this.selected )
						{
							this.element.options[i].selected = true;
						}
						// Not working in IE
						if ( typeof item.disabled != "undefined" && item.disabled ) {
							this.element.options[i].disabled = true;
						}
						
						this.element.options[i].style.backgroundColor = 'white';
						
					} else {
						for ( var id in item ) 
						{
							if ( item.hasOwnProperty(id) ) 
							{
								var text = item[id];
								this.element.options[i] = new Option( '', id, false, false );
								this.element.options[i].innerHTML = text[0];
								
								if ( this.selected !== false && id == this.selected )
								{
									this.element.options[i].selected = true;
								}
							}
						}
					}
				}
				
			} 
			else 
			{
				var i=0;
			
				for ( idx in this.items ) 
				{
					if ( this.items.hasOwnProperty( idx ) )
					{
						var text=this.items[idx][0].replace(/&equal;/g,"=");
						this.element.options[i] = new Option('', idx, false, false);
						this.element.options[i].innerHTML = text;
						
						if ( this.selected !== false && idx == this.selected )
						{
							this.element.options[i].selected = true;
						}
						
						i++;
					}
				}
			}	
		}
	},
	
	
	setEnhancedOptionList: function( obj ) 
	{
		if ( obj != null ) 
		{
			this.items = obj;
		} else if ( typeof EKCombos[this.id] != "undefined" ) {
			this.items = EKCombos[this.id];
		}
		
		var optionList			= document.createElement('TABLE');
		
		optionList.className 	= this.element.className + '-options';
		optionList.style.width	= "100%";
		optionList.cellPadding 	= 0;
		optionList.cellSpacing 	= 0;
		optionList.border		= 0;
		
		optionList.style.borderWidth 	= '0px';
		optionList.style.padding 		= '0px';
		
		var length = this.items.length;

		if ( typeof this.items == "object" && this.items instanceof Array ) 
		{
			for ( var i=0; i < this.items.length; i++ ) 
			{
				var item = this.items[i];
				
				if ( typeof item.value != "undefined" ) {
					if ( typeof item.text == "string" )
						item.text = [item.text];
					
					this.insertEnhancedOption( optionList, item.value, item.text, i );
				} else {
					for ( var id in item ) 
					{}
				}
			}
		} else {
			var i=0;
			
			for ( idx in this.items ) 
			{
				var selected 	= false;
				var options 	= this.items[idx];
				
				this.insertEnhancedOption(optionList, idx, options, i);
				i++;
			}
		}

		this.optionList = optionList;
		this.setOptionsContainer();
	},
	
	insertEnhancedOption : function (optionList, idx, options, i ) 
	{
		var row 		= optionList.insertRow(i);
		row.className	= this.element.className + '-rows';
		row.style.backgroundColor = this.bgColor;
		
		Event.observe( row, 'click', this.onOptionClick.bindAsEventListener(this) );
		Event.observe( row, 'mouseover', this.onOptionOver.bindAsEventListener(this) );
		Event.observe( row, 'mouseout', this.onOptionOut.bindAsEventListener(this) );
		
		row.setAttribute( 'value', idx );
		
		var selected = false;
		
		if ( this.selected !== false && ( idx == this.selected || i == this.selected ) )
		{
			selected = true;
		}
			
		for (var k=0; k < options.length; k++) 
		{
			var text 		= options[k];
			
			var cellValue 	= (text == '') ? '&nbsp;' : text;
			var cell 		= row.insertCell(k);
			
			cell.style.padding 	= '2px';
			cell.style.color 	= this.textColor;
			
			cell.innerHTML 		= cellValue;
			
			if ((k+1) == this.displayTextColIdx)
			{
				row.setAttribute( 'displayText', text );
				
				if (selected) 
				{
					this.element.options[i] = new Option(text, this.selected, false, true);
					this.textDisplay.value = text;
				}
			}
		}
	},
	
	onOptionOver: function(evt) 
	{
		var row = $GE(evt).parentNode;
		
		row.style.backgroundColor = ( color = row.getAttribute('bgColorHl') ) ? color : this.bgColorHl;
		
		if ( ! (cells = row.cells) )
		{
			return;
		}
		
		var textColorHl = (color = row.getAttribute('textColorHl') ) ? color : this.textColorHl;
		var length 		= cells.length;
		
		for ( i=0; i < length; i++ ) 
		{
			cells[i].style.color = textColorHl;
		}
		
		Event.stop( evt );
	},
	
	onOptionOut: function(evt)
	{
		var row = $GE(evt).parentNode;
		
		row.style.backgroundColor = ( color = row.getAttribute('bgColor') ) ? color : this.bgColor;
		
		if ( ! (cells = row.cells) )
		{
			return;
		}

		var textColor 	= (color = row.getAttribute('textColor') ) ? color : this.textColor;
		var length		= cells.length;
		
		for ( i=0; i < length; i++ )
		{
			cells[i].style.color = textColor;
		}
			
		Event.stop( evt );
	},
	
	onOptionClick: function(evt)
	{
		var row = $GE(evt).parentNode;
		
		if ( ! row.cells )
		{
			return;
		}
		
		this.element.options[0] = new Option( row.getAttribute('value'), row.getAttribute('value'), false, true );
		
		this.textDisplay.value 			= row.getAttribute('displayText');
		this.textDisplay.style.color 	= this.textColor;
		
		if ( this.element.onchange )
		{
			this.element.onchange.call( this.element );
		}
	},
		
	
	
	createEnhancedCombo: function()
	{
		this.element.style.visibility = 'hidden';
		
		if (this.isInTable)
		{
			var select = this.element.parentNode.removeChild( this.element );
			this.element = select;
			
			var combo = $(document.forms[0]).down('select[id="' + this.id + '"]' );
			
			if ( combo )
				document.forms[0].removeChild( combo );
				
			document.forms[0].appendChild( this.element );
		}
		
		this.bgColorHl 		= Element.getAttributeValue( this.element, 'backgroundcolorhighlight', 'highlight');
		this.textColorHl 	= Element.getAttributeValue( this.element, 'textcolorhighlight', 'highlighttext');
		
		this.setTextDisplay();
		this.setComboButton();
		
		Event.observe(this.textDisplay, 'click', this.toggleCombo.bindAsEventListener(this), false);
		Event.observe(this.comboButton, "click", this.toggleCombo.bindAsEventListener(this), false);
		
		if (this.isInTable)
		{
			var column = $GE( this.columnId );
			column.appendChild( this.posTable );
		}
		
		this.setEnhancedOptionList();
	},
	
	
	
	setTextDisplay: function()
	{
		var textDisplay = document.createElement('INPUT');
		
		textDisplay.className 		= 'easygui-combobox-textdisplay';
		
		if ( is.ie5 || is.ie5_5 ) 
		{
			textDisplay.className 		= 'easygui-combobox-textdisplay-ie5';
		}
		
		textDisplay.readOnly 		= true;
		
		if ( this.element.selectedIndex > -1 )
			textDisplay.value			= this.element.options[this.element.selectedIndex].text;
		
		var padding = '0px';
		var paddingLeft = '4px';
		var paddingTop = '2px';
		
		var height = '18px';
		var width  = parseInt( this.getOffsetWidth() ) - 24 + 'px';
		
		if (is.ie5 || is.ie5_5) 
		{
			height = '22px';
			width  = parseInt( this.getOffsetWidth() ) - 18 + 'px';
		}
	
		if (is.ie5 || is.ie5_5)
		{
			paddingLeft = '3px';
			paddingTop = '1px';
		}
		
		textDisplay.style.backgroundColor = this.bgColor;
		textDisplay.style.color = this.textColor;
		textDisplay.style.height = height;
		textDisplay.style.width = width;
		
		
		
		//var editable = Element.getAttributeValue(this.element, 'editable' );
	
		//if (editable) {
			
			
		//}
	
		//Event.observe( textDisplay, 'mouseover', this.setHighlightColors.bindAsEventListener(this), false);
		//Event.observe( textDisplay, 'mouseout', this.setNormalColors.bindAsEventListener(this), false);
		
		
		if (this.isInTable)
		{
			textDisplay.style.position = 'relative';
			this.textDisplayColumn.appendChild( textDisplay );
		} 
		else 
		{
			Element.setPosition( textDisplay, this.topPos, this.leftPos );
			document.body.appendChild( textDisplay );
		}
		
		this.textDisplay = textDisplay;
	},
	
	
	setComboButton: function()
	{
		var comboButton 		= document.createElement('IMG');
		
		comboButton.style.padding = '1px';
		
		var border 		= '1px solid #7f9db9';
		var borderLeft 	= '1px solid #ffffff';
			
		if (is.ie5 || is.ie5_5)
		{
			var border = '2px inset';
			var borderLeft = '0px solid #ffffff';
		} 

		comboButton.style.backgroundColor = 'white';
		comboButton.style.border = border;
		comboButton.style.borderLeft = borderLeft;
				
		if ( is.winxp && (is.ie6 || is.gecko) )
		{
			comboButton.src = Element.getAttributeValue(this.element, 'combobuttonsrc', ek_path + '/gfx/combobut_xp.gif');
			comboButton.mouseoverimage = Element.getAttributeValue(this.element, 'combobuttonhlsrc', ek_path + '/gfx/combobut_xp_hl.gif');
			
			Event.observe(comboButton, "mouseover", flipImage, false);
			Event.observe(comboButton, "mouseout", flipImage, false);
		} 
		else 
		{
			comboButton.src = Element.getAttributeValue(this.element, 'combobuttonsrc', ek_path + '/gfx/combobut.gif');
			comboButton.mouseoverimage = Element.getAttributeValue(this.element, 'combobuttonhlsrc', ek_path + '/gfx/combobut_hl.gif');
		}
		
		this.comboButton = comboButton;
		
		if (this.isInTable) 
		{
			this.comboButtonColumn.appendChild( this.comboButton);
		} 
		else 
		{
			this.comboButton.style.position = 'absolute';
			Element.setPosition( this.comboButton, this.topPos, this.leftPos + this.textDisplay.offsetWidth );
			document.body.appendChild( this.comboButton );
		}
	},
	
	
	setOptionsContainer: function()
	{
		if (this.optionsContainer != null)
		{
			this.optionsContainer = null;
		}
		
		var optionsContainer 	= document.createElement('DIV');
		
		var droppedWidth 		= parseInt( Element.getAttributeValue(this.element, 'droppedwidth', this.getOffsetWidth()));
		var droppedHeight 		= parseInt( Element.getAttributeValue(this.element, 'droppedheight', 100));
	
		optionsContainer.className 	= this.element.className + '-optionsContainer';
		
		optionsContainer.style.overflowX 	= 'hidden';
		optionsContainer.style.overflowY 	= 'auto';
		optionsContainer.style.position 	= 'absolute';
		optionsContainer.style.border 		= '1px solid black';
		
		Element._hide( optionsContainer );
		
		optionsContainer.appendChild(this.optionList);
		
		document.body.appendChild(optionsContainer);
		
		var optionsHeight = parseInt(this.optionList.offsetHeight);
		var optionsWidth = parseInt(this.optionList.offsetWidth);
		
		if (droppedHeight > optionsHeight)
		{
			droppedHeight = optionsHeight;
		}
		
		Element.setDimension(optionsContainer, droppedWidth, droppedHeight);
		Element.setPosition(optionsContainer, 0, 0);
	
		this.optionsContainer = optionsContainer;
		
		if (is.ie5up)
		{
			optionsContainer.iframeEl = optionsContainer.parentNode.insertBefore( Util.getIframe(), optionsContainer);
			
			Element.hide( optionsContainer.iframeEl );
			optionsContainer.iframeEl.style.position = "absolute";
		}
	},
	
	
	toggleCombo: function( evt )
	{
		if (this.active)
		{
			this.closeCombo();
			return;
		}

		this.openCombo();
		Event.stop( evt );
	},
	
	openCombo: function()
	{
		this.active = true;
		
		var container 	= this.optionsContainer;
		var display 	= this.textDisplay;
		var table 		= dialog[this.tableId]; //this.table;
		
		var pos = Position.cumulativeOffset( display );
		
		var left 	= pos[0];
		var top 	= pos[1] + display.offsetHeight;
			
		if (this.isInTable)
		{
			alert( "Combobox: " + table.currentScrollTop );
			left 	-= parseInt( table.currentScrollLeft);
			top 	-= parseInt( table.currentScrollTop );
		}
		
		var openHeight 	= top + container.offsetHeight;
		var innerHeight = Dialog.getInnerHeight();
			
		if ( openHeight > innerHeight )
		{
			top = top - display.offsetHeight - container.offsetHeight;
		}
			
		Element.setPosition(container, top , left );
		
		if (this.optionsContainer.iframeEl != null)
		{
			var iframeEl = container.iframeEl;
			
			Element.setPosition( iframeEl, container.style.top,  container.style.left);
			Element.setDimension( iframeEl, container.offsetWidth, container.offsetHeight);
	    	
			Element.show( container.iframeEl );
		}
		
		container.style.visibility = 'visible';
		container.style.zIndex = 100000;
	},
	
	
	closeCombo: function( evt )
	{
		this.active = false;
		this.optionsContainer.style.visibility = 'hidden';
		
		if (this.optionsContainer.iframeEl != null)
		{
	      	Element.hide( this.optionsContainer.iframeEl );
		}
	},
	
	
	showCombo : function(evt) {
		return false;
	},
	
	
	hideCombo : function(evt) {
		return false;
	},
	
	
	createAddRemoveBox: function()
	{
		var element = this.element;

		this.setOptionList();
		var width = (this.getOffsetWidth() / 2 - 25) + 'px';
		
		element.style.width = width;
		
		var leftOffset = this.leftPos + this.getOffsetWidth();
		targetList = element.cloneNode(false);
		targetList.multiple = true;
		
		element.setAttribute('id', this.id + '_SOURCE');
		element.setAttribute('name', this.id + '_SOURCE');
	
		targetList.style.position = 'absolute';
		targetList.style.zIndex = 0;
		
		Element.setPosition( targetList, this.topPos, leftOffset + 50 );
		
		var topOffset 	= this.topPos + (this.getOffsetHeight() / 2);
		
		this.addButton 		= Element.create('button', this.id + '_ADD_BUTTON', 23, 23, (leftOffset + 12), (topOffset - 23) );
		this.removeButton 	= Element.create('button', this.id + '_REMOVE_BUTTON', 23, 23, (leftOffset + 12), (topOffset) );
		
		this.addButton.style.position = 'absolute';
		this.addButton.style.padding = '0px';
		this.addButton.style.fontFamily = 'Arial, sans serif';
		this.addButton.style.fontSize = '12px';
		
		this.removeButton.style.position = 'absolute';
		this.removeButton.style.padding = '0px';
		this.removeButton.style.fontFamily = 'Arial, sans serif';
		this.removeButton.style.fontSize = '12px';
		
		this.addButton.innerHTML 	= '<b>>></b>';
		this.removeButton.innerHTML = '<b><<</b>';
		
		Event.observe(this.addButton, 'click', this.addItems.bindAsEventListener( this ), false);
		Event.observe(this.removeButton, 'click', this.removeItems.bindAsEventListener(this), false);
		
		this.targetList = targetList;
		
		document.forms[0].appendChild(this.targetList);
		document.body.appendChild(this.addButton);
		document.body.appendChild(this.removeButton);
	},
	
	
	removeItems: function()
	{
		var tgtList = this.targetList;
		
		for (var i = tgtList.length - 1; i >= 0; i--)
		{
			if (tgtList.options[i].selected)
			{
				tgtList.options[i] = null;
				i = tgtList.length;
			}
		}
	},
	
	
	addItems: function()
	{
		var srcList = this.element;
		var tgtList = this.targetList;
		
		for ( var i = 0; i < srcList.options.length; i++ )
		{
			if ( srcList.options[i].selected )
			{
				var tgtListIdx 	= tgtList.length;	
				var exists 		= false;
				
				for (var j=0; j < tgtList.length; j++)
				{
					if (srcList.options[i].value == tgtList.options[j].value)
					{
						exists = true;
					}
					
					tgtList.options[j].selected = true;
				}
				
				if (!exists)
				{
					tgtList.options[tgtListIdx] = new Option(srcList.options[i].text, srcList.options[i].value, false, false);
					tgtList.options[tgtListIdx].selected = true;
				}			
			}
		}
		
		srcList.selectedIndex = -1;
	},
	
	
	update: function()
	{
		this.init();
	},
	
	
	disable: function() 
	{
		this.element.disabled = true;
		
		if (this.isAddRemove)
		{	
			this.addButton.disabled 	= true;
			this.removeButton.disabled 	= true;
			this.targetList.disabled	= true;
		}
		
		if (this.isEnhanced)
		{
			this.textDisplay.disabled = true;
			this.comboButton.disabled = true;
			
			Event.stopObserving(this.textDisplay, 'click', this.toggleCombo, false);
			Event.stopObserving(this.comboButton, 'click', this.toggleCombo, false);
		}
	},
	
	
	enable: function() 
	{
		this.element.disabled = false;
		
		if (this.isAddRemove)
		{
			this.addButton.disabled 	= false;
			this.removeButton.disabled 	= false;
			this.targetList.disabled 	= false;
		}
		
		if (this.isEnhanced)
		{
			this.textDisplay.disabled 	= false;
			this.comboButton.disabled 	= false;
			
			Event.observe(this.textDisplay, 'click', this.toggleCombo.bindAsEventListener( this ), false);
			Event.observe(this.comboButton, 'click', this.toggleCombo.bindAsEventListener( this ), false);
		}
	},
	
	
	getValue: function() 
	{
		return $F(this.element);
	},
	
	
	getSelected: function()
	{
		return this.getValue();
	},
	
	
	getSelectedText: function()
	{
		return this.element.options[this.element.selectedIndex].text;
	},
	
	
	setSelectedIndex: function( idx ) 
	{
		if ( idx < 0 ) 
		{
			alert( 'New selected Index out of range !');
		}
		
		if (!this.isEnhanced) 
		{
			if ( idx == null )
			{
				idx = 0;
			}
			
			if ( typeof idx == 'string' )
			{
				for ( var i=0; i < this.element.options.length; i++ )
				{
					var option = this.element.options[i].value;
				
					if ( option == idx )
					{
						idx = i;
					}
				}
			}
				
			this.element.selectedIndex = idx;
			
			if (this.isInTable)
			{
				this.textDisplay.value = this.element.options[idx].text;
				this.textDisplay.style.color = this.element.options[idx].style.color;
			}
		} 
		else 
		{
			for ( var i=0; i < this.optionList.rows.length; i++)
			{
				if ( i == idx ) 
				{
					this.textDisplay.value = this.optionList.rows[i].getAttribute('displayText');
					this.textDisplay.style.color = this.optionList.rows[i].textColor;
					
					this.element.options[0].value = this.optionList.rows[i].value;
					this.element.selectedIndex = 0;
				}
			}
		}
	},

	
	setOptionColor: function( idx, color, hl ) 
	{
		if (idx == null)
		{
			return;
		}
		
		var color 	= (color == null) ? 'black' : color;
		var hl		= (hl == null) ? 'highlighttext': hl;
		
		if (this.isEnhanced)
		{
			var rows 	= this.optionList.rows;
			var rlength 	= rows.length;
			
			for (var i=0; i < rlength; i++)
			{
				if (idx == i)
				{
					var cells = rows[i].cells;
					var clength = cells.length;
					
					for (var j=0; j < clength; j++)
					{
						cells[j].style.color = color;
					}
				
					rows[i].setAttribute( 'textColor', color );
					rows[i].setAttribute( 'textColorHl', hl );
				}
			}
		} 
		else
		{
			this.element.options[idx].style.color = color;
		}
	},
	
	
	setOptionBgColor: function( idx, color, hl )
	{
		if (idx == null)
		{
			return;
		}
		
		var color = (color == null) ? 'white' : color;
		var hl		= (hl == null) ? 'highlight': hl;
		
		if (this.isEnhanced)
		{
			var rows 	= this.optionList.rows;
			var length 	= rows.length;
			
			for (var i=0; i < length; i++) 
			{
				if (idx == i)
				{
					rows[i].style.backgroundColor = color;
					rows[i].setAttribute( 'bgColor', color );
					rows[i].setAttribute( 'bgColorHl', hl );
				}
			}
		} 
		else
		{
			this.element.options[idx].style.backgroundColor = color;
		}
	},
	
	
	setComboValue: function() 
	{
		this.textDisplay.value = this.element.options[this.element.selectedIndex].text;
		this.textDisplay.style.color = this.element.options[this.element.selectedIndex].style.color;
	},
	
	setNewItemList: function ( items ) 
	{
		this.setItemList( items );
		this.setOptionList();
	}
});

var EasyGUI_edit = Class.create();

Object.extend( Object.extend( EasyGUI_edit.prototype, EasyGUI_widget.prototype ), {
	multiline: false,
	maxlength: null,
	value: null,
	defaultText: '',
	
	
	render: function() {
		this.multiline = Element.getAttributeValue( this.element, 'multiline' );
		this.value = Element.getAttributeValue( this.element, 'value' );
		
		if ( this.multiline ) {
			this.maxlength = Element.getAttributeValue( this.element, 'maxlength' );
			this.value = Element.getAttributeValue( this.element, 'text' );
		}
			
		this.defaultText = Element.getAttributeValue( this.element, 'defaulttext', '');

		if (!this.value) {
			if(this.defaultText){
				this.element.value = this.defaultText.replace(/(<br\s+\/>|<br>|\\\\r\\\\n|\\r\\n)/g, '\r\n');
			}
		} else {
			this.element.value = this.value.replace(/(<br\s+\/>|<br>|\\\\r\\\\n|\\r\\n)/g, '\r\n');
		}

		Event.observe(this.element, "focus", this.onFocus.bindAsEventListener(this) );
		Event.observe(this.element, "blur", this.onBlur.bindAsEventListener(this));
		
		if (this.multiline)
			 Event.observe(this.element, "keyup", this.onKeyUp.bindAsEventListener(this));
		
		this.element.blur();
	},
	
	
	onFocus: function() {
		this.delDefaultText();
		this.selectText();
	},
	
	
	onBlur: function() {
		this.setDefaultText();
	},
	
	
	onKeyUp: function() {
		this.checkMaxLength();
	},
	
	
	delDefaultText: function() {
		if ( this.defaultText && ( $F(this.element) == this.defaultText ) ) {
			this.element.value = '';
		}
	},
	
	
	setDefaultText: function() {
		if ( this.defaultText && ($F(this.element) == '') ) {
			this.element.value = this.defaultText;
		}
	},
	
	
	selectText: function() {
		this.element.select();
	},
	
	
	checkMaxLength: function() {
		if (this.maxlength && (parseInt($F(this.element).length) > this.maxlength) )
			this.element.value = $F(this.element).substring(0, this.maxlength);
	},
	
	
	update: function() {
		this.init();
	},
	
	
	setReadonly: function() 
	{
		this.element.readOnly = true;
	},
	
	
	setReadWrite: function() 
	{
		this.element.readOnly = false;
	},
	
	
	setText: function( value ) 
	{
		this.setValue( value );
	}
});
var EasyGUI_image = Class.create();

Object.extend( Object.extend(EasyGUI_image.prototype, EasyGUI_widget.prototype ), {
	render: function() {
		document.writeln( 'image.src' + this.image );
	},
	
	update: function( src ) {
		this.element.src = src;
	}
});


var zIndex= 100000;


var EasyGUI_Menu = Class.create();

Object.extend( Object.extend( EasyGUI_Menu.prototype, EasyGUI_widget.prototype), 
{
	
	activeButton: null,
	
	
	activeContextMenu: null,
	
	
	cmi: null,
	
		
	activateOnMouseover: null,
	
	
	orientation: 'horizontal',
	
	
	isContextMenu: null,
	
	
	defaulticon: null,
	
	
	icons: null,
	
	
	submitHandler: null,
	
	
	render: function()
	{
		this.activateOnMouseover 	= Element.getAttributeValue( this.element, 'activateonmouseover' ),
		this.orientation 			= Element.getAttributeValue( this.element, 'orientation', this.orientation ),
		this.isContextMenu 			= Element.getAttributeValue( this.element, 'contextmenu' ),
		this.defaulticon 			= Element.getAttributeValue( this.element, 'defaulticon', ek_path + '/gfx/blank.gif' ),
		this.icons 					= Element.getAttributeValue( this.element, 'icons' );
		
		if ( isEmptyValue(this.element.className) ) {
			this.element.className = 'easygui-menu';
		}
		
		if ( !this.isContextMenu ) {
			this.menubuttons = [];
			this.menubar = this.buildMenubar();
			this.element.parentNode.appendChild( this.menubar );
		} else {
			this.buildContextMenu();
		}
		
		Event.observe(document, 'mousedown', this.pageMousedown.bindAsEventListener(this) );
		
		if ( this.element.onclick ) {
			this.submitHandler = this.element.onclick;
			this.element.onclick = null;
		} else {
			this.submitHandler = navigate;
		}
	},
	
	
	buildContextMenu: function()
	{
		this.buildMenu( this.element, true, this.id );
		
		if ((contextElementId = Element.getAttributeValue(this.element, 'contextelement') ) == false ) {
			this.contextElement = document;
			this.cmi = this.id;
		} else {
			this.contextElement = $(contextElementId);
			this.contextElement.setAttribute('contextmenuid', this.id );
		}
		
		Event.observe( this.contextElement, "contextmenu", this.displayContextMenu.bindAsEventListener( this ) );
		Event.observe( this.contextElement, "click", this.hideContextMenu.bindAsEventListener( this ) );
	},
	
	
	buildMenubar: function ()
	{
		var menubar = document.createElement( 'DIV' );
		document.body.appendChild( menubar );
		
		menubar.className 	= this.getStyleDefinition('menubar');
		
		var position = this.element.style.position;
		var width = this.element.style.width;
			
		menubar.style.position = position;
		menubar.style.width = width;
		menubar.style.margin = '0px';
		
		Element.setPosition( menubar, this.element.style.top, this.element.style.left );
		
		var menubuttons = Element.getChildNodesByTagName( this.element, 'DIV' );
		
		
		for (var i=0; i < menubuttons.length; i++) {
			if (Element.getDepth( menubuttons[i], 'DIV', 'Menu' ) == 0) {
				menubutton = Element.getFirstChildByTagName( menubuttons[i], 'A');
			
				menubutton.className = this.getStyleDefinition('menubutton');
				menubutton.menuId = menubutton.id + '_MENU';
				
				if (this.orientation == 'vertical') {
					//menubutton.style.display = 'block';
				}
				
				//menubutton.onfocus = function() { this.blur() };
				Event.observe(menubutton, "focus", this.onFocus.bindAsEventListener(this) );
				Event.observe(menubutton, 'click', this.openMenu.bindAsEventListener(this), false);
				Event.observe(menubutton, 'mouseover', this.menuButtonOver.bindAsEventListener(this), false);
				
				menubar.appendChild( menubutton );
				
				if (is.ie5) {
					menubutton.style.width = '10px';
				}
	
				this.buildMenu( menubuttons[i], true, menubutton.id );
			}
		}
		
		return menubar;
	},
	
	
	buildMenu: function ( menuitem, isButton, parentId, parentMenu )
	{
		if (! Element.hasChildNodesWithTagName( menuitem, 'DIV' )) {
			return;
		}
		
		if (!isButton) {
			var parentMenuItem = Element.getFirstChildByTagName( menuitem, 'A');
			var menuItemIcon = this.getIcon( menuitem );
			
			var menuId = parentMenuItem.id + '_MENU';				
			var menuItemText = document.createElement('span');
							
			menuItemText.className = this.getStyleDefinition('menuitem') + '-text';
			menuItemText.menuId = menuId;
							
			var menuItemArrow = document.createElement('span');
						
			menuItemArrow.className = this.getStyleDefinition('menuitem') + '-arrow';
			menuItemArrow.menuId = menuId;
							
			menuItemText.innerHTML = parentMenuItem.innerHTML;
			
			if ( is.ie5up ) {
				menuItemArrow.innerHTML = '<b>></b>';
			} else {
				menuItemArrow.innerHTML = '<b>&#9658;</b>';
			}
			
			parentMenuItem.innerHTML = '';
			
			if (menuItemIcon) {
				parentMenuItem.appendChild(menuItemIcon);
			}
				
			parentMenuItem.appendChild(menuItemText);
			parentMenuItem.appendChild(menuItemArrow);
	
			parentMenuItem.menuId = menuId;
			
			Event.observe( parentMenuItem, 'mouseover', this.menuItemOver.bindAsEventListener( this) );
			Event.observe( parentMenu, 'mouseover', this.menuOver.bindAsEventListener( this ) );
		}
	
		var menu = document.createElement('DIV');
		
		menu.style.lineHeight = '2.5ex';
		menu.style.zIndex = zIndex++;
						
		menu.id = parentId + '_MENU';
						
		menu.className 	= this.getStyleDefinition('menu');
		menu.setAttribute('isMenu', 'true');
		
		var cNodes  = Element.getChildNodesByTagName( menuitem, 'DIV' );
		
		for (var i=0; i < cNodes.length; i++) {
			menuitem = Element.getFirstChildByTagName( cNodes[i], 'A');
			var sep =  Element.getAttributeValue(menuitem, 'separator');
	
			if ( sep ) {
				menu.appendChild(this.getSeparator());
				continue;
			}
			
			//menuitem.onfocus = function() { this.blur(); };
			Event.observe(menuitem, "focus", this.onFocus.bindAsEventListener(this) );
			this.buildMenu(cNodes[i], false, menuitem.id, menu);
			menuitem.className = this.getStyleDefinition('menuitem');
			
			if (! Element.hasChildNodesWithTagName(menuitem, 'SPAN') ) {
				var menuItemIcon = this.getIcon( cNodes[i] );
				var menuItemText = document.createElement('span');
				var menuItemLabel = document.createTextNode( Element.getInnerText(menuitem) );
				
				menuItemText.className = this.getStyleDefinition('menuitem') + '-text';
				menuitem.innerHTML 		= '';
				menuItemText.appendChild( menuItemLabel );
				menuItemText.itemId 	= menuitem.id;
				
				if (menuItemIcon) {
					menuitem.appendChild( menuItemIcon );
				}
					
				menuitem.appendChild( menuItemText );
				
				Event.observe( menuitem, 'click', this.onClick.bindAsEventListener( this ) );
			}
			
			menu.appendChild( menuitem );
		}
		
		document.body.appendChild(menu);
		this.correctMenu(menu);
	},
	
	onFocus : function( evt )
	{
		var element = $GE(evt);
		element.blur();
	},
	
	
	enable: function( element )
	{
		var element = $( element );
		element.disabled = false;
	},
	
	
	disable: function( element )
	{
		var element = $( element );
		element.disabled = true;
	},
	
	
	getIcon: function(menuitem)
	{
		if (!this.icons) {
			return false;
		}
		
		var menuItemIcon = document.createElement('span');
		menuItemIcon.className = this.getStyleDefinition('menuitem') + '-icon';
			
		var iconImg = document.createElement('img');	
		var icon = Element.getAttributeValue(menuitem, 'icon', this.defaulticon);
			
		iconImg.src 			= icon;
		iconImg.border 			= 0;
		
		iconImg.style.position = 'relative';
		Element.setDimension( iconImg, '16px', '16px');
		
		iconImg.height 	= 16;
		iconImg.width 	= 16;
		
		menuItemIcon.appendChild( iconImg );
		
		return menuItemIcon;
	},
	
	
	correctMenu: function ( menu )
	{
		var itemList = menu.getElementsByTagName("A");
		
		if (itemList.length > 0) {
			itemWidth = itemList[0].offsetWidth;
		} else {
			return;
		}
		
		for (i = 0; i < itemList.length; i++) {
			spanList = itemList[i].getElementsByTagName("SPAN");
			
			textEl  = null;
			arrowEl = null;
			
			for (j = 0; j < spanList.length; j++) {
		  		if ( Element.hasClassName(spanList[j], this.getStyleDefinition("menuitem") + "-text")) {
		  			textEl = spanList[j];
		  		}
		  			
		  		if ( Element.hasClassName(spanList[j], this.getStyleDefinition("menuitem") + "-arrow")) {
		    		arrowEl = spanList[j];
		  		}
		  	}
			
			if (textEl != null && arrowEl != null) {
	  			textEl.style.paddingRight = (itemWidth - ( textEl.offsetWidth  + arrowEl.offsetWidth)) + "px";
			
	  			if (is.opera5up) {
	    			arrowEl.style.marginRight = '0px';
	  			}
			}
			
		}
		
		if (is.ie5up) {
			w = itemList[0].offsetWidth;
			itemList[0].style.width = w + 'px';
			
			dw = itemList[0].offsetWidth - w;
			w -= dw;
			
			itemList[0].style.width = w + 'px';
			
			menu.iframeEl = menu.parentNode.insertBefore( Util.getIframe(), menu);
			
			Element.hide( menu.iframeEl );
			menu.iframeEl.style.position = 'absolute';
			menu.iframeEl.style.zIndex = 10000;
		}
		
		menu.isInitialized = true;
	},
	
	
	getSeparator: function( menuitem )
	{
		var separator = document.createElement( 'DIV' );
		separator.className = this.getStyleDefinition('menuitem') + '-separator';
		return separator;
	},
	
	
	openMenu: function( evt )
	{
		var button = $GE( evt );
		button.blur();
	
		if ( this.activeButton != null ) {
			this.resetButton( this.activeButton );
		}
		
		if ( button != this.activeButton ) {
			this.activeButton = button;
			this.menuButtonOut();
		} else {
			this.activeButton = null;
		}
	},
	
	
	menuButtonOver: function( evt )
	{
		var button = $GE( evt );
		
		if ( this.activateOnMouseOver) {
			if ( this.activeButton == null ) {
				this.openMenu( evt );
				return;
			}
		}
		
		if ( this.activeButton != null && this.activeButton != button ) {
			this.openMenu( evt );
		}
	},
	
	
	menuButtonOut: function()
	{
		var x, y;
		var button = this.activeButton;
		
		button.className += ' ' + this.getStyleDefinition("menubutton") + "-active";
		var menu = $(button.menuId);
		
		if (this.activateOnMouseover) {
			Event.observe( button, 'mouseout', buttonOrMenuMouseout, false );
			
			if ( menu != null )
	  			Event.observe( menu, 'mouseout', buttonOrMenuMouseout, false );
		}
	
		var pos = Position.cumulativeOffset( button );
		x = pos[0];
		y = pos[1];
		
		if (button.style.display == 'block') {
			x += button.offsetWidth;
		} else {
	  		y += button.offsetHeight;
		}
		
	  	if (menu != null) {
	  		Element.setPosition( menu, y, x );
	  		Element._show( menu );
	
	  		if (menu.iframeEl != null) {
	    		Element.setPosition( menu.iframeEl, y , x );
	    		Element.setDimension( menu.iframeEl, menu.offsetWidth, menu.offsetHeight );
	    		Element.show( menu.iframeEl );
	  		}
		}
	},
	
	
	resetButton: function( button )
	{
		Element.removeClassName( button, this.getStyleDefinition("menubutton") + '-active' );
		var menu = $(button.menuId);
		
		if ( menu != null ) {
			this.closeSubMenu( menu );
			
			menu.style.visibility = "hidden";
		    	
			if (menu.iframeEl != null) {
		  		menu.iframeEl.style.display = "none";
			}
		}
	},
	
	
	menuOver: function( evt )
	{
		var menu = $GE(evt);
		
		if (menu.nodeName != 'DIV') {
			menu = Element.getParentElementByTagName( menu, 'DIV');
		}
		
	  	if (menu.activeItem != null) {
	    	this.closeSubMenu(menu);
	  	}
	},
	
	
	menuItemOver: function( evt )
	{
		var x, y;
		var element = $GE(evt);
	
		var item = Element.getParentElementByTagName( element, 'A');
		var menu = Element.getParentElementByTagName( item, 'DIV' );
		
	  	if (menu.activeItem != null)
	    	this.closeSubMenu(menu);
	  	
	    if (menu.activeItem == item )
	    	return;
	    	
	    menu.activeItem = item;
	    
	  	item.className += " " + this.getStyleDefinition("menuitem") + "-over";
	  	
	  	if (item.subMenu == null)
	    	item.subMenu = $(item.menuId);
	    	
	    if (this.activateOnMouseover) {
	    	if (item.subMenu.onmouseout == null) {
	    		Event.observe( item.subMenu, 'mouseout', this.buttonOrMenuMouseout.bindAsEventListener(this) );
	    	}
	    }
	    
	    var itempos = Position.cumulativeOffset( item );
	    
	  	x = itempos[0] + item.offsetWidth;
	  	y = itempos[1]
	  	
	  	var maxX, maxY;
	
	  	if (is.ie5up) {
	    	maxX = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) +
	      		(document.documentElement.clientWidth != 0 ? document.documentElement.clientWidth : document.body.clientWidth);
	    	maxY = Math.max(document.documentElement.scrollTop, document.body.scrollTop) +
	      		(document.documentElement.clientHeight != 0 ? document.documentElement.clientHeight : document.body.clientHeight);
	  	}
	  	
	  	if (is.opera5up) {
	    	maxX = document.documentElement.scrollLeft + window.innerWidth;
	    	maxY = document.documentElement.scrollTop  + window.innerHeight;
	  	}
	  	
	  	if (is.nav6up || is.gecko) {
	   		maxX = window.scrollX + window.innerWidth;
	    	maxY = window.scrollY + window.innerHeight;
	  	}
	  	
	  	maxX -= item.subMenu.offsetWidth;
	  	maxY -= item.subMenu.offsetHeight;
	
	  	if (x > maxX) {
	    	x = Math.max(0, x - item.offsetWidth - item.subMenu.offsetWidth + (menu.offsetWidth - item.offsetWidth));
	  	}
	  		
	    y = Math.max(0, Math.min(y, maxY));

	    
	  	item.subMenu.style.left       = x + "px";
	  	item.subMenu.style.top        = y + "px";
	  	item.subMenu.style.visibility = "visible";
		
	  	if (item.subMenu.iframeEl != null) {
	    	item.subMenu.iframeEl.style.left    = item.subMenu.style.left;
	    	item.subMenu.iframeEl.style.top     = item.subMenu.style.top;
	    	item.subMenu.iframeEl.style.width   = item.subMenu.offsetWidth + "px";
	    	item.subMenu.iframeEl.style.height  = item.subMenu.offsetHeight + "px";
	    	item.subMenu.iframeEl.style.display = "";
	  	}
	  	
		Event.stop( evt );
	},
	
	
	closeSubMenu: function( menu )
	{
		if (menu == null || menu.activeItem == null) {
	    	return;
		}
	
	  	if (menu.activeItem.subMenu != null) {
	    	this.closeSubMenu(menu.activeItem.subMenu);
	
	    	menu.activeItem.subMenu.style.visibility = "hidden";
	    	
			if (menu.activeItem.subMenu.iframeEl != null) {
	      		menu.activeItem.subMenu.iframeEl.style.display = "none";
			}
	      		
	    	menu.activeItem.subMenu = null;
	  	}
	
	  	Element.removeClassName(menu.activeItem, this.getStyleDefinition("menuitem") + "-over");
	  	menu.activeItem = null;
	},
	
	
	pageMousedown: function( evt )
	{
		var el = $GE(evt);
		
		if (this.activeButton == null) {
	    	return;
		}
	    	
		if (el == this.activeButton) {
			return;
		}
	
		if (!Element.hasParentWithAttribute( el, 'isMenu')) {
			this.resetButton( this.activeButton );
		    this.activeButton = null;
		}
	},
	
	
	buttonOrMenuMouseout: function( evt ) 
	{
		if (this.activeButton == null) {
	    	return;
	  	}
	    
	    var el = getTargetElement(evt);
	 
	  	if (!Element.hasParentWithAttribute( el, 'isMenu')) {
	    	this.resetButton( this.activeButton );
	    	this.activeButton = null;
	  	}
	},
	
	
	frameMousedown: function( evt )
	{
		if (this.activeButton == null) {
	    	return;
		}
	    	
		this.resetButton( this.activeButton );
		this.activeButton = null;
	},
	
	
	hideContextMenu: function( evt )
	{
		if (this.activeContextMenu != null ) {
			this.activeContextMenu.style.visibility = 'hidden';
		}
		
		Event.stop( evt );
		return false;
	},
	
	
	displayContextMenu: function( evt ) 
	{
		if ( this.activeContextMenu != null ) {
			Element.show( this.activeContextMenu );
		}
		
		var element = $GE( evt );
		var contextMenuId = Element.getAttributeValue( element, 'contextmenuid' );
	
		if ( !contextMenuId ) {
			contextMenuId = this.cmi;
		}
		
		var contextMenu = $( contextMenuId + '_MENU' );
	
		x = Event.pointerX( evt );
		y = Event.pointerY( evt );
		
		x -= 2; y -= 2;
	
		Element.setPosition( contextMenu, y, x );
		Element._show( contextMenu );
		Event.stop( evt );
		
		this.activeContextMenu = contextMenu;
		return false;
	},
	
	
	onClick: function( evt )
	{	
		var element = Element.getParentElementByTagName( $GE(evt), 'A' );
		
		if ( element.disabled ) {
			return;
		}
		
		this.submitHandler.call( this, element );
		this.pageMousedown( this.id );
		Event.stop( evt );
	},
	
	
	show: function()
	{
		Element.show( this.menubar );
	},
	
	
	hide: function()
	{
		Element.hide( this.menubar );
	}
});



var EasyGUI_MenuTree = Class.create();

Object.extend( Object.extend( EasyGUI_MenuTree.prototype, EasyGUI_widget.prototype ),
{ 
	
	modus: 'TreeCtrl',
	
	render: function() {
		this.modus = Element.getAttributeValue( this.element, 'modus', 'TreeCtrl' );
		
		if (this.modus == 'TreeCtrl') {
			this.element.setAttribute( 'ektype', 'TreeCtrl' );
			dialog.registerWidget( new EasyGUI_TreeCtrl( id ) );
		} else {
			this.domElement.setAttribute( 'ektype', 'Menu' );
			dialog.registerWidget( new EasyGUI_Menu( id ) );
		}
	}
});

var EasyGUI_radiobutton = Class.create();


Object.extend( Object.extend( EasyGUI_radiobutton.prototype, EasyGUI_widget.prototype ), {
	selected: null,
	checked: false,
	
	render: function() {
		this.group = document.forms[0].elements[this.element.name];
		this.groupElement = $( this.element.name + '_GROUP' );
		this.checked = Element.getAttributeValue( this.element, 'checked' );
		
		if (this.groupElement) {
			this.selected = Element.getAttributeValue( this.groupElement, 'selected' );
			this.switchRadio( this.selected );
		}
		
		if (this.checked) {
			this.reset();
			this.element.checked = true;
		}
		
		this.initialized = true;
	},
	
	
	switchRadio: function ( value, fireEvent ) {
		var group 		= this.group;
		var fireEvent 	= (fireEvent || fireEvent == null) ? true : false;
		
		if (!group.length) {
			if ( group.value == value ) {
				group.checked = true;
			}
		} else {
			for (i=0; i < group.length; i++) {
				group[i].checked = false;
				
				if (group[i].value == value || group[i].id == value) {
					
					group[i].checked = true;
				
					if (this.initialized && document.fireEvent && fireEvent ) {
						bfired = group[i].fireEvent('onclick');
					}
				}
			}
		}
	},
	
	
	getValue: function () {
		var group = this.group;
		
		if ( !group.length ) {
			return group.value;
		} else {
			for (i=0; i < group.length; i++) {
				if (group[i].checked == true) {
					return group[i].value;
				}
			}
		}
		
		return false;
	},
	
	
	getSelected: function()
	{
		return this.getValue();
	},
	
	
	reset: function () {
		var group = this.group;
		
		if ( !group.length ) {
			group.checked = false;
		} else {
			for (var i=0; i < group.length; i++) {
				if (group[i].checked == true) {
					group[i].checked == false;
				}
			}
		}
	},
	
	hide: function() {
		var group = this.group;
		
		if ( !group.length ) {
			Element.hide( group );
		} else {
			for ( var i=0; i < group.length; i++ ) {
				Element.hide( group[i] );
			}
		}
	},
	
	show: function() {
		var group = this.group;
		
		if ( !group.length ) {
			Element.show( group );
		} else {
			for ( var i=0; i < group.length; i++ ) {
				Element.show( group[i] );
			}
		}
	}
});



var EasyGUI_EKTabCtrl = Class.create();

Object.extend( Object.extend( EasyGUI_EKTabCtrl.prototype, EasyGUI_widget.prototype ),
{
	panels: null,
	tabs: [],
	tabArea: null,
	leftButton: null,
	rightButton: null,
	selectedIndex: 0,
	activateScrollCtrl: false,
	hiddenTabs: [],
	
	init: function() 
	{
		if ( isEmptyValue(this.element.className) ) {
			this.element.className = 'easygui-tabctrl';
		}
		
		
		this.selected = Element.getAttributeValue( this.element, 'selected' );
		
		
		this.panels = Element.getChildNodesByTagName( this.element, 'div' );
		
		if ( this.panels.length == 0 ) {
			return;
		}
		
		this.tabs = [];
		
		
		this.tabArea = document.createElement('div');
		this.tabArea.className = this.getStyleDefinition( 'area' );
		
		var firstPanel = Element.getFirstChildByTagName( this.element, 'DIV' );
		firstPanel.parentNode.insertBefore( this.tabArea, firstPanel );
		
		
		this.selectedIndex = 0;
		this.element.style.visibility = 'hidden';
		
		var offsetWidth = 0;
		
		// Fix for TabCtrl nested inside another TabCtrl
		var tabId = Element.isInTab(this.element);
		
		if (tabId)
			Element.show(tabId);
		
		for (var i=0; i < this.panels.length; i++) {
			if (this.panels[i].id == this.selected) {
				this.selectedIndex = i;
			}
			
			var tab = Element.getFirstChildByTagName( this.panels[i], 'A' );
			tab.setAttribute('panelid', this.panels[i].id );
			
			
			var isyheader = Element.getFirstChild( this.panels[i] );
			var isytext = "";
			
			if ( isyheader && isyheader.nodeName == "SPAN" ) {
				isyheaderTable = Element.getFirstChildByTagName( isyheader, 'TABLE' );
				
				isytext = Element.getInnerText( isyheaderTable.rows[0].cells[0] );
				this.panels[i].removeChild( isyheader );
			} 
			
			tabtext = Element.getInnerText( tab );
						
			if (!tabtext)
				tab.innerHTML = isytext;
			
			var header = tab.cloneNode(true);
			
			if (header.style.visibility == 'hidden') {
				Element.hide( header );
				Element._show( header );
			}
			
			if (is.ie5)
				header.style.width = '10px';
				
			header.className = this.getStyleDefinition( 'tab');
			header.style.position = 'relative';

			Event.observe( header, 'click', this.switchTab.bindAsEventListener(this), false);
			
			// Find a better solution one day to handle all user defined event handlers
			header.onclick = this.panels[i].onclick;
			//header.onfocus = function() { this.blur(); };
			Event.observe(header, "focus", this.onFocus.bindAsEventListener(this) );
			
			this.panels[i].onclick = function() { return true; };
			
			header.setAttribute('panelid', this.panels[i].id );
			header.setAttribute('widgetid', this.id );
			this.panels[i].setAttribute('widgetid', this.id );
			
			this.tabArea.appendChild( header );
			this.tabs[this.tabs.length] = header;
			
			offsetWidth += header.offsetWidth;
			
			if ( offsetWidth > this.element.offsetWidth - 50) {
				this.activateScrollCtrl = true;
				this.hiddenTabs[this.hiddenTabs.length] = header;
			}
			
			this.panels[i].className = this.getStyleDefinition( 'panel' );
			
			this.panels[i].style.position = 'relative';
			this.panels[i].style.zIndex = 101;

			this.panels[i].removeChild( tab );
		}
		
		var realHeight 	= this.getOffsetHeight();
		var tabsHeight 	= this.tabs[this.selectedIndex].offsetHeight;
		
		var height = realHeight - tabsHeight;
		
		for(var i=0; i < this.panels.length; i++)
			this.panels[i].style.height = height + 'px';
		
		Form.insertHidden( this.id + '_EK_WIDGET_VALUE', '' );
		
		this.selected = this.tabs[this.selectedIndex].getAttribute('tabpanel');
		this.renderScrollCtrl( tabsHeight );
	},
	
	onFocus : function( evt )
	{
		var element = $GE(evt);
		element.blur();
	},
	
	renderScrollCtrl: function( tabsHeight )
	{
		if ( this.activateScrollCtrl )
		{
			var scrollCtrl = document.createElement( 'div' );
			scrollCtrl.style.position = "absolute";
			scrollCtrl.style.width = "100%";
			scrollCtrl.style.top = "0px";
			scrollCtrl.style.textAlign = "right";
			scrollCtrl.style.zIndex = 1000;
			
			var scrollCtrlTable = document.createElement( 'table' );
			scrollCtrlTable.cellSpacing="0";
			scrollCtrlTable.cellPadding="0";
			var scrollRow = scrollCtrlTable.insertRow(0);
			
			var	leftScrollCell = scrollRow.insertCell(0);
			
			this.leftButton = document.createElement( 'button' );
			this.leftButton.style.height = tabsHeight + "px";
			this.leftButton.value = "<b>&lt;</b>";
			//this.leftButton.onfocus = function() { this.blur(); };
			Event.observe( this.leftButton, "focus", this.onFocus.bindAsEventListener(this) );
			Event.observe( this.leftButton, 'click', this.scrollLeft.bindAsEventListener(this) );
			
			leftScrollCell.appendChild( this.leftButton );
			
			var rightScrollCell = scrollRow.insertCell(1);
				
			this.rightButton = document.createElement( 'button' );
			this.rightButton.style.height = tabsHeight + "px";
			this.rightButton.value = "<b>&gt;</b>";
			//this.rightButton.onfocus = function() { this.blur(); };
			Event.observe( this.rightButton, "focus", this.onFocus.bindAsEventListener(this) );
			Event.observe( this.rightButton, 'click', this.scrollRight.bindAsEventListener(this) );
			
			rightScrollCell.appendChild( this.rightButton );
			
			scrollCtrl.appendChild( scrollCtrlTable );
			this.element.appendChild( scrollCtrl );
			
			this.leftButton.disabled = true;
		}
	},
	
	finalize: function() 
	{
		this.initialized = true;
		
		if ( this.panels.length == 0 )
			return;
		

		for (var i=0; i < this.hiddenTabs.length; i++ )
			this.hiddenTabs[i].style.display = "none";
			
		
		var selectedIndex = this.getSelectedIndex();
		
		if ( this.tabs[selectedIndex].style.display == "none"  ) 
		{
			for (var i=0; i < this.tabs.length; i++ ) {
				this.scrollRight();
				
				if ( this.tabs[selectedIndex].style.display == "" )
					break;
			}
		}
		
		this.switchTab( this.selected );
		Element._show( this.element );
	},
	
	getSelected: function()
	{
		return this.selected;
	},
	
	getSelectedIndex: function()
	{
		for ( var i=0; i < this.tabs.length; i++ )
			if ( this.tabs[i].getAttribute('panelid') == this.selected )
			 	return i;
		
		return 0;
	},
	
	
	updateWidget: function ()
	{
		this.selected = Element.getAttributeValue( this.element, 'selected' );
		
		if (this.selected)
			this.switchTab( this.selected );
	},
	
	
	getTab: function( node )
	{	
		var tab = $GE(node);
		
		if ( typeof( node ) == 'string' ) {
			for (var i=0; i < this.panels.length; i++)
				if ( this.panels[i].id == node )
					this.selectedIndex = i;
	
			tab = this.tabs[this.selectedIndex];
		} else {
			
			if ( node.nodeName == 'DIV' ) {
				for (var i=0; i < this.tabs.length; i++) {
					var tabpanel = this.tabs[i].getAttribute('tabpanel');
					
					if (tabpanel == node.id)
						tab = this.tabs[i];
				}
			}
		}
		
		return tab;
	},
	
	
	switchTab: function( evt )
	{
		var pageYOffset = Dialog.getPageYOffset();
		
		var tab = this.getTab( evt );
		tab.blur();
		
		for (var i = 0; i < this.panels.length; i++) {
			Element.hide( this.panels[i] );
			//Element._hide( this.panels[i] );
		}
		
		for (var i = 0; i < this.tabs.length; i++) {
			this.tabs[i].className = this.getStyleDefinition( 'tab' );
		}
		
		if (is.ie5)
			var correctTop = Element.getStyle( tab, 'top' );
		
		tab.className += ' ' + this.getStyleDefinition('tab') + '-active';
		
		if (is.ie5)
			tab.style.top = correctTop;
			
		var id = tab.getAttribute('tabpanel');
		
		Element.show( $( id ) );
		//Element._show( $( id ) );
		
		if ( this.initialized ) {
			this.selected = id;
			Form.Element.setValue( this.id + '_EK_WIDGET_VALUE', id );
		}
		
		if ( typeof evt == "object" ) //&& evt instanceof Event )
			Event.stop( evt );
	},

	
	hideTab: function( tab )
	{
		var tab 	= this.getTab( tab );
		var id 		= tab.getAttribute('tabpanel');
		var panel 	= $GE( id );
		
		Element.hide( panel );
		Element.hide( tab );
        
        for ( var i=0; i < this.tabs.length; i++ )
		{
			if ( this.tabs[i].style.display != 'none' ) {
				this.switchTab( this.tabs[i].getAttribute('panelid'));
				break;
			}
		}
	},
	
	
	showTab: function( tab )
	{
		var tab= this.getTab( tab );
		Element.show(tab);
	},
	
	
	scrollLeft: function( evt )
	{
		for ( var i=( this.tabs.length - 1 );i >= 0; i-- ) 
		{
			if ( this.tabs[i].style.display != 'none' ) {
				this.tabs[i].style.display = 'none';
				break;
			}
		}
		
		for ( --i; i >= 0 ; i-- )
		{
			if ( this.tabs[i].style.display == 'none' ) {
				this.tabs[i].style.display = '';
				break;
			}
		}
		// First Tab
		if ( i == 0 )
			this.leftButton.disabled = true;
			
		this.rightButton.disabled = false;
	},
	
	
	scrollRight: function( evt )
	{		
		for ( var i=0; i < this.tabs.length; i++ )
		{
			if ( this.tabs[i].style.display != 'none' ) {
				this.tabs[i].style.display = 'none';
				break;
			}
		}
		
		for ( ++i; i < this.tabs.length; i++ )
		{
			if ( this.tabs[i].style.display == 'none' ) {
				this.tabs[i].style.display = '';
				break;
			}
		}
		// Last Tab
		if ( i == ( this.tabs.length - 1 ) )
			this.rightButton.disabled = true;
			
		this.leftButton.disabled = false;
	},
	
	
	setTabText: function( tab, text )
	{
		var tab = this.getTab( tab );
		tab.innerHTML = text;
	},
	
	
	addSelectionChangedHandler: function()
	{
		if (!this.selectionChangedHandler)
			return;
			
		Event.observe( this.element, 'click', this.onSelectionChanged.bindAsEventListener(this) , false );
	},
	
	
	removeTab: function( tab )
	{
		this.hideTab( tab );
	},
	
	
	disableTab: function( tab )
	{
		;
	},
	
	
	enableTab: function( tab )
	{
		;
	}
});

var EasyGUI_TabCtrl = Class.create();

Object.extend( Object.extend( EasyGUI_TabCtrl.prototype, EasyGUI_widget.prototype ),
{
	render : function() {
		var modus = this.element.readAttribute('modus') || 'normal';
		
		if ( modus == 'normal' ) {
			Object.extend( this, new EasyGUI_EKTabCtrl( this.id ) );
		} else {
			Object.extend( this, new EasyGUI_ExtTabCtrl( this.id ) );
		}
		
		this.init();
	}
});

var EasyGUI_ExtTabCtrl = Class.create();

Object.extend( Object.extend( EasyGUI_ExtTabCtrl.prototype, EasyGUI_widget.prototype ),
{
	
	panels: [],
	
	
	tabs: [],
	
	
	selectedIndex: 0,
	
	
	tabBody: {},
	
	selected: 0,
	
	
	init: function() 
	{
		var panels = this.element.getElementsBySelector('div[ctrltype="tabpanel"]');
		
		if ( isEmptyValue(this.element.className) ) {
			this.element.className = 'easygui-tabs';
		}
		
		var tabStrip = document.createElement('div');
		tabStrip.className = this.getStyleDefinition('wrap');
		this.element.appendChild( tabStrip );
		
		this.tabBody = document.createElement('div');
		this.tabBody.className = this.getStyleDefinition('body');
		this.tabBody.style.height = this.element.getHeight() + "px";
		this.tabBody.style.position = 'relative';
		
		this.element.appendChild( this.tabBody );
		
		var html = '<div class="' + this.getStyleDefinition('strip-wrap') + '">';
		html += '<table class="' + this.getStyleDefinition('strip') + '" cellspacing="0" cellpadding="0" border="0">';
		html += '<tbody><tr></tr></tbody></table></div>';
		
		tabStrip.innerHTML = html;
		
		// Jetzt f�gen wir die Strip Elemente hinzu
		stripEl = tabStrip.firstChild.firstChild.firstChild.firstChild;
		
		for (var i=0; i < panels.length; i++ ) {
			var text = panels[i].readAttribute('text');
			var col = document.createElement('td');
			
			var td = stripEl.insertCell(i);
			
			html = '<a href="#" class="' + this.getStyleDefinition('right') + '">';
			html += '<span class="' + this.getStyleDefinition('left') + '">';
			html += '<em class="' + this.getStyleDefinition( 'inner' ) + '">';
			html += '<span title="' + text + '" class="' + this.getStyleDefinition('text') + '">' + text + '</span>';
			html += '</em></span></a>';
			
			td.innerHTML = html;
			
			Event.observe( td, 'click', this.switchTab.bindAsEventListener(this), false);
			// Hier ziehen wir jetzt noch das Panel aus dem Document und f�gen es wieder
			
			panels[i].firstDescendant().remove();
			panels[i].firstDescendant().remove();
			
			var panel = panels[i].remove();
			panel.addClassName( this.getStyleDefinition('item-body') );
			panel.setAttribute( 'widgetid', this.id );
			td.setAttribute('panelid', panel.id );
			td.onclick = panel.onclick;
			
			this.tabBody.appendChild( panel );
		}
		
		this.panels = $(this.tabBody).getElementsBySelector('div[ctrltype="tabpanel"]');
		this.tabs = $(stripEl).childElements();
		this.element.addClassName( this.getStyleDefinition('top') );
		
		Form.insertHidden( this.id + '_EK_WIDGET_VALUE', '' );
		
		this.selected = this.element.readAttribute('selected') || 0;
	},
	
	
	finalize: function() 
	{
		this.switchTab( this.selected );
		this.initialized = true;
	},
	
	
	getSelected: function()
	{
		return $F( this.id + '_EK_WIDGET_VALUE');
	},
	
	
	getSelectedIndex: function()
	{
		var selectedIndex = 0;
		
		this.tabs.each( function( tab, id ) {
			if ( tab.hasClassName('selected') ) {
				selectedIndex = id;
			}
		});
		
		return selectedIndex;
	},
	
	
	getTab: function( node )
	{},
	
	
	switchTab: function( evt )
	{
		var idx;
		var fieldId = this.id + '_EK_WIDGET_VALUE';
		
		if ( typeof evt == "object" ) {
			var el = Event.findElement(evt, 'td' );
			el.addClassName('selected');
			idx = el.cellIndex;
		} else {
			idx = evt;
		}
		
		this.tabs.each( function( tab, id ) {
			tab.removeClassName('selected');
			var panelid = tab.getAttribute('panelid');
			
			if ( idx == id || idx == panelid ) {
				tab.addClassName('selected');
				idx = id;
				
				$( fieldId ).value = panelid;
				tab.down('a').blur();
			}
		});
		
		this.panels.each( function( panel, id ) {
			panel.hide();
			
			if ( idx == id ) {
				panel.show();
			}
		});
	},
	
	
	hideTab: function( tab )
	{},
	
	
	showTab: function( tab )
	{},
	
	
	setTabText: function( tab, text )
	{},
	
	
	removeTab: function( tab )
	{},
	
	
	disableTab: function( tab )
	{},
	
	
	enableTab: function( tab )
	{}
});

var EasyGUI_text = Class.create();


Object.extend( Object.extend( EasyGUI_text.prototype, EasyGUI_widget.prototype ), {
	text: '',
	
	render: function() {
		this.text = Element.getInnerText( this.element );
		return;
		
		this.text = Element.getAttributeValue( this.element, 'text' );
		
		if ( !this.text ) {
			this.text = Element.getInnerText( this.element );
			this.element.innerHTML = Element.getInnerText( this.element );
		}else {
			this.element.innerHTML = this.text;
		}
	},
	
	getText: function() {
		return this.text;
	},
	
	setText: function( text ) {
		this.text = text;
		this.element.innerHTML = text;
	}
});

var activeButton = null;


var EasyGUI_TreeCtrl = Class.create();

Object.extend( Object.extend( EasyGUI_TreeCtrl.prototype, EasyGUI_widget.prototype), {
	
	type: 'easygui-treectrl',
	
	
	closeSiblings: true,
	
	
	closeChilds: true,
	
	
	items: null,
	
	
	target: '_self',
	
	
	styleDefinitions: null,
	
	
	targetDlg: null,
	
	
	selected: null,
	
	
	treeitems: [],
	
	
	search: null,
	
	
	searchInitialized: false,
	
	
	currentSearchExpr: false,
	
	
	currentSearchIdx: 0,
	
	
	currentDepth: 0,
	
	root: null,
	
	handlers: [],
	
	evt: null,
	
	setEvent: function( evt ) {
		this.evt = evt;
	},
	
	
	render: function()
	{
		if (!this.element.childNodes.length) {
			return;
		}

		this.styleDefinitions = { defaults: 'easygui-treectrl-node-default', leaf: null, levels:[] };
		
		this.items 				= Element.getElementsByTagName( this.element, 'DIV' );
		
		var defs			= Element.getAttributeValue( this.element, 'styledefinitions', null );
		styleDefinitions 	= Util.getJSObject( defs );
		
		if ( !styleDefinitions ) {
			this.setStyleDefinitions( defs );
		} else {
			this.styleDefinitions = styleDefinitions;
		}
		
		this.target 			= Element.getAttributeValue( this.element, 'target', this.target );
		this.targetDlg 			= Element.getAttributeValue( this.element, 'targetdlg' );
		this.focusFirstItem		= Element.getAttributeValue( this.element, 'focusfirstitem', false );
		this.openRoot		    = Element.getAttributeValue( this.element, 'openroot', false );
		this.closeChilds		= Element.getAttributeValue( this.element, 'closechilds', true );
		this.prevSelChange 		= Element.getAttributeValue( this.element, 'preventselectionchange', false );
		
		this.onSelectionChange = Element.getAttributeValue( this.element, 'onselectionchange', 'navigate' );
		
		if ( this.onSelectionChange ) 
			this.onSelectionChange = eval( this.onSelectionChange );
		
		Event.observe( this.element, 'click', this.defaultHandler.bindAsEventListener( this ), false );
		Event.observe( this.element, 'click', this.focusItem.bindAsEventListener( this ) );

		this.element.style.display 	= 'block';
		this.element.state 			= 'opened';

		this.root = Element.getFirstChild( this.element );
		
		Form.insertHidden( this.id + '_EK_WIDGET_VALUE' );
		
		this.openTreeItem( this.element );
		
        this.selected = Element.getAttributeValue( this.element, 'selected' );
        
        if ( this.focusFirstItem )
            this.selected = Element.getAttributeValue( this.element, 'selected', Element.getFirstChild( this.root ).id );
		
		if ( ( this.selected && this.selected != this.id ) || this.focusFirstItem ) {
			this.focusItem( this.selected );
			
			if ( this.target != '_self' && !this.prevSelChange ) {
				this.onSelectionChange.call( this, this.selected );
			}
				
			this.setSelected( this.selected );
		} else {
            if ( this.openRoot ) {
                this.openTreeItem( this.root );
            }
        }
	},
	
	setStyleDefinitions: function( defs ) {	
		if ( defs == null ) {
			return;
		}
			
		var definition;
		var pattern = /\[([^\]]*)\]/g;
		
		while ((definition = pattern.exec(defs)) != null) {
			var def		= definition[1].split(':');	
			var defName = parseInt( def[0] );
			
			if ( isNaN( defName ) ) {
				//alert( def[0] );
				if ( def[0] == 'default' ) {
					this.styleDefinitions['defaults'] = def[1];
				}
				else {
					this.styleDefinitions[def[0]] = def[1];
				}
			}
			else {
				this.styleDefinitions.levels[defName] = def[1];
			}
		}
	},
	
	
	getStyleDefinition: function(level, childNodes, treeitem )
	{
		var customstyle = Element.getAttributeValue( treeitem, 'customstyle' );
		
		if (!customstyle) {
			if (this.styleDefinitions['leaf'] != null && childNodes == 0) {
				if ( this.styleDefinitions['leaf'] != null ) {
					return this.styleDefinitions['leaf'];
				}
			}
				
			if (typeof(level) == 'number') {
				if ( this.styleDefinitions.levels ) {
					while (this.styleDefinitions.levels[level] == null && level > 0) {
						level--;
					}
					
					if (this.styleDefinitions.levels[level] != null) {
						return this.styleDefinitions.levels[level];
					}
				}
			}
			
			return this.styleDefinitions.defaults;
		} else {
			return customstyle;
		}
	},
	
	onDblClick: function( evt ) {
		alert( 'Detected a Dbl Click on ' + $GE(evt).id );
	},
	
	
	prepareSubTree: function( subtree )
	{
		if (subtree == null) {
			subtree = this.element;
		}
		
		var prepared = Element.getAttributeValue( subtree, 'prepared' );
		
		if (prepared == 'true' || prepared) {			
			return ;
		}
		
		for (var i=0; i < subtree.childNodes.length; i++ ) 
		{
			if ( subtree.childNodes[i].nodeName == 'DIV' ) 
			{
				var treeitem 	= Element.getFirstChildByTagName( subtree.childNodes[i], 'A');
				var depth	 	= Element.getDepth( subtree.childNodes[i], 'DIV', 'TreeCtrl' );
				
				var cn			= subtree.childNodes[i].getElementsByTagName('DIV');
				var selector	= this.getStyleDefinition( depth, parseInt( cn.length ), treeitem );
				
				var paddingLeft = parseInt( Dialog.Style.getStyle( selector, 'paddingLeft') );
					
				if (isNaN(paddingLeft)) {
					paddingLeft = 0;
				}
				
				var marginLeft = parseInt( Dialog.Style.getStyle( selector, 'marginLeft' ) );
			
				if (isNaN(marginLeft)) {
					marginLeft = 0;
				}
				
				var bgPos = Dialog.Style.getStyle( selector, 'backgroundPosition' );
				
				if (!bgPos) {
					bgPos = "0 0";
				}
				
				var bgPos = bgPos.split(' ');
				
				vPos = parseInt(bgPos[0]);
				hPos = parseInt(bgPos[1]);
				
				
				if (isNaN(hPos)) {
					hPos = bgPos[1];
				} else {
					hPos += 'px';
				}
				
				if (isNaN(vPos)) {
					vPos = bgPos[0];
				} else {
					vPos = (((depth * paddingLeft) - (depth * marginLeft)) + vPos)
					vPos += 'px';
				}
				
				subtree.childNodes[i].style.marginLeft = marginLeft;
				treeitem.className = selector + ' ' + selector + '-closed';
				
				
				
				//treeitem.onfocus = function() { this.blur(); };
				Event.observe(treeitem, "focus", this.onFocus.bindAsEventListener(this) );
				treeitem.style.marginLeft = '0px';
				var paddingLeft = (( (depth * paddingLeft) - (depth * marginLeft) ) + paddingLeft);
			
				treeitem.style.paddingLeft = paddingLeft + 'px';
				treeitem.style.backgroundPosition =  vPos + ' ' + hPos;
			}
		}
		
		subtree.setAttribute( 'prepared', true );
	},
	
	onFocus : function( evt )
	{
		var item = $GE( evt );
		item.blur();;
	},
	
	onTreeItemClick: function( evt ) {
		var element = $GE(evt);
		this.setSelected( element.id );
		this.setEvent( evt );
		
		if (this.handlers[element.id] )
			this.handlers[element.id].call( this, evt );
	},
	
	defaultHandler: function( evt ) {
		var element = Event.element(evt);
		
		if ( element === this.element ) 
			return;
			
		this.onSelectionChange.call( this, evt );
		Event.stop( evt );
	},
			
	
	setSelected: function( id )
	{
		Form.Element.setValue( this.id + '_EK_WIDGET_VALUE', id );
		
		this.element.selected 	= id;
		this.selected			= id;
	},
	
	
	getSelected: function()
	{
		return this.selected;
	},
		
	
	openTreeItem: function( item )
	{
		this.prepareSubTree( item );
		var cNodes = item.childNodes;
		
		for (var i=0; i < cNodes.length; i++) {
			if (cNodes[i].nodeName == 'DIV' ) {
				cNodes[i].style.display = 'block';
			}
		}
	},
	
	
	closeTreeItem: function( item )
	{
		if ( item.nodeName == 'DIV' ) {
			var cNodes = item.childNodes;
			
			if (cNodes.length == 0 ) {
				return;
			}
			
			for (var i=0; i < cNodes.length; i++) {
				if (cNodes[i].nodeName == 'DIV') {
					if (this.closeChilds && (cNodes[i].state == 'opened-sibling' || cNodes[i].state == 'opened' || cNodes[i].state == 'focused') ) {
						this.closeTreeItem( cNodes[i] );
					}
					
					this.setTreeStyle( cNodes[i], 'closed' );
					cNodes[i].style.display = 'none';
				}
			}
		}
	},
	
	
	hideTreeItem: function( item )
	{
		var element = Element.getParentElementByTagName( $(item), "DIV" );
		element.setAttribute( 'display', 'false' );
		this.prepareSubTree( element.parentNode );
		
		if ( element.parentNode.state == "focused" )
			element.style.display = "none";
	},
	
	
	displayTreeItem: function( item )
	{
		var element = Element.getParentElementByTagName( $(item), "DIV" );
		element.setAttribute( 'display', 'true' );
		this.prepareSubTree( element.parentNode );
		
		if ( element.parentNode.state == "focused" )
			element.style.display = "block";
	},

	
	setTreeStyle: function(item, state)
	{
		if ( item.nodeName == 'DIV' ) {
			var treeitem = Element.getFirstChildByTagName(item, 'A');
		
			styleClass = treeitem.className.split(' ');
			treeitem.className = styleClass[0] + ' ' + styleClass[0] + '-' + state;
		}
	},

	
	resetTree: function()
	{
		var currentItem 	= $( this.selected ).parentNode;
		var currentDepth 	= Element.getDepth( currentItem, 'DIV', 'TreeCtrl' );
	
		while ( currentDepth > 1 ) {
			if ( currentItem.nodeName == 'DIV' ) {
				currentDepth = Element.getDepth( currentItem, 'DIV', 'TreeCtrl' );
			}
			
			currentItem = currentItem.parentNode;
		}
		
		if (currentItem) 
			this.closeTreeItem( currentItem );
	},
	
	
	searchTree: function( expr )
	{
		var match = '';
		
		if ( expr != this.currentSearchExpr ) {
			this.currentSearchIdx 	= 0;
			this.currentSearchExpr 	= expr;
			this.search 			= [];
			
			for ( var i=0; i < this.items.length; i++ ) {
				var treeitem 	= Element.getFirstChildByTagName( this.items[i], 'A');
				var text 		= Element.getInnerText( treeitem );
				
				if ( text.indexOf( expr ) != -1 ) {
					this.search[this.search.length] = treeitem.id;
				}
			}
		} else {
			this.currentSearchIdx++;
			
			if ( (this.currentSearchIdx + 1)  > this.search.length) {
				this.currentSearchIdx = 0;
			}
		}
	
		if ( this.search.length > 0 ) {
			this.focusItem( this.search[ this.currentSearchIdx ] );
			
			var treeitem = $( this.search[ this.currentSearchIdx ] );
			treeitem.parentNode.parentNode.scrollIntoView( true );
			
			return true;
		} 
			
		return false;
	},
	
	
	focusItem: function( el )
	{
		var el = $GE(el);
		
		if ( el === this.element ) 
			return;
			
		el = Element.getParentElementByTagName( el, 'A', true );
		el.blur();
		this.setSelected( el.id );
		
		var targetDlg = Element.getAttributeValue( el, 'targetdlg' );

		var evtEl = el;
		
		var id 	= el.id;
		
		el = el.parentNode;

		if (!targetDlg) {
			if ( this.targetDlg )
				targetDlg = this.targetDlg;
			else targetDlg = '';
		} 
		
		evtEl.setAttribute( 'targetdlg', targetDlg );
		
		this.resetTree();
		this.openTreeItem( el );
		
		el.state = 'focused';
		
		sourceElement = el;
		var parentItem = sourceElement.parentNode;
		
		this.prepareSubTree( parentItem );
		this.setTreeStyle( el, el.state );
		
		while( el = el.nextSibling ) {
			if (el.nodeName == 'DIV') {
				el.state = 'focused-sibling';
				this.closeTreeItem( el );
				this.setTreeStyle( el, el.state );
			}
		}
		
		el = sourceElement;
		
		while ( el = el.previousSibling ) {
			if (el.nodeName == 'DIV' ) {
				el.state = 'focused-sibling';
			
				this.closeTreeItem( el );
				this.setTreeStyle( el, el.state );
				lastel = el;
			}
		}
		
		while (parentItem.nodeType != 9 ) {
			var ektype = Element.getAttributeValue( parentItem, 'ektype' );
			
			if ( ektype == 'TreeCtrl') break;
			
			if (parentItem.nodeName == 'DIV') {
				parentItem.state = 'opened';
				
				this.openTreeItem( parentItem );
				this.setTreeStyle( parentItem, parentItem.state );
				
				sibling = parentItem.nextSibling;
				
				while ( sibling != null ) {
					if ( sibling.nodeName == 'DIV' ) {
						sibling.state = 'opened-sibling';
						this.setTreeStyle( sibling, sibling.state );
					}
					
					sibling = sibling.nextSibling;
				}
				
				sibling = parentItem.previousSibling;
				
				while( sibling != null ) {
					if (sibling.nodeName == 'DIV' ) {
						sibling.state = 'opened-sibling';
						this.setTreeStyle( sibling, sibling.state );
					}
					
					sibling = sibling.previousSibling;
				}
				
			}
			
			parentItem = parentItem.parentNode;
		}
	}
});

var descend = false;
var EasyGUI_table = Class.create();


Object.extend( Object.extend( EasyGUI_table.prototype, EasyGUI_widget.prototype ),
{
	
	selectedElements: null,
	
	
	submitValues: null,
	
	
	activeFilter: null,
	
	
	lastSortCol: null,
	
	
	rowHeader: null,
	
	
	columnHeader: null,
	
	
	fixedHeader: null,
	
	
	currentScrollTop: 0,
	
	
	currentScrollLeft: 0,
		
	
	toggleRowStyles: false,
	
	
	bgColor: 'white',
	
	
	textColor: 'black',
	
	
	bgColorHl: 'highlight',
	
	
	textColorHl: 'highlighttext',
	
	
	bgColorEven: 'buttonface',
	
	
	textColorEven: 'black',
	
	
	fixedLines: 0,
	
	
	fixedColumns: 0,
	
	
	selectionType: 'none',
	
	
	multipleSelection: false,
	
	
	isSortable: false,
	
	
	sortTitle: '',
	
	
	presortedColumn: 1,
	
	
	cellSpacing: 0,
	
	
	onSelectionChange: null,
	
	
	selected: '',
	
	
	action: null,
	
	
	targetdlg: null,
	
	disabled: false,
	
	
	setAction: function( action ) 
	{
		this.container.setAttribute('action', action );
	},
	
	
	setTargetDlg: function( id ) 
	{
		this.container.setAttribute('targetdlg', id );
	},
	
	
	render: function() 
	{
		//var timer = new JS_Timer();
		//timer.startTimer();
		this.element = $( this.id + '_TABLE' );
		
		var type	= Element.getAttributeValue(this.element, 'type' );
		
		if ( type == "html" ) {
			var container = Element.getParentElementByTagName( this.element, 'DIV' );
			var table = Element.getFirstChildByTagName( container, 'TABLE' );
			
			if ( container.parentNode.nodeName.toLowerCase() != "td" )
			{
				table.style.position = 'absolute';
				table.style.top = container.style.top;
				table.style.left = container.style.left;
			} else {
				table.style.position = 'relative';
			}
			
			container.parentNode.appendChild( table );
			return;
		}
		
		this.selectedElements = [];
		this.submitValues = [];
		
		this.toggleRowStyles = Element.getAttributeValue( this.element, 'togglerowstyles' );
	
		this.bgColor = Element.getStyle( this.element, 'background-color' );
		
		if ( this.bgColor == 'transparent' && this.toggleRowStyles )
			this.bgColor = 'white';
	
		this.fixedLines 	= parseInt( Element.getAttributeValue(this.element, 'fixedlines', this.fixedLines));
		this.fixedColumns 	= parseInt( Element.getAttributeValue(this.element, 'fixedcolumns', this.fixedColumns));
		
		this.hasRowHeader	= Element.getAttributeValue(this.element, 'rowheader' );
		this.hasColumnHeader= Element.getAttributeValue(this.element, 'columnheader' );
		
		this.tableLayout 	= Element.getAttributeValue(this.element, 'tablelayout' );
		
		if ( this.tableLayout != 'fixed' ) {
			this.element.style.width = "100%";
		} else {
			this.element.style.tableLayout = this.tableLayout;
		}
		
		if ( this.hasRowHeader ) {
			this.fixedColumns = 1;
		}
		
		if ( this.hasColumnHeader ) {
			this.fixedLines = 1;
		}
		
		this.selectionType 	= Element.getAttributeValue( this.element, 'selectiontype', this.selectionType );
		
		this.selectionType = this.selectionType.toLowerCase();
		
		this.multipleSelection 			= Element.getAttributeValue( this.element, 'multipleselection' );
		
		this.onClicked = eval( this.element.onclick );
		
		this.element.onclick = function () { return true; };
		
		if ( this.onClicked != null ) {
			Event.observe( this.element, 'click', this.onRowClicked.bindAsEventListener(this) );
		}
		
		
		if ( this.selectionType != 'none' ) {
			this.element.onmouseover = null;
			this.element.onmouseout = null;
		
			for ( var i=this.fixedLines; i < this.element.rows.length; i++ ) {
				Event.observe(this.element.rows[i],'mouseover',this.onRowOver.bindAsEventListener(this) );
			}
	
			for ( var i=this.fixedLines; i < this.element.rows.length; i++ ) {
				Event.observe(this.element.rows[i],'mouseout', this.onRowOut.bindAsEventListener(this) );
			}	
		}
		
		this.onSelectionChange = Element.getAttributeValue( this.element, 'onselectionchange' );
		
		if ( this.onSelectionChange ) {
			this.onSelectionChange = eval( this.onSelectionChange );
			Event.observe( this.element, 'click', this.onSelectionChanged.bindAsEventListener(this) );
		}
		
		this.onDblClicked				= Element.getAttributeValue( this.element, 'ondblclicked' );
		
		if ( this.onDblClicked ) {
			this.onDblClicked = eval( this.onDblClicked );
			Event.observe( this.element, 'dblclick', this.onRowDblClicked.bindAsEventListener(this) );
		}
			
		this.isSortable = Element.getAttributeValue( this.element, 'sortable' );
		this.sortTitle 	= Element.getAttributeValue( this.element, 'sorttitle', 'Click to sort !');
		
		this.presortedColumn = parseInt( Element.getAttributeValue( this.element, 'presortedcolumn', 1));
		
		if (isNaN(this.presortedColumn)) {
			var column = $GE( Element.getAttributeValue( this.element, 'presortedcolumn', '' ));
			this.presortedColumn = parseInt(this.presortedColumn.cellIndex);
			
			if (isNaN(this.presortedColumn))
				this.presortedColumn = 1;
		}
		
		
		this.cellSpacing		= parseInt( Element.getAttributeValue( this.element, 'cellSpacing', 0 ));
		this.element.setAttribute('cellSpacing', this.cellSpacing );
		
		this.isFiltrable 		= Element.getAttributeValue( this.element, 'filtrable' );
		this.filterboxAllText 	= Element.getAttributeValue( this.element, 'filterboxalltext', 'All');
		this.filterTitle 		= Element.getAttributeValue( this.element, 'filtertitle', 'Choose to filter !' );
		this.prefilteredColumn 	= parseInt( Element.getAttributeValue( this.element, 'prefilteredcolumn', 1));
		this.selected 			= Element.getAttributeValue( this.element, 'selected' );
		this.selectFirstItem	= Element.getAttributeValue( this.element, 'selectfirstitem' );
		
		this.container 			= Element.getParentElementByTagName( this.element, 'DIV' );
		this.scrollSelectionIntoView = Element.getAttributeValue( this.element, 'scrollselectionintoview', true );
		
		this.action			= Element.getAttributeValue( this.element, 'action', '' );
		this.targetdlg		= Element.getAttributeValue( this.element, 'targetdlg', '' );
		
		var tabCtrl = null;
		
		if ( tabid = Element.isInTab( this.id ) ) {
			tabCtrl = dialog[$( tabid ).getAttribute('widgetid')];
			tabCtrl.switchTab( tabid );
		}
		
		if ( this.element.rows.length == 0 ) {
			return;
		}
		
		if ( isEmptyValue(this.element.className) ) {
			this.element.className = 'easygui-table';
			this.element.style.zIndex = 0;
		}
		
		if (this.fixedLines > 0) {
			var headerHeight		= Element.getAttributeValue( this.element, 'headerheight' );
			
			for (var i=0; i < this.fixedLines; i++) {
				if (headerHeight)
					this.element.rows[i].style.height = headerHeight + 'px';
				
				var len = this.element.rows[i].cells.length;
				var cells = this.element.rows[i].cells;
				
				var issetSortable = false;
				var issetFiltrable = false;
				
				for (var j=0; j < len; j++) {
					var headerTextColor 	= Element.getAttributeValue( cells[j], 'headertextcolor', Element.getAttributeValue( this.element, 'headertextcolor' ) );
					var headerBgColor		= Element.getAttributeValue( cells[j], 'headerbackgroundcolor', Element.getAttributeValue( this.element, 'headerbackgroundcolor' ) );
			
					var headerFont 			= Element.getAttributeValue( cells[j], 'headerfont', Element.getAttributeValue( this.element, 'headerfont' ) );
					var headerFontSize 		= Element.getAttributeValue( cells[j], 'headerfontsize', Element.getAttributeValue( this.element, 'headerfontsize' ) );
					var headerFontWeight 	= Element.getAttributeValue( cells[j], 'headerfontweight', Element.getAttributeValue( this.element, 'headerfontweight' ) );
					var headerFontStyle 	= Element.getAttributeValue( cells[j], 'headerfontstyle', Element.getAttributeValue( this.element, 'headerfontstyle' ) );
			
					var headerAlign 		= Element.getAttributeValue( cells[j], 'headerhorizontalalign', Element.getAttributeValue( this.element, 'headerhorizontalalign' ) );
					var headerValign 		= Element.getAttributeValue( cells[j], 'headerverticalalign', Element.getAttributeValue( this.element, 'headerverticalalign' ) );
					
					// @@@Hacked Hacked Hacked
					// @todo find a better solution for attribute value conversions on the server side
					if ( headerValign == 'center' ) {
						headerValign = 'middle';
					}
					
					var sortable = Element.getAttributeValue( cells[j], 'sortable' );
					var filtrable = Element.getAttributeValue( cells[j], 'filtrable' );
					
					if (sortable && !issetSortable) {
						this.isSortable = true;
						issetSortable = true;
					}
					
					if (filtrable && !issetFiltrable) {
						this.isFiltrable = true;
						issetFiltrable = true;
					}
					
					cells[j].className += ' header';
					
					cells[j].style.backgroundRepeat = 'no-repeat';
					cells[j].style.backgroundPosition = 'center right';
					
					if (headerTextColor)
						cells[j].style.color = headerTextColor;
								
					if (headerBgColor)
						cells[j].style.backgroundColor = headerBgColor;
				
					if (headerFont)
						cells[j].style.fontFamily = headerFont;
					
					if (headerFontSize)
						cells[j].style.fontSize = headerFontSize + 'pt';
					
					if (headerFontWeight)
						cells[j].style.fontWeight = headerFontWeight;
					
					if (headerFontStyle)
						cells[j].style.fontStyle = headerFontStyle;
						
					if (headerAlign)
						cells[j].style.textAlign = headerAlign;
						
					if (headerValign)
						cells[j].style.verticalAlign = headerValign;
						
				}
			}
		}
		
		if ( this.fixedColumns > 0 && this.hasRowHeader ) {
			for ( var i=0; i < this.element.rows.length; i++ ) {
				var row = this.element.rows[i];
				
				for (var j=0; j < this.fixedColumns; j++) {
					row.cells[j].className += ' rowheader';
				}
			}
		}
		
		var rowLength = this.element.rows.length;
		
		for (var i = this.fixedLines; i < rowLength; i++) {
			var row = this.element.rows[i];

			if ( i % 2 == 0 && this.toggleRowStyles )
				row.className += ' altrow';
		}
	
		if ( (this.element.offsetWidth <= this.container.clientWidth) && !this.hasRowHeader ) 
			this.fixedColumns = 0;
			
		if ( (this.element.offsetHeight > this.container.offsetHeight) && 
			 (this.element.offsetWidth == this.container.offsetWidth) ) {
				this.element.style.width = this.container.clientWidth + 'px';
				if (!this.hasRowHeader)
					this.fixedColumns = 0;
		}
		
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		this.container.style.visibility = 'visible';
		this.container.style.zIndex = 0;
		
		if (this.fixedLines > 0 && this.isFiltrable) {
			var sourceRow = this.element.tBodies[0].insertRow(this.fixedLines);
			
			if (this.headerBgColor)
				sourceRow.style.backgroundColor = this.headerBgColor;
				
			var filterCount = 0;
			this.fixedLines++;
			
			for (var i=0; i < this.element.rows[0].cells.length; i++) {
				var filterCell = sourceRow.insertCell(i);
				var filtrable = Element.getAttributeValue( this.element.rows[0].cells[i], 'filtrable' );
				
				if (filtrable) {
					var filterBox = document.createElement('select');
					
					filterCell.appendChild(filterBox);
					filterBox.options[0] = new Option(this.filterboxAllText, 'ALL', true, true);
					filterBox.setAttribute('isFilterBox', 'true' );
					filterCount++;
				} else
					filterCell.innerHTML = '&nbsp;';
			}
			
			var rowLength 	= this.element.rows.length;
			var cellLength 	= this.element.rows[0].cells.length;
				
			var filters = new Array( filterCount );
			
			for (var i = this.fixedLines; i < rowLength; i++) {
				for (var j=0; j < cellLength; j++) {
					var filtrable = Element.getAttributeValue( this.element.rows[0].cells[j], 'filtrable' );
					
					if (filtrable) {

						if (!filters[j])
							filters[j] = new Array();
						
						var currentFilter = filters[j];
						var filtercriterium = null;
						
						if (this.element.rows[i].cells[j].firstChild.nodeType == 3)
							var filtercriterium = this.element.rows[i].cells[j].firstChild.data;
							
						filtercriterium = Element.getAttributeValue( this.element.rows[i].cells[j], 'filtercriterium', filtercriterium);
						
						var filterBox = Element.getFirstChildByTagName(this.element.rows[1].cells[j], 'SELECT');
						
						if ( !currentFilter.inArray( filtercriterium ) )
							currentFilter[currentFilter.length] = filtercriterium;
							
						this.element.rows[i].cells[j].filtercriterium = filtercriterium;
						
						filterCount++;
					} else
						filters[j] = false;
				}
			}
			
			for ( var i=0; i < filters.length; i++ ) {
				var filter = filters[i];
				
				if (filter) {
					filter.sort( Sort.compareValues );
					var filterBox = Element.getFirstChildByTagName(this.element.rows[1].cells[i], 'SELECT');
				
					for (var j=0; j < filter.length; j++)
						filterBox.options[filterBox.options.length] = new Option( filter[j], filter[j], false, false );
				}
			}
		}
		
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		if (this.fixedColumns > 0)
			this.rowHeader	= new EasyGUI_TableRowHeader( this );

		if (this.fixedLines > 0)
			this.columnHeader = new EasyGUI_TableColumnHeader( this );
		
		if (this.fixedColumns > 0 && this.fixedLines > 0)
			this.fixedHeader = new EasyGUI_TableFixedHeader( this );

		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		if (this.fixedLines > 0) {
			
			if (this.isSortable) {
				
				var header = this.columnHeader.headerTable;
				var length = header.rows[0].cells.length;
				
				for (var j=0; j < length; j++) {
					var sortable = Element.getAttributeValue( this.element.rows[0].cells[j], 'sortable', true );
					
					if (sortable) {
						if ( this.fixedColumns > 0 ) {
							var fixedHeader = this.fixedHeader.headerTable;
							
							Event.observe( fixedHeader.rows[0].cells[j], 'click', this.sortTable.bindAsEventListener( this ) );
							fixedHeader.rows[0].cells[j].title = this.sortTitle;
						}
						
						Event.observe( header.rows[0].cells[j], 'click', this.sortTable.bindAsEventListener( this ) );
						header.rows[0].cells[j].title = this.sortTitle;
					}
				}
				
				if (this.presortedColumn && this.element.rows.length > this.fixedLines ) {
					//this.sortTable( this.columnHeader.headerTable.rows[0].cells[ ( this.presortedColumn - 1 ) ] );
				}
			}
			
					
			if (this.isFiltrable) {
				for (var i=0; i < cellLength; i++) {
					var filterBox = Element.getFirstChildByTagName( this.element.rows[1].cells[i], 'SELECT' );
					
					if (filterBox) {
						filterBox.style.visibility = 'hidden';
						var cloneBox = Element.getFirstChildByTagName( this.columnHeader.headerTable.rows[1].cells[i], 'SELECT' );
						
						Event.observe( cloneBox, 'change', this.filterTable.bindAsEventListener( this ) );
						
						cloneBox.cellIdx = i;
						cloneBox.selectedIndex = 0;
					}
				}
			}
		}
		
		Form.insertHidden( this.id + '_EK_WIDGET_VALUE', '' );
		
		this.setSelectionHandler();
		this.setSelection();
		
		if ( this.selected && this.scrollSelectionIntoView )
			this.scrollRowIntoView( this.selected );
		
		if ( tabCtrl != null ) {
			tabCtrl.switchTab( tabCtrl.getSelected() );
		}
		
		// Needs further investigation.
		// Resize fails in IE in Linsize project
		//Event.observe( this.element, 'resize', this.resizeTable.bindAsEventListener(this) );
		
		this.initialized = true;
		
		//alert( 'Init table took: ' + timer.stopTimer()  + ' seconds' );
	},
	
	onRowOver : function( evt )
	{
		if ( this.container.disabled ) {
			return;
		}
		
		var target = $GE(evt);
		var tr = $(target).up('tr');
		tr.addClassName('hilite');
	},
	
	onRowOut : function( evt )
	{
		if ( this.container.disabled ) {
			return;
		}
		
		var target = $GE(evt);
		var tr = $(target).up('tr');
		tr.removeClassName('hilite');
	},
	
	
	setSelection: function()
	{
		var submitValues = new Array();
		
		if (!this.selected && this.selectFirstItem ) {
			if (this.element.rows.length > this.fixedLines ) {
				if ( this.selectionType == 'selectrow' ) {
					var row = this.element.rows[this.fixedLines];
					submitValues[0] = row.id;
				}
				
				if (this.selectionType == 'selectcell') {
					cell = this.element.rows[this.fixedLines].cells[this.fixedColumns];
					submitValues[0] = cell.id;
				}
			}
		} else if ( this.selected ) {
			submitValues = this.selected.split(',');
		}
		
		for ( var i=0; i < submitValues.length; i++) {
			if (this.selectionType == 'selectrow')
				this.selectRow( submitValues[i] );
			
			if (this.selectionType == 'selectcell')
				this.selectCell( submitValues[i] );
		}		
	},
	
	
	setSelectionHandler: function() 
	{
		switch (this.selectionType.toLowerCase()) {
			case 'selectrow':
				Event.observe( this.element, 'click', this.selectRow.bindAsEventListener(this), false );
				
				if (this.fixedColumns > 0)
					Event.observe( this.rowHeader.header, 'click', this.selectRow.bindAsEventListener(this), false);
					
				break;
				
			case 'selectcell':
				Event.observe( this.element, 'click', this.selectCell.bindAsEventListener(this), false );
				
				if (this.fixedColumns > 0)
					Event.observe( this.rowHeader.header, 'click', this.selectCell.bindAsEventListener(this), false);
					
				break;
				
			case 'selectrowandsubmit':
				Event.observe( this.element, 'click', this.selectRowAndSubmit.bindAsEventListener(this), false );
				
				if (this.fixedColumns > 0)
					Event.observe( this.rowHeader.header, 'click', this.selectRowAndSubmit.bindAsEventListener(this), false);
					
				break;
				
			default:
				break;
		}
		
		Event.observe( this.container, 'scroll', this.onScrollStart.bindAsEventListener(this), false );
		Event.observe( this.container, 'mousewheel', this.onMouseWheel.bindAsEventListener(this), false);
	},
			
	onRowClicked: function( evt )
	{
		if (this.container.disabled) {
			return;
		}
		
		this.onClicked.call( this, evt );
	},
		
	
	onSelectionChanged: function( evt ) 
	{
		if (this.container.disabled) {
			return;
		}
		
		this.onSelectionChange.call( this, evt );
	},
	
	
	onRowDblClicked: function( evt )
	{
		var element = $GE(evt);
		
		element.setAttribute('action', this.action );
		element.setAttribute('targetdlg', this.targetdlg );
		
		this.onDblClicked.call( this, element );
	},
	
	
	reset: function()
	{
		if (!this.initialized)
			return;
		
		for (var i=0; i < this.selectedElements.length; i++)
			this.deselectRow( this.selectedElements[i] );
		
		this.submitValues = [];
		this.selectedElements = [];
		this.setSubmitValue('');
	},
	
	
	setSubmitValue: function( value )
	{
		$(this.id + '_EK_WIDGET_VALUE').value = value;
	},
	
	
	getSubmitValue: function()
	{
		return $F( this.id + '_EK_WIDGET_VALUE' );
	},
	
	
	selectRow: function( evt )
	{
		if ( this.container.disabled ) {
			return;
		}
		
		var modifier = Event.getModifier( evt );
		var element	 = $GE( evt );
        
		if ( element == null ) {
			if ( this.element.rows.length <= this.fixedLines ) 
				return;
				
			element = this.element.rows[this.fixedLines];
		}
		
		if (!this.multipleSelection || (this.multipleSelection && modifier != 'ctrl')) {
            this.reset();
		}
		
		var row = Element.getParentElementByTagNameAndAttribute( element, 'TR', 'id' );
		
		if (!row) {
			this.setSubmitValue('');
			return;
		}
		
		if ( !this.submitValues.inArray( row.id ) ) {
			this.submitValues[this.submitValues.length] = row.id;
			this.selectedElements[this.selectedElements.length] = element;
		} else {
			this.deselectRow( element );
			return;
		}
	
		row.setAttribute( 'selected', true );
		row.className += " selected";
		
		if( this.fixedColumns > 0 && !this.hasRowHeader) {
            this.element.rows[row.rowIndex].className += " selected";
            this.element.rows[row.rowIndex].setAttribute('selected', true);
            
            var fixedRow = this.rowHeader.headerTable.rows[row.rowIndex];
			fixedRow.className += " selected";
			fixedRow.setAttribute( 'selected', true );
		}
		
		if ( this.hasRowHeader ) {
			this.element.rows[row.rowIndex].className += ' rowheader';
		}
		this.setSubmitValue( this.submitValues.toString() );
	},
	
	
	deselectRow: function( element )
	{
		var row = Element.getParentElementByTagNameAndAttribute(element, 'TR', 'id');
		
		if (!row) {
			this.setSubmitValue('');
			return;
		}
		
		row.className = row.className.replace( "selected", "" );
		row.setAttribute('selected', false);
		
		if (this.fixedColumns > 0 && !this.hasRowHeader) {
            $(this.element.rows[row.rowIndex]).removeClassName('selected'); //.className
            this.element.rows[row.rowIndex].setAttribute('selected', false);
            
			var fixedRow = this.rowHeader.headerTable.rows[row.rowIndex];
			fixedRow.setAttribute('selected', false);
			fixedRow.className = fixedRow.className.replace('selected', '');
		}
		
		if ( this.hasRowHeader ) {
			this.element.rows[row.rowIndex].className = this.element.className + ' rowheader';
		}
			
		this.submitValues.removeEntry( row.id );
		this.setSubmitValue( this.submitValues.toString() );
	},
	
	
	selectRowAndSubmit: function( evt )
	{
		if ( this.container.disabled ) {
			return;
		}
		
		this.selectRow( evt );
		ekSubmit( this.id );
	},
	
	
	selectCell: function( evt )
	{
		if (this.container.disabled) {
			return;
		}
		
		var modifier = Event.getModifier( evt );
		var element	 = $GE( evt );
		
		if (!this.multipleSelection || (this.multipleSelection && modifier != 'ctrl'))
			this.reset();
		
		var cell 	= Element.getParentElementByTagName(element, 'TD');
		
		if ( !cell )
			return;
			
		if ( this.hasRowHeader ) {
			if ( cell.cellIndex < this.fixedLines ) {
				this.selectRow( evt );
				return;
			}
		}
		
		var row		= Element.getParentElementByTagName( cell, 'TR' );
		var className = this.element.className + '-cell-highlight';
		
		if ( !this.submitValues.inArray( cell.id ) ) {
			this.submitValues[this.submitValues.length] = cell.id;
			this.selectedElements[this.selectedElements.length] = element;
		} else { 
			this.deselectCell( element );
			return;
		}
		
		if (this.fixedColumns > 0 && !this.hasRowHeader) {
			var row 	 = Element.getParentElementByTagName( cell, 'TR' );
			var fixedCell = this.rowHeader.headerTable.rows[row.rowIndex].cells[cell.cellIndex];
			
			fixedCell.setAttribute('selected', true );
			
			fixedCell.className = className
		}
		
		cell.setAttribute('selected', true);
		
		cell.className = className
		
		this.setSubmitValue( this.submitValues.toString() );
	},
	
	
	deselectCell: function( element )
	{
		var cell = Element.getParentElementByTagName(element, 'TD');
		
		if ( !cell )
			return;

		if ( this.hasRowHeader ) {
			if ( cell.cellIndex < this.fixedColumns ) {
				this.deselectRow( evt );
			}
		}
						
		var row	= Element.getParentElementByTagName( cell, 'TR' );
		
		var className = this.element.className + '-cell';
		
		if ( (row.rowIndex ) % 2 == 0 && this.toggleRowStyles)
			className = this.element.className + '-altcell';
			
		cell.setAttribute('selected', false);
		cell.className = className;
		
		this.submitValues.removeEntry( cell.id );
		this.setSubmitValue( this.submitValues.toString() );
	},	
	 
	
	filterTable: function ( evt )
	{
		if (this.container.disabled) {
			return;
		}
		
		var filterBox	= $GE( evt );
		var rows 		= this.element.rows;
		var cellIdx 	= filterBox.cellIdx;
		var filterVal 	= filterBox.options[filterBox.selectedIndex].value;
		
		if (this.activeFilter != null && this.activeFilter != filterBox)
			this.activeFilter.selectedIndex = 0;
			
		for (var i=this.fixedLines; i < rows.length; i++) {
			if (this.fixedColumns > 0)
				this.rowHeader.headerTable.rows[i].style.display = '';
				
			rows[i].style.display = '';
			
			if (filterVal != 'ALL' && rows[i].cells[cellIdx].filtercriterium != filterVal) {
				rows[i].style.display = 'none';	
				
				if (this.fixedColumns > 0)
					this.rowHeader.headerTable.rows[i].style.display = 'none';
			}		
		}
		
		this.activeFilter = filterBox;
		
		if ( this.toggleRowStyles )
			this.setRowStyles();
		
		
	},
	
		
	sortTable: function( element )
	{
		if (this.container.disabled) {
			return;
		}
		
		var element = $GE(element);
		
		var col = Element.getParentElementByTagName( element, 'TD', true );
		var cellIndex = col.cellIndex;
	
		var tmpEl;
	  	var i, j;
	  	var minVal, minIdx;
	  	var compVal;
	  	var cmp;
	  	
		descend = col.descend;
		
		var descendStyle = 'easygui-table-header-za-sorted';
		
		if (Dialog.Style.ruleExists( this.element.className + '-header-za-sorted' ))
			descendStyle = this.element.className + '-header-za-sorted';
					
		var ascendStyle 	= 'easygui-table-header-az-sorted';
		
		if (Dialog.Style.ruleExists( this.element.className + '-header-az-sorted' ))
			ascendStyle = this.element.className + '-header-az-sorted';
		
		if(descend) {
			col.descend = false;
		
			if (this.isSortable)
				col.className = this.element.className + ' header ' + descendStyle;
		} else {
			col.descend = true;
			
			if (this.isSortable)
				col.className = this.element.className + ' header ' + ascendStyle;
		}

		if (this.lastSortCol && this.lastSortCol != col) {
			if (this.lastSortCol.descend)
				Element.removeClassName( this.lastSortCol, ascendStyle );	
			else
				Element.removeClassName( this.lastSortCol, descendStyle );
					
			this.lastSortCol.descend = false;
		}
		
	  	for (i = this.fixedLines; i < this.element.rows.length; i++) {
			minIdx = i;
			
			minVal = ( sortcriterium = this.element.rows[i].cells[cellIndex].getAttribute( 'sortcriterium' ) ) ? sortcriterium : Element.getInnerText( this.element.rows[i].cells[cellIndex]);
			
	    	//minVal = this.element.rows[i].cells[cellIndex].sortcriterium;
	    	
			for (j = i+1; j < this.element.rows.length; j++) {
	      		//compVal = this.element.rows[j].cells[cellIndex].sortcriterium;
	      		compVal = ( sortcriterium = this.element.rows[j].cells[cellIndex].getAttribute('sortcriterium' ) ) ? sortcriterium : Element.getInnerText( this.element.rows[j].cells[cellIndex]);
	      		cmp = Sort.compareValues(minVal, compVal);
	
	      		if (cmp > 0) {
	        		minIdx = j;
	        		minVal = compVal;
	      		}
	    	}
	    	
	    	if (minIdx > i) {
	    		if (this.fixedColumns > 0 ) {
	    			tmpEl = this.rowHeader.headerTable.tBodies[0].removeChild( this.rowHeader.headerTable.rows[minIdx] );
	    			this.rowHeader.headerTable.tBodies[0].insertBefore( tmpEl, this.rowHeader.headerTable.rows[i] );
	    		}
	    		
	      		tmpEl = this.element.tBodies[0].removeChild( this.element.rows[minIdx] );
	      		this.element.tBodies[0].insertBefore(tmpEl, this.element.rows[i]);
	    	}
	  	}
	  	
	  	this.lastSortCol = col;
	  	this.setRowStyles();
	},
		
	sortTable_: function( element )
	{
		var timer = new JS_Timer();
		timer.startTimer();
		
		var element = $GE(element);
		
		var col 		= Element.getParentElementByTagName( element, 'TD', true );
		var cellIdx 	= col.cellIndex;
	
		var descendStyle = 'easygui-table-header-za-sorted';
		
		if (Dialog.Style.ruleExists( this.element.className + '-header-za-sorted' ))
			descendStyle = this.element.className + '-header-za-sorted';
					
		var ascendStyle 	= 'easygui-table-header-az-sorted';
		
		if (Dialog.Style.ruleExists( this.element.className + '-header-az-sorted' ))
			ascendStyle = this.element.className + '-header-az-sorted';
		
		if( col.descend ) {
			col.descend = false;
		
			if (this.isSortable)
				col.className = this.element.className + ' header ' + descendStyle;
		} else {
			col.descend = true;
			
			if (this.isSortable)
				col.className = this.element.className + ' header ' + ascendStyle;
		}
		
		if (this.lastSortCol && this.lastSortCol != col) {
			if (this.lastSortCol.descend)
				Element.removeClassName( this.lastSortCol, ascendStyle );	
			else
				Element.removeClassName( this.lastSortCol, descendStyle );
					
			this.lastSortCol.descend = false;
		}
		
		var tBody = this.element.tBodies[0];
		var trs = tBody.rows;
		var a = new Array();
		var j = 0;
		
		for (var i=this.fixedLines; i < trs.length; i++) {
		  	a[j] = trs[j];
		  	j++;
		}
			
		a.sort( this.compareByColumn( cellIdx, col.descend ) );
			
		for (var i=0; i<a.length; i++) {
		  	tBody.appendChild(a[i]);
		  	
		  	if ( this.fixedColumns > 0 )
				this.rowHeader.headerTable.tBodies[0].appendChild( this.rowHeader.headerTable.rows[a[i].rowIndex] );	
		}
		
		alert( 'DOM Operations took: ' + timer.stopTimer()  + 's' );
		
		if ( this.toggleRowStyles )
			this.setRowStyles();
			
	  	this.lastSortCol = col;
	},
	
	compareByColumn : function (c, d)
	{
		descend = d;
		
		return function (n1, n2) 
		{
			var a = Element.getInnerText( n1.cells[c] );
			var b = Element.getInnerText( n2.cells[c] );
			
			return Sort.compareValues( a, b );
		};
	},
	
	
	setRowStyles: function()
	{
		var rows = this.element.rows;
		var rowsLength = rows.length;
		var j=0;
		
		for (var i = this.fixedLines; i < rowsLength; i++) {
			if (rows[i].style.display != 'none') {
				Element.removeClassName( rows[i], 'altrow' );
				if ( (j++ % 2) != 0 )
					Element.addClassName( rows[i], 'altrow' );

				if ( this.selectionType == "selectcell" ) {
					var cells 		= rows[i].cells;
					var cellsLength = cells.length;
				
					if (this.fixedColumns > 0)
						var headerCells = this.rowHeader.headerTable.rows[i].cells;
						
					for (var j=0; j < cellsLength; j++) {
						if (this.fixedColumns > 0 && !headerCells[j].selected )
							headerCells[j].className = className;
						
						if (!cells[j].selected)
							cells[j].className = className;
					}
				}
			}
		}
	},
	
	getRowCount: function()
	{
		return this.element.rows.length - parseInt(this.fixedLines);
	},
		
	hasFixedLines: function()
	{
		return (this.fixedLines > 0);
	},
	
	hasFixedColumns: function()
	{
		return ( this.fixedColumns > 0 );
	},
	
	hide: function()
	{
		Element._hide( this.container );
		
		if ( this.hasFixedLines() ) {
			Element._hide( this.id + '_FL' );
			
			if ( is.ie5up )
				Element._hide( this.columnHeader.header.iframeEl );
		}
		
		if ( this.hasFixedColumns() ) {
			Element._hide( this.id + '_FC' );
			
			if ( is.ie5up )
				Element._hide( this.rowHeader.header.iframeEl );
		}
		
		if ( this.hasFixedLines() && this.hasFixedColumns() ) {
			Element._hide( this.id + '_FIX' );
			
			if ( is.ie5up )
				Element._hide( this.fixedHeader.header.iframeEl );
		}
	},

	show: function()
	{
		Element._show( this.container );
		
		if ( this.hasFixedLines() ) {
			Element._show( this.id + '_FL' );
			
			if ( is.ie5up )
				Element._show( this.columnHeader.header.iframeEl );
		}
		
		if ( this.hasFixedColumns() ) {
			Element._show( this.id + '_FC' );
			
			if ( is.ie5up )
				Element._show( this.rowHeader.header.iframeEl );
		}
		
		if ( this.hasFixedLines() && this.hasFixedColumns() ) {
			Element._show( this.id + '_FIX' );
			
			if ( is.ie5up )
				Element._show( this.fixedHeader.header.iframeEl );
		}
	},
	
	disable : function()
	{
		this.container.disabled = true;
	},
	
	enable : function()
	{
		this.container.disabled = false;
	},
	
	
	getSelected: function()
	{
		return this.getSubmitValue();
	},
	
	resizeTable: function( evt )
	{
		if (this.fixedLines > 0) {
			this.columnHeader.header.style.width 			= this.container.clientWidth + 'px';
			this.columnHeader.header.iframeEl.style.width 	= this.container.clientWidth + 'px';
			self.status = "Resizing to : " + this.columnHeader.header.style.width;
		}
	},
	
	
	scrollRowIntoView: function( element )
	{
		var target 	= $GE( element );

		if (!target)
			return;
			
		var tableScrollTop = 0;
		
		for ( var i=this.fixedLines; i < target.rowIndex; i++ ) {
			tableScrollTop += this.element.rows[i].offsetHeight;
		}
		
		this.container.scrollTop = tableScrollTop;
	},
	
	
	onScrollStart: function( evt )
	{
		var target 	= $GE( evt );
		var table 	= Element.getFirstChildByTagName( target, 'TABLE');
		
		if ( (this.fixedLines == 0 && this.fixedColumns == 0))
			return;
			
		var fixedLine			= $( this.id + "_FL" );
		var fixedColumn			= $( this.id + "_FC" );
		
		var fixedLineTable		= null;
		var fixedColumnTable	= null;
		
		if (this.fixedLines > 0)
			fixedLineTable 		= Element.getFirstChildByTagName( fixedLine, 'TABLE');
	
		if (this.fixedColumns > 0)
			fixedColumnTable 	= Element.getFirstChildByTagName( fixedColumn , 'TABLE');
		
		if (this.currentScrollTop != target.scrollTop) {
			if ( fixedColumnTable )
				fixedColumnTable.style.top = - target.scrollTop + 'px';
		} else {
			if (fixedLineTable)
				fixedLineTable.style.left = - target.scrollLeft + 'px';
		}
		
		this.currentScrollTop 	= target.scrollTop;
		this.currentScrollLeft 	= target.scrollLeft;
	},
	
	onMouseWheel: function( evt )
	{
		if (this.container.disabled) {
			Event.stop(evt);
			return false;
		}
	}
});

var EasyGUI_TableHeader = Class.create();

 
EasyGUI_TableHeader.prototype =
{
	id: null,
	header: null,
	headerTable: null,
	element: null,
	container: null,
	zIndex: 200,
	fl: 0,
	fc: 0,
	height: 0,
	width: 0,
	
	
	initialize: function( table ) 
	{
		this.id 			= table.id;
		this.element 		= table.element;
		this.container 		= table.container;
		
		this.fl				= table.fixedLines;
		this.fc				= table.fixedColumns;
		
		this.header 		= table.container.cloneNode( true );
		
		this.header.style.overflow 	= 'hidden';
		
		this.headerTable 	= Element.getFirstChildByTagName( this.header, 'TABLE' );
		this.headerTable.id = this.header.id + '_TABLE';
		
		this.headerTable.style.position = 'absolute';
		
		Element.setPosition( this.headerTable, '0px', '0px');
		
		this.headerTable.style.width = this.container.clientWidth + 'px';
		
		this.removeHeaderInputs();
		
		this.setHeight();
		this.setWidth();
		
		this.render();
		
		this.header.style.zIndex 	= this.zIndex;
	},
	
	
	removeHeaderInputs: function()
	{
		for ( var i=0; i < this.fl; i++ ) {
			var nodes = $(this.element.rows[i]).getElementsBySelector('select');
			var element = this.element;
			
			['select','input','textarea'].each( function(name,index) {
				var nodes = $(element.rows[i]).getElementsBySelector(name);
				
				nodes.each( function(node, idx ) {
					node.id += '_EK_REMOVED';
					node.name += '_EK_REMOVED';
					node.style.visibility = "hidden";
				});
			});
				
			
		}
	},

	
	setIframe: function() {
		if (is.ie5up) {
			this.header.iframeEl = this.header.parentNode.insertBefore( Util.getIframe(), this.header);
			
			Element.setPosition( this.header.iframeEl, this.header.offsetTop, this.header.offsetLeft );
			
			Element.show( this.header.iframeEl );
			//Element.setStyle( this.header.iframeEl, { 'position': 'absolute', 'z-index': this.zIndex - 1 } );
			
			this.header.iframeEl.style.position = 'absolute';
			this.header.iframeEl.zIndex = this.zIndex - 1;
			
			Element.setDimension(this.header.iframeEl, this.container.clientWidth, this.height);
		}
	},
	
	
	setWidth: function() {
		for (var i=0; i < this.fl; i++)
			this.width += parseInt(this.element.rows[0].cells[i].offsetWidth);
	},
	
	
	setHeight: function() {
		for (var i=0; i < this.fl; i++)
			this.height += parseInt(this.element.rows[i].offsetHeight);
			
		var tableBorderTop = parseInt( Element.getStyle( this.element, 'border-top-width' ) );
		
		if ( isNaN( tableBorderTop ) )
			tableBorderTop = 0;
			
		this.height += tableBorderTop;
	}
};

var EasyGUI_TableFixedHeader = Class.create();

Object.extend( Object.extend( EasyGUI_TableFixedHeader.prototype, EasyGUI_TableHeader.prototype ), 
{
	render: function()
	{
		this.zIndex 	= 400;	
		this.header.id 	= this.id + '_FIX';
		
		var header = $(this.header.id);
		
		if ( header != null ) {
			header.remove();
		}
		
		this.container.parentNode.appendChild( this.header );
		
		Element.setDimension( this.header, this.width, this.height );
	},
	
	
	setWidth: function() {
		for (var i=0; i < this.fc; i++)
			this.width += parseInt(this.element.rows[0].cells[i].offsetWidth);
	}
});


var EasyGUI_TableColumnHeader = Class.create();
 
Object.extend( Object.extend( EasyGUI_TableColumnHeader.prototype, EasyGUI_TableHeader.prototype ), 
{
	render: function() 
	{
		this.zIndex		= 300;
		this.header.id 	= this.id + '_FL';
		
		var header = $(this.header.id);
		
		if ( header != null ) {
			header.remove();
		}
		
		this.container.parentNode.appendChild( this.header );
		
		this.setIframe();
		
		Element.setDimension(this.header, this.container.clientWidth, this.height);
	},
	
	setHeight_: function() 
	{
		var cellSpacing 	= 4;
		var borderIdx 		= (this.fl > 0) ? (this.fl - 1) : 0;
		var tabBorderTop 	= parseInt( Element.getStyle( this.element, 'border-top-width'));
			
		if (isNaN(tabBorderTop))
		{
			tabBorderTop = 0;
		}
		
		this.height += tabBorderTop;
		
		var rowBorderBottom = parseInt( Element.getStyle( this.element.rows[borderIdx], 'border-bottom-width' ));
		
		if ( isNaN( rowBorderBottom ))
		{
			rowBorderBottom = 0;
		}
	
		this.height += rowBorderBottom;
		
		if ( this.element.cellSpacing != '' )
		{
			cellSpacing = 2 * parseInt( this.element.cellSpacing ); 
		}
	
		for ( var i=0; i < this.fl; i++ ) 
		{
			if ( is.ie5up ) 
			{
				rowBorderTop = parseInt( Element.getStyle( this.element.rows[i], 'border-top-width' ));
				
				if ( isNaN( rowBorderTop ))
				{
					rowBorderTop = 0;
				}
			
				this.height += rowBorderTop;	
			}
			
			this.height += parseInt(this.element.rows[i].offsetHeight) + cellSpacing;
		}
	}
});

var EasyGUI_TableRowHeader = Class.create();

Object.extend( Object.extend( EasyGUI_TableRowHeader.prototype, EasyGUI_TableHeader.prototype ), 
{
	render: function()
	{
		this.header.id 	= this.id + '_FC';	
		this.setIframe();
		
		var header = $(this.header.id);
		
		if ( header != null ) {
			header.remove();
		}
		
		this.container.parentNode.appendChild( this.header );
		
		Element.setDimension( this.header, this.width, this.container.clientHeight );
	},

	
	setWidth: function() {
		for (var i=0; i < this.fc; i++)
			this.width += parseInt(this.element.rows[0].cells[i].offsetWidth);
	}
});

function onComplete( obj )
{
	
		
	if ( obj.responseText ) 
	{
		var serverResponse = obj.responseText.stripTags();
	} 
	else
	{
		var serverResponse = extractIframeBody( obj ).body.innerHTML;
	}
	
	eval( serverResponse );
}

function extractIframeBody( IFrameObj ) 
{
	if (IFrameObj.contentDocument)
	{
    	return IFrameObj.contentDocument; 
	}
  	else if (IFrameObj.contentWindow)
  	{
    	return IFrameObj.contentWindow.document;
  	}
  	else if (IFrameObj.document)
  	{
    	return IFrameObj.document;
  	}
  	else
  	{
    	return false;
  	}
}

var DEBUGTIME	= false;
var DEBUG 		= false;
var validate 	= true;
var closeWindow = false;
var remoteCall	= false;
var initialized = false;
var IFrameObj; 				// our IFrame object

var GUITIME		= '';

var widgets		= new Array();
var dialog;

var EasyGUI = 
{
  	Version: 'XP',
  	Build: '292',

  	PATH: 		'',
	JS_PATH: 	'',
	CSS_PATH: 	'',
	YUI_PATH:	'',
	YUI_EXT_PATH:'',
	
	DEBUG: 		false,
	DEBUGTIME: 	false,
	
	
	initUI: function()
	{
		if ( EasyGUI.DEBUGTIME ) {
			var timer = new JS_Timer();
			timer.startTimer();
		}
		
		dialog = new Dialog();
		dialog.init();
		
		if ( EasyGUI.DEBUGTIME ) {
			alert( 'Time to build GUI: ' + timer.stopTimer() + "\r\n\r\n" + GUITIME );
		}
	},
	
	
  	setPath: function()
	{
		var allScripts = document.getElementsByTagName('script');
		
		for ( var i=0; i < allScripts.length; i++ )
		{
			if ( allScripts[i].src.match(/easygui\.js(\?.*)?$/) )
			{
				EasyGUI.PATH 		= allScripts[i].src.replace( /\/easygui\.js(\?.*)?$/,'');
				break;
			}
			
		}	
	},
	
	
  	require: function( library )
  	{
  		document.writeln('<script type="text/javascript" src="' + library + '"></script>');
  	},
  	
  	
  	load: function( ) 
  	{
  		if ( typeof( BUILD ) != "undefined" && BUILD ) return;
  		
  		EasyGUI.setPath();
  		
  		EasyGUI.require( EasyGUI.PATH + "/core/lib/scriptaculous/lib/prototype.js" );
  		EasyGUI.require( EasyGUI.PATH + "/core/lib/scriptaculous/src/scriptaculous.js" );
  		EasyGUI.require( EasyGUI.PATH + "/core/lib/scriptaculous/src/builder.js" );
  		EasyGUI.require( EasyGUI.PATH + "/core/lib/scriptaculous/src/effects.js" );
  		EasyGUI.require( EasyGUI.PATH + "/core/lib/scriptaculous/src/dragdrop.js" );
  		EasyGUI.require( EasyGUI.PATH + "/core/lib/scriptaculous/src/controls.js" );
  		EasyGUI.require( EasyGUI.PATH + "/core/lib/scriptaculous/src/slider.js" );
  		
  		EasyGUI.require( EasyGUI.PATH + "/core/lib/lib.core.js" );
  		EasyGUI.require( EasyGUI.PATH + "/core/lib/lib.compat.js" );
  		
  		EasyGUI.require( EasyGUI.PATH + "/core/class.browser.js" );
  		EasyGUI.require( EasyGUI.PATH + "/core/class.dialog.js" );
  		
  		EasyGUI.require( EasyGUI.PATH + "/lib/lib.easygui.js" );
  		EasyGUI.require( EasyGUI.PATH + "/lib/lib.element.js" );
  		EasyGUI.require( EasyGUI.PATH + "/lib/lib.event.js" );
  		EasyGUI.require( EasyGUI.PATH + "/lib/lib.form.js" );
  		EasyGUI.require( EasyGUI.PATH + "/lib/lib.util.js" );
  		EasyGUI.require( EasyGUI.PATH + "/lib/lib.sort.js" );
  		EasyGUI.require( EasyGUI.PATH + "/lib/lib.datetime.js" );
  		
		EasyGUI.require( EasyGUI.PATH + "/utils/class.timer.js" );
	
		EasyGUI.require( EasyGUI.PATH + "/validator/class.validator.js" );
		EasyGUI.require( EasyGUI.PATH + "/validator/class.validator.date.js" );
		EasyGUI.require( EasyGUI.PATH + "/validator/class.validator.alphanum.js" );
		EasyGUI.require( EasyGUI.PATH + "/validator/class.validator.email.js" );
		EasyGUI.require( EasyGUI.PATH + "/validator/class.validator.num.js" );
		EasyGUI.require( EasyGUI.PATH + "/validator/class.validator.time.js" );
		
		EasyGUI.require( EasyGUI.PATH + "/win/class.guiwindow.js" );
		EasyGUI.require( EasyGUI.PATH + "/win/class.winregistry.js" );
		EasyGUI.require( EasyGUI.PATH + "/win/window.js" );
		
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.widget.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.button.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.checkbox.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.combobox.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.menu.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.treectrl.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.menutree.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.radiobutton.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.tabctrl.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.exttabctrl.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.edit.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/class.text.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/table/class.table.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/table/class.tableheader.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/table/class.fixedheader.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/table/class.columnheader.js" );
		EasyGUI.require( EasyGUI.PATH + "/widgets/table/class.rowheader.js" );
		
		EasyGUI.require( EasyGUI.PATH + "/remote/class.request.js" );
  	}
};

EasyGUI.load();
