/* prototype [ 'jscore/prototype.js' */
/*  Prototype JavaScript framework, version 1.5.0_rc1
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.0_rc1',
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

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

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

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 == undefined) return 'undefined';
      if (object == null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

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

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

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

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

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

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

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

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

    return returnValue;
  }
}

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

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  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);
  },

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

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
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 += (replacement(match) || '').toString();
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

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

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

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

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

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

  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 div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
  },

  toQueryParams: function() {
    var pairs = this.match(/^\??(.*)$/)[1].split('&');
    return pairs.inject({}, function(params, pairString) {
      var pair  = pairString.split('=');
      var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
      params[decodeURIComponent(pair[0])] = value;
      return params;
    });
  },

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

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

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

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

    return camelizedString;
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.replace(/\\/g, '\\\\');
    if (useDoubleQuotes)
      return '"' + escapedString.replace(/"/g, '\\"') + '"';
    else
      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }
});

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

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

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

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

var $break    = new Object();
var $continue = new Object();

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

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

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

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

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

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

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

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

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

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

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

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

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

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

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

  sortBy: function(iterator) {
    return this.collect(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.collect(Prototype.K);
  },

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

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

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

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

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; i < this.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 != undefined || value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

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

  indexOf: function(object) {
    for (var i = 0; i < this.length; i++)
      if (this[i] == object) return i;
    return -1;
  },

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

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

  uniq: function() {
    return this.inject([], function(array, value) {
      return array.include(value) ? array : array.concat([value]);
    });
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});
var Hash = {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (typeof value == 'function') continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

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

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

  merge: function(hash) {
    return $H(hash).inject($H(this), function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  toQueryString: function() {
    return this.map(function(pair) {
      return pair.map(encodeURIComponent).join('=');
    }).join('&');
  },

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

function $H(object) {
  var hash = Object.extend({}, object || {});
  Object.extend(hash, Enumerable);
  Object.extend(hash, Hash);
  return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  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(responderToAdd) {
    if (!this.include(responderToAdd))
      this.responders.push(responderToAdd);
  },

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

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

Object.extend(Ajax.Responders, Enumerable);

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

  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      parameters:   ''
    }
    Object.extend(this.options, options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

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

    /* Simulate other verbs over post */
    if (this.options.method != 'get' && this.options.method != 'post') {
      parameters += (parameters.length > 0 ? '&' : '') + '_method=' + this.options.method;
      this.options.method = 'post';
    }

    try {
      this.url = url;
      if (this.options.method == 'get' && parameters.length > 0)
        this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;

      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open((this.options.method=='post'?'POST':'GET'), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous)
        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

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

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

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

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

  setRequestHeaders: function() {
    var requestHeaders =
      ['X-Requested-With', 'XMLHttpRequest',
       'X-Prototype-Version', Prototype.Version,
       'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type', this.options.contentType);

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
       * header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

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

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

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

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

  evalJSON: function() {
    try {
      return eval('(' + this.header('X-JSON') + ')');
    } catch (e) {}
  },

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

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

    if (event == 'Complete') {
      try {
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

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

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

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

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

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.containers = {
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      onComplete(transport, object);
    }).bind(this);

    this.request(url);
  },

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

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

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        Element.update(receiver, response);
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(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(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $() {
  var results = [], element;
  for (var i = 0; i < arguments.length; i++) {
    element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);
    results.push(Element.extend(element));
  }
  return results.reduce();
}

document.getElementsByClassName = function(className, parentElement, el) {
  var children = ($(parentElement) || document.body).getElementsByTagName((typeof el!="undefined"?el:'*'));
  return $A(children).inject([], function(elements, child) {
    if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      elements.push(Element.extend(child));
    return elements;
  });
}

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

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

Element.extend = function(element) {
  if (!element) return;
  if (_nativeExtensions || element.nodeType == 3) return element;

  if (!element._extended && element.tagName && element != window) {
    var methods = Object.clone(Element.Methods), cache = Element.extend.cache;

    if (element.tagName == 'FORM')
      Object.extend(methods, Form.Methods);
    if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
      Object.extend(methods, Form.Element.Methods);

    for (var property in methods) {
      var value = methods[property];
      if (typeof value == 'function')
        element[property] = cache.findOrStore(value);
    }
  }

  element._extended = true;
  return element;
}

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
}

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

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

  update: function(element, html) {
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  replace: function(element, html) {
    element = $(element);
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  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) {
    element = $(element);
    return $A(element.getElementsByTagName('*'));
  },

  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) {
    element = $(element);
    if (typeof selector == 'string')
      selector = new Selector(selector);
    return selector.match(element);
  },

  up: function(element, expression, index) {
    return Selector.findElement($(element).ancestors(), expression, index);
  },

  down: function(element, expression, index) {
    return Selector.findElement($(element).descendants(), expression, index);
  },

  previous: function(element, expression, index) {
    return Selector.findElement($(element).previousSiblings(), expression, index);
  },

  next: function(element, expression, index) {
    return Selector.findElement($(element).nextSiblings(), expression, index);
  },

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

  getElementsByClassName: function(element, className) {
    element = $(element);
    return document.getElementsByClassName(className, element);
  },

  getHeight: function(element) {
    element = $(element);
    return element.offsetHeight;
  },

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

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

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

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).remove(className);
    return element;
  },

  observe: function() {
    Event.observe.apply(Event, arguments);
    return $A(arguments).first();
  },

  stopObserving: function() {
    Event.stopObserving.apply(Event, arguments);
    return $A(arguments).first();
  },

  // 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.match(/^\s*$/);
  },

  childOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var x = element.x ? element.x : element.offsetLeft,
        y = element.y ? element.y : element.offsetTop;
    window.scrollTo(x, y);
    return element;
  },

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

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

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

  setStyle: function(element, style) {
    element = $(element);
    for (var name in style)
      element.style[name.camelize()] = style[name];
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    if (Element.getStyle(element, 'display') != 'none')
      return {width: element.offsetWidth, height: element.offsetHeight};

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

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    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._overflow = element.style.overflow || 'auto';
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

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

// IE is missing .innerHTML support for TABLE-related elements
if(document.all){
  Element.Methods.update = function(element, html) {
    element = $(element);
    var tagName = element.tagName.toUpperCase();
    if (['THEAD','TBODY','TR','TD'].indexOf(tagName) > -1) {
      var div = document.createElement('div');
      switch (tagName) {
        case 'THEAD':
        case 'TBODY':
          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
          depth = 2;
          break;
        case 'TR':
          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
          depth = 3;
          break;
        case 'TD':
          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
          depth = 4;
      }
      $A(element.childNodes).each(function(node){
        element.removeChild(node)
      });
      depth.times(function(){ div = div.firstChild });

      $A(div.childNodes).each(
        function(node){ element.appendChild(node) });
    } else {
      element.innerHTML = html.stripScripts();
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  }
}

Object.extend(Element, Element.Methods);

var _nativeExtensions = false;

if (!window.HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  /* Emulate HTMLElement, HTMLFormElement, HTMLInputElement, HTMLTextAreaElement,
     and HTMLSelectElement in Safari */
  ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
    var klass = window['HTML' + tag + 'Element'] = {};
    klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
  });
}

Element.addMethods = function(methods) {
  Object.extend(Element.Methods, methods || {});

  function copy(methods, destination) {
    var cache = Element.extend.cache;
    for (var property in methods) {
      var value = methods[property];
      destination[property] = cache.findOrStore(value);
    }
  }

  if (typeof HTMLElement != 'undefined') {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Form.Methods, HTMLFormElement.prototype);
    [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
      copy(Form.Element.Methods, klass.prototype);
    });
    _nativeExtensions = true;
  }
}

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

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

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toLowerCase();
        if (tagName == 'tbody' || tagName == 'tr') {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

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

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

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

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

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

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

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(this.toArray().concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set(this.select(function(className) {
      return className != classNameToRemove;
    }).join(' '));
  },

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

Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
  initialize: function(expression) {
    this.params = {classNames: []};
    this.expression = expression.toString().strip();
    this.parseExpression();
    this.compileMatcher();
  },

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

    if (this.expression == '')  abort('empty expression');

    var params = this.params, expr = this.expression, match, modifier, clause, rest;
    while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
      params.attributes = params.attributes || [];
      params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
      expr = match[1];
    }

    if (expr == '*') return this.params.wildcard = true;

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

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

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

    if (params.wildcard)
      conditions.push('true');
    if (clause = params.id)
      conditions.push('element.id == ' + clause.inspect());
    if (clause = params.tagName)
      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    if ((clause = params.classNames).length > 0)
      for (var i = 0; i < clause.length; i++)
        conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
    if (clause = params.attributes) {
      clause.each(function(attribute) {
        var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
        var splitValueBy = function(delimiter) {
          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
        }

        switch (attribute.operator) {
          case '=':       conditions.push(value + ' == ' + attribute.value.inspect()); break;
          case '~=':      conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
          case '|=':      conditions.push(
                            splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
                          ); break;
          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
          case '':
          case undefined: conditions.push(value + ' != null'); break;
          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
        }
      });
    }

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

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

  findElements: function(scope) {
    var element;

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

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

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

    return results;
  },

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

Object.extend(Selector, {
  matchElements: function(elements, expression) {
    var selector = new Selector(expression);
    return elements.select(selector.match.bind(selector));
  },

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

  findChildElements: function(element, expressions) {
    return expressions.map(function(expression) {
      return expression.strip().split(/\s+/).inject([null], function(results, expr) {
        var selector = new Selector(expr);
        return results.inject([], function(elements, result) {
          return elements.concat(selector.findElements(result || element));
        });
      });
    }).flatten();
  }
});

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

Form.Methods = {
  serialize: 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.join('&');
  },

  getElements: function(form) {
    form = $(form);
    var elements = new Array();

    for (var tagName in Form.Element.Serializers) {
      var tagElements = form.getElementsByTagName(tagName);
      for (var j = 0; j < tagElements.length; j++)
        elements.push(tagElements[j]);
    }
    return elements;
  },

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

    if (!typeName && !name)
      return inputs;

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

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.blur();
      element.disabled = 'true';
    }
    return form;
  },

  enable: function(form) {
    form = $(form);
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.disabled = '';
    }
    return form;
  },

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

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

Object.extend(Form, Form.Methods);

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

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

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

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter) {
      var key = encodeURIComponent(parameter[0]);
      if (key.length == 0) return;

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

      return parameter[1].map(function(value) {
        return key + '=' + encodeURIComponent(value);
      }).join('&');
    }
  },

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

    if (parameter)
      return parameter[1];
  },

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

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

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select)
      element.select();
    return element;
  },

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

  enable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = 'true';
    return element;
  }
}

Object.extend(Form.Element, Form.Element.Methods);
var Field = Form.Element;

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

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

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

  textarea: function(element) {
    return [element.name, element.value];
  },

  select: function(element) {
    return Form.Element.Serializers[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var value = '', opt, index = element.selectedIndex;
    if (index >= 0) {
      opt = element.options[index];
      value = opt.value || opt.text;
    }
    return [element.name, value];
  },

  selectMany: function(element) {
    var value = [];
    for (var i = 0; i < element.length; i++) {
      var opt = element.options[i];
      if (opt.selected)
        value.push(opt.value || opt.text);
    }
    return [element.name, value];
  }
}

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

var $F = Form.Element.getValue;

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

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

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

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

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

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

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

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  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() {
    var elements = Form.getElements(this.element);
    for (var i = 0; i < elements.length; i++)
      this.registerCallback(elements[i]);
  },

  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();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

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

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,

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

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0; i < Event.observers.length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    Event._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      try {
        element.detachEvent('on' + name, observer);
      } catch (e) {}
    }
  }
});

/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
  Event.observe(window, 'unload', Event.unloadCache, false);
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;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

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

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

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

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

    return document.body;
  },

  // 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 = this.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 = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.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;
  },

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

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

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

    } while (element = element.offsetParent);

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

    return [valueL, valueT];
  },

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

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

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

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

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

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

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

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

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

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

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

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

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

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

    return [valueL, valueT];
  }
}

Element.addMethods();
/* prototype ]*/


var agt=navigator.userAgent.toLowerCase();
var NiceBrowser=(typeof encodeURIComponent != 'undefined') && (typeof document.getElementById != 'undefined');
var SafariBrowser=(agt.indexOf('safari')!=-1);
var OperaBrowser=(typeof window.opera=="undefined"?false:true);
var OperaVersion=(OperaBrowser?parseInt(agt.charAt(agt.lastIndexOf("opera")+6)):false);
var AjaxEnabled=Ajax.getTransport();

var MozBrowser = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1) && (agt.indexOf('compatible') == -1) && (!OperaBrowser) && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var IEBrowser=(navigator.appVersion.indexOf('MSIE') != -1) && !OperaBrowser;
var IEBrowserPNG=false;
var IEBrowserOld=false;
var weReady=false;

if (!OperaBrowser && IEBrowser && window.attachEvent)
{
  var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
  IEBrowserPNG = (rslt != null && Number(rslt[1]) >= 5.5 && Number(rslt[1]) < 7);
  IEBrowserOld = (rslt != null && Number(rslt[1]) < 6);
}

var JSList=new Array();

if (!JSRoot)
{
 var JSRoot="";
 if (NiceBrowser)
 {
   var scriptTags = document.getElementsByTagName("script");
   for(var i=0;i<scriptTags.length;i++)
   {
     if(scriptTags[i].src && scriptTags[i].src.match(/js\/base\.(.*)?$/))
     {
       JSRoot = scriptTags[i].src.replace(/js\/base\.(.*)?$/,'');
       break;
     }
   }
 }
}

// Code originally from jQuery: http://jquery.com/
(OnReady = {
    initialize: function() {
        if (!NiceBrowser) return false;
        var browser = navigator.userAgent.toLowerCase()
        if ((/mozilla/.test(browser) && !/compatible/.test(browser)) ||
            /opera/.test(browser)) {
            document.addEventListener( "DOMContentLoaded", OnReady.fire, false );
        } else if (/msie/.test(browser) && !/opera/.test(browser)) {
            document.write("<scr" + "ipt id=__ie_init defer "+"src=javascript:void(0)><\/script>");
            var script = document.getElementById("__ie_init");
            script.onreadystatechange = function() {
            if (this.readyState == "complete")
                OnReady.fire();
            };
            script = null;
        } else if (/webkit/.test(browser)) {
            OnReady.safariTimer = setInterval(function() {
                if (document.readyState == "loaded" || document.readyState == "complete") {
                    clearInterval( OnReady.safariTimer );
                    OnReady.safariTimer = null;
                    OnReady.fire();
                }
            }, 10);
        }
        Event.observe(window, 'load', OnReady.fire);
    },

    isReady: false,
    readyList: [],

    register: function(func) {
        if (OnReady.isReady )
            func.apply( document );
        else
            OnReady.readyList.push(func);
        return this;
    },

    fire: function() {
        if (!OnReady.isReady) {
            OnReady.isReady = true;
            if (OnReady.readyList) {
                for (var i = 0, func; func = OnReady.readyList[i]; ++i)
                    func.apply(document);
                OnReady.readyList = null;
            }
        }
    }
}).initialize();
if (!NiceBrowser) Event.observe=refalse;

function load_js(libraryName, condition)
{
  if (typeof condition!="undefined" && !condition) return false;
  if (!NiceBrowser) return false;

  for (var i=0;i<JSList.length;i++)
  {
    if (JSList[i]==JSRoot+libraryName) return;
  }

  JSList[JSList.length]=JSRoot+libraryName;

  // inserting via DOM fails in Safari 2.0
  document.write('<script type="text/javascript" src="'+JSRoot+libraryName+'"></script>');
}

function refalse()
{
  return false;
}

function trashCan(element)
{
  var garbageBin = document.getElementById('IELeakGarbageBin');
  if (!garbageBin)
  {
    garbageBin = document.createElement('DIV');
    garbageBin.id = 'IELeakGarbageBin';
    garbageBin.style.display = 'none';
    document.body.appendChild(garbageBin);
  }

  // move the element to the garbage bin
  garbageBin.appendChild(element);
  garbageBin.innerHTML = '';
}

/* base [ */
var Base={
 s:'',
 iwin:false,
 force_iwin:false,

 // try find session (it must be in field "sess")
 init: function()
 {
   if (!$("is_frame") && top != self) top.location.href = self.location.href;

   if ($('f_sess') && $('f_sess').title) Base.s=$('f_sess').title;

   if (SafariBrowser) SafariLabel.init();

   SearchForm.init();
   Base.we_ready();
   Base.check_vote();
 },

 // first argument - action, other elements id`s
 // stop selected event, becouse Event.stop not work in Safari
 stop_event: function()
 {

   for (var i = 1; i < arguments.length; i++) if ($(arguments[i]))
   {
     $(arguments[i])["on"+arguments[0]] = refalse;
   }
 },

 // return element where event "e" appear
 ev: function(e)
 {
   var el=false;
   if (e)
   {
     if (e.target) el = e.target; else if (e.srcElement) el = e.srcElement;

     if (el && el.nodeType == 3) // defeat Safari bug
     el = el.parentNode;
   }
   return el;
 },

 myescape: function(s)
 {
   return encodeURIComponent(s);
 },

 wopen: function(url,name,w,h,antiblock,resizable,scrollbars)
 {
   if (Base.force_iwin && antiblock)
   {
     //Base.iopen(url,name,w,h,resizable);
     //return true;
   }

   var win=window.open(url,name,"width="+w+",height="+h+",resizable="+((typeof resizable!="undefined")?resizable:"1")+",toolbar=0,location=0,status=0,menubar=0,directories=0,scrollbars="+((typeof scrollbars!="undefined")?scrollbars:"yes"));

   /*
   if (antiblock)
   {
    if (win == null) {
      Base.iopen(url,name,w,h,resizable);
    } else {
        setTimeout(function() {
            if (typeof win.parent == 'undefined') { // opera
               Base.iopen(url,name,w,h,resizable);
            }
        }, 200);
    }
   }
   */
   return win;
 },


 fix_opera: function()
 {
   $("body").setAttribute("tagName", "div");
 },

 add_city: function(vvalue,vtext,field)
 {
   var all=['f_location','f_slocation','f_tlocation','f_school_city'];

   if (typeof field=="undefined")
   {
     for (var i=0;i<all.length;i++)
     {
       if ($(all[i])) Base.add_city(vvalue,vtext,all[i]);
     }
     return true;
   }
   //if (typeof field=="undefined") field="f_location";
   //if (!$(field)) field="f_slocation";

   fcity=$(field);

   for (var i=0;i<fcity.options.length;i++)
    {
      if (fcity.options[i].value==vvalue)
       {
         fcity.options[i].selected=true;
         return false;
       }
    }
   var s=$(field).options.length;
   last=(fcity.options[s-1].value.substr(0,5)=="http:" || fcity.options[s-1].value.substr(0,8)=="/signup/");

   if (last)
   {
     opt=$(field).options[s-1];
     $(field).options[s]=new Option(opt.text,opt.value);

     $(field).options[$(field).length-2]=new Option(vtext,vvalue);
   }
   else
   {
     $(field).options[$(field).length]=new Option(vtext,vvalue);
     s++;
   }
   $(field).options[s-1].selected=true;
   //$(field).focus();

   if ($("f_tlocation") && (field!="f_tlocation") )
   {
     Base.add_city(vvalue,vtext,"f_tlocation");
   }
   return true;
 },

 form_post: function(form_el, post_id)
 {
   if ($(post_id).name)
   {
     var i = '<input type="hidden" name="'+$(post_id).name+'" value="'+$(post_id).value+'" />';
     new Insertion.Before($(post_id),i);
   }

   var i = '<img src="'+JSRoot+'loader-15.gif" width="15" height="15" border="0" style="visibility:hidden" align="absmiddle" />';
   new Insertion.After($(post_id),i);

   var form_post_submit = function(e)
   {
     $(post_id).nextSibling.style.visibility="visible";
     $(post_id).disabled=true;
   };
   Event.observe(form_el, "submit", form_post_submit , false);
 },


 form_post_enable: function(post_id)
 {
   $(post_id).nextSibling.style.visibility="hidden";
   $(post_id).disabled=false;
 },


 we_ready: function()
 {
   if (typeof $("Baloon")!="undefined" && Flash.init(7))
   {
     if ($("f_baloon_ts").value=="*")
      $("Baloon").innerHTML=Flash.draw(JSRoot+"flash/Baloon6.swf",24,24,false,$("f_baloon_vars").value, true);
     else
      $("Baloon").innerHTML=Flash.draw(JSRoot+"flash/Baloon"+(Flash.init(8)?"":"7")+".swf?"+$("f_baloon_ts").value,24,24,false,$("f_baloon_vars").value, true);
   }

   if (OperaBrowser && (typeof $("body")!="undefined")) window.setTimeout('Base.fix_opera()',5);

   if ($("f_post"))
   {
     var f=$("f_post");
     do
     {
       f=f.parentNode;
       if (f.tagName=='FORM')
       {
         Base.form_post(f, "f_post");
         break;
       }
     } while (f.tagName!='FORM' && f.tagName!='BODY');
   }

   var ef=document.getElementsByClassName('error');

   if (ef.length>0)
    var af=document.getElementsByClassName('autofocus',ef[0]);
   else
    var af=document.getElementsByClassName('autofocus');

   if (af.length>0) af[0].focus();
 },

 check_vote: function()
 {
   if ($("sign_vote"))
   {
     var l = new lightbox(false, "/popup-ws.phtml?do=getPromoServicePopup&data[type]=PromoVoteService&output=html"+Base.s);
     l.activate();
   }
   else if ($("signin_import"))
   {
     var l = new lightbox(false, "/popup-ws.phtml?do=getPromoServicePopup&data[type]=PromoAuthImportService&output=html"+Base.s);
     l.activate();
   }
 },

 init_signin_import: function()
 {
   Event.observe("liNext", "click", function(){
    var url="/contacts-ws.phtml?do=getPopup&data[type]=login&data[provider_id]="+$F("f_i_provider_id");
    url+="&data[invite_on]="+$F("fi_invite_on");
    url+="&promo_id="+$F("fi_promo_id");
    url+="&popup_id="+$F("fi_popup_id");

    var l = new lightbox($("liNext"), url+"&output=html"+Base.s);
    l.activate();
   });

   Base.stop_event("click","liNext");
   Base.stop_event("submit","li_form");
 },

 add_href: function(href, add)
 {
   return (href.indexOf("?")!=-1?"&":"?")+add;
 }
}
/* base ] */


/* flash [ 'jscore/flash.js' */
var Flash={
  init: function(version)
  {
    var n=navigator.userAgent;
    return Flash.detect(version, (n.indexOf("MSIE") != -1 && n.indexOf("Windows") != -1 && n.indexOf("Opera") == -1) );
  },

  detect: function (version,ie)
  {
    if (ie)
    {
     try {
       return new ActiveXObject('ShockwaveFlash.ShockwaveFlash.'+version);
     }
     catch(exception)
     {
       return false;
     }
    }
    else if (navigator.plugins['Shockwave Flash'])
    {
      plugin_descr = navigator.plugins['Shockwave Flash'].description;
      return (parseInt(plugin_descr.substring(plugin_descr.indexOf(".") - 1)) >= version);
    }
    return false;
  },

  draw: function(src,width,height,bgcolor,vars,transparent)
  {
    var ret='<object style="z-index:0" type="application/x-shockwave-flash" data="'+src+'"';
    ret+=(width?' width="'+width+'"':'')+(height?' height="'+height+'"':'')+'>';

    if (bgcolor)	ret+='<param name="bgcolor" value="'+bgcolor+'" />';
    if (vars)		ret+='<param name="FlashVars" value="'+vars+'" />';
    if (transparent)	ret+='<param name="wmode" value="transparent" />';

    ret+='<param name="allowScriptAccess" value="always" />';
    ret+='<param name="movie" value="'+src+'" />';
    ret+='<param name="menu" value="false" />';
    ret+='<param name="quality" value="high" />';
    ret+='</object>';

    return ret;
  }

}
/* flash ] */


/* safari [ 'jscore/safari_label.js' */
var SafariLabel={
 init: function()
 {
   var l=document.getElementsByTagName('label');
   for (var i=0;i<l.length;i++) if (l[i].getAttribute("for"))
   {
     Event.observe(l[i], "click", SafariLabel.click);
   }
 },

 click: function(e)
 {
   var t=Base.ev(e).getAttribute("for");
   if ($(t).click) $(t).click();
 }
}
/* safari ] */


/* moo fx [ 'jscore/moo.fx.js' */
/*
moo.fx, simple effects library built with prototype.js (http://prototype.conio.net).
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE.
for more info (http://moofx.mad4milk.net).
Sunday, March 05, 2006
v 1.2.3
*/

var fx = new Object();
//base
fx.Base = function(){};
fx.Base.prototype = {
	setOptions: function(options) {
	this.options = {
		duration: 500,
		onComplete: '',
		transition: fx.sinoidal
	}
	Object.extend(this.options, options || {});
	},

	step: function() {
		var time  = (new Date).getTime();
		if (time >= this.options.duration+this.startTime) {
			this.now = this.to;
			clearInterval (this.timer);
			this.timer = null;
			if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
		}
		else {
			var Tpos = (time - this.startTime) / (this.options.duration);
			this.now = this.options.transition(Tpos) * (this.to-this.from) + this.from;
		}
		this.increase();
	},

	custom: function(from, to) {
		if (this.timer != null) return;
		this.from = from;
		this.to = to;
		this.startTime = (new Date).getTime();
		this.timer = setInterval (this.step.bind(this), 13);
	},

	hide: function() {
		this.now = 0;
		this.increase();
	},

	clearTimer: function() {
		clearInterval(this.timer);
		this.timer = null;
	}
}

//stretchers
fx.Layout = Class.create();
fx.Layout.prototype = Object.extend(new fx.Base(), {
	initialize: function(el, options) {
		this.el = $(el);
		this.el.style.overflow = "hidden";
		this.iniWidth = this.el.offsetWidth;
		this.iniHeight = this.el.offsetHeight;
		this.setOptions(options);
	}
});

fx.Height = Class.create();
Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), {
	increase: function() {
		this.el.style.height = this.now + "px";
	},

	toggle: function() {
		if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
		else this.custom(0, this.iniHeight);
	}
});

fx.Width = Class.create();
Object.extend(Object.extend(fx.Width.prototype, fx.Layout.prototype), {
	increase: function() {
		this.el.style.width = this.now + "px";
	},

	toggle: function(){
		if (this.el.offsetWidth > 0) this.custom(this.el.offsetWidth, 0);
		else this.custom(0, this.iniWidth);
	}
});

fx.onCompleteHeight = function(el)
{
  $(el).style.height="";
}
//transitions
fx.sinoidal = function(pos){
	return ((-Math.cos(pos*Math.PI)/2) + 0.5);
	//this transition is from script.aculo.us
}
fx.linear = function(pos){
	return pos;
}
fx.cubic = function(pos){
	return Math.pow(pos, 3);
}
fx.circ = function(pos){
	return Math.sqrt(pos);
}

//smooth scroll
fx.Scroll = Class.create();
fx.Scroll.prototype = Object.extend(new fx.Base(), {
	initialize: function(options) {
		this.setOptions(options);
	},

	scrollTo: function(el){
		var dest = Position.cumulativeOffset($(el))[1];
		var client = window.innerHeight || document.documentElement.clientHeight;
		var full = document.documentElement.scrollHeight;
		var top = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
		if (dest+client > full) this.custom(top, dest - client + (full-dest));
		else this.custom(top, dest);
	},

	increase: function(){
		window.scrollTo(0, this.now);
	}
});

fx_s1 = function(el)
{
  $(el).style.height="";
  $(el).style.visibility="hidden";
  $(el).style.position="relative";
}
fx_s2 = function(el,next, nh)
{
 var h=$(el).offsetHeight;
 if (next) fx_s3(el, nh);
 return h;
}
fx_s3 = function(el, h)
{
  $(el).style.height=(typeof h=="undefined"?"0":h);
  $(el).style.visibility="visible";
  $(el).style.position="static";
}
fx_error = function(block, error)
{
  if ($(block).innerHTML==error) return false;
  fx_s1(block);

  $(block).innerHTML=error;

  var h=fx_s2(block);

  fx_s3(block)

  var myEffect = new fx.Height(block , {duration: 250});
  myEffect.custom(0,h);
  myEffect.toggle();
}

/* moo fx ] */


/* auto complete [ 'jscore/controls.js' */
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
//           (c) 2005 Jon Tirsen (http://www.tirsen.com)
// Contributors:  Richard Livsey  Rahul Bhargava  Rob Wills
// See scriptaculous.js for full license.

var Autocompleter = {}
Autocompleter.Base = function() {};
Autocompleter.Base.prototype = {
  baseInitialize: function(element, update, options) {
    this.element     = $(element);
    this.update      = $(update);
    this.hasFocus    = false;
    this.changed     = false;
    this.active      = false;
    this.index       = 0;
    this.lastIndex   = -1;
    this.entryCount  = 0;

    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.1;
    this.options.minChars     = this.options.minChars || 3;
    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});
      }
      Element.show(update);
    };
    this.options.onHide = this.options.onHide ||
    function(element, update){ Element.hide(update); };

    if (typeof(this.options.tokens) == 'string')
      this.options.tokens = new Array(this.options.tokens);

    this.observer = null;

    this.element.setAttribute('autocomplete','off');

    Element.hide(this.update);

    Event.observe(this.element, "click", this.onBlur.bindAsEventListener(this));
    //Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this));
    new Form.Element.DelayedObserver(this.element, 0.5, this.onKeyPress.bindAsEventListener(this));
  },

  show: function() {
    if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);

    if(!this.iefix &&
      (navigator.appVersion.indexOf('MSIE')>0) &&
      (navigator.userAgent.indexOf('Opera')<0) &&
      (Element.getStyle(this.update, 'position')=='absolute')) {

      new Insertion.After(this.update,
       '<iframe id="' + this.update.id + '_iefix" '+
       'style="display:block;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);
    this.iefix.style.zIndex = 100;
    this.update.style.zIndex = 200;
    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();
         if (this.update.firstChild.childNodes[this.index].scrollIntoView)
         {
           this.update.firstChild.childNodes[this.index].scrollIntoView(false)
         }
         this.render();
         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         if (this.update.firstChild.childNodes[this.index].scrollIntoView)
         {
           this.update.firstChild.childNodes[this.index].scrollIntoView(false)
         }
         this.render();
         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
         return;
      }
     else
      if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN)
        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, 'div');
    if(this.index != element.autocompleteIndex)
    {
        this.index = element.autocompleteIndex;
        this.render();
    }
    Event.stop(event);
  },

  onClick: function(event) {
    var element = Event.findElement(event, 'div');
    this.index = element.autocompleteIndex;
    this.selectEntry();
    this.hide();
  },

  onBlur: function(event) {
    // needed to make click events working
    //setTimeout(this.hide.bind(this), 250);
    this.hide();
    this.hasFocus = false;
    this.active = false;
  },

  render: function() {
    if(this.entryCount > 0) {
      if (this.lastIndex!=-1) Element.removeClassName(this.getEntry(this.lastIndex),"selected");
      if (this.index!="-1") Element.addClassName(this.getEntry(this.index),"selected");

      this.selectEntry();
      this.lastIndex=this.index;
      if(this.hasFocus) {
        this.show();
        this.active = true;
      }
    } else {
      this.active = false;
      this.hide();
    }
  },

  markPrevious: function() {
    this.lastIndex=this.index;
    if(this.index > 0) this.index--
      else this.index = this.entryCount-1;
  },

  markNext: function() {
    this.lastIndex=this.index;
    if(this.index < this.entryCount-1) this.index++
      else this.index = 0;
  },

  getEntry: function(index) {
    return this.update.firstChild.childNodes[index];
  },

  getCurrentEntry: function() {
    return (this.index==-1?false:this.getEntry(this.index));
  },

  selectEntry: function() {
    this.active = false;
    this.updateElement(this.getCurrentEntry());
  },

  updateElement: function(selectedElement) {
    if (!selectedElement) return;
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';

    if (this.options.select) {
      var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');

    var lastTokenPos = this.findLastToken();
    if (lastTokenPos != -1) {
      var newValue = this.element.value.substr(0, lastTokenPos + 1);
      var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value;
    } else {
      this.element.value = 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.firstChild);

      if(this.update.firstChild && this.update.firstChild.childNodes) {
        this.entryCount =
          this.update.firstChild.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 = -1;
      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;
    if(this.getToken().length>=this.options.minChars) {
      this.startIndicator();
      this.getUpdatedChoices();
    } else {
      this.active = false;
      this.hide();
    }
  },

  getToken: function() {
    var tokenPos = this.findLastToken();
    if (tokenPos != -1)
      var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,'');
    else
      var ret = this.element.value;

    return /\n/.test(ret) ? '' : ret;
  },

  findLastToken: function() {
    var lastTokenPos = -1;

    for (var i=0; i<this.options.tokens.length; i++) {
      var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
      if (thisTokenPos > lastTokenPos)
        lastTokenPos = thisTokenPos;
    }
    return lastTokenPos;
  }
}

Ajax.Autocompleter = Class.create();
Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {
  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() {
    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);
  }

});

Form.Element.DelayedObserver = Class.create();
Form.Element.DelayedObserver.prototype = {
  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));
  }
};

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('');
}
/* auto complete ] */


/* lightbox [ 'jscore/lightbox.js' */
/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006
*/

if (IEBrowserPNG)
{
  document.write("<style type='text/css'>.lb_top{filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='image', src='"+JSRoot+"lb_top_line.png')}");
  document.write(".lb_head{filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='scale', src='"+JSRoot+"lb_top_body.png');}");
  document.write(".lb_line{filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='image', src='"+JSRoot+"lb_line.png');}");
  document.write(".lb_body{filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='scale', src='"+JSRoot+"lb_bottom_body.png');}");
  document.write(".lb_bottom{filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='image', src='"+JSRoot+"lb_bottom_line.png');}</style>");
}

var lightbox = Class.create();
var lightbox_ready = false;
var lightbox_height = 0;

lightbox.prototype = {
 yPos : 0,
 xPos : 0,
 inner: "",
 iframe: [],

 initialize: function(ctrl, url, iframe_w, iframe_h) {
  if (!lightbox_ready) addLightboxMarkup();
  if (typeof(iframe_w)!="undefined")
  {
    this.iframe = [iframe_w, iframe_h];
  }

  this.content = url || ctrl.href;
  if (ctrl)
  {
    Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
    ctrl.onclick = refalse;
  }
 },

 // Turn everything on - mainly the IE fixes
 activate: function(){
  this.displayLightbox("block");
 },

 // Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
 prepareIE: function(height, overflow){
  bod = document.getElementsByTagName('body')[0];
  bod.style.height = height;
  bod.style.overflow = overflow;
  if (!IEBrowserOld) bod.style.overflowY = (overflow=="hidden"?"scroll":"");


  htm = document.getElementsByTagName('html')[0];
  htm.style.height = height;
  htm.style.overflow = overflow;
 },

 // In IE, select elements hover on top of the lightbox
 hideSelects: function(visibility){
  selects = document.getElementsByTagName('select');
  for(var i = 0; i < selects.length; i++) {
   selects[i].style.visibility = visibility;
  }
 },

 // Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
 getScroll: function(){
  if (self.pageYOffset) {
   this.yPos = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop){
   this.yPos = document.documentElement.scrollTop;
  } else if (document.body) {
   this.yPos = document.body.scrollTop;
  }
 },

 setScroll: function(x, y){
  window.scrollTo(x, y);
 },

 displayLightbox: function(display){
  if(display != 'none'){
   this.loadInfo();
  }
  else
  {
    $('overlay').style.display = display;
    $('lightbox').style.display = display;
  }
 },

 // Begin Ajax request based off of the href of the clicked linked
 loadInfo: function() {
   if (this.iframe.length==2)
   {
     var r={responseText:"<a href='#' id='lbClose' title='Close' style='left:600px'>&nbsp;</a><iframe id='lbFrame' frameborder='0' width='"+this.iframe[0]+"' height='"+this.iframe[1]+"' src='"+this.content+"'></iframe>"};
     this.processInfo(r);
   }
   else
   {
     var myAjax = new Ajax.Request(
           this.content,
           {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
     );
   }
 },

 // Display Ajax response
 processInfo: function(response){
  if (response.responseText=="") return false;

  if (IEBrowser){
   this.getScroll();
   this.prepareIE('100%', 'hidden');
   this.setScroll(0,0);
   this.hideSelects('hidden');
  }
  $('overlay').style.display = "block";
  $('lightbox').style.display = "block";
  this.inner=response.responseText;

  /*
  if ($('lbContent'))
  {
    //
    var myEffect = new fx.Height("lbContent" , {duration: 150, onComplete:
      this.processInfoFX.bindAsEventListener(this) }
     );
     myEffect.toggle();
  }
  else
  {
    this.processInfoFX();
  }
  */

  this.processInfoFX();
 },

 processInfoFX: function()
 {
  if ($('lbContent')) Element.remove($('lbContent'));

  var info = "<div id='lbContent'>" + this.inner + "</div>";
  new Insertion.Before($('lbLoadMessage'), info);

  $('lightbox').className = "done";
  $('lightbox').style.height=$("lbContent").offsetHeight+"px";

  var clse=$("lbClose");

  if (clse)
  {
    Event.observe(clse, 'click', this.deactivate.bindAsEventListener(this), false);
    clse.onclick = refalse;

    Event.observe(document, "keypress", this.deactivateESC.bindAsEventListener(this), false);
  }

  var clse=document.getElementsByClassName("laClose");
  if (clse) for (var i in clse)
  {
    Event.observe(clse[i], 'click', this.deactivate.bindAsEventListener(this), false);
    clse[i].onclick = refalse;
  }

  this.actions();
 },

 // Search through new links within the lightbox, and attach click event
 actions: function(){
  lbActions = document.getElementsByClassName('lbAction');

  for(var i = 0; i < lbActions.length; i++) {
   eval(lbActions[i].value);
   //Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
   //lbActions[i].onclick = function(){return false;};
  }

 },

 // Example of creating your own functionality once lightbox is initiated
 insert: function(e){
    link = Event.element(e).parentNode;
    Element.remove($('lbContent'));

    var myAjax = new Ajax.Request(
     link.href,
     {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
    );

 },

 // Example of creating your own functionality once lightbox is initiated
 deactivate: function(){
  var clse=$("lbClose");

  if (clse)
  {
    Event.stopObserving(clse, 'click', this.deactivate.bindAsEventListener(this), false);
    Event.stopObserving(document, 'keypress', this.deactivateESC.bindAsEventListener(this), false);
  }

  var clse=document.getElementsByClassName("laClose");
  if (clse) for (var i in clse)
  {
    Event.stopObserving(clse[i], 'click', this.deactivate.bindAsEventListener(this), false);
  }

  if ($('lbContent')) Element.remove($('lbContent'));

  if (IEBrowser){
   this.setScroll(0,this.yPos);
   this.prepareIE("", "");
   this.hideSelects("visible");
  }

  this.displayLightbox("none");
 },

 deactivateESC: function(e){
   if (e.keyCode==Event.KEY_ESC) this.deactivate();
 }

}


// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
 if (lightbox_ready) return;
 lightbox_ready=true;
 var bod         = document.getElementsByTagName('body')[0];
 var overlay     = document.createElement('div');
 overlay.id  = 'overlay';

 if (IEBrowser)
 {
   overlay.style.backgroundImage="none";
   overlay.style.backgroundColor="#000";
   overlay.style.filter="alpha(opacity=70)";
 }
 else if (MozBrowser)
 {
   overlay.style.backgroundImage="";
   overlay.style.backgroundColor="#000";
   overlay.style.MozOpacity="0.7";
 }
 else if (OperaBrowser && OperaVersion>8)
 {
   overlay.style.backgroundImage="";
   overlay.style.backgroundColor="#000";
   overlay.style.opacity="0.7";
 }

 var lb          = document.createElement('div');
 lb.id       = 'lightbox';
 lb.className= 'loading';
 lb.innerHTML= '<div id="lbLoadMessage"><p>&nbsp;</p></div>';
 bod.appendChild(overlay);
 bod.appendChild(lb);
}
/* lightbox ] */


/* search form [ 'js/searchform.js' */
if (NiceBrowser) document.write('<style type="text/css">#a_tlocation,#a_slocation{display:none}</style>');
var SearchForm={
 active:false,
 e_inited:false,
 e_mask:[],
 e_clear:0,
 e_cache:{},

 init: function()
 {
   if ($("a_search_people"))
   {

     if (typeof SearchFormDefault!="undefined")
      SearchForm.active=SearchFormDefault;
     else
      SearchForm.active="";

     if (Element.hasClassName($("a_search_people").parentNode,"active"))
      SearchForm.active="people";
     else if ($("a_search_some") && Element.hasClassName($("a_search_some").parentNode,"active"))
      SearchForm.active="some";
     else if ($("a_search_top") && Element.hasClassName($("a_search_top").parentNode,"active"))
      SearchForm.active="top";



     if (SearchForm.active)
     {
       $("a_search_"+SearchForm.active).parentNode.className="active";
       $("b_search_"+SearchForm.active).className="active";
     }

     if ($("a_options") && AjaxEnabled)
     {
       SearchForm.es_init();
       Event.observe("a_options","click", SearchForm.es);
     }

     Event.observe("a_search_people","click", SearchForm.click_tab);
//     Event.observe("a_search_some","click", SearchForm.click_tab);

     Base.stop_event("click","a_search_people", "a_options");

     if ($("a_search_top"))
     {
       Event.observe("a_search_top","click", SearchForm.click_tab);
       Base.stop_event("click","a_search_top");
     }

     if ($("a_search_some"))
     {
       Event.observe("a_search_some","click", SearchForm.click_tab);
       Base.stop_event("click","a_search_some");
     }

     var f=$("f_slocation");
     if (f)
     {
         var a=$("a_slocation");

         if (Flash.init(7)) a.href+="&flash=1";

         f.options[f.options.length]=new Option(a.innerHTML,a.href);
         //$("a_slocation").remove();
         trashCan(a);

         Event.observe(f, "change", SearchForm.more_locations, false);
     }

     var f=$("f_tlocation");
     if (f)
     {
         var a=$("a_tlocation");
         a.href+="&top=1";

         if (Flash.init(7)) a.href+="&flash=1";

         f.options[f.options.length]=new Option(a.innerHTML,a.href);
         //$("a_tlocation").remove();
         trashCan(a);

         Event.observe(f, "change", SearchForm.more_locations, false);
     }


     SearchForm.show_title(0,"f_q")

     Event.observe("f_search_some", 'submit', SearchForm.search_submit, false);
     Event.observe("f_q", 'focus', SearchForm.hide_title, false);
     Event.observe("f_q", 'blur', SearchForm.show_title, false);
     Event.observe("f_q", 'keypress', SearchForm.check_length, false);

     Event.observe("f_search_people", 'submit', SearchForm.search_people_submit, false);
     Base.stop_event("submit","f_search_some", "f_search");


     if ($("a_example"))
     {
       Event.observe("a_example", 'click', SearchForm.click_example, false);
       Base.stop_event("click","a_example");
     }

     if (AjaxEnabled) new Ajax.Autocompleter('f_q', 'f_q_auto', '/search_suggest.phtml', {parameters:Base.s});
   }
 },

 click_example: function()
 {
   SearchForm.hide_title(0,"f_q");
   if ($("f_q").value==$("a_example").innerHTML)
   {
     $("f_search_some").submit()
   }
   else
   {
     $("f_q").value=$("a_example").innerHTML.unescapeHTML();$("f_q").focus()
   }
 },

 search_people_submit: function()
 {
   if (!Element.hasClassName($("a_options"),"open"))
   {
     $("b_e1").innerHTML='';
     $("b_e2").innerHTML='';
     $("b_e3").innerHTML='';
   }
   $("f_search_people").submit();
 },

 es_init: function()
 {
  $("a_options").style.display="inline";

  if (Element.hasClassName($("a_options"),"open") && !SearchForm.e_inited)
   {

     if (!$("f_e1") || !$("f_e2") || !$("f_e3"))
     {
       var url = "/search-ws.phtml";
       var pars = "do=getBlock&data[block]=1&data[type]=type&output=json"+Base.s;
       var myAjax = new Ajax.Request(
            url,
            {method: 'get', parameters: pars, onComplete: SearchForm.es_loaded }
            );
     }
     else
     {
       SearchForm.es_init_options();
     }
   }
 },

 es_init_options: function()
 {
   SearchForm.e_inited=true;
   Event.observe("f_e1", "change", SearchForm.es_change, false);
   Event.observe("f_e2", "change", SearchForm.es_change, false);
   Event.observe("f_e3", "change", SearchForm.es_change, false);

   for (var i=1;i<4;i++)
   {
    SearchForm.e_mask[i]=$("f_e"+i).selectedIndex;
   }

   if ($("height_cm")) SearchForm.es_init_sizes("height");
   if ($("weight_kg")) SearchForm.es_init_sizes("weight");
   if ($("eb_languages")) SearchForm.es_init_languages();
   SearchForm.es_change_selects_mask();

 },

 es: function()
 {
   var o=Element.hasClassName($("a_options"),"open");

   $("a_options").className=( o?"":"open");

   if (!o) fx_s1("b_extended");

   if (!o)
   {
     var h=fx_s2("b_extended",1);
     $("b_extended").className="open";

     var myEffect = new fx.Height("b_extended" , {duration: 250, onComplete: function(){this.el.style.height=""} });
     myEffect.custom(0,h);
     myEffect.toggle();
     SearchForm.es_init();
   }
   else
   {
     var myEffect = new fx.Height("b_extended" , {duration: 250, onComplete: function(){this.el.className="";this.el.style.height=""}});
     myEffect.toggle();
   }
 },

 es_change: function(e)
 {
   var el=Base.ev(e);
   var block=el.id.substr(3);

   if (!SearchForm.es_change_selects(block, $(el.id).selectedIndex)) return false;;

   $("b_e"+block+"criteria").innerHTML='<div align="center"><img src="'+JSRoot+'loader-15.gif" width="15" height="15" border="0" align="absmiddle" /></div>';

   if (typeof SearchForm.e_cache[$F(el.id)]!="undefined")
   {
     SearchForm.es_loaded(SearchForm.e_cache[$F(el.id)],block);
   }
   else
   {
     var url = "/search-ws.phtml";
     var pars = "do=getBlock&data[block]="+block+"&data[type]="+$F(el.id)+"&output=json"+Base.s;
     var myAjax = new Ajax.Request(
          url,
          {method: 'get', parameters: pars, onComplete: SearchForm.es_loaded }
          );
   }
 },

 es_loaded: function(r, block)
 {
   if (block)
   {
     var res=r;
     res.block=block;
   }
   else
   {
     var res = eval('(' + r.responseText + ')');
     SearchForm.e_cache[res.type]=res;
   }

   if (res.errno == 0)
   {
     if (res.type=="type")
     {
       var s=res.html;
       var se=[];
       var i=0;
       do{
        var p=s.indexOf('</select>')
        if (p==-1) break;
        se[i]=s.substr(0,p+9);

        s=s.substr(p+9);
        i++;
       } while (p>-1);

       for (var i=0;i<se.length;i++)
       {
         if (!$("f_e"+(i+1)))
         {
           var fn="b_e"+(i+1)+"criteria";
           se[i]=se[i].replace(/<select/gi,'<select id="f_e'+(i+1)+'"');
           new Insertion.Before($(fn),se[i]);
         }
       }
       SearchForm.es_init_options();
     }
     else
     {
       $("b_e"+res.block+"criteria").innerHTML='<div '+(res.type=="na"?"class":"id")+'="eb_'+res.type+'">'+res.html+'</div>';

       if (res.type=="weight" || res.type=="height") SearchForm.es_init_sizes(res.type);
       if (res.type=="languages") SearchForm.es_init_languages();
     }
   }
 },

 es_init_languages: function()
 {
   var e=$("eb_languages").getElementsByTagName('input');

   for (var i=0;i<e.length;i++) if (e[i].value=="other")
   {
     Event.observe(e[i], 'click', SearchForm.es_languages, false);
     SearchForm.es_languages(false, e[i]);
     break;
   }

 },

 es_languages: function(e, el_other)
 {
   var el=el_other || Base.ev(e);

   var l=$("eb_languages").getElementsByTagName('select');
   if (el.checked)
   {
     l[0].style.visibility="visible";
   }
   else
   {
     l[0].style.visibility="hidden";
   }
 },

 es_init_sizes: function(s)
 {
   if (s=="weight")
   {
     Event.observe("es_kg", 'click', SearchForm.es_sizes, false);
     Event.observe("es_lbs", 'click', SearchForm.es_sizes, false);

     if ($("es_kg").checked) $("weight_lbs").hide();
     if ($("es_lbs").checked) $("weight_kg").hide();
   }
   else if (s=="height")
   {
     Event.observe("es_cm", 'click', SearchForm.es_sizes, false);
     Event.observe("es_inch", 'click', SearchForm.es_sizes, false);

     if ($("es_cm").checked) $("height_inch").hide();
     if ($("es_inch").checked) $("height_cm").hide();
   }
 },


 es_change_selects: function(must_be_here, el_index)
 {
   if ($("f_e"+must_be_here).options[el_index].disabled)
   {
     $("f_e"+must_be_here).selectedIndex = 0;
     return false;
   }

   var last=SearchForm.e_mask[must_be_here];
   SearchForm.e_mask[must_be_here]=el_index;

   SearchForm.es_change_selects_mask(must_be_here, last);

   return true;
 },

 es_change_selects_mask: function(must_be_here, clear)
 {
   if (must_be_here && clear)
   {
    for (var i=1;i<4;i++) if (i!=must_be_here)
    {
      $("f_e"+i).options[clear].disabled=false;
      if (IEBrowser) $("f_e"+i).options[clear].style.color="#000";
    }
   }

   for (var i=1;i<4;i++)
   {
    for (var j=1;j<4;j++)
    {
      if ( (i!=j) && (SearchForm.e_mask[i]!=0))
      {
        $("f_e"+j).options[SearchForm.e_mask[i]].disabled=true;
        if (IEBrowser) $("f_e"+j).options[SearchForm.e_mask[i]].style.color="#ccc";
      }
    }
   }
 },

 es_sizes: function(e, id)
 {
   var el=(id?$(id):Base.ev(e))
   switch (el.id)
   {
     case "es_cm":
       $("height_inch").hide();
       $("height_cm").show();
     break;
     case "es_inch":
       $("height_inch").show();
       $("height_cm").hide();
     break;
     case "es_kg":
       $("weight_lbs").hide();
       $("weight_kg").show();
     break;
     case "es_lbs":
       $("weight_lbs").show();
       $("weight_kg").hide();
     break;
   }

 },

 click_tab: function(e)
 {
   var el=Base.ev(e);
   el.blur();
   if (el.id.substr(9)!=SearchForm.active)
   {

     if (SearchForm.active)
     {
       Element.removeClassName($("a_search_"+SearchForm.active).parentNode,"active");
       Element.removeClassName($("b_search_"+SearchForm.active),"active");
     }
     SearchForm.active=el.id.substr(9);

     fx_s1("b_menu_toggler");

     $("a_search_"+SearchForm.active).parentNode.className="active";
     $("b_search_"+SearchForm.active).className="active";

     var iniHeight=fx_s2("b_menu_toggler", 1);

     var myEffect = new fx.Height("b_menu_toggler" , {duration: 250, onComplete:function(){this.el.style.height=""} });
     myEffect.custom(0,iniHeight);
     myEffect.toggle();
   }

   Event.stop(e);
 },


 hide_title: function(e,id)
 {
   var el=(id?$(id):$(Base.ev(e).id));

   if (el.value==el.title)
   {
     el.value="";
     Element.removeClassName(el,"disabled");
     return true;
   }
   return false;
 },

 show_title: function(e,id)
 {
   var el=(id?$(id):$(Base.ev(e).id));

   if (el.value=="")
   {
     el.value=el.title;
     Element.addClassName(el,"disabled");
     return true;
   }
   else if (el.value==el.title)
   {
     return true;
   }

   return false;
 },

 search_submit: function(e)
 {
   SearchForm.hide_title(0,"f_q");
   $("f_search_some").submit();
 },

 check_length: function()
 {
   if (Element.hasClassName("f_q","disabled"))
   {
     SearchForm.hide_title(0,"f_q");
   }
 },

 more_locations: function(e)
 {
   var field=(Base.ev(e).id);
   if ($(field).selectedIndex==$(field).options.length-1)
   {
     Base.wopen($F(field)+"&location=#slocation","_more_locations",620,575,true);
     $(field).options[0].selected=true;
   }
 }

}

function add_city(vvalue,vtext)
{
  Base.add_city(vvalue,vtext);
}
/* search form ] */

/* popup contacts [ 'js/popup_contacts.js' */
//load_js("jscore/lightbox.js");
var PopupContacts={

 init: function()
 {
   if (!AjaxEnabled) return false;
   if ($("b_import_contacts"))
   {
     var ia=$("b_import_contacts").getElementsByTagName("a");
     for (var i=0;i<ia.length;i++) if (ia[i].className!="more_a")
     {
       PopupContacts.create(ia[i], "login", ia[i].rel.substr(2));
     }
   }
 },

 create: function(el, part, provider_id)
 {
   var url="/contacts-ws.phtml?do=getPopup&data[type]="+part+"&data[provider_id]="+provider_id;
   if ($("f_invite_on")) url+="&data[invite_on]=Vote";

   var l = new lightbox(el, url+"&output=html"+Base.s);
 },

 enable_post: function(e)
 {
   if (e)
   {
    $('lf_post').disabled=false;
    $('lbAjax').style.visibility="hidden";
   }
   else
   {
    $('lf_post').disabled=true;
    $('lbAjax').style.visibility="visible";
   }
 },

 login_init: function()
 {
   $("lf_username").focus();

   Event.observe("lf_form", "submit", function(){PopupContacts.login_post();return false;});
   Base.stop_event("submit","lf_form");
 },

 login_post: function()
 {
   var pars=PopupContacts.get($("lf_form"));
   $("b_login_form").style.display="none";
   $("lbClose").style.display="none";
   $("b_login_process").style.display="block";

   PopupContacts.post_data("getContacts",pars);
 },

 list_init: function()
 {
   Event.observe("a_show_list", "click", PopupContacts.list_show);
   Base.stop_event("click","a_show_list");

   Event.observe("lf_form_list", "submit", function(){PopupContacts.list_post();return false;});
   Base.stop_event("submit","lf_form_list");

   Event.observe("lf_form_list_open", "submit", function(){PopupContacts.list_post(true);return false;});
   Base.stop_event("submit","lf_form_list_open");

   var t=$("lb_list").getElementsByTagName("tr");
   var j=1;
   for (var i=0;i<t.length;i++)
   {
     if (i%2) t[i].style.backgroundColor="#f0f0f0";
   }
 },
 list_show: function(e)
 {
   Event.stop(e);
   $("a_found").hide();
   $("a_found_list").style.display="inline";

   $("lb_found").hide();
   $("lb_found_list").style.display="block";
 },

 list_post: function(open)
 {
   var pars=PopupContacts.get($("lf_form_list"+(typeof(open)!="undefined"?"_open":"") ));

   $("b_list_form").style.display="none";
   $("b_list_process").style.display="block";

   PopupContacts.post_data("addContacts",pars);
 },

 error_done: function()
 {
   var el=$("lf_again");
   PopupContacts.create(el, "login", el.rel.substr(2));
 },

 done_init: function()
 {
   var li=$("lf_form_done").getElementsByTagName('a');

   for (var i=0;i<li.length;i++) if (li[i].rel)
   {
     PopupContacts.create(li[i], "login", li[i].rel.substr(2));
   }
 },

 invite_init: function()
 {
   $("fl_folder_id").value=$("f_folder_id").value;
 },

 post_data: function(action, pars)
 {
   var myAjax = new Ajax.Request(
        "/contacts-ws.phtml",
        {
         method: 'post',
         parameters: "do="+action+"&"+pars+"&output=html"+Base.s,
         onComplete: PopupContacts.check_data
        }
       );
 },

 check_data: function(r)
 {
   switch (r.responseText){
    case "WAIT":window.setTimeout("PopupContacts.process_data()",5000); break;
    case "SUCCESS":
     var l = new lightbox(false, "/contacts-ws.phtml?do=getPopup&data[provider_id]="+$("lf_provider_id").value+"&output=html"+Base.s);
     l.activate();
    break;
    case "ERROR":
     var l = new lightbox(false, "/contacts-ws.phtml?do=getPopup&data[type]=error&data[provider_id]="+$("lf_provider_id").value+"&output=html"+Base.s);
     l.activate();
    break;
   }
 },

 process_data: function()
 {
    var myAjax = new Ajax.Request(
        "/contacts-ws.phtml",
        {
         method: 'post',
         parameters: "do=checkData&output=html"+Base.s,
         onComplete: PopupContacts.check_data
        }
       );
 },

 /* get form fields */
 get: function(obj)
 {
   var getstr = "";
   var inp=obj.getElementsByTagName("input");
   for (var i=0; i<inp.length; i++)
   {
     var n=(inp[i].name=="uin[]"?"uin][":inp[i].name);
     if ((inp[i].type == "text" || inp[i].type == "hidden" || inp[i].type == "password") && inp[i].name!="")
     {
       getstr += "data["+n+"]=" + Base.myescape(inp[i].value) + "&";
     }
     if (inp[i].type == "checkbox")
     {
       if (inp[i].checked)
       {
         getstr += "data["+n+ "]=" + Base.myescape(inp[i].value) + "&";
       }
     }
     if (inp[i].type == "radio")
     {
       if (inp[i].checked)
       {
         getstr += "data["+n+ "]=" + Base.myescape(inp[i].value) + "&";
       }
     }
   }

   var inp=obj.getElementsByTagName("select");
   for (var i=0; i<inp.length; i++)
   {
     var sel = inp[i];
     getstr += "data["+sel.name + "]=" + Base.myescape(sel.options[sel.selectedIndex].value) + "&";
   }

   var txt=obj.getElementsByTagName("textarea");
   for (var i=0; i<txt.length; i++)
   {
     getstr += "data["+txt[i].name + "]=" + Base.myescape(txt[i].value) + "&";
   }

   return getstr;
 }


}

OnReady.register( PopupContacts.init);
/* popup contacts ] */

OnReady.register( Base.init);
//Event.observe(window, 'load', Base.we_ready, false);
