/*  Prototype JavaScript framework, version 1.6.0.1
 *  (c) 2005-2007 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://www.prototypejs.org/
 *
 *--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.6.0.1',

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

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

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

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

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


/* Based on Alex Arnell's inheritance implementation. */
var Class = {
  create: function() {
    var parent = null, properties = $A(arguments);
    if (Object.isFunction(properties[0]))
      parent = properties.shift();

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

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

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

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

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

    klass.prototype.constructor = klass;

    return klass;
  }
};

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

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

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

    return this;
  }
};

var Abstract = { };

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

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

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

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

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

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

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

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

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

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

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

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

  isArray: function(object) {
    return object && object.constructor === Array;
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return returnValue;
  }
};

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

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

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

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

    this.registerCallback();
  },

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

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

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

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

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

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

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

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

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

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

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

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

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

    return camelized;
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

var $break = { };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Array.from = $A;

Object.extend(Array.prototype, Enumerable);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  activeRequestCount: 0
};

Ajax.Responders = {
  responders: [],

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

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

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

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

Object.extend(Ajax.Responders, Enumerable);

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

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

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

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

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

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

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

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

    this.parameters = params;

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

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

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

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

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

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

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

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

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

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

    if (this.method == 'post') {
      headers['Content-type'] = this.options.contentType +
        (this.options.encoding ? '; charset=' + this.options.encoding : '');

      /* Force "Connection: close" for older Mozilla browsers to work
       * around a bug where XMLHttpRequest sends an incorrect
       * Content-length header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  status:      0,
  statusText: '',

  getStatus: Ajax.Request.prototype.getStatus,

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

  getHeader: Ajax.Request.prototype.getHeader,

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

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

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

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

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

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

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

    $super(url, options);
  },

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

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

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

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

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

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

    this.start();
  },

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

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

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

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

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

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

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

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

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

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

Element.cache = { };

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

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

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

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

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

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

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

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

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

    var content, insert, tagName, childNodes;

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

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

      content = Object.toHTML(content);

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

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

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

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

    return element;
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return element;
  },

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

  getDimensions: function(element) {
    element = $(element);
    var display = $(element).getStyle('display');
    if (display != 'none' && display != null) // Safari bug
      return {width: element.offsetWidth, height: element.offsetHeight};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return $(document.body);
  },

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

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

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

    } while (element = element.offsetParent);

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

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

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

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

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

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

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

Element.Methods.identify.counter = 1;

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

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

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

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

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

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

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

else if (Prototype.Browser.IE) {
  $w('positionedOffset getOffsetParent viewportOffset').each(function(method) {
    Element.Methods[method] = Element.Methods[method].wrap(
      function(proceed, element) {
        element = $(element);
        var position = element.getStyle('position');
        if (position != 'static') return proceed(element);
        element.setStyle({ position: 'relative' });
        var value = proceed(element);
        element.setStyle({ position: position });
        return value;
      }
    );
  });

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

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

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

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

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

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

  Element._attributeTranslations.write = {
    names: Object.clone(Element._attributeTranslations.read.names),
    values: {
      checked: function(element, value) {
        element.checked = !!value;
      },

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

  Element._attributeTranslations.has = {};

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

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

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

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

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

    return element;
  };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Element.Methods.ByTag = { };

Object.extend(Element, Element.Methods);

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

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

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

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

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

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

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

    element._extendedByPrototype = Prototype.emptyFunction;
    return element;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  getScrollOffsets: function() {
    return Element._returnOffset(
      window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
      window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
  }
};
/* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
 * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
 * license.  Please see http://www.yui-ext.com/ for more information. */

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

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

    var e = this.expression;

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

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

    return true;
  },

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

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

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

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

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

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

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

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

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

    this.xpath = this.matcher.join('');
    Selector._cache[this.expression] = this.xpath;
  },

  findElements: function(root) {
    root = root || document;
    if (this.xpath) return document._getElementsByXPath(this.xpath, root);
    return this.matcher(root);
  },

  match: function(element) {
    this.tokens = [];

    var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
    var le, p, m;

    while (e && le !== e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        p = ps[i];
        if (m = e.match(p)) {
          // use the Selector.assertions methods unless the selector
          // is too complex.
          if (as[i]) {
            this.tokens.push([i, Object.clone(m)]);
            e = e.replace(m[0], '');
          } else {
            // reluctantly do a document-wide search
            // and look for a match in the array
            return this.findElements(document).include(element);
          }
        }
      }
    }

    var match = true, name, matches;
    for (var i = 0, token; token = this.tokens[i]; i++) {
      name = token[0], matches = token[1];
      if (!Selector.assertions[name](element, matches)) {
        match = false; break;
      }
    }

    return match;
  },

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

  inspect: function() {
    return "#<Selector:" + this.expression.inspect() + ">";
  }
});

Object.extend(Selector, {
  _cache: { },

  xpath: {
    descendant:   "//*",
    child:        "/*",
    adjacent:     "/following-sibling::*[1]",
    laterSibling: '/following-sibling::*',
    tagName:      function(m) {
      if (m[1] == '*') return '';
      return "[local-name()='" + m[1].toLowerCase() +
             "' or local-name()='" + m[1].toUpperCase() + "']";
    },
    className:    "[contains(concat(' ', @class, ' '), ' #{1} ')]",
    id:           "[@id='#{1}']",
    attrPresence: function(m) {
      m[1] = m[1].toLowerCase();
      return new Template("[@#{1}]").evaluate(m);
    },
    attr: function(m) {
      m[1] = m[1].toLowerCase();
      m[3] = m[5] || m[6];
      return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
    },
    pseudo: function(m) {
      var h = Selector.xpath.pseudos[m[1]];
      if (!h) return '';
      if (Object.isFunction(h)) return h(m);
      return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
    },
    operators: {
      '=':  "[@#{1}='#{3}']",
      '!=': "[@#{1}!='#{3}']",
      '^=': "[starts-with(@#{1}, '#{3}')]",
      '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
      '*=': "[contains(@#{1}, '#{3}')]",
      '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
      '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
    },
    pseudos: {
      'first-child': '[not(preceding-sibling::*)]',
      'last-child':  '[not(following-sibling::*)]',
      'only-child':  '[not(preceding-sibling::* or following-sibling::*)]',
      'empty':       "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
      'checked':     "[@checked]",
      'disabled':    "[@disabled]",
      'enabled':     "[not(@disabled)]",
      'not': function(m) {
        var e = m[6], p = Selector.patterns,
            x = Selector.xpath, le, v;

        var exclusion = [];
        while (e && le != e && (/\S/).test(e)) {
          le = e;
          for (var i in p) {
            if (m = e.match(p[i])) {
              v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
              exclusion.push("(" + v.substring(1, v.length - 1) + ")");
              e = e.replace(m[0], '');
              break;
            }
          }
        }
        return "[not(" + exclusion.join(" and ") + ")]";
      },
      'nth-child':      function(m) {
        return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
      },
      'nth-last-child': function(m) {
        return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
      },
      'nth-of-type':    function(m) {
        return Selector.xpath.pseudos.nth("position() ", m);
      },
      'nth-last-of-type': function(m) {
        return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
      },
      'first-of-type':  function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
      },
      'last-of-type':   function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
      },
      'only-of-type':   function(m) {
        var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
      },
      nth: function(fragment, m) {
        var mm, formula = m[6], predicate;
        if (formula == 'even') formula = '2n+0';
        if (formula == 'odd')  formula = '2n+1';
        if (mm = formula.match(/^(\d+)$/)) // digit only
          return '[' + fragment + "= " + mm[1] + ']';
        if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
          if (mm[1] == "-") mm[1] = -1;
          var a = mm[1] ? Number(mm[1]) : 1;
          var b = mm[2] ? Number(mm[2]) : 0;
          predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
          "((#{fragment} - #{b}) div #{a} >= 0)]";
          return new Template(predicate).evaluate({
            fragment: fragment, a: a, b: b });
        }
      }
    }
  },

  criteria: {
    tagName:      'n = h.tagName(n, r, "#{1}", c);   c = false;',
    className:    'n = h.className(n, r, "#{1}", c); c = false;',
    id:           'n = h.id(n, r, "#{1}", c);        c = false;',
    attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;',
    attr: function(m) {
      m[3] = (m[5] || m[6]);
      return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);
    },
    pseudo: function(m) {
      if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
      return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
    },
    descendant:   'c = "descendant";',
    child:        'c = "child";',
    adjacent:     'c = "adjacent";',
    laterSibling: 'c = "laterSibling";'
  },

  patterns: {
    // combinators must be listed first
    // (and descendant needs to be last combinator)
    laterSibling: /^\s*~\s*/,
    child:        /^\s*>\s*/,
    adjacent:     /^\s*\+\s*/,
    descendant:   /^\s/,

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  findChildElements: function(element, expressions) {
    var exprs = expressions.join(',');
    expressions = [];
    exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
      expressions.push(m[1].strip());
    });
    var results = [], h = Selector.handlers;
    for (var i = 0, l = expressions.length, selector; i < l; i++) {
      selector = new Selector(expressions[i].strip());
      h.concat(results, selector.findElements(element));
    }
    return (l > 1) ? h.unique(results) : results;
  }
});

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

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

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

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

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

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

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

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

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

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

    return matchingInputs;
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,
  KEY_INSERT:   45,

  cache: { },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  function getEventID(element) {
    if (element._eventID) return element._eventID;
    arguments.callee.id = arguments.callee.id || 1;
    return element._eventID = ++arguments.callee.id;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      return element;
    },

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

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

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

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

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

      destroyWrapper(id, eventName, handler);

      return element;
    },

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

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

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

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

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

Object.extend(Event, Event.Methods);

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

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

(function() {
  /* Support for the DOMContentLoaded event is based on work by Dan Webb,
     Matthias Miller, Dean Edwards and John Resig. */

  var timer;

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

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

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

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

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

Hash.toQueryString = Object.toQueryString;

var Toggle = { display: Element.toggle };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  cumulativeOffset: Element.Methods.cumulativeOffset,

  positionedOffset: Element.Methods.positionedOffset,

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

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

  realOffset: Element.Methods.cumulativeScrollOffset,

  offsetParent: Element.Methods.getOffsetParent,

  page: Element.Methods.viewportOffset,

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

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

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

  instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
  function(element, className) {
    className = className.toString().strip();
    var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
    return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
  } : function(element, className) {
    className = className.toString().strip();
    var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
    if (!classNames && !className) return elements;

    var nodes = $(element).getElementsByTagName('*');
    className = ' ' + className + ' ';

    for (var i = 0, child, cn; child = nodes[i]; i++) {
      if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
          (classNames && classNames.all(function(name) {
            return !name.toString().blank() && cn.include(' ' + name + ' ');
          }))))
        elements.push(Element.extend(child));
    }
    return elements;
  };

  return function(className, parentElement) {
    return $(parentElement || document.body).getElementsByClassName(className);
  };
}(Element.Methods);

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

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

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

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

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

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

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

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

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

Element.addMethods();// -------------------------------------------------------------------
// Virtual Pagination Script- By Dynamic Drive, available at: http://www.dynamicdrive.com
// Last updated: Nov 21st, 2008 to v2.0
// ** Adds ability to define multiple pagination DIVs (the secondary DIVs mirror primary DIV's contents)
// ** Last viewed page persistence, so last viewed page can be remembered/ recalled within browser session.
// ** Improvements to instance.navigate() to select a page using an arbitrary link or inside another script.
// ** Ability to select a page using a URL parameter (ie: target.htm?virtualpiececlass=index).
//
// PUBLIC: virtualpaginate()
// Main Virtual Paginate Object function.
// -------------------------------------------------------------------

document.write('<style type="text/css">' //write out CSS for class ".hidepeice" that hides pieces of contents within pages
	+'.hidepiece{display:none}\n'
	+'@media print{.hidepiece{display:block !important;}}\n'
	+'</style>')
	
function virtualpaginate(config){ //config: {piececlass:, piececontainer:, pieces_per_page:, defaultpage:, persist}
	this.piececlass=config.piececlass
	var elementType=(typeof config.piececontainer=="undefined")? "div" : config.piececontainer //The type of element used to divide up content into pieces. Defaults to "div"
	this.pieces=virtualpaginate.collectElementbyClass(config.piececlass, elementType) //get total number of divs matching class name
	//Set this.chunksize: 1 if "chunksize" param is undefined, "chunksize" if it's less than total pieces available, or simply total pieces avail (show all)
	this.chunksize=(typeof config.pieces_per_page=="undefined")? 1 : (config.pieces_per_page>0 && config.pieces_per_page<this.pieces.length)? config.pieces_per_page : this.pieces.length
	this.pagecount=Math.ceil(this.pieces.length/this.chunksize) //calculate number of "pages" needed to show the divs
	this.paginatediv=[], this.flatviewlinks=[], this.cpspan=[], this.selectmenu=[]
	this.persist=config.persist
	var persistedpage=virtualpaginate.getCookie("dd_"+this.piececlass) || 0
	var urlselectedpage=virtualpaginate.urlparamselect(this.piececlass) //returns null or index from: mypage.htm?piececlass=index
	this.currentpage=(typeof urlselectedpage=="number")? urlselectedpage : ((this.persist)? persistedpage : config.defaultpage)
	this.currentpage=(this.currentpage<this.pagecount)? parseInt(this.currentpage) : 0 //ensure currentpage is within range of available pages
	this.showpage(this.currentpage) //Show selected page
}

// -------------------------------------------------------------------
// PUBLIC: navigate(keyword)- Calls this.showpage() based on parameter passed (0=page1, 1=page2 etc, "next", "first", or "last")
// -------------------------------------------------------------------

virtualpaginate.prototype.navigate=function(keyword){
	var prevlinkindex=this.currentpage //Get index of last clicked on page
	if (keyword=="previous")
		this.currentpage=(this.currentpage>0)? this.currentpage-1 : (this.currentpage==0)? this.pagecount-1 : 0
	else if (keyword=="next")
		this.currentpage=(this.currentpage<this.pagecount-1)? this.currentpage+1 : 0
	else if (keyword=="first")
		this.currentpage=0
	else if (keyword=="last")
		this.currentpage=this.pagecount-1 //last page number
	else
		this.currentpage=parseInt(keyword)
	this.currentpage=(this.currentpage<this.pagecount)? this.currentpage : 0 //ensure pagenumber is within range of available pages
	this.showpage(this.currentpage)
	for (var p=0; p<this.paginatediv.length; p++){ //loop through all pagination DIVs
		if (this.flatviewpresent)
			this.flatviewlinks[p][prevlinkindex].className="" //"Unhighlight" previous page (before this.currentpage increments)
		if (this.selectmenupresent)
			this.selectmenu[p].selectedIndex=this.currentpage
		if (this.flatviewpresent)
			this.flatviewlinks[p][this.currentpage].className="selected" //"Highlight" current page
	}
}


// -------------------------------------------------------------------
// PUBLIC: buildpagination()- Create pagination interface by calling one or more of the paginate_build_() functions
// -------------------------------------------------------------------

virtualpaginate.prototype.buildpagination=function(divids, optnavtext){
	var divids=(typeof divids=="string")? [divids] : divids //force divids to be an array of ids
	var primarypaginatediv=divids.shift() //get first id within divids[]
	var paginaterawHTML=document.getElementById(primarypaginatediv).innerHTML
	this.paginate_build(primarypaginatediv, 0, optnavtext)
	for (var i=0; i<divids.length; i++){
		document.getElementById(divids[i]).innerHTML=paginaterawHTML
		this.paginate_build(divids[i], i+1, optnavtext)
	}
}

// -------------------------------------------------------------------
// PRIVATE utility functions
// -------------------------------------------------------------------

virtualpaginate.collectElementbyClass=function(classname, element){ //Returns an array containing DIVs with specified classname
	if (document.querySelectorAll){
		var pieces=document.querySelectorAll(element+"."+classname) //return pieces as HTMLCollection
	}
	else{
		var classnameRE=new RegExp("(^|\\s+)"+classname+"($|\\s+)", "i") //regular expression to screen for classname within element
		var pieces=[]
		var alltags=document.getElementsByTagName(element)
		for (var i=0; i<alltags.length; i++){
			if (typeof alltags[i].className=="string" && alltags[i].className.search(classnameRE)!=-1)
				pieces[pieces.length]=alltags[i] //return pieces as array
		}
	}
	return pieces
}

virtualpaginate.urlparamselect=function(vpclass){
	var result=window.location.search.match(new RegExp(vpclass+"=(\\d+)", "i")) //check for "?piececlass=2" in URL
	return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected virtual page's index
}

virtualpaginate.getCookie=function(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return null
}

virtualpaginate.setCookie=function(name, value){
	document.cookie = name+"="+value
}

// -------------------------------------------------------------------
// PRIVATE: showpage(pagenumber)- Shows a page based on parameter passed (0=page1, 1=page2 etc)
// -------------------------------------------------------------------

virtualpaginate.prototype.showpage=function(pagenumber){
	var totalitems=this.pieces.length //total number of broken up divs
	var showstartindex=pagenumber*this.chunksize //array index of div to start showing per pagenumber setting
	var showendindex=showstartindex+this.chunksize-1 //array index of div to stop showing after per pagenumber setting
	for (var i=0; i<totalitems; i++){
		if (i>=showstartindex && i<=showendindex)
			this.pieces[i].style.display="block"
		else
			this.pieces[i].style.display="none"
	}
	if (this.persist){ //if persistence enabled
		virtualpaginate.setCookie("dd_"+this.piececlass, this.currentpage)
	}
	if (this.cpspan.length>0){ //if <span class="paginateinfo> element is present, update it with the most current info (ie: Page 3/4)
		for (var p=0; p<this.cpspan.length; p++)
			this.cpspan[p].innerHTML='Page '+(this.currentpage+1)+'/'+this.pagecount
	}
}

// -------------------------------------------------------------------
// PRIVATE: build() methods- Various methods to create pagination interfaces
// paginate_paginate_build()- Main build() paginate function
// paginate_output_flatview()- Accepts <span class="flatview"> element and populates it with sequential pagination links
// paginate_paginate_build_flatview()- Parses the modified <span class="flatview"> element and assigns click behavior to the pagination links
// paginate_build_selectmenu(paginatedropdown)- Accepts an empty SELECT element and turns it into pagination menu
// paginate_build_regularlinks(paginatelinks)- Accepts a collection of links and screens out/ creates pagination out of ones with specific "rel" attr
// paginate_build_cpinfo(cpspan)- Accepts <span class="paginateinfo"> element and displays current page info (ie: Page 1/4)
// -------------------------------------------------------------------

virtualpaginate.prototype.paginate_build=function(divid, divpos, optnavtext){
	var instanceOfBox=this
	var paginatediv=document.getElementById(divid)
	if (this.chunksize==this.pieces.length){ //if user has set to display all pieces at once, no point in creating pagination div
		paginatediv.style.display="none"
		return
	}
	var paginationcode=paginatediv.innerHTML //Get user defined, "unprocessed" HTML within paginate div
	if (paginatediv.getElementsByTagName("select").length>0) //if there's a select menu in div
		this.paginate_build_selectmenu(paginatediv.getElementsByTagName("select")[0], divpos, optnavtext)
	if (paginatediv.getElementsByTagName("a").length>0) //if there are links defined in div
		this.paginate_build_regularlinks(paginatediv.getElementsByTagName("a"))
	var allspans=paginatediv.getElementsByTagName("ul") //Look for span tags within passed div
	for (var i=0; i<allspans.length; i++){
		if (allspans[i].className=="flatview")
			this.paginate_output_flatview(allspans[i], divpos, optnavtext)
		else if (allspans[i].className=="paginateinfo")
			this.paginate_build_cpinfo(allspans[i], divpos)
	}
	this.paginatediv[divpos]=paginatediv
}

virtualpaginate.prototype.paginate_output_flatview=function(flatviewcontainer, divpos, anchortext){
	var flatviewhtml=""
	var anchortext=anchortext || new Array()
	for (var i=0; i<this.pagecount; i++){
		if (typeof anchortext[i]!="undefined") //if custom anchor text for this link exists
			flatviewhtml+= '<li><span>'+(i+1)+'</span><a href="#flatview" rel="'+i+'">'+anchortext[i]+'</a></li> ' //build pagination link using custom anchor text
		else
			flatviewhtml+='<li><a href="#flatview" rel="'+i+'">'+(i+1)+'</a></li> ' //build  pagination link using auto incremented sequential number instead
	}
	flatviewcontainer.innerHTML=flatviewhtml
	this.paginate_build_flatview(flatviewcontainer, divpos, anchortext)
}

virtualpaginate.prototype.paginate_build_flatview=function(flatviewcontainer, divpos, anchortext){
	var instanceOfBox=this
	var flatviewhtml=""
	this.flatviewlinks[divpos]=flatviewcontainer.getElementsByTagName("a")
	for (var i=0; i<this.flatviewlinks[divpos].length; i++){
		this.flatviewlinks[divpos][i].onclick=function(){
			var prevlinkindex=instanceOfBox.currentpage //Get index of last clicked on flatview link
			var curlinkindex=parseInt(this.getAttribute("rel"))
			instanceOfBox.navigate(curlinkindex)
			return false
		}
	}
	this.flatviewlinks[divpos][this.currentpage].className="selected" //"Highlight" current flatview link
	this.flatviewpresent=true //indicate flat view links are present
}

virtualpaginate.prototype.paginate_build_selectmenu=function(paginatedropdown, divpos, anchortext){
	var instanceOfBox=this
	var anchortext=anchortext || new Array()
	this.selectmenupresent=1
	for (var i=0; i<this.pagecount; i++){
		if (typeof anchortext[i]!="undefined") //if custom anchor text for this link exists, use anchor text as each OPTION's text
			paginatedropdown.options[i]=new Option(anchortext[i], i)
		else //else, use auto incremented, sequential numbers
			paginatedropdown.options[i]=new Option("Page "+(i+1)+" of "+this.pagecount, i)
	}
	paginatedropdown.selectedIndex=this.currentpage
	setTimeout(function(){paginatedropdown.selectedIndex=instanceOfBox.currentpage}, 500) //refresh currently selected option (for IE's sake)
	paginatedropdown.onchange=function(){
	instanceOfBox.navigate(this.selectedIndex)
	}
	this.selectmenu[divpos]=paginatedropdown
	this.selectmenu[divpos].selectedIndex=this.currentpage //"Select" current page's corresponding option
}

virtualpaginate.prototype.paginate_build_regularlinks=function(paginatelinks){
	var instanceOfBox=this
	for (var i=0; i<paginatelinks.length; i++){
		var currentpagerel=paginatelinks[i].getAttribute("rel")
		if (currentpagerel=="previous" || currentpagerel=="next" || currentpagerel=="first" || currentpagerel=="last"){ //screen for these "rel" values
			paginatelinks[i].onclick=function(){
				instanceOfBox.navigate(this.getAttribute("rel"))
				return false
			}
		}
	}
}

virtualpaginate.prototype.paginate_build_cpinfo=function(cpspan, divpos){
	this.cpspan[divpos]=cpspan
	cpspan.innerHTML='Page '+(this.currentpage+1)+'/'+this.pagecount
}


/*  Prototype-UI, version trunk
 *
 *  Prototype-UI is freely distributable under the terms of an MIT-style license.
 *  For details, see the PrototypeUI web site: http://www.prototype-ui.com/
 *
 *--------------------------------------------------------------------------*/

if(typeof Prototype == 'undefined' || !Prototype.Version.match("1.6"))
  throw("Prototype-UI library require Prototype library >= 1.6.0");

if (Prototype.Browser.WebKit) {
  Prototype.Browser.WebKitVersion = parseFloat(navigator.userAgent.match(/AppleWebKit\/([\d\.\+]*)/)[1]);
  Prototype.Browser.Safari2 = (Prototype.Browser.WebKitVersion < 420);
}

if (Prototype.Browser.IE) {
  Prototype.Browser.IEVersion = parseFloat(navigator.appVersion.split(';')[1].strip().split(' ')[1]);
  Prototype.Browser.IE6 =  Prototype.Browser.IEVersion == 6;
  Prototype.Browser.IE7 =  Prototype.Browser.IEVersion == 7;
}

Prototype.falseFunction = function() { return false };
Prototype.trueFunction  = function() { return true  };

/*
Namespace: UI

  Introduction:
    Prototype-UI is a library of user interface components based on the Prototype framework.
    Its aim is to easilly improve user experience in web applications.

    It also provides utilities to help developers.

  Guideline:
    - Prototype conventions are followed
    - Everything should be unobstrusive
    - All components are themable with CSS stylesheets, various themes are provided

  Warning:
    Prototype-UI is still under deep development, this release is targeted to developers only.
    All interfaces are subjects to changes, suggestions are welcome.

    DO NOT use it in production for now.

  Authors:
    - Sébastien Gruhier, <http://www.xilinus.com>
    - Samuel Lebeau, <http://gotfresh.info>
*/

var UI = {
  Abstract: { },
  Ajax: { }
};
Object.extend(Class.Methods, {
  extend: Object.extend.methodize(),

  addMethods: Class.Methods.addMethods.wrap(function(proceed, source) {
    // ensure we are not trying to add null or undefined
    if (!source) return this;

    // no callback, vanilla way
    if (!source.hasOwnProperty('methodsAdded'))
      return proceed(source);

    var callback = source.methodsAdded;
    delete source.methodsAdded;
    proceed(source);
    callback.call(source, this);
    source.methodsAdded = callback;

    return this;
  }),

  addMethod: function(name, lambda) {
    var methods = {};
    methods[name] = lambda;
    return this.addMethods(methods);
  },

  method: function(name) {
    return this.prototype[name].valueOf();
  },

  classMethod: function() {
    $A(arguments).flatten().each(function(method) {
      this[method] = (function() {
        return this[method].apply(this, arguments);
      }).bind(this.prototype);
    }, this);
    return this;
  },

  // prevent any call to this method
  undefMethod: function(name) {
    this.prototype[name] = undefined;
    return this;
  },

  // remove the class' own implementation of this method
  removeMethod: function(name) {
    delete this.prototype[name];
    return this;
  },

  aliasMethod: function(newName, name) {
    this.prototype[newName] = this.prototype[name];
    return this;
  },

  aliasMethodChain: function(target, feature) {
    feature = feature.camelcase();

    this.aliasMethod(target+"Without"+feature, target);
    this.aliasMethod(target, target+"With"+feature);

    return this;
  }
});
Object.extend(Number.prototype, {
  // Snap a number to a grid
  snap: function(round) {
    return parseInt(round == 1 ? this : (this / round).floor() * round);
  }
});
/*
Interface: String

*/

Object.extend(String.prototype, {
  camelcase: function() {
    var string = this.dasherize().camelize();
    return string.charAt(0).toUpperCase() + string.slice(1);
  },

  /*
    Method: makeElement
      toElement is unfortunately already taken :/

      Transforms html string into an extended element or null (when failed)

      > '<li><a href="#">some text</a></li>'.makeElement(); // => LI href#
      > '<img src="foo" id="bar" /><img src="bar" id="bar" />'.makeElement(); // => IMG#foo (first one)

    Returns:
      Extended element

  */
  makeElement: function() {
    var wrapper = new Element('div'); wrapper.innerHTML = this;
    return wrapper.down();
  }
});
Object.extend(Array.prototype, {
  empty: function() {
    return !this.length;
  },

  extractOptions: function() {
    return this.last().constructor === Object ? this.pop() : { };
  },

  removeAt: function(index) {
    var object = this[index];
    this.splice(index, 1);
    return object;
  },

  remove: function(object) {
    var index;
    while ((index = this.indexOf(object)) != -1)
      this.removeAt(index);
    return object;
  },

  insert: function(index) {
    var args = $A(arguments);
    args.shift();
    this.splice.apply(this, [ index, 0 ].concat(args));
    return this;
  }
});
Element.addMethods({
  getScrollDimensions: function(element) {
    return {
      width:  element.scrollWidth,
      height: element.scrollHeight
    }
  },

  getScrollOffset: function(element) {
    return Element._returnOffset(element.scrollLeft, element.scrollTop);
  },

  setScrollOffset: function(element, offset) {
    element = $(element);
    if (arguments.length == 3)
      offset = { left: offset, top: arguments[2] };
    element.scrollLeft = offset.left;
    element.scrollTop  = offset.top;
    return element;
  },

  // returns "clean" numerical style (without "px") or null if style can not be resolved
  // or is not numeric
  getNumStyle: function(element, style) {
    var value = parseFloat($(element).getStyle(style));
    return isNaN(value) ? null : value;
  },

  // by Tobie Langel (http://tobielangel.com/2007/5/22/prototype-quick-tip)
  appendText: function(element, text) {
    element = $(element);
    text = String.interpret(text);
    element.appendChild(document.createTextNode(text));
    return element;
  }
});

document.whenReady = function(callback) {
  if (document.loaded)
    callback.call(document);
  else
    document.observe('dom:loaded', callback);
};

Object.extend(document.viewport, {
  // Alias this method for consistency
  getScrollOffset: document.viewport.getScrollOffsets,

  setScrollOffset: function(offset) {
    Element.setScrollOffset(Prototype.Browser.WebKit ? document.body : document.documentElement, offset);
  },

  getScrollDimensions: function() {
    return Element.getScrollDimensions(Prototype.Browser.WebKit ? document.body : document.documentElement);
  }
});
/*
Interface: UI.Options
  Mixin to handle *options* argument in initializer pattern.

  TODO: find a better example than Circle that use an imaginary Point function,
        this example should be used in tests too.

  It assumes class defines a property called *options*, containing
  default options values.

  Instances hold their own *options* property after a first call to <setOptions>.

  Example:
    > var Circle = Class.create(UI.Options, {
    >
    >   // default options
    >   options: {
    >     radius: 1,
    >     origin: Point(0, 0)
    >   },
    >
    >   // common usage is to call setOptions in initializer
    >   initialize: function(options) {
    >     this.setOptions(options);
    >   }
    > });
    >
    > var circle = new Circle({ origin: Point(1, 4) });
    >
    > circle.options
    > // => { radius: 1, origin: Point(1,4) }

  Accessors:
    There are builtin methods to automatically write options accessors. All those
    methods can take either an array of option names nor option names as arguments.
    Notice that those methods won't override an accessor method if already present.

     * <optionsGetter> creates getters
     * <optionsSetter> creates setters
     * <optionsAccessor> creates both getters and setters

    Common usage is to invoke them on a class to create accessors for all instances
    of this class.
    Invoking those methods on a class has the same effect as invoking them on the class prototype.
    See <classMethod> for more details.

    Example:
    > // Creates getter and setter for the "radius" options of circles
    > Circle.optionsAccessor('radius');
    >
    > circle.setRadius(4);
    > // 4
    >
    > circle.getRadius();
    > // => 4 (circle.options.radius)

  Inheritance support:
    Subclasses can refine default *options* values, after a first instance call on setOptions,
    *options* attribute will hold all default options values coming from the inheritance hierarchy.
*/

(function() {
  UI.Options = {
    methodsAdded: function(klass) {
      klass.classMethod($w(' setOptions allOptions optionsGetter optionsSetter optionsAccessor '));
    },

    // Group: Methods

    /*
      Method: setOptions
        Extends object's *options* property with the given object
    */
    setOptions: function(options) {
      if (!this.hasOwnProperty('options'))
        this.options = this.allOptions();

      this.options = Object.extend(this.options, options || {});
    },

    /*
      Method: allOptions
        Computes the complete default options hash made by reverse extending all superclasses
        default options.

        > Widget.prototype.allOptions();
    */
    allOptions: function() {
      var superclass = this.constructor.superclass, ancestor = superclass && superclass.prototype;
      return (ancestor && ancestor.allOptions) ?
          Object.extend(ancestor.allOptions(), this.options) :
          Object.clone(this.options);
    },

    /*
      Method: optionsGetter
        Creates default getters for option names given as arguments.
        With no argument, creates getters for all option names.
    */
    optionsGetter: function() {
      addOptionsAccessors(this, arguments, false);
    },

    /*
      Method: optionsSetter
        Creates default setters for option names given as arguments.
        With no argument, creates setters for all option names.
    */
    optionsSetter: function() {
      addOptionsAccessors(this, arguments, true);
    },

    /*
      Method: optionsAccessor
        Creates default getters/setters for option names given as arguments.
        With no argument, creates accessors for all option names.
    */
    optionsAccessor: function() {
      this.optionsGetter.apply(this, arguments);
      this.optionsSetter.apply(this, arguments);
    }
  };

  // Internal
  function addOptionsAccessors(receiver, names, areSetters) {
    names = $A(names).flatten();

    if (names.empty())
      names = Object.keys(receiver.allOptions());

    names.each(function(name) {
      var accessorName = (areSetters ? 'set' : 'get') + name.camelcase();

      receiver[accessorName] = receiver[accessorName] || (areSetters ?
        // Setter
        function(value) { return this.options[name] = value } :
        // Getter
        function()      { return this.options[name]         });
    });
  }
})();
/*
  Class: UI.Carousel

  Main class to handle a carousel of elements in a page. A carousel :
    * could be vertical or horizontal
    * works with liquid layout
    * is designed by CSS

  Assumptions:
    * Elements should be from the same size

  Example:
    > ...
    > <div id="horizontal_carousel">
    >   <div class="previous_button"></div>
    >   <div class="container">
    >     <ul>
    >       <li> What ever you like</li>
    >     </ul>
    >   </div>
    >   <div class="next_button"></div>
    > </div>
    > <script>
    > new UI.Carousel("horizontal_carousel");
    > </script>
    > ...
*/
UI.Carousel = Class.create(UI.Options, {
  // Group: Options
  options: {
	// Property: direction
	//   Can be horizontal or vertical, horizontal by default
    direction               : "horizontal",

    // Property: previousButton
    //   Selector of previous button inside carousel element, ".previous_button" by default,
    //   set it to false to ignore previous button
    previousButton          : ".previous_button",

    // Property: nextButton
    //   Selector of next button inside carousel element, ".next_button" by default,
    //   set it to false to ignore next button
    nextButton              : ".next_button",

    // Property: container
    //   Selector of carousel container inside carousel element, ".container" by default,
    container               : ".container",

    // Property: scrollInc
    //   Define the maximum number of elements that gonna scroll each time, auto by default
    scrollInc               : "auto",

    // Property: disabledButtonSuffix
    //   Define the suffix classanme used when a button get disabled, to '_disabled' by default
    //   Previous button classname will be previous_button_disabled
    disabledButtonSuffix : '_disabled',

    // Property: overButtonSuffix
    //   Define the suffix classanme used when a button has a rollover status, '_over' by default
    //   Previous button classname will be previous_button_over
    overButtonSuffix : '_over'
  },

  /*
    Group: Attributes

      Property: element
        DOM element containing the carousel

      Property: id
        DOM id of the carousel's element

      Property: container
        DOM element containing the carousel's elements

      Property: elements
        Array containing the carousel's elements as DOM elements

      Property: previousButton
        DOM id of the previous button

      Property: nextButton
        DOM id of the next button

      Property: posAttribute
        Define if the positions are from left or top

      Property: dimAttribute
        Define if the dimensions are horizontal or vertical

      Property: elementSize
        Size of each element, it's an integer

      Property: nbVisible
        Number of visible elements, it's a float

      Property: animating
        Define whether the carousel is in animation or not
  */

  /*
    Group: Events
      List of events fired by a carousel

      Notice: Carousel custom events are automatically namespaced in "carousel:" (see Prototype custom events).

      Examples:
        This example will observe all carousels
        > document.observe('carousel:scroll:ended', function(event) {
        >   alert("Carousel with id " + event.memo.carousel.id + " has just been scrolled");
        > });

        This example will observe only this carousel
        > new UI.Carousel('horizontal_carousel').observe('scroll:ended', function(event) {
        >   alert("Carousel with id " + event.memo.carousel.id + " has just been scrolled");
        > });

      Property: previousButton:enabled
        Fired when the previous button has just been enabled

      Property: previousButton:disabled
        Fired when the previous button has just been disabled

      Property: nextButton:enabled
        Fired when the next button has just been enabled

      Property: nextButton:disabled
        Fired when the next button has just been disabled

      Property: scroll:started
        Fired when a scroll has just started

      Property: scroll:ended
        Fired when a scroll has been done,
        memo.shift = number of elements scrolled, it's a float

      Property: sizeUpdated
        Fired when the carousel size has just been updated.
        Tips: memo.carousel.currentSize() = the new carousel size
  */

  // Group: Constructor

  /*
    Method: initialize
      Constructor function, should not be called directly

    Parameters:
      element - DOM element
      options - (Hash) list of optional parameters

    Returns:
      this
  */
  initialize: function(element, options) {
    this.setOptions(options);
    this.element = $(element);
    this.id = this.element.id;
    this.container   = this.element.down(this.options.container).firstDescendant();
    this.elements    = this.container.childElements();
    this.previousButton = this.options.previousButton == false ? null : this.element.down(this.options.previousButton);
    this.nextButton = this.options.nextButton == false ? null : this.element.down(this.options.nextButton);

    this.posAttribute = (this.options.direction == "horizontal" ? "left" : "top");
    this.dimAttribute = (this.options.direction == "horizontal" ? "width" : "height");

    this.elementSize = this.computeElementSize();
    this.nbVisible = this.currentSize() / this.elementSize;

    var scrollInc = this.options.scrollInc;
    if (scrollInc == "auto")
      scrollInc = Math.floor(this.nbVisible);
    [ this.previousButton, this.nextButton ].each(function(button) {
      if (!button) return;
      var className = (button == this.nextButton ? "next_button" : "previous_button") + this.options.overButtonSuffix;
      button.clickHandler = this.scroll.bind(this, (button == this.nextButton ? -1 : 1) * scrollInc * this.elementSize);
      button.observe("click", button.clickHandler)
            .observe("mouseover", function() {button.addClassName(className)}.bind(this))
            .observe("mouseout",  function() {button.removeClassName(className)}.bind(this));
    }, this);
    this.updateButtons();
  },

  // Group: Destructor

  /*
    Method: destroy
      Cleans up DOM and memory
  */
  destroy: function($super) {
    [ this.previousButton, this.nextButton ].each(function(button) {
      if (!button) return;
        button.stopObserving("click", button.clickHandler);
    }, this);
	  this.element.remove();
	  this.fire('destroyed');
  },

  // Group: Event handling

  /*
    Method: fire
      Fires a carousel custom event automatically namespaced in "carousel:" (see Prototype custom events).
      The memo object contains a "carousel" property referring to the carousel.

    Example:
      > document.observe('carousel:scroll:ended', function(event) {
      >   alert("Carousel with id " + event.memo.carousel.id + " has just been scrolled");
      > });

    Parameters:
      eventName - an event name
      memo      - a memo object

    Returns:
      fired event
  */
  fire: function(eventName, memo) {
    memo = memo || { };
    memo.carousel = this;
    return this.element.fire('carousel:' + eventName, memo);
  },

  /*
    Method: observe
      Observe a carousel event with a handler function automatically bound to the carousel

    Parameters:
      eventName - an event name
      handler   - a handler function

    Returns:
      this
  */
  observe: function(eventName, handler) {
    this.element.observe('carousel:' + eventName, handler.bind(this));
    return this;
  },

  /*
    Method: stopObserving
      Unregisters a carousel event, it must take the same parameters as this.observe (see Prototype stopObserving).

    Parameters:
      eventName - an event name
      handler   - a handler function

    Returns:
      this
  */
  stopObserving: function(eventName, handler) {
	  this.element.stopObserving('carousel:' + eventName, handler);
	  return this;
  },

  // Group: Actions

  /*
    Method: checkScroll
      Check scroll position to avoid unused space at right or bottom

    Parameters:
      position       - position to check
      updatePosition - should the container position be updated ? true/false

    Returns:
      position
  */
  checkScroll: function(position, updatePosition) {
    if (position > 0)
      position = 0;
    else {
      var limit = this.elements.last().positionedOffset()[this.posAttribute] + this.elementSize;
      var carouselSize = this.currentSize();

      if (position + limit < carouselSize)
        position += carouselSize - (position + limit);
      position = Math.min(position, 0);
    }
    if (updatePosition)
      this.container.style[this.posAttribute] = position + "px";

    return position;
  },

  /*
    Method: scroll
      Scrolls carousel from maximum deltaPixel

    Parameters:
      deltaPixel - a float

    Returns:
      this
  */
  scroll: function(deltaPixel) {
    if (this.animating)
      return this;

    // Compute new position
    var position =  this.currentPosition() + deltaPixel;

    // Check bounds
    position = this.checkScroll(position, false);

    // Compute shift to apply
    deltaPixel = position - this.currentPosition();
    if (deltaPixel != 0) {
      this.animating = true;
      this.fire("scroll:started");

      var that = this;
      // Move effects
      this.container.morph("opacity:0.5", {duration: 0.2, afterFinish: function() {
        that.container.morph(that.posAttribute + ": " + position + "px", {
          duration: 0.4,
          delay: 0.2,
          afterFinish: function() {
            that.container.morph("opacity:1", {
              duration: 0.2,
              afterFinish: function() {
                that.animating = false;
                that.updateButtons()
                  .fire("scroll:ended", { shift: deltaPixel / that.currentSize() });
              }
            });
          }
        });
      }});
    }
    return this;
  },

  /*
    Method: scrollTo
      Scrolls carousel, so that element with specified index is the left-most.
      This method is convenient when using carousel in a tabbed navigation.
      Clicking on first tab should scroll first container into view, clicking on a fifth - fifth one, etc.
      Indexing starts with 0.

    Parameters:
      Index of an element which will be a left-most visible in the carousel

    Returns:
      this
  */
  scrollTo: function(index) {
    if (this.animating || index < 0 || index > this.elements.length || index == this.currentIndex() || isNaN(parseInt(index)))
      return this;
    return this.scroll((this.currentIndex() - index) * this.elementSize);
  },

  /*
    Method: updateButtons
      Update buttons status to enabled or disabled
      Them status is defined by classNames and fired as carousel's custom events

    Returns:
      this
  */
  updateButtons: function() {
	  this.updatePreviousButton();
    this.updateNextButton();
    return this;
  },

  updatePreviousButton: function() {
    var position = this.currentPosition();
    var previousClassName = "previous_button" + this.options.disabledButtonSuffix;

    if (this.previousButton.hasClassName(previousClassName) && position != 0) {
      this.previousButton.removeClassName(previousClassName);
      this.fire('previousButton:enabled');
    }
    if (!this.previousButton.hasClassName(previousClassName) && position == 0) {
	    this.previousButton.addClassName(previousClassName);
      this.fire('previousButton:disabled');
    }
  },

  updateNextButton: function() {
    var lastPosition = this.currentLastPosition();
    var size = this.currentSize();
    var nextClassName = "next_button" + this.options.disabledButtonSuffix;

    if (this.nextButton.hasClassName(nextClassName) && lastPosition != size) {
      this.nextButton.removeClassName(nextClassName);
      this.fire('nextButton:enabled');
    }
    if (!this.nextButton.hasClassName(nextClassName) && lastPosition == size) {
	    this.nextButton.addClassName(nextClassName);
      this.fire('nextButton:disabled');
    }
  },

  // Group: Size and Position

  /*
    Method: computeElementSize
      Return elements size in pixel, height or width depends on carousel orientation.

    Returns:
      an integer value
  */
  computeElementSize: function() {
    return this.elements.first().getDimensions()[this.dimAttribute];
  },

  /*
    Method: currentIndex
      Returns current visible index of a carousel.
      For example, a horizontal carousel with image #3 on left will return 3 and with half of image #3 will return 3.5
      Don't forget that the first image have an index 0

    Returns:
      a float value
  */
  currentIndex: function() {
    return - this.currentPosition() / this.elementSize;
  },

  /*
    Method: currentLastPosition
      Returns the current position from the end of the last element. This value is in pixel.

    Returns:
      an integer value, if no images a present it will return 0
  */
  currentLastPosition: function() {
    if (this.container.childElements().empty())
      return 0;
    return this.currentPosition() +
           this.elements.last().positionedOffset()[this.posAttribute] +
           this.elementSize;
  },

  /*
    Method: currentPosition
      Returns the current position in pixel.
      Tips: To get the position in elements use currentIndex()

    Returns:
      an integer value
  */
  currentPosition: function() {
    return this.container.getNumStyle(this.posAttribute);
  },

  /*
    Method: currentSize
      Returns the current size of the carousel in pixel

    Returns:
      Carousel's size in pixel
  */
  currentSize: function() {
    return this.container.parentNode.getDimensions()[this.dimAttribute];
  },

  /*
    Method: updateSize
      Should be called if carousel size has been changed (usually called with a liquid layout)

    Returns:
      this
  */
  updateSize: function() {
    this.nbVisible = this.currentSize() / this.elementSize;
    var scrollInc = this.options.scrollInc;
    if (scrollInc == "auto")
      scrollInc = Math.floor(this.nbVisible);

    [ this.previousButton, this.nextButton ].each(function(button) {
      if (!button) return;
      button.stopObserving("click", button.clickHandler);
      button.clickHandler = this.scroll.bind(this, (button == this.nextButton ? -1 : 1) * scrollInc * this.elementSize);
      button.observe("click", button.clickHandler);
    }, this);

    this.checkScroll(this.currentPosition(), true);
    this.updateButtons().fire('sizeUpdated');
    return this;
  }
});
/*
  Class: UI.Ajax.Carousel

  Gives the AJAX power to carousels. An AJAX carousel :
    * Use AJAX to add new elements on the fly

  Example:
    > new UI.Ajax.Carousel("horizontal_carousel",
    >   {url: "get-more-elements", elementSize: 250});
*/
UI.Ajax.Carousel = Class.create(UI.Carousel, {
  // Group: Options
  //
  //   Notice:
  //     It also include of all carousel's options
  options: {
	// Property: elementSize
	//   Required, it define the size of all elements
    elementSize : -1,

	// Property: url
	//   Required, it define the URL used by AJAX carousel to request new elements details
    url         : null
  },

  /*
    Group: Attributes

      Notice:
        It also include of all carousel's attributes

      Property: elementSize
        Size of each elements, it's an integer

      Property: endIndex
        Index of the last loaded element

      Property: hasMore
        Flag to define if there's still more elements to load

      Property: requestRunning
        Define whether a request is processing or not

      Property: updateHandler
        Callback to update carousel, usually used after request success

      Property: url
        URL used to request additional elements
  */

  /*
    Group: Events
      List of events fired by an AJAX carousel, it also include of all carousel's custom events

      Property: request:started
        Fired when the request has just started

      Property: request:ended
        Fired when the request has succeed
  */

  // Group: Constructor

  /*
    Method: initialize
      Constructor function, should not be called directly

    Parameters:
      element - DOM element
      options - (Hash) list of optional parameters

    Returns:
      this
  */
  initialize: function($super, element, options) {
    if (!options.url)
      throw("url option is required for UI.Ajax.Carousel");
    if (!options.elementSize)
      throw("elementSize option is required for UI.Ajax.Carousel");

    $super(element, options);

    this.endIndex = 0;
    this.hasMore  = true;

    // Cache handlers
    this.updateHandler = this.update.bind(this);
    this.updateAndScrollHandler = function(nbElements, transport, json) {
	    this.update(transport, json);
	    this.scroll(nbElements);
	  }.bind(this);

    // Run first ajax request to fill the carousel
    this.runRequest.bind(this).defer({parameters: {from: 0, to: Math.ceil(this.nbVisible) - 1}, onSuccess: this.updateHandler});
  },

  // Group: Actions

  /*
    Method: runRequest
      Request the new elements details

    Parameters:
      options - (Hash) list of optional parameters

    Returns:
      this
  */
  runRequest: function(options) {
    this.requestRunning = true;
    new Ajax.Request(this.options.url, Object.extend({method: "GET"}, options));
    this.fire("request:started");
    return this;
  },

  /*
    Method: scroll
      Scrolls carousel from maximum deltaPixel

    Parameters:
      deltaPixel - a float

    Returns:
      this
  */
  scroll: function($super, deltaPixel) {
    if (this.animating || this.requestRunning)
      return this;

    var nbElements = (-deltaPixel) / this.elementSize;
    // Check if there is not enough
    if (this.hasMore && nbElements > 0 && this.currentIndex() + this.nbVisible + nbElements - 1 > this.endIndex) {
      var from = this.endIndex + 1;
      var to   = Math.ceil(from + this.nbVisible - 1);
      this.runRequest({parameters: {from: from, to: to}, onSuccess: this.updateAndScrollHandler.curry(deltaPixel).bind(this)});
      return this;
    }
    else
      $super(deltaPixel);
  },

  /*
    Method: update
      Update the carousel

    Parameters:
      transport - XMLHttpRequest object
      json      - JSON object

    Returns:
      this
  */
  update: function(transport, json) {
    this.requestRunning = false;
    this.fire("request:ended");
    if (!json)
      json = transport.responseJSON;
    this.hasMore = json.more;

    this.endIndex = Math.max(this.endIndex, json.to);
    this.elements = this.container.insert({bottom: json.html}).childElements();
    return this.updateButtons();
  },

  // Group: Size and Position

  /*
    Method: computeElementSize
      Return elements size in pixel

    Returns:
      an integer value
  */
  computeElementSize: function() {
    return this.options.elementSize;
  },

  /*
    Method: updateSize
      Should be called if carousel size has been changed (usually called with a liquid layout)

    Returns:
      this
  */
  updateSize: function($super) {
    var nbVisible = this.nbVisible;
    $super();
    // If we have enough space for at least a new element
    if (Math.floor(this.nbVisible) - Math.floor(nbVisible) >= 1 && this.hasMore) {
      if (this.currentIndex() + Math.floor(this.nbVisible) >= this.endIndex) {
        var nbNew = Math.floor(this.currentIndex() + Math.floor(this.nbVisible) - this.endIndex);
        this.runRequest({parameters: {from: this.endIndex + 1, to: this.endIndex + nbNew}, onSuccess: this.updateHandler});
      }
    }
    return this;
  },

  updateNextButton: function($super) {
    var lastPosition = this.currentLastPosition();
    var size = this.currentSize();
    var nextClassName = "next_button" + this.options.disabledButtonSuffix;

    if (this.nextButton.hasClassName(nextClassName) && lastPosition != size) {
      this.nextButton.removeClassName(nextClassName);
      this.fire('nextButton:enabled');
    }
    if (!this.nextButton.hasClassName(nextClassName) && lastPosition == size && !this.hasMore) {
	    this.nextButton.addClassName(nextClassName);
      this.fire('nextButton:disabled');
    }
  }
});
// script.aculo.us effects.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

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

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

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

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

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

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

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

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

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

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

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

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

/* ------------- core effects ------------- */

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/* ------------- combination effects ------------- */

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return styleRules;
};

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

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

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

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

Element.addMethods(Effect.Methods);
function enterKey(e,action){
	if(window.event) // IE
	{
		if (window.event.keyCode==13) {
			eval(action);
		}
	}
	else if(e.which){
		if (e.which==13) {
			eval(action);
		}
	}
	
	
}
function showXDiv(divID,link){
	var div=document.getElementById(divID);
	//alert(link.offsetLeft);
	div.style.top=link.offsetLeft+'px';
	div.style.left=link.offsetTop+'px';
	div.style.display = "block";
}
function hideXDiv(divID){
	var div=document.getElementById(divID);
	div.style.display = "none";
}
function closeClearBox(){
	top.document.location.reload();
}
function loadMenu(menu){
	//frames['mainFrame'].location.href=menu;
	location.href=menu;
	return false;
}

function reloadPage(){
	document.location.reload();
}
function openRegister(){
	//showElement('message');
}
function closeRegister(){
	hideElement('message');
}

function register(){
	
	var name=window.document.getElementById('registerName');
	var email=window.document.getElementById('registerEmail');
	//var timezoneelement=window.document.getElementById('timezoneselect');
	//var timezone=timezoneelement.options[timezoneelement.selectedIndex].value;
	var href=document.location.href;
	var classid=href.startsWith('http://www.linkua.com/book_now/')?href.substr(31):0;
	//alert(classid);
	var pars='name='+name.value+'&email='+email.value+'&classid='+classid;
	actionName='/registerStudent';
	ajaxRequest = new Ajax.Request(
					actionName, 
				{
					method: 'post',
					onSuccess: registerSuccess,
					onFailure: registerFail,
					parameters: pars
				}
			);
	

}
function registerFail(request){
	showRegError('Error unknown');
	
}
function registerSuccess(request){
	//alert('success '+request.responseText);
	response=parseInt(request.responseText)
	if(response==0){
		var email=window.document.getElementById('registerEmail');
		pars='operation=retrieve_password&email='+email.value+'&form_retrieve_password_proceed=Retrieve your Password';
		actionName='/retrieve_password.php';
		ajaxRequestEmail = new Ajax.Request(
					actionName, 
				{
					method: 'post',
					onSuccess: showResponse,
					onFailure: showResponse,
					parameters: pars
				}
			);	
		
		document.location.reload();
	}
	else{
		showRegError(request.responseText);
	}
}
function showResponse(request){
	//alert(request.responseText);
}
function showRegError(message){
	//alert(message);
	var errorElement=window.document.getElementById('regError');
	errorElement.innerHTML=message;
	errorElement.style.color='#FF0000';
}
function search(paramType,paramValue){
	var learnSel=document.getElementById('language');
	var langLearn=learnSel[learnSel.selectedIndex].value;
	var langLearnText=learnSel[learnSel.selectedIndex].innerHTML;
	var searchText=document.getElementById('searchBox');
	
	var elang2=document.getElementById('lang2');
	var ecity=document.getElementById('city');
	var ecountry=document.getElementById('country');
	var etag=document.getElementById('tag');
	var epage=document.getElementById('page');
    var academy=document.getElementById('academy');
    var chk_courses=document.getElementById('chk_courses');
	
	if(elang2) lang2= elang2.value; else lang2=null;
	if(ecity) city= ecity.value; else city=null;
	if(ecountry) country= ecountry.value; else country=null;
	if(etag) tag= etag.value; else tag=null;
	//if(epage) page= epage.value; else page=null;
	
	if(paramType!=null && paramValue==null){
		switch(paramType){
			case 'lang2':
				lang2=null;
				break;
			case 'city':
				city=null;
				break;
			case 'country':
				country=null;
				break;
		}
	}
	if(paramType!=null && paramValue!=null){
		switch(paramType){
			case 'lang2':
				lang2=paramValue;
				break;
			case 'city':
				city=paramValue;
				break;
			case 'country':
				country=paramValue;
				break;
			case 'tag':
				if(tag!=null){
					tag+="-"+paramValue;
				}
				else{
					tag=paramValue;
				}
				break;
			case 'tagRemove':
				
				tag=tag.replace("-"+paramValue,"");
				tag=tag.replace(paramValue+"-","");
				tag=tag.replace(paramValue,"");
				break;
		}
	}
	var url='';
	if(academy){
        url="/search.htm?type=academies";
    }
    else {
    	if(chk_courses.checked==false){
        	url="/search.htm?type=teachers";
        }
        else{
        	url="/search.htm?type=courses";
        }
    }

//	if(langLearn!=0 && langLearn!=-1){
		if(langLearn!=null && langLearn!=0){
            url+='&lang='+langLearn;
        }else{
            url+='&lang=0';
        }
		
		if(lang2!=null){
			url+='&lang2='+lang2;
		}
		if(city!=null){
			url+='&city='+city;
		}
		if(country!=null){
			url+='&country='+country;
		}
		if(tag!=null){
			url+='&tag='+tag;
		}
		//if(page!=null){
		//	url+='&page='+page;
		//}
		if(searchText.value!=''){
			url+='&term='+URLEncode(searchText.value);
			document.location.href=url;
		}
		else{
			//alert(url);
			document.location.href=url;
		}
//	}
//	else{
//		alert(langLearnText);
//	}
	
	
	
	
}
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function updateTZ(select){

	var	actionName='/register_teacher/XgetTimeZone';
	var country=select[select.selectedIndex].value;
	
	
	
	var ac = AjaxCaller.getInstance();
	ac.pars='&country='+country;

	if(ac){
		ac.actionName = actionName;
		ac.elementID = 'timezoneSelect';
		ac.getUpdate();
	}	





}
function selectCVS(){
	
	var	actionName='/traduccion/XactualizarTextBox';	
	var ac = AjaxCaller.getInstance();
	var text=document.getElementById('tabla').value;
	
	ac.pars='&value='+text;

	if(ac){
		ac.actionName = actionName;
		ac.elementID = 'traduccion';
		ac.getUpdate();
	}	
}
function saveAll(type){

}
function translateAll(lang){
	langAll=lang;
	var txtAreas = document.getElementsByTagName('textarea');
	keys= new Array();
	for(var i in txtAreas){
		var txtID=new String(txtAreas[i].id);
		if(txtID.substring(0,2)=="c_"){
			key=txtID.substring(2,txtID.length);
			var newText=document.getElementById('c_'+key);
			//translateGoogle(key);
			keys.push(key);
		}
	}
	translateGoogleAll()


}
function translateGoogleAll(){
	key=keys.shift();
	var newText=document.getElementById('g_'+key);
	text=newText.value;
	end=false;
	google.language.translate(text, "en", langAll, googleCallBackAll);

}
function googleCallBackAll(result){
	if (!result.error) {
	    	//alert(key);
	    	var container = document.getElementById('g_'+key);
	    	container.style.borderColor ="blue";
	    	container.value = result.translation;
	  	}
	  else{
	 	 //alert(key);
	 	 var container = document.getElementById('g_'+key);
	 	 container.style.borderColor ="red";
	  }
	  translateGoogleAll();

}
function translateGoogle(keyid,lang){
	var newText=document.getElementById('g_'+keyid);
	text=newText.value;
	key = keyid;
	google.language.translate(text, "en", lang, googleCallBack);
}
function googleCallBack(result){
	if (!result.error) {
	    	//alert(key);
	    	var container = document.getElementById('g_'+key);
	    	container.style.borderColor ="blue";
	    	container.value = result.translation;
	  	}
	  else{
	 	 //alert(key);
	 	 var container = document.getElementById('g_'+key);
	 	 container.style.borderColor ="red";
	  }
}
function saveLangUpdate(keyID,type,page){
	
	var	actionName='/traduccion/save';	
	var ac = AjaxCaller.getInstance();
	var newText=document.getElementById(type+'_'+keyID);
	
	ac.pars='&newText='+encodeURIComponent(newText.value);
	ac.pars+="&keyid="+keyID;
	ac.pars+="&type="+type;
	ac.pars+="&page="+page;
	if(ac){
		ac.actionName = actionName;
		ac.elementID = type+'Div_'+keyID
		ac.getUpdate();
	}
}
function saveLangUpdateT(keyID,type,page){
	
	var	actionName='/traduccion/save';	
	var ac = AjaxCaller.getInstance();
	var newText=document.getElementById(type+'_'+keyID);
	
	ac.pars='&newText='+encodeURIComponent(newText.value);
	ac.pars+="&keyid="+keyID;
	ac.pars+="&type="+type;
	ac.pars+="&page="+page;
	if(ac){
		ac.actionName = actionName;
		ac.elementID = type+'Div_'+keyID
		ac.getUpdateT();
	}
}

function saveAll(pageIn){
	var txtAreas = document.getElementsByTagName('textarea');
	page=pageIn;
	type='c';
	keys= new Array();
	for(var i in txtAreas){
		var txtID=new String(txtAreas[i].id);
		if(txtID.substring(0,2)=="c_"){
			key=txtID.substring(2,txtID.length);
			var newText=document.getElementById('c_'+key);
			keys.push(key);
		}
	}
	saveAllData();
}
function saveAllData(){
	key=keys.shift();
	saveLangUpdateT(key,type,page);
}
function saveAllTranslate(pageIn){
	var txtAreas = document.getElementsByTagName('textarea');
	page=pageIn;
	type='g';
	keys= new Array();
	for(var i in txtAreas){
		var txtID=new String(txtAreas[i].id);
		if(txtID.substring(0,2)=="g_"){
			key=txtID.substring(2,txtID.length);
			var newText=document.getElementById('g_'+key);
			keys.push(key);
		}
	}
	saveAllData();
}
function updateEditorLang(select){

	var tabla=document.getElementById('tabla').value;
	
	var	actionName='/traduccion/'+tabla;
	var ac = AjaxCaller.getInstance();
	var lang=select[select.selectedIndex].value;
	ac.pars='&lang='+lang;

	if(ac){
		ac.actionName = actionName;
		ac.elementID = 'editDiv';
		ac.getUpdate();
	}	


}

function updateTags(e,cont,group){
	
	if (!(e.keyCode ==13 || cont.name=="add")) return;

	var	actionName='/register_teacher/XgetTags'; 
	var ac = AjaxCaller.getInstance();
	var tag=document.getElementById('tao_'+group).value;	
	if (tag.length==0) return;
	var chk=document.getElementsByTagName('INPUT');

	var c="";
	c=c.concat(tag);
	var x="";   
	for(i=0;i<chk.length;i++){
		var tmp=chk[i].name;
		var estate=chk[i].checked?1:0; 
		if (tmp.match("checks_"+group+"_")){
			x=x.concat(chk[i].value+";"+String(estate));
			x=x.concat("|");
		}
		
	};
	
	x=x.concat(c+";0");
   ac.pars='&tag='+x+"&group="+group;

	if(ac){
		ac.actionName = actionName;
		ac.elementID = 'tagsDiv'+"_"+group;
		ac.getUpdate();
	}
	document.getElementById('tao_'+group).value="";
}

function estiloTabla(obj, componente, color){
	var fila=document.getElementById(componente);
	fila.style.backgroundColor=color ;
}

function redirect(enlace, obj){

	//alert(obj.cellIndex);
	if (obj.cellIndex){
		window.location = enlace;
	}
}
function editClass(enlace){
	window.location = enlace;
}

function marcarTodosLevels(){

	document.getElementById('l2').checked=true;
	document.getElementById('l3').checked=true;
	document.getElementById('l4').checked=true;
	document.getElementById('l5').checked=true;
}
function nuevaClase(id){
	var url="/registerClass/";
	var salida=url+id;
	window.location.href(salida);
}

function finishRegistration(){
	document.forms.formClass.action="/validation";
	document.getElementById('salida').value=1;
	document.forms.formClass.submit();
}
function searchSmall(){
	var searchText=document.getElementById('searchBox');
	var urlText=document.getElementById('url');
	var	url=urlText.value+'/'+searchText.value;
	document.location.href=url;
}

	function color(celda, fila){
	if (celda.checked)
		document.getElementById(fila).style.backgroundColor="#dddddd" ;
	else 
		document.getElementById(fila).style.backgroundColor="#ffffff" ;
		
		
	}
	


function mostrarTagsAsociados(grupo){

	var	actionName='/tagsadmin/XgetTagsAsociados';
	var ac = AjaxCaller.getInstance();

	ac.pars='&grupo='+grupo.value;
	if(ac){
		ac.actionName = actionName;
		ac.elementID = 'tagsAsociados';
		ac.getUpdate();
	}

}

function borrarTag(id, grupo, tagtext){

	var	actionName='/tagsadmin/XdesTags';
	var ac = AjaxCaller.getInstance();

	var sel_tag=document.getElementById('tag_lista');
	
	var option=new Option(tagtext, id);

	
	sel_tag.options[sel_tag.options.length]=option;
	
	ac.pars='&grupo='+grupo+'&id='+id;
	if(ac){
		ac.actionName = actionName;
		ac.elementID = 'tagsAsociados';
		ac.getUpdate();
	}	
}
	
function asociarTag(){

	var arr=document.getElementById('tag_lista');
	grupo=document.getElementById('grupo').value;
	
	if (grupo==0) return;
	selected = new Array(); 
	var ac = AjaxCaller.getInstance();
	ac.pars="&grupo="+grupo;
	var cont=0;
	for (var i=0; i<arr.options.length; i++) 
		if (arr.options[i].selected) {
			
			selected.push(arr.options[i].value);	
			ac.pars+='&id'+[cont++]+'='+arr.options[i].value;
			arr.options[i].remove()
		}
	
	var	actionName='/tagsadmin/XasocTag';

	if(ac){
		ac.actionName = actionName;
		ac.elementID = 'tagsAsociados';
		ac.getUpdate();
	}	
	
	

}

function adminBorrarTags(){
	
	var arr=document.getElementById('tag');
	
	selected = new Array(); 
	var ac = AjaxCaller.getInstance();
	ac.pars="";;
	var cont=0;
	for (var i=0; i<arr.options.length; i++) 
		if (arr.options[i].selected) {
			selected.push(arr.options[i].value);	
			ac.pars+='&id'+[cont++]+'='+arr.options[i].value;
		}
	
	var	actionName='/tagsadmin/XborrarTags';

	
	if(ac){
		ac.actionName = actionName;
		ac.elementID = 'tag';
		ac.getUpdate();
	}	
	
}

function adminAgregarTags(){
	

	var texto=document.getElementById('edit_tag').value;
	

	var ac = AjaxCaller.getInstance();
	ac.pars="&text="+texto;

	var	actionName='/tagsadmin/XagregarTags';

	
	if(ac){
		ac.actionName = actionName;
		ac.elementID = 'tag';
		ac.getUpdate();
	}

	document.getElementById('edit_tag').value="";
}
function step4(update,idioma){
	
	var nuevo=document.getElementById('nuevo').value;
	var price=document.getElementById('price').value;
	var update=document.getElementById('update').value;
	var lang=document.getElementById('ln1').value;
	var next_step=document.getElementById('next_step').value;

//obtener elementos dentro de divs;
	var x="";
	var tao="";
	var tg=document.getElementsByTagName('DIV');
	var c="";
	var cont=1;
	for(i=0;i<(tg.length);i++){
		var tmp=tg[i].id;
		if (tmp.match("tagsDiv")){
			tao+=document.getElementById('tao_'+cont).value+"|";
			arr=tmp.split("_");
			var chk=tg[i].getElementsByTagName('INPUT');
			x+=arr[1]+"[title]";
			for(z=0;z<chk.length;z++){
				var tmp=chk[z].name;
				var estate=chk[z].checked?1:0; 
				if (tmp.match("che")){
					x=x.concat(chk[z].value+";"+estate);
					x=x.concat("|");
				}	
			}
			x+="[group]";
			cont++;
		
		}
	}

	if (document.getElementById('FirstClassFree').checked) var fcf=1; else var fcf=0;

	var pars="&price="+price+"&tag="+x+"&update="+update+"&lang="+lang+"&tao="+tao+"&fcf="+fcf+"&idioma="+idioma+"&next_step="+next_step+"&nuevo="+nuevo;
		new Ajax.Updater('step', '/register_teacher/Xvalidation_4',	{
					method: 'post',
					parameters: pars,
					onComplete: Xredirect
				});


}

function step4_2(update){
	var nuevo=document.getElementById('nuevo').value;
	var titulo=document.getElementById('title').value;
	var descripcion=document.getElementById('descripcion').value;
	var clase=document.getElementById('class').value;
	var updateClass=document.getElementById('update').value;
	var next_step=document.getElementById('next_step').value;

	var next_lang=document.getElementById('lang_id').value;

	var pars="&descripcion="+descripcion+"&titulo="+titulo+"&clase="+clase+"&update="+updateClass+"&next_lang="+next_lang+"&nuevo="+nuevo+"&next_step="+next_step;
		new Ajax.Updater('step', '/register_teacher/validation_4_2',	{
					method: 'post',
					parameters: pars,
					onComplete: Xredirect
				});
}

function step4_3(update){
	switch(update){
	case 2:
		var id_class=document.getElementById('id_class').value;
		var nuevo=document.getElementById('nuevo').value;
		var next_step=document.getElementById('next_step').value;
		var pars="&id_class="+id_class+"&nuevo="+nuevo+"&next_step="+next_step;
		new Ajax.Updater('step', '/register_teacher/Xstep4_2',	{
				method: 'post',
				parameters: pars,
				onComplete: Xredirect
			});
		return;
	break;
	
	case 3:
		var id_class=document.getElementById('id_class').value;
		var nuevo=document.getElementById('nuevo').value;
		var next_step=document.getElementById('next_step').value;
		var pars="&id_class="+id_class+"&nuevo="+nuevo+"&next_step="+next_step;
		new Ajax.Updater('step', '/register_teacher/step4_question',	{
				method: 'post',
				parameters: pars,
				onComplete: Xredirect
			});
		return;
	break;
	}
}

function onChangeRadioLanguage(radio){
	var level=0;

	if (radio.value==1){
		document.getElementById('chk_levels').style.display="none";
		document.getElementById('skill_language').style.display="block";
		
		
	}
	else{
		document.getElementById('chk_levels').style.display="block";
		document.getElementById('skill_language').style.display="none";
		if (document.getElementById('level1').checked) level=1;
		if (document.getElementById('level2').checked) level=2;
		if (document.getElementById('level3').checked) level=3;
		
		if (level==0) document.getElementById('level1').checked=true;
	}
	

}

function updateLanguages(id_class, lang_id){
	if(lang_id!='0'){
		new Ajax.Updater('step', '/updateClassDesc/'+id_class+'/'+lang_id,	{
			method: 'get',
			onComplete: Xredirect
		});
	}
	else{
		window.location='/updateClass/'+id_class;
	}
	
}
function step3(update){
	var nuevo=document.getElementById('nuevo').value;	
	if (nuevo==0 && update==1){
		update=2;
		}
		
	var tablang=document.getElementById('tablang').value;	
	var description=document.getElementById('description').value;	
	var next_step=document.getElementById('next_step').value;	
	var pars="&description="+description+"&tablang="+tablang+"&next_step="+next_step+"&nuevo="+nuevo;

	switch(update){
	case 0:	
		var funcion='/register_teacher/Xvalidation_3';
		break;
	case 1:	
		var funcion='/register_teacher/Xvalidation_3_Next_Lang';
		break;
	case 2:	
		var funcion='/register_teacher/xstep3';
		break;
	case 3: 
		var funcion='/register_teacher/XStep3Finish';
		break;
	case 5: 
		var funcion='/register_teacher/Xvalidation_3_Next_Lang_question';
		break;
	
	}

	
	
	new Ajax.Updater('step', funcion,	{
			  	method: 'post',
				parameters: pars,
				onComplete: Xredirect
			});


}

function step2_0(){
	var pars="";

	var next_step=document.getElementById('next_step').value;
	var tablang=document.getElementById('tablang').value;
	var nuevo=document.getElementById('nuevo').value;
	var stepn=document.getElementById('stepn').value;
	
	var teach=0;		
	var language=document.getElementById('ln1').value;
	
	if (document.getElementById('teach').checked) teach=1;
	if (document.getElementById('speack').checked) teach=0;
	pars="&teach="+teach;
	
	if (teach==0){
		var level=1;
		if (document.getElementById('level1').checked) level="1";
		if (document.getElementById('level2').checked) level="2";
		if (document.getElementById('level3').checked) level="3";
		
		pars+="&level="+level;
		
		
	}
	else{
		var sk1="0";var sk2="0";var sk3="0"
	 	if (document.getElementById('sk1').checked)  sk1="1";else sk1="0";
		if (document.getElementById('sk2').checked)  sk2="1";else sk2="0";
		if (document.getElementById('sk3').checked)  sk3="1";else sk3="0";
		pars+="&sk1="+sk1+"&sk2="+sk2+"&sk3="+sk3;
	}

	pars+="&language="+language+"&next_step="+next_step+"&tablang="+tablang+"&nuevo="+nuevo+"&stepn="+stepn;
	

	
	new Ajax.Updater('step2', '/register_teacher/Xvalidation_2_1',	{
			  	method: 'post',
				parameters: pars,
				onComplete: Xredirect
			});


}
function profile_changeLang(lang){
	pars="&lang="+lang
	new Ajax.Updater('step', '/members/show_lang',	{
	  	method: 'post',
		parameters: pars
	});
}
function profile_deleteLang(lang){
	pars="&lang="+lang
	new Ajax.Updater('step', '/members/remove_lang',	{
	  	method: 'post',
		parameters: pars
	});
}
function profile_updateLang(){
	var pars="";
	var learn=0;
	var language=document.getElementById('langselect').value;
	
	if (document.getElementById('learn').checked) learn=1;
	if (document.getElementById('speak').checked) learn=0;
	pars="&learn="+learn;
	
	var level=1;
	if (document.getElementById('level1').checked) level="1";
	if (document.getElementById('level2').checked) level="2";
	if (document.getElementById('level3').checked) level="3";
	pars+="&level="+level;
	pars+="&language="+language;
	new Ajax.Updater('step', '/members/update_lang',	{
			  	method: 'post',
				parameters: pars
			});
}
function profile_addLang(){
	var pars="";
	var learn=0;
	var language=document.getElementById('langselect').value;
	
	if (document.getElementById('learn').checked) learn=1;
	if (document.getElementById('speak').checked) learn=0;
	pars="&learn="+learn;
	
	var level=1;
	if (document.getElementById('level1').checked) level="1";
	if (document.getElementById('level2').checked) level="2";
	if (document.getElementById('level3').checked) level="3";
	pars+="&level="+level;
	pars+="&language="+language;
	new Ajax.Updater('step', '/members/add_lang',	{
			  	method: 'post',
				parameters: pars
			});

}

function step2(update){
	

	if (update==3){
		document.getElementById('teach').checked=1;
		document.getElementById('level1').checked=1;
		
	 	document.getElementById('sk1').checked=0;
		document.getElementById('sk2').checked=0;
		document.getElementById('sk3').checked=0;
		onChangeRadioLanguage(document.getElementById('teach'));
		
		document.getElementById('ln1').value=0;

		

		
		document.getElementById('tablang').value=-1;
		
		new Ajax.Updater('div_lang', '/register_teacher/XReloadTabs',	{
					method: 'post'
				});
		
		
	}else{
		
		var next_step=document.getElementById('next_step').value;
		
		var pars="&next_step="+next_step;

		new Ajax.Updater('step2', '/register_teacher/Xvalidation_2',	{
		  		 method: 'post',
				 parameters: pars,
				 onComplete: Xredirect
				});
		

		}

	
}

function Xredirect(){
	
	var desStr=document.getElementById('enviar').value;

	var txt=desStr.split(":");
	if (txt[0]=="url"){
		location.href=txt[1];return;
	}
	
	var step4=document.getElementById('lang_id').value;
	if (step4=="") location.href='/register_teacher/step4';
}
function step1(step){
	
	
	 if (document.getElementById('iframeUpload').contentDocument){ 
   rv = document.getElementById('iframeUpload').contentDocument; 
 } else { 
   // IE 
   rv = document.frames['iframeUpload'].document; 
 } 

	var ns=document.getElementById('next_step').value;
	var stepn=document.getElementById('stepn').value;
	
	var oldPass=document.getElementById('oldPass').value;
	var salt=document.getElementById('salt').value;
	var fname=document.getElementById('fname').value;
	var lname=document.getElementById('lname').value;
	var email=document.getElementById('email').value;
	var skype=document.getElementById('skype').value;
	var password_old=document.getElementById('password_old').value;
	
	var password_reg=document.getElementById('password_reg').value;
	var rpassword=document.getElementById('rpassword').value;
	var country=document.getElementById('country');
	var country_id=country[country.selectedIndex].value;
	var city_text=document.getElementById('ciudad_reg').value;
	var registration=document.getElementById('registration').value;
	var fr=rv;
	var archivo=fr.getElementById('archivo').value;
	var registerAccept=document.getElementById('registerAccept').checked;

	if (country_id==0){

		var pars="&fname="+fname+"&lname="+lname+"&email="+email+"&skype="+skype+"&password_reg="+password_reg+"&rpassword="+rpassword+"&country="+country_id+"&city_text="+city_text+"&registerAccept="+registerAccept+"&country_index="+country.selectedIndex+"&registration="+registration+"&archivo="+archivo+"&next_step="+ns+"&password_old="+password_old+"&oldPass="+oldPass+"&salt="+salt+"&stepn="+stepn;	
	}
	else{
		
		var time_zone=document.getElementById('timezone');
		var time_zone_id=time_zone[time_zone.selectedIndex].value;

		var city=document.getElementById('cities_list');
		var city_id=city[city.selectedIndex].value;

		var chk=document.getElementById('chk_city').checked;

		var pars="&fname="+fname+"&lname="+lname+"&email="+email+"&skype="+skype+"&password_reg="+password_reg+"&rpassword="+rpassword+"&country="+country_id+"&timezone="+time_zone_id+"&registerAccept="+registerAccept+"&city_id="+city_id+"&city_text="+city_text+"&chk="+chk+"&country_index="+country.selectedIndex+"&city_index="+city.selectedIndex+"&tmz_index="+time_zone.selectedIndex+"&registration="+registration+"&archivo="+archivo+"&next_step="+ns+"&password_old="+password_old+"&oldPass="+oldPass+"&salt="+salt+"&stepn="+stepn;				

	}	
	var ac = AjaxCaller.getInstance();
	
		new Ajax.Updater('step', '/register_teacher/Xvalidation_1',	{
					method: 'post',
					parameters: pars,
					onComplete: Xredirect
				});

}

function step1_school(step){

    if (document.getElementById('iframeUpload').contentDocument){
        rv = document.getElementById('iframeUpload').contentDocument;
    } else {
        // IE
        rv = document.frames['iframeUpload'].document;
    }

    var ns=document.getElementById('next_step').value;
    var stepn=document.getElementById('stepn').value;

    var oldPass=document.getElementById('oldPass').value;
    var salt=document.getElementById('salt').value;
    var fname=document.getElementById('fname').value;
    var lname=document.getElementById('lname').value;
    var email=document.getElementById('email').value;
    var skype=document.getElementById('skype').value;
    var password_old=document.getElementById('password_old').value;

    var password_reg=document.getElementById('password_reg').value;
    var rpassword=document.getElementById('rpassword').value;
    var country=document.getElementById('country');
    var country_id=country[country.selectedIndex].value;
    var city_text=document.getElementById('ciudad_reg').value;
    var registration=document.getElementById('registration').value;
    var fr=rv;
    var archivo=fr.getElementById('archivo').value;
    var registerAccept=document.getElementById('registerAccept').checked;

    if (country_id==0){

        var pars="&fname="+fname+"&lname="+lname+"&email="+email+"&skype="+skype+"&password_reg="+password_reg+"&rpassword="+rpassword+"&country="+country_id+"&city_text="+city_text+"&registerAccept="+registerAccept+"&country_index="+country.selectedIndex+"&registration="+registration+"&archivo="+archivo+"&next_step="+ns+"&password_old="+password_old+"&oldPass="+oldPass+"&salt="+salt+"&stepn="+stepn;
    }
    else{

        var time_zone=document.getElementById('timezone');
        var time_zone_id=time_zone[time_zone.selectedIndex].value;

        var city=document.getElementById('cities_list');
        var city_id=city[city.selectedIndex].value;

        var chk=document.getElementById('chk_city').checked;

        var pars="&fname="+fname+"&lname="+lname+"&email="+email+"&skype="+skype+"&password_reg="+password_reg+"&rpassword="+rpassword+"&country="+country_id+"&timezone="+time_zone_id+"&registerAccept="+registerAccept+"&city_id="+city_id+"&city_text="+city_text+"&chk="+chk+"&country_index="+country.selectedIndex+"&city_index="+city.selectedIndex+"&tmz_index="+time_zone.selectedIndex+"&registration="+registration+"&archivo="+archivo+"&next_step="+ns+"&password_old="+password_old+"&oldPass="+oldPass+"&salt="+salt+"&stepn="+stepn;

    }
    var ac = AjaxCaller.getInstance();

    new Ajax.Updater('step', '/register_school/Xvalidation_1',	{
        method: 'post',
        parameters: pars,
        onComplete: Xredirect
    });

}

function TutorSubmit(step, update){

	if (step==2) {
		var idx = document.getElementById('ln1').selectedIndex;
		if(idx!=0){
			alert('Please save first!');
		}
		else{
			step2(update);
		}
		

		return;
	}
	if (step==20) {
		
		var form=document.getElementById('formulario').value;

		if (form=='2_1'){step2_0();return;}
		if (form=='2_2'){step2(4);return;}
			
	}
	if (step==1) {step1(update);return;}
	
	if (step==3) {	
		if (update==10)
			location.href='/home';
		else
			step3(update);
		
		}

	if (step==4) {
		var form=document.getElementById('formulario').value;
	
		if (form=='4_1'){step4(update,0);return;}

		if (form=='4_2'){
			step4_2(update);return;
		}
		
		if (form=='4_3'){
			step4_3(update);return;

		}
	}
	
	
	if (step==42) {step4_2(update);return;}
	
	if (step==5){

		var next_stepStr=document.getElementById('next_step').value;

		var txt=next_stepStr.split(":");
		if (txt[0]=="url"){
			location.href=txt[1];return;
		}
	}
}
function SchoolSubmit(update){

    step1_school(update);
    return;

}
function save_profile(){
		 if (document.getElementById('iframeUpload').contentDocument){ 
			 rv = document.getElementById('iframeUpload').contentDocument; 
		 } else { 
			 // IE 
			 rv = document.frames['iframeUpload'].document; 
		 } 

		//var ns=document.getElementById('next_step').value;
		//var stepn=document.getElementById('stepn').value;
		
		//var oldPass=document.getElementById('oldPass').value;
		//var salt=document.getElementById('salt').value;
		var fname=document.getElementById('fname').value;
		var lname=document.getElementById('lname').value;
		var email=document.getElementById('email').value;
		var skype=document.getElementById('skype').value;
		var password_old=document.getElementById('password_old').value;
		var password_reg=document.getElementById('password_reg').value;
		var rpassword=document.getElementById('rpassword').value;
		var country=document.getElementById('country');
		var country_id=country[country.selectedIndex].value;
		var city_text=document.getElementById('ciudad_reg').value;
		//var registration=document.getElementById('registration').value;
		var archivo=rv.getElementById('archivo').value;
		if (country_id==0){
			var pars="&fname="+fname+"&lname="+lname+"&email="+email+"&skype="+skype+"&password_reg="+password_reg+"&rpassword="+rpassword+"&country="+country_id+"&city_text="+city_text+"&country_index="+country.selectedIndex+"&archivo="+archivo+"&password_old="+password_old;	
		}
		else{
			var time_zone=document.getElementById('timezone');
			var time_zone_id=time_zone[time_zone.selectedIndex].value;
			var city=document.getElementById('cities_list');
			var city_id=city[city.selectedIndex].value;
			var chk=document.getElementById('chk_city').checked;
			var pars="&fname="+fname+"&lname="+lname+"&email="+email+"&skype="+skype+"&password_reg="+password_reg+"&rpassword="+rpassword+"&country="+country_id+"&timezone="+time_zone_id+"&city_id="+city_id+"&city_text="+city_text+"&chk="+chk+"&country_index="+country.selectedIndex+"&city_index="+city.selectedIndex+"&tmz_index="+time_zone.selectedIndex+"&archivo="+archivo+"&password_old="+password_old;				
		}	
		var ac = AjaxCaller.getInstance();
			new Ajax.Updater('step', '/members/save_personal',	{
						method: 'post',
						parameters: pars
					});

}

function updateCity(sel){
	

	var	actionName='/register_teacher/XgetCityList';
	
	var ciudad=document.getElementById('citylist');
	ciudad.style.display = "inline";
	var chk=document.getElementById('chk_city').checked;
	var pars="&pais="+sel.value+"&chk_city="+chk;
	
	new Ajax.Updater('citylist', actionName,	{
					method: 'post',
					parameters: pars
				});
	

	
	var chk=document.getElementById('chk');
	chk.style.display = "inline";
}

function chkCity(){
	var cityCheckBox=document.getElementById('chk_city');
	var div=document.getElementById('input_ciudad');
	var div_combo=document.getElementById('cities_list');
	//alert(cityCheckBox.checked)
	if (cityCheckBox.checked){
		div.style.display = "inline";
		div_combo.disabled = "true";
	}
	else {
		div_combo.disabled = 0;
		div.style.display = "none";	
	}
}

var upload_number = 2;
function addFileInput() {
 	var d = document.createElement("div");
 	var file = document.createElement("input");
 	file.setAttribute("type", "file");
 	file.setAttribute("name", "attachment"+upload_number);
 	d.appendChild(file);
 	document.getElementById("moreUploads").appendChild(d);
 	upload_number++;
}

function tagClasses(tagID){
	var ac = AjaxCaller.getInstance();
	ac.pars="&tag_id="+tagID;

	var	actionName='/tagsadmin/tagTag';

	
	if(ac){
		ac.actionName = actionName;
		ac.elementID = 'tag_'+tagID;
		ac.getUpdate();
	}


}	

function showLanguages(lang){		
	if (lang=='-1') {
		TutorSubmit(2,3);

		return;
		}

	var nuevo=document.getElementById('nuevo').value;	
	var stp=document.getElementById('step_lang').value;
	var stepn=document.getElementById('stepn').value;
	
	
	if(stp==22){
		document.getElementById('next_lang').value=lang;
		step2(2);
	}

	if(stp==21){
		var next_step=document.getElementById('next_step').value;
		var pars="&lang_id="+lang+"&next_step="+next_step+"&nuevo="+nuevo+"&stepn="+stepn;
		new Ajax.Updater('step2', '/register_teacher/step22',	{
					method: 'post',
					parameters: pars
				});	

	}

}




function contactUsForm(){
	
	var email=document.getElementById('email').value;		
	var name=document.getElementById('name').value;
	var content=document.getElementById('question_content').value;

	pars="&email="+email+"&name="+name+"&content="+content;
		
	new Ajax.Updater('contact_us_div', '/home/XValidationContactUs',	{
					method: 'post',
					parameters: pars,
					onComplete: Xredirect
				});	


}

function showLanguagesDescription(lang){


	var next_step=document.getElementById('next_step').value;	
	var nuevo=document.getElementById('nuevo').value;	
	

	var pars="&lang="+lang+"&next_step="+next_step+"&nuevo="+nuevo;


	new Ajax.Updater('step', '/register_teacher/xstep3',	{
			  	method: 'post',
				parameters: pars,
				onComplete: Xredirect
			});
	
}



function borrarLang(lang){
	if(confirm('Are your sure you want to delete this language?')){
		nuevo=document.getElementById('nuevo').value;
		stepn=document.getElementById('stepn').value;
		next_step=document.getElementById('next_step').value;
		pars="&lang="+lang+"&stepn="+stepn+"&nuevo="+nuevo+"&next_step="+next_step;
		
		new Ajax.Updater('step2', '/register_teacher/XborrarLangs',	{
						method: 'post',
						parameters: pars,
						onComplete: Xredirect
					});	
	}
	
}

 function addAcademyLang(){
    
        id=document.getElementById('id').value;
        lang=document.getElementById('lang').value;
        pars="&lang="+lang+"&id="+id;
        new Ajax.Updater('lang', '/academies/addLang', {
            method:'post',
            parameters: pars,
            onComplete: location.reload(true)
        });
 }
function submitPayForm(form_name){

  var j=0;
  for(var i=0; i < document.form_other.length; i++){
        if(eval('document.form_other.check'+i+'.checked==true')){
            j++;
        }
    }
    if (j==0){
        alert("Please, select at least one language");
    }else if(j>3){
        alert("Please, select no more than 3 languages");
    }else{
        if(form_name=='form_other'){
            eval('document.'+form_name+'.submit();');
        }
        else{
            ACA($('form_other'),'formResponse','/academies/highlightsHome/'+form_name,"paypalSubmit('"+form_name+"')");
        }
    }
}
 function paypalSubmit(form_name){
		alert('Redirecting to payment gateway..');
		//alert('document.'+form_name+'.submit();');
		eval('document.'+form_name+'.submit();')
 }
 function saveAcademyCampaing(){
     var j=0;
  for(var i=0; i < document.form_other.length; i++){
        if(eval('document.form_other.check'+i+'.checked==true')){
            j++;
        }
    }
    if (j==0){
        alert("Please, select at least one language");
    }else if(j>3){
        alert("Please, select no more than 3 languages");
    }else{
	 ACA($('form_other'),'paymentForm','/academies/saveCampaing',"saveCampCallBack()");
	 //ACS($('form_other'),'/academies/saveCampaing');
 }
 }
 function saveCampCallBack(){
	 document.location.reload(true);
 }
 function cancelCampaign(){
	 ACA($('form_other'),'paymentForm','/academies/cancelCampaign',"cancelCampCallBack()");
	 //ACS($('form_other'),'/academies/saveCampaing');
 }
  function mailCampaign(){
	 ACA($('form_other'),'paymentForm','/academies/suspendMailCampaign',"mailCampCallBack()");
	 //ACS($('form_other'),'/academies/saveCampaing');
 }
 function cancelCampCallBack(){
	 document.location.reload(true);
 }
  function mailCampCallBack(){
	 document.location.reload(true);
 }
/*	SWFObject v2.0 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var Z="undefined",P="object",B="Shockwave Flash",h="ShockwaveFlash.ShockwaveFlash",W="application/x-shockwave-flash",K="SWFObjectExprInst",G=window,g=document,N=navigator,f=[],H=[],Q=null,L=null,T=null,S=false,C=false;var a=function(){var l=typeof g.getElementById!=Z&&typeof g.getElementsByTagName!=Z&&typeof g.createElement!=Z&&typeof g.appendChild!=Z&&typeof g.replaceChild!=Z&&typeof g.removeChild!=Z&&typeof g.cloneNode!=Z,t=[0,0,0],n=null;if(typeof N.plugins!=Z&&typeof N.plugins[B]==P){n=N.plugins[B].description;if(n){n=n.replace(/^.*\s+(\S+\s+\S+$)/,"$1");t[0]=parseInt(n.replace(/^(.*)\..*$/,"$1"),10);t[1]=parseInt(n.replace(/^.*\.(.*)\s.*$/,"$1"),10);t[2]=/r/.test(n)?parseInt(n.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof G.ActiveXObject!=Z){var o=null,s=false;try{o=new ActiveXObject(h+".7")}catch(k){try{o=new ActiveXObject(h+".6");t=[6,0,21];o.AllowScriptAccess="always"}catch(k){if(t[0]==6){s=true}}if(!s){try{o=new ActiveXObject(h)}catch(k){}}}if(!s&&o){try{n=o.GetVariable("$version");if(n){n=n.split(" ")[1].split(",");t=[parseInt(n[0],10),parseInt(n[1],10),parseInt(n[2],10)]}}catch(k){}}}}var v=N.userAgent.toLowerCase(),j=N.platform.toLowerCase(),r=/webkit/.test(v)?parseFloat(v.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,i=false,q=j?/win/.test(j):/win/.test(v),m=j?/mac/.test(j):/mac/.test(v);/*@cc_on i=true;@if(@_win32)q=true;@elif(@_mac)m=true;@end@*/return{w3cdom:l,pv:t,webkit:r,ie:i,win:q,mac:m}}();var e=function(){if(!a.w3cdom){return }J(I);if(a.ie&&a.win){try{g.write("<script id=__ie_ondomload defer=true src=//:><\/script>");var i=c("__ie_ondomload");if(i){i.onreadystatechange=function(){if(this.readyState=="complete"){this.parentNode.removeChild(this);V()}}}}catch(j){}}if(a.webkit&&typeof g.readyState!=Z){Q=setInterval(function(){if(/loaded|complete/.test(g.readyState)){V()}},10)}if(typeof g.addEventListener!=Z){g.addEventListener("DOMContentLoaded",V,null)}M(V)}();function V(){if(S){return }if(a.ie&&a.win){var m=Y("span");try{var l=g.getElementsByTagName("body")[0].appendChild(m);l.parentNode.removeChild(l)}catch(n){return }}S=true;if(Q){clearInterval(Q);Q=null}var j=f.length;for(var k=0;k<j;k++){f[k]()}}function J(i){if(S){i()}else{f[f.length]=i}}function M(j){if(typeof G.addEventListener!=Z){G.addEventListener("load",j,false)}else{if(typeof g.addEventListener!=Z){g.addEventListener("load",j,false)}else{if(typeof G.attachEvent!=Z){G.attachEvent("onload",j)}else{if(typeof G.onload=="function"){var i=G.onload;G.onload=function(){i();j()}}else{G.onload=j}}}}}function I(){var l=H.length;for(var j=0;j<l;j++){var m=H[j].id;if(a.pv[0]>0){var k=c(m);if(k){H[j].width=k.getAttribute("width")?k.getAttribute("width"):"0";H[j].height=k.getAttribute("height")?k.getAttribute("height"):"0";if(O(H[j].swfVersion)){if(a.webkit&&a.webkit<312){U(k)}X(m,true)}else{if(H[j].expressInstall&&!C&&O("6.0.65")&&(a.win||a.mac)){D(H[j])}else{d(k)}}}}else{X(m,true)}}}function U(m){var k=m.getElementsByTagName(P)[0];if(k){var p=Y("embed"),r=k.attributes;if(r){var o=r.length;for(var n=0;n<o;n++){if(r[n].nodeName.toLowerCase()=="data"){p.setAttribute("src",r[n].nodeValue)}else{p.setAttribute(r[n].nodeName,r[n].nodeValue)}}}var q=k.childNodes;if(q){var s=q.length;for(var l=0;l<s;l++){if(q[l].nodeType==1&&q[l].nodeName.toLowerCase()=="param"){p.setAttribute(q[l].getAttribute("name"),q[l].getAttribute("value"))}}}m.parentNode.replaceChild(p,m)}}function F(i){if(a.ie&&a.win&&O("8.0.0")){G.attachEvent("onunload",function(){var k=c(i);if(k){for(var j in k){if(typeof k[j]=="function"){k[j]=function(){}}}k.parentNode.removeChild(k)}})}}function D(j){C=true;var o=c(j.id);if(o){if(j.altContentId){var l=c(j.altContentId);if(l){L=l;T=j.altContentId}}else{L=b(o)}if(!(/%$/.test(j.width))&&parseInt(j.width,10)<310){j.width="310"}if(!(/%$/.test(j.height))&&parseInt(j.height,10)<137){j.height="137"}g.title=g.title.slice(0,47)+" - Flash Player Installation";var n=a.ie&&a.win?"ActiveX":"PlugIn",k=g.title,m="MMredirectURL="+G.location+"&MMplayerType="+n+"&MMdoctitle="+k,p=j.id;if(a.ie&&a.win&&o.readyState!=4){var i=Y("div");p+="SWFObjectNew";i.setAttribute("id",p);o.parentNode.insertBefore(i,o);o.style.display="none";G.attachEvent("onload",function(){o.parentNode.removeChild(o)})}R({data:j.expressInstall,id:K,width:j.width,height:j.height},{flashvars:m},p)}}function d(j){if(a.ie&&a.win&&j.readyState!=4){var i=Y("div");j.parentNode.insertBefore(i,j);i.parentNode.replaceChild(b(j),i);j.style.display="none";G.attachEvent("onload",function(){j.parentNode.removeChild(j)})}else{j.parentNode.replaceChild(b(j),j)}}function b(n){var m=Y("div");if(a.win&&a.ie){m.innerHTML=n.innerHTML}else{var k=n.getElementsByTagName(P)[0];if(k){var o=k.childNodes;if(o){var j=o.length;for(var l=0;l<j;l++){if(!(o[l].nodeType==1&&o[l].nodeName.toLowerCase()=="param")&&!(o[l].nodeType==8)){m.appendChild(o[l].cloneNode(true))}}}}}return m}function R(AE,AC,q){var p,t=c(q);if(typeof AE.id==Z){AE.id=q}if(a.ie&&a.win){var AD="";for(var z in AE){if(AE[z]!=Object.prototype[z]){if(z=="data"){AC.movie=AE[z]}else{if(z.toLowerCase()=="styleclass"){AD+=' class="'+AE[z]+'"'}else{if(z!="classid"){AD+=" "+z+'="'+AE[z]+'"'}}}}}var AB="";for(var y in AC){if(AC[y]!=Object.prototype[y]){AB+='<param name="'+y+'" value="'+AC[y]+'" />'}}t.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AD+">"+AB+"</object>";F(AE.id);p=c(AE.id)}else{if(a.webkit&&a.webkit<312){var AA=Y("embed");AA.setAttribute("type",W);for(var x in AE){if(AE[x]!=Object.prototype[x]){if(x=="data"){AA.setAttribute("src",AE[x])}else{if(x.toLowerCase()=="styleclass"){AA.setAttribute("class",AE[x])}else{if(x!="classid"){AA.setAttribute(x,AE[x])}}}}}for(var w in AC){if(AC[w]!=Object.prototype[w]){if(w!="movie"){AA.setAttribute(w,AC[w])}}}t.parentNode.replaceChild(AA,t);p=AA}else{var s=Y(P);s.setAttribute("type",W);for(var v in AE){if(AE[v]!=Object.prototype[v]){if(v.toLowerCase()=="styleclass"){s.setAttribute("class",AE[v])}else{if(v!="classid"){s.setAttribute(v,AE[v])}}}}for(var u in AC){if(AC[u]!=Object.prototype[u]&&u!="movie"){E(s,u,AC[u])}}t.parentNode.replaceChild(s,t);p=s}}return p}function E(k,i,j){var l=Y("param");l.setAttribute("name",i);l.setAttribute("value",j);k.appendChild(l)}function c(i){return g.getElementById(i)}function Y(i){return g.createElement(i)}function O(k){var j=a.pv,i=k.split(".");i[0]=parseInt(i[0],10);i[1]=parseInt(i[1],10);i[2]=parseInt(i[2],10);return(j[0]>i[0]||(j[0]==i[0]&&j[1]>i[1])||(j[0]==i[0]&&j[1]==i[1]&&j[2]>=i[2]))?true:false}function A(m,j){if(a.ie&&a.mac){return }var l=g.getElementsByTagName("head")[0],k=Y("style");k.setAttribute("type","text/css");k.setAttribute("media","screen");if(!(a.ie&&a.win)&&typeof g.createTextNode!=Z){k.appendChild(g.createTextNode(m+" {"+j+"}"))}l.appendChild(k);if(a.ie&&a.win&&typeof g.styleSheets!=Z&&g.styleSheets.length>0){var i=g.styleSheets[g.styleSheets.length-1];if(typeof i.addRule==P){i.addRule(m,j)}}}function X(k,i){var j=i?"visible":"hidden";if(S){c(k).style.visibility=j}else{A("#"+k,"visibility:"+j)}}return{registerObject:function(l,i,k){if(!a.w3cdom||!l||!i){return }var j={};j.id=l;j.swfVersion=i;j.expressInstall=k?k:false;H[H.length]=j;X(l,false)},getObjectById:function(l){var i=null;if(a.w3cdom&&S){var j=c(l);if(j){var k=j.getElementsByTagName(P)[0];if(!k||(k&&typeof j.SetVariable!=Z)){i=j}else{if(typeof k.SetVariable!=Z){i=k}}}}return i},embedSWF:function(n,u,r,t,j,m,k,p,s){if(!a.w3cdom||!n||!u||!r||!t||!j){return }r+="";t+="";if(O(j)){X(u,false);var q=(typeof s==P)?s:{};q.data=n;q.width=r;q.height=t;var o=(typeof p==P)?p:{};if(typeof k==P){for(var l in k){if(k[l]!=Object.prototype[l]){if(typeof o.flashvars!=Z){o.flashvars+="&"+l+"="+k[l]}else{o.flashvars=l+"="+k[l]}}}}J(function(){R(q,o,u);if(q.id==u){X(u,true)}})}else{if(m&&!C&&O("6.0.65")&&(a.win||a.mac)){X(u,false);J(function(){var i={};i.id=i.altContentId=u;i.width=r;i.height=t;i.expressInstall=m;D(i)})}}},getFlashPlayerVersion:function(){return{major:a.pv[0],minor:a.pv[1],release:a.pv[2]}},hasFlashPlayerVersion:O,createSWF:function(k,j,i){if(a.w3cdom&&S){return R(k,j,i)}else{return undefined}},createCSS:function(j,i){if(a.w3cdom){A(j,i)}},addDomLoadEvent:J,addLoadEvent:M,getQueryParamValue:function(m){var l=g.location.search||g.location.hash;if(m==null){return l}if(l){var k=l.substring(1).split("&");for(var j=0;j<k.length;j++){if(k[j].substring(0,k[j].indexOf("="))==m){return k[j].substring((k[j].indexOf("=")+1))}}}return""},expressInstallCallback:function(){if(C&&L){var i=c(K);if(i){i.parentNode.replaceChild(L,i);if(T){X(T,true);if(a.ie&&a.win){L.style.display="block"}}L=null;T=null;C=false}}}}}();/*                                                                                                                                                                              
	ClearBox JS by pyro
	
	script home:		http://www.clearbox.hu
	developer's e-mail:	pyrex(at)chello(dot)hu
	developer's msn:	pyro(at)radiomax(dot)hu
	support forum:		http://www.sg.hu/listazas.php3?id=1172325655

	LICESE:

	Using of the script is free for any non-commercial webpages without any commercial activities,
	without advertising or selling anything. If you want to use it on a commercial page, please contact the developer.
	The source code of the script (except of user variable settings) can be changed only with the developer's written permission.

*/


//
// 	User variable settings:
//

var

	CB_HideColor='#000', 
	CB_WinPadd=10,
	CB_RoundPix=12,
	CB_Animation='double',
	CB_ImgBorder=0,
	CB_ImgBorderColor='#000',
	CB_Padd=4,
	CB_ShowImgURL='on',
	CB_ImgNum='on',
	CB_ImgNumBracket='()',
	CB_SlShowTime=3,
	CB_TextH=40,
	CB_Font='Verdana',
	CB_FontSize=12,
	CB_FontColor='#777',
	CB_FontWeight='normal',
	CB_Font2='arial',
	CB_FontSize2=11,
	CB_FontColor2='#999',
	CB_FontWeight2='normal',
	CB_PicDir='/pic',
	CB_BodyMarginLeft=0,
	CB_BodyMarginRight=0,
	CB_BodyMarginTop=0,
	CB_BodyMarginBottom=0,
	CB_Preload='on',
	CB_TextNav='on',
	CB_NavTextPrv='previous',
	CB_NavTextNxt='next',
	CB_NavTextFull='original size and download',
	CB_NavTextDL='download',
	CB_NavTextClose='close',
	CB_NavTextStart='start SlideShow',
	CB_NavTextStop='stop SlideShow',
	CB_NavTextImgPrv='on',
	CB_NavTextImgNxt='on',
	CB_NavTextImgFull='on',
	CB_NavTextImgDL='on',
	CB_PictureStart='start.png',
	CB_PicturePause='pause.png',
	CB_PictureClose='close.png',
	CB_PictureLoading='loading.gif',
	CB_PictureNext='next.png',
	CB_PicturePrev='prev.png',

//
//	NEW in ClearBox since 2.5:
//

	CB_HideOpacitySpeed=400,
	CB_ImgOpacitySpeed=450,
	CB_TextOpacitySpeed=350,
	CB_HideOpacity=.85,
	CB_AnimSpeed=600,
	CB_ImgTextFade='on',
	CB_FlashHide='off',
	CB_SelectsHide='on',
	CB_NoThumbnails='off', 
	CB_SimpleDesign='off',
	CB_ImgMinWidth=200,
	CB_ImgMinHeight=160,
	CB_CloseOnH='on',
	CB_ShowGalName='on',
	CB_AllowedToRun='on',
	CB_AllowExtFunct='off',
	CB_FullSize='on'

;

//
//	Do not change the following code!
//

eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('2 $6(){d(4.j==1)3 7$6(4[0]);5 b=[];$c(4).h(2(a){b.x(7$6(a))});3 b;2 7$6(a){d(s a==\'r\')a=p.n(a);3 a}};m.l.k=2(a){5 b=8;3 2(){3 b.e(a,4)}};i=2(a,b){o(9 q b)a[9]=b[9];3 a};d(!g.f)5 f=u t();5 v={w:2(){3 2(){8.y.e(8,4)}}};',35,35,'||function|return|arguments|var|CB|get|this|kifejezes||||if|apply|CBEE|window|each|Kiterjeszt|length|lancol|prototype|Function|getElementById|for|document|in|string|typeof|Object|new|Osztaly|letrehoz|push|azonnallefut'.split('|'),0,{}));eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('s i=t 1i();i.F=3(){};i.F.1z={1r:3(a){1.7=14({z:3(){},y:3(){},Y:i.1v.1p,n:1h,N:\'k\',S:18,E:C},a||{})},B:3(){s a=t A().T();4(a<1.m+1.7.n){4(1.8.f(\'d\')==\'1t\'&&1o==\'1n\'){1.9=1.j;1.g();6}4((1.8.f(\'d\')==\'u\'||1.8.f(\'d\')==\'1g\'||1.8.f(\'d\')==\'1e\')&&1b==\'1a\'){1.g();6}1.H=a-1.m;1.V()}r{D(1.7.y.w(1,1.8),10);1.g();1.9=1.j}1.O()},V:3(){1.9=1.P(1.Q,1.j)},P:3(a,b){s c=b-a;6 1.7.Y(1.H,a,c,1.7.n)},g:3(){13(1.l);1.l=12;6 1},x:3(a,b){4(!1.7.S)1.g();4(1.l)6;D(1.7.z.w(1,1.8),10);1.Q=a;1.j=b;1.m=t A().T();1.l=11(1.B.w(1),Z.1y(1x/1.7.E));6 1},1w:3(a,b){6 1.x(a,b)},X:3(a){1.9=a;1.O();6 1},1u:3(){6 1.X(0)},1s:3(e,p,v){4(1.8.f(\'d\')==\'u\'&&p==\'R\'){I=M(1l-(1k+1.9+1j+(2*(L+o+K)))/2);J.5.1f=(I-(1m/2))+\'k\';1d.5.R=1.9+(2*o)+\'k\'}4(1.8.f(\'d\')==\'u\'&&p==\'1c\'){U=M(1q-(1.9+(2*(L+o+K)))/2);J.5.19=U+\'k\'}4(p==\'q\'){4(v==0&&e.5.h!="W")e.5.h="W";r 4(e.5.h!="G")e.5.h="G";4(17.16)e.5.15="1A(q="+v*C+")";e.5.q=v}r e.5[p]=v+1.7.N}};',62,99,'|this||function|if|style|return|params|CBe|most||||id||getAttribute|clearTimer|visibility|CB_effektek|hova|px|timer|time|idotartam|CB_ImgBorder||opacity|else|var|new|CB_Image||lancol|_start|halefutott|haelindul|Date|effekt_lepes|100|setTimeout|fps|alap|visible|cTime|CB_MarginT|CB_Win|CB_Padd|CB_RoundPix|parseInt|egyseg|noveles|compute|honnan|height|varakozas|getTime|CB_MarginL|setNow|hidden|set|effekt|Math||setInterval|null|clearInterval|Kiterjeszt|filter|ActiveXObject|window|true|marginLeft|on|CB_Break|width|CB_ImgCont|CB_iFrame|marginTop|CB_TL|500|Object|CB_TextH|CB_ieRPBug|DocScrY|FF_ScrollbarBug|off|CB_SSTimer|evlassitva|DocScrX|parameterek|setStyle|CB_SlideShowBar|elrejt|Effektek|sajat|1000|round|prototype|alpha'.split('|'),0,{}));eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('7.z=r.j();7.z.i=f(w 7.n(),{m:5(a,b){3.4=$u(a);3.g(b);3.4.E.D=\'B\'},l:5(){k(3.4.A>0)6 3.8(3.4.A,0);h 6 3.8(0,3.4.x)},q:5(){6 3.e(3.4.x)},s:5(){3.v(3.4,\'M\',3.9)}});7.F=r.j();7.F.i=f(w 7.n(),{m:5(a,b){3.4=$u(a);3.g(b);3.4.E.D=\'B\';3.p=3.4.o},l:5(){k(3.4.o>0)6 3.8(3.4.o,0);h 6 3.8(0,3.p)},q:5(){6 3.e(3.p)},s:5(){3.v(3.4,\'L\',3.9)}});7.C=r.j();7.C.i=f(w 7.n(),{m:5(a,b){3.4=$u(a);3.g(b);3.9=1},l:5(){k(3.9>0)6 3.8(1,0);h 6 3.8(0,1)},q:5(){6 3.e(1)},s:5(){3.v(3.4,\'K\',3.9)}});7.J={I:5(t,b,c,d){6 c*t/d+b},H:5(t,b,c,d){6-c/2*(y.G(y.N*t/d)-1)+b}};',50,50,'|||this|CBe|function|return|CB_effektek|sajat|most|||||set|Kiterjeszt|parameterek|else|prototype|letrehoz|if|toggle|azonnallefut|alap|offsetWidth|iniWidth|show|Osztaly|noveles||CB|setStyle|new|scrollHeight|Math|magassag|offsetHeight|hidden|Atlatszosag|overflow|style|szelesseg|cos|evlassitva|egyenletes|Effektek|opacity|width|height|PI'.split('|'),0,{}));eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('F 7E=\'2.6\',3i=1;2a=-50,1R=5,3G=\'G\';l(1B==\'G\'){1B=\'46\';29=1}p 6O(a){F b;l(!a)F a=Q.4K;F b=(a.6h)?a.6h:a.7B;F c=7u.7o(b);l(2d==\'o\'){l(x>1&&(c=="%"||b==37||b==52)){l(1l==\'o\'){1y()}1n(x-1);v M}l(x<u.C-1&&(c=="\'"||b==39||b==54)){l(1l==\'o\'){1y()}1n(x+1);v M}l((c==" "||b==32)&&2P==0){l(u.C<3){v M}l(2g==\'2M\'){4A();v M}t{58();v M}}l(c==""||b==27){42();v M}l(b==13){v M}}t{l(2P==1&&(c==" "||b==32||b==13)){v M}}}p 4A(){1O.k.y=\'K\';1W.k.y=\'16\';2g=\'4L\';1M.k.y=\'16\';5e()}p 58(){1W.k.y=\'K\';1O.k.y=\'16\';5g()}3u=P(3u);l(3u<0){3u=0}3r=P(3r);l(3r<0){3r=0}3q=P(3q);l(3q<0){3q=0}3p=P(3p);l(3p<0){3p=0}l(2V<0||2V>1){2V=0.75}2n=P(2n);l(2n<1||2n>57){2n=56}2k=P(2k);l(2k<1||2k>57){2k=6R}2R=P(2R);l(2R<1||2R>57){2R=83}1F=P(1F);l(1F<0){1F=1}l(1B!=\'G\'&&1B!=\'6I\'&&1B!=\'46\'&&1B!=\'3Q\'){1B=\'46\'}J=P(J);l(J<0){J=1}1o=P(1o);l(1o<0){1o=2}l(3h!=\'o\'&&3h!=\'G\'){3h=\'G\'}1R=P(1R);l(1R<0){1R=0}V=P(V);l(V<0){V=12}1j=P(1j);l(1j<25){1j=25}l(3d==\'o\'){1j=0;1R=0}2N=P(2N);l(2N<6){2N=12}3c=P(3c);l(3c<6){3c=11}l(3b!=\'o\'&&3b!=\'G\'){3b=\'o\'}2K=P(2K);l(2K<1){2K=5}2K*=6j;l(3G!=\'o\'&&3G!=\'G\'){3G=\'G\'}l(38!=\'o\'&&38!=\'G\'){38=\'o\'}l(2e!=\'o\'&&2e!=\'G\'){2e=\'o\'}l(2I!=\'o\'&&2I!=\'G\'){2I=\'G\'}l(2Q!=\'o\'&&2Q!=\'G\'){2Q=\'o\'}l(3O!=\'o\'&&3O!=\'G\'){3O=\'G\'}l(3d!=\'o\'&&3d!=\'G\'){3d=\'G\'}l(3F!=\'o\'&&3F!=\'G\'){3F=\'o\'}l(3j!=\'o\'&&3j!=\'G\'){3j=\'o\'}l(2x!=\'o\'&&2x!=\'G\'){2x=\'o\'}l(34!=\'o\'&&34!=\'G\'){34=\'G\'}l(3Y!=\'o\'&&3Y!=\'G\'){3Y=\'o\'}l(45!=\'o\'&&45!=\'G\'){45=\'o\'}l(48!=\'o\'&&48!=\'G\'){48=\'o\'}l(3v!=\'o\'&&3v!=\'G\'){3v=\'o\'}l(3w!=\'o\'&&3w!=\'G\'){3w=\'o\'}29=P(29);l(29<1){29=6R}2E=P(2E);l(2E<50){2E=50}2F=P(2F);l(2F<50){2F=50}F 3A,2G=3B,5V=2a,3C,7j,3f,3I=\'\',7g=0,2f,7c,2P,2q,2X,4T=0,4Z=\'\',2d,3Z=3u+3r,47=3q+3p,44,N,43=0,1l,2g=\'2M\',20,5f,5d,71,A,H,41,2w,1N,D,1S,1U,2h,2m,x,u,3X,2T,3V,3n,3m,2y,2z;O+=\'/\';F 4X=m.82?3B:M;l(!4X)m.81(80.7Z);l(3Y==\'o\'){F 1H=4R;4R=\'<1w 1u="3P" B="\'+O+\'6E.1b" 1f="\'+1H+\'" 1D="\'+1H+\'" />\'}l(45==\'o\'){F 1H=4P;4P=\'<1w 1u="3P" B="\'+O+\'6w.1b" 1f="\'+1H+\'" 1D="\'+1H+\'" />\'}l(48==\'o\'){F 1H=3N;3N=\'<1w 1u="3P" B="\'+O+\'6v.1b" 1f="\'+1H+\'" 1D="\'+1H+\'" />\'}l(3v==\'o\'){F 1H=4N;4N=\'<1w 1u="3P" B="\'+O+\'6t.1b" 1f="\'+1H+\'" 1D="\'+1H+\'" />\'}p 6r(a,b){l(3g Q.2O!=\'3e\'){Q.2O(a,b,M)}t l(3g m.2O!=\'3e\'){m.2O(a,b,M)}t l(3g Q.6o!=\'3e\'){Q.6o("o"+a,b)}}6r(\'7V\',6m);p 6m(){m.7Q=6O;m.X.k.7O="7M";F a=\'<I 1u="7I" k="E: \'+V+\'q; R: \'+V+\'q;"></I>\';l(14.17.Z("2H")!=-1){3I=\'<1w z="4O" 1f="" B="\'+O+\'2s.1b" />\'}t{3I=\'<I z="4O"></I>\'}l(!m.r(\'4w\')&&3i!=0){F b=m.2b("X").7z(0);F c=m.4Q("I");c.68(\'z\',\'67\');b.1v(c);F d=m.4Q("I");d.68(\'z\',\'4w\');b.1v(d)}m.r(\'4w\').T=\'<I z="64"></I><I z="63"></I><60 7w="0" 7v="0" z="5Y"><2D z="3n"><1c z="4a">\'+a+\'</1c><1c z="4n"></1c><1c z="4d">\'+a+\'</1c></2D><2D z="7s"><1c z="2y"></1c><1c z="71" 7r="33" 7p="2c"><I z="5M"><I z="5L"><1w z="4j" 1f="\'+5K+\'" 1D="\'+5K+\'" B="\'+O+5J+\'" /><I z="5R"></I>\'+3I+\'<I z="4r"><I z="5H"></I></I><1w z="6c" 1f="7i" B="\'+O+5F+\'" /><1w z="5E" 1f="" B="\'+O+\'2s.1b" /><I z="3H"><1w z="4g" 1f="" B="\'+O+5B+\'" /><1w z="4f" 1f="" B="\'+O+6k+\'" /><I z="5y"></I><1w z="4e" 1f="\'+5x+\'" 1D="\'+5x+\'" B="\'+O+5w+\'" /><1w z="4c" 1f="\'+5v+\'" 1D="\'+5v+\'" B="\'+O+5u+\'" /><a z="5t"></a><a z="5r"></a></I></I><I z="5p"><I z="6P"></I><I z="5n"></I><I z="6Y"></I></I></I></1c><1c z="2z"></1c></2D><2D z="3m"><1c z="5l">\'+a+\'</1c><1c z="5j"></1c><1c z="5i">\'+a+\'</1c></2D></60>\';l(14.17.Z("2H 6")!=-1&&V==0){4Z=1}l(14.17.Z("2H")!=-1&&V<2){4T=6}m.r(\'5M\').k.8d=1o+\'q\';2Y=m.r(\'4O\');1p=m.r(\'5y\');1p.k.73=\'#8c\';1p.k.1g=0.75;1p.k.1d=\'2o(1g=75)\';2w=m.r(\'5Y\');2C=m.r(\'4r\');3t=m.r(\'5H\');l(3O==\'o\'){2Y.k.y=\'K\'}1a=m.r(\'64\');1a.k.73=8b;1a.k.1g=0;1a.k.1d=\'2o(1g=0)\';5c=U 1I.2B(1a,{1G:2n,1V:p(){5b(\'3o\')}});5c.2W();5a=U 1I.2B(1a,{1G:2n,1V:p(){1n()}});5a.2W();59=U 1I.2B(1a,{1G:2n,1V:p(){1a.k.E=\'1k\';1a.k.R=\'1k\';20.k.w=\'S\'}});59.2W();D=m.r(\'5E\');20=m.r(\'6c\');2U=m.r(\'5L\');D.k.8a=J+\'q 89 \'+88;2A=m.r(\'4j\');2A.1r=p(){42()};1O=m.r(\'4c\');1W=m.r(\'4e\');1O.1r=p(){4A();v M};1W.1r=p(){58();v M};1M=m.r(\'63\');1M.k.1g=0.5;1M.k.1d=\'2o(1g=50)\';2j=m.r(\'4g\');2j.28=p(){2j.k.w=\'19\'};2j.1r=p(){l(1l==\'o\'){1y()}1n(x-1);v M};2l=m.r(\'4f\');2l.28=p(){2l.k.w=\'19\'};2l.1r=p(){l(1l==\'o\'){1y()}1n(x+1);v M};1S=m.r(\'5t\');1S.k.1T=\'6W(\'+O+\'2s.1b)\';1S.28=p(){2j.k.w=\'19\'};1S.6V=p(){2j.k.w=\'S\'};1U=m.r(\'5r\');1U.k.1T=\'6W(\'+O+\'2s.1b)\';1U.28=p(){2l.k.w=\'19\'};1U.6V=p(){2l.k.w=\'S\'};1t=m.r(\'6Y\');1N=m.r(\'5p\');1N.k.R=(1j-1R)+\'q\';1t.k.33=\'-\'+(1j-1R)+\'q\';1t.k.R=(1j-1R+3)+\'q\';1N.k.6U=1R+\'q\';l(3d==\'o\'){1N.k.y=\'K\';1j=0}t{1N.k.y=\'16\'}W=m.r(\'6P\');W.k.53=6T;W.k.51=6S;W.k.6Q=87;W.k.4Y=2N+\'q\';1i=m.r(\'67\');1i.k.53=6T;1i.k.51=6S;1i.k.4Y=2N+\'q\';1h=m.r(\'5n\');1h.k.53=86;1h.k.51=85;1h.k.6Q=84;1h.k.4Y=3c+\'q\';3n=m.r(\'3n\').k;3n.R=V+\'q\';3m=m.r(\'3m\').k;3m.R=V+\'q\';2y=m.r(\'2y\').k;2y.E=V+4Z+\'q\';2z=m.r(\'2z\').k;2z.E=V+\'q\';4W=m.r(\'5R\');l(2e==\'o\'){4V=U 1I.2B(1t,{1G:2R,1V:p(){3s()}});5h=U 1I.2B(D,{1G:2k,1V:p(){3T()}});5h.2W();6M=U 1I.2B(D,{1G:2k});6M.2W()}5k=m.r(\'3H\').k;2Y.28=p(){6K();v};1p.28=p(){3S();v};1N.28=p(){3S();v};1a.28=p(){3S();v};l(14.17.Z("3k")!=-1){3Z=0;47=0}l(14.17.Z("3R")!=-1){47=0}m.r(\'4r\').7Y=6H;F e=0;F f=0;F g=U 2v("2s.1b","6G.1b","6F.1e","6D.1e","6C.1e","6B.1e","6A.1e","6z.1e","6y.1e","6x.1e","7X.1b",5u,5w,5J,5F,6k,5B,"6E.1b","6w.1b","6v.1b","6t.1b");F h=U 2v();N=m.2b(\'a\');1x(i=0;i<N.C;i++){L=N[i].1A;7W=N[i].15(\'2i\');l(L.6u(\'1s\')!=1Y&&3i!=0){l(L==\'1s\'){N[i].1r=p(){l(2x==\'o\'){4M(Y.1A+\'+\\\\+\'+Y.15(\'2i\')+\'+\\\\+\'+Y.15(\'1D\'));v M}}}t{l(L.1E(0,8)==\'1s\'&&L.3M(8)==\'[\'&&L.3M(L.C-1)==\']\'){l(N[i].1A.1E(9,N[i].1A.C-1).21(\',,\')[0]!=\'1s\'){N[i].1r=p(){l(2x==\'o\'){4M(Y.1A.1E(9,Y.1A.C-1)+\'+\\\\+\'+Y.15(\'2i\')+\'+\\\\+\'+Y.15(\'1D\'));v M}}}t{6q(\'6p 6n#1:\\n\\7U 7T 7S 7R 7P "1s[1s]"!\\n(6l: m, \'+i+\'. <a>.)\')}l(N[i].15(\'2t\')!=1Y&&N[i].15(\'2t\')!=\'1Y\'){g.1Z(N[i].15(\'2t\'));F j=m.4Q(\'1w\');j.B=N[i].15(\'2t\');j.1f=\'\';j.7N=\'7L\';N[i].1v(j)}}t l(L.1E(0,8)==\'1s\'&&L.3M(8)==\'(\'&&L.3M(L.C-1)==\')\'){l(L.1E(9,L.C-1).21(\',,\')[2]==\'7K\'){N[i].1r=p(){l(2x==\'o\'){4J(Y.1A.1E(9,Y.1A.C-1)+\'+\\\\+\'+Y.15(\'2i\')+\'+\\\\+\'+Y.15(\'1D\'));v M}}}t{N[i].28=p(){l(2x==\'o\'){4J(Y.1A.1E(9,Y.1A.C-1)+\'+\\\\+\'+Y.15(\'2i\')+\'+\\\\+\'+Y.15(\'1D\'));v M}}}}t{6q(\'6p 6n#2:\\n\\n: 7J 7H 7G: "\'+N[i].1A+\'"!\\n(6l: m, \'+i+\'. <a>.)\')}}}}1x(i=0;i<g.C;i++){h[i]=U 2J();h[i].B=O+g[i]}2h=A=56;2m=H=56-1j;l(14.17.Z("2H")!=-1&&14.17.Z("7F")!=-1&&14.17.Z("2H 7")==-1){6i()}}p 4M(a){l(3i==0){v M}2G=M;3A=\'G\';1m=a.21(\'+\\\\+\');L=1m[0].21(\',,\');l(L[1]>0){4H=P(L[1])*6j}t{4H=2K}l(L[2]==\'2M\'){2g=\'4L\'}l(u&&L[0]==u[0][0]&&u[0][0]!=\'1s\'){}t{u=U 2v;u.1Z(U 2v(L[0],L[1],L[2]));l(1m[0]==\'1s\'){u.1Z(U 2v(1m[1],1m[2]))}t{1x(i=0;i<N.C;i++){l(N[i].1A.1E(9,N[i].1A.C-1).21(\',,\')[0]==u[0][0]){3f=O+\'6G.1b\';l(N[i].15(\'2t\')==1Y||N[i].15(\'2t\')==\'1Y\'){1x(j=0;j<N[i].4G.C;j++){l(N[i].4G[j].B!=3e){3f=N[i].4G[j].B}}}t{3f=N[i].15(\'2t\')}u.1Z(U 2v(N[i].15(\'2i\'),N[i].15(\'1D\'),3f))}}}}x=0;7C(u[x][0]!=1m[1]){x++}4F();l(2Q==\'o\'){4E()}l(2I==\'o\'){4D()}4C()}p 4F(){6g();6f();6e();l(1q>1Q){1Q=1q}l((14.17.Z("6d")!=-1||14.17.Z("3R")!=-1)&&1z!=1P){44=Q.4z+Q.4y-1Q}t{44=0}4x();l(3Z==0){l(1P>7A.E){1a.k.E=1P+\'q\'}t{1a.k.E=\'35%\'}}t{1a.k.E=1P+3Z+\'q\'}1a.k.R=1q+2u+\'q\';1a.k.w=\'19\';v}p 4J(a){l(3i==0){v M}3A=\'G\';4W.T=\'<6a 7y="0" z="69" B=""></6a>\';1L=m.r(\'69\');1L.k.1g=0;1L.k.1d=\'2o(1g=0)\';l(2e==\'o\'){4v=U 1I.2B(1L,{1G:2k,1V:p(){2A.k.y=\'16\';D.k.w=\'S\';4V.1C(1,0)}});4v.2W()}2G=M;1N.k.E=\'1k\';1t.k.E=\'1k\';49();2d=\'G\';1m=a.21(\'+\\\\+\');1L.B=1m[1];5k.y=\'K\';L=1m[0].21(\',,\');4F();A=P(L[0]);H=P(L[1]);l(A>1z-(2*(V+J+1o+1F))){A=1z-(2*(V+J+1o+1F))}l(H>1q-(2*(V+J+1o+1F))-1j){H=1q-(2*(V+J+1o+1F))-1j}D.k.E=2h+\'q\';D.k.R=2m+\'q\';D.k.y=\'16\';D.k.w=\'S\';2w.k.w=\'19\';2A.k.y=\'K\';1O.k.y=\'K\';1W.k.y=\'K\';l(2Q==\'o\'){4E()}l(2I==\'o\'){4D()}4C(\'3o\')}p 4C(a){l(a==\'3o\'){20.k.w=\'19\';5c.1C(0,2V)}t{66();5a.1C(0,2V)}1a.k.R=1Q+47+\'q\'}p 66(){4u();D.k.E=2h+\'q\';D.k.R=2m+\'q\';D.k.y=\'16\';D.k.w=\'S\';2w.k.w=\'19\'}p 4u(){1O.k.y=\'K\';1W.k.y=\'K\';2A.k.y=\'K\';1S.k.y=\'K\';1U.k.y=\'K\'}p 1n(a){2d=\'G\';4t();4u();2j.k.w=\'S\';2l.k.w=\'S\';1N.k.E=\'1k\';1t.k.E=\'1k\';2C.k.E=\'1k\';1p.k.E=\'1k\';1p.k.R=\'1k\';2Y.k.w=\'S\';2C.k.y=\'K\';1p.k.w=\'S\';49();l(a){l(A>2q){D.k.E=A+\'q\'}l(H>2X){D.k.R=H+\'q\'}}l(a){x=P(a)}l(1B!=\'3Q\'){D.k.w=\'S\';20.k.w=\'19\'}W.T=\'\';1h.T=\'\';3X=0;2T=U 2J();2T.B=u[x][0];3V=M;3s();4s()}p 4s(){l(3X==1){4S();3V=3B;4q(3U);65();v}l(3V==M&&2T.7x){3X++}3U=62("4s()",5);v}p 65(){A=2T.E;H=2T.R;2q=A;2X=H;41=A/H;l(A<2E){A=2E}l(H<2F){H=2F}61();D.B=u[x][0];5b();v}p 5b(a){2P=1;l(1B==\'46\'){55(a)}t l(1B==\'3Q\'){l(!a){20.k.w=\'S\';D.k.w=\'19\';D.k.1g=1;D.k.1d=\'2o(1g=35)\'}55(a)}t l(1B==\'G\'){4x();2U.k.R=H+(2*J)+\'q\';D.k.E=A+\'q\';D.k.R=H+\'q\'}t l(1B==\'6I\'){6X(a)}v}p 6X(a){3D=U 1I.4p(D,{1G:29,1V:p(){5Z(a)}});3D.1C(2h,A)}p 5Z(a){40=U 1I.5X(D,{1G:29,1V:p(){l(a==\'3o\'){4B()}t{4l()}}});40.1C(2m,H)}p 55(a){3D=U 1I.4p(D,{1G:29,1V:p(){l(a==\'3o\'){4B()}t{4l()}}});3D.1C(2h,A);40=U 1I.5X(D,{1G:29});40.1C(2m,H)}p 4B(){5W()}p 5W(){l(34==\'o\'){5U()}u=\'\';4o();D.k.w=\'19\';D.k.1g=1;D.k.1d=\'2o(1g=35)\';20.k.w=\'S\';1L.k.33=J+\'q\';1L.k.2c=J+\'q\';1L.k.E=A+\'q\';1L.k.R=H+\'q\';W.k.5T=\'7t\';l(1m[2]&&1m[2]!=\'1Y\'&&1m[2]!=1Y){1i.T=\'\';1i.1v(m.1K(1m[2]));l(1i.2Z>A+(2*J)){4m(1m[2])}t{W.1v(m.1K(1m[2]))}}t{l(3h==\'o\'){W.T=1m[1]}}2d=\'o\';2P=0;l(2e==\'o\'){4v.1C(0,1)}t{1t.k.w=\'S\';1L.k.1g=1;1L.k.1d=\'2o(1g=35)\';2A.k.y=\'16\';3s()}v}p 3s(){l(3F==\'o\'){1a.1r=p(){42();v M}}}p 4S(){1a.1r=\'\'}p 4l(){l(A>2q){2U.k.E=A+(2*J)+\'q\';D.k.E=2q+\'q\'}l(H>2X){2U.k.R=H+(2*J)+\'q\';D.k.R=2X+\'q\'}l(1B!=\'3Q\'){W.T=\'\';1h.T=\'\';20.k.w=\'S\';D.B=u[x][0];l(2e==\'o\'){5S()}t{D.k.w=\'19\';3T()}}t{3T()}}p 3T(){l(34==\'o\'){5U()}W.k.5T=\'2c\';4o();l(u.C<3){1O.k.y=\'K\';1W.k.y=\'K\'}t{l(2g==\'2M\'){1O.k.y=\'16\';1W.k.y=\'K\'}t{1W.k.y=\'16\';1O.k.y=\'K\'}}5k.y=\'16\';2A.k.y=\'16\';1S.k.R=H+\'q\';1U.k.R=H+\'q\';l(u[x][1]&&u[x][1]!=\'1Y\'&&u[x][1]!=1Y){1i.T=\'\';1i.1v(m.1K(u[x][1]));l(1i.2Z>A+(2*J)){4m(u[x][1])}t{W.1v(m.1K(u[x][1]))}}t{l(3h==\'o\'){W.1v(m.1K((u[x][0].21(\'/\'))[(u[x][0].21(\'/\').C)-1]))}}l(3j==\'o\'&&L[0]!="1s"){1h.1v(m.1K(L[0]))}l(3b==\'o\'&&u.C>2){1h.1v(m.1K(\' \'+5Q.1E(0,1)+x+\'/\'+(u.C-1)+5Q.1E(1,2)+\' \'))}l(3w==\'o\'){l((3j==\'o\'||3b==\'o\')&&L[0]!="1s"){1h.T+=\'<2p 1u="3y"> | </2p>\'}F a=4N;l(2q>A||2X>H){a=3N}l(u[x][0].1E(u[x][0].C-4,u[x][0].C)==\'7q\'){a=3N;1h.T+=\'<a 1u="2r" 5P="5O" 2i="\'+u[x][0].1E(0,u[x][0].C-4)+\'">\'+a+\'</a>\'}t{1h.T+=\'<a 1u="2r" 5P="5O" 2i="\'+u[x][0]+\'">\'+a+\'</a>\'}}l(2r==\'o\'&&L[0]!="1s"){1h.T+=\'<2p 1u="3y"> | </2p>\'}3H();l(u.C>0){l(A>2q){2U.k.E=\'\'}2h=A;2m=H}l(u.C>2){l(2g==\'4L\'){1W.k.y=\'16\';1M.k.y=\'16\';5e()}t{1O.k.y=\'16\'}}t{2g=\'2M\'}2d=\'o\';2P=0;1p.k.E=A+(2*J)+\'q\';1p.k.R=H+(2*J)+\'q\';5N();l(2e==\'o\'){4V.1C(1,0)}t{1t.k.w=\'S\';3s()}v}p 4m(a){1i.T=\'\';1i.1v(m.1K(a));1i.T+=\' | \';1i.1v(m.1K(a));1i.T+=\' | \';W.T=\'\';W.1v(m.1K(a));W.T+=\'<2p 1u="3y"> | </2p>\';W.1v(m.1K(a));W.T+=\'<2p 1u="3y"> | </2p>\';4k()}p 4k(){l(2a<0){2a++}t{l(2a<1i.2Z/2){W.k.2c=-2a+\'q\';2a++}t{W.k.2c=\'1k\';2a=0}}3C=62("4k()",30)}p 5N(){l(L[0]!="1s"){2Y.k.w=\'19\';2C.k.E=A+(2*J)+\'q\';2C.k.33=H-70+\'q\';F a=\'\';F b=10;F c=0;F d=0;2f=0;3z=U 2J();3K=U 2J();1x(i=1;i<u.C;i++){3z.B=u[i][2];c=3W.3x(3z.E/3z.R*50);l(c>0){}t{c=50}2f+=c}2f+=(u.C-2)*b;1x(i=1;i<u.C;i++){3K.B=u[i][2];a+=\'<a 1r="l(1l==\\\'o\\\'){1y();}1n(\'+i+\')"><1w k="2c: \'+d+\'q;" B="\'+u[i][2]+\'" R="50" 1u="7n" 1f="" /></a>\';d+=3W.3x(3K.E/3K.R*50)+b}3t.k.E=2f+\'q\';3t.T=a;3t.k.4i=(A-2f)/2+\'q\'}v}p 4o(){1t.k.E=A+(2*J)+\'q\';1N.k.E=A+(2*J)+\'q\'}p 49(){1t.k.1g=1;1t.k.1d=\'2o(1g=35)\';1t.k.y=\'16\';1t.k.w=\'19\'}p 5S(){5h.1C(0,1)}p 6K(){1p.k.w=\'19\';2C.k.y=\'16\';v}p 3S(){1p.k.w=\'S\';2C.k.y=\'K\';v}p 6H(e){l(2f>A){l(4X){31=4K.7m}t{31=e.7l}l(31<0){31=0}3t.k.4i=((1z-A)/2-31)/(A/(2f-A-(2*J)))+\'q\'}}p 4t(){l(3C){4q(3C)}W.k.2c=\'1k\';2a=5V}p 5g(){1l=\'G\';2g=\'2M\';1y()}p 1y(){1M.k.E=\'1k\';1l=\'G\';43=0;1M.k.y=\'K\'}p 5e(){1l=\'o\';1M.k.2c=(P((1z-A)/2)+18+2S-J)+\'q\';1M.k.33=(P((1q-H-1j)/2)+4+2u-J)+\'q\';5I=U 1I.4p(1M,{1G:4H,1V:p(){43=0;1M.k.E=43+\'q\';l(1l==\'o\'){l(x==u.C-1){1n(1)}t{1n(x+1)}}}});5I.1C(0,A+(2*J)-36)}p 61(){l(A>1z-(2*(V+J+1o+1F))){A=1z-(2*(V+J+1o+1F));H=3W.3x(A/41)}l(H>1q-(2*(V+J+1o+1F))-1j){H=1q-(2*(V+J+1o+1F))-1j;A=3W.3x(41*H)}v}p 4x(){5f=P(2S-(A+(2*(V+J+1o)))/2);5d=P(2u-(4T+H+1j+(2*(V+J+1o)))/2);2w.k.4i=5f+\'q\';2w.k.6U=(5d-(44/2))+\'q\';v}p 3H(){l(x>1){l(38==\'o\'){5G=U 2J();5G.B=u[x-1][0]}l(2r==\'o\'){1h.T+=\'<a 1u="2r" 1r="l(1l==\\\'o\\\'){1y();}1n(\'+(x-1)+\')" 1f="&7k;">\'+4R+\'</a>\'}1S.k.y=\'16\';1S.1r=p(){l(1l==\'o\'){1y()}1n(x-1);v M}}l(x<u.C-1){l(38==\'o\'){6b=U 2J();6b.B=u[x+1][0]}l(2r==\'o\'){1h.T+=\'<a 1u="2r" 1r="l(1l==\\\'o\\\'){1y();}1n(\'+(x+1)+\')" 1f="&7D;">\'+4P+\'</a>\'}1U.k.y=\'16\';1U.1r=p(){l(1l==\'o\'){1y()}1n(x+1);v M}}v}p 42(){l(L[0]==\'1s\'||u.C>2){l(3U){4q(3U)}}3A=\'o\';2G=3B;4t();1N.k.E=\'1k\';1t.k.E=\'1k\';1p.k.E=\'1k\';1p.k.R=\'1k\';1p.k.w=\'S\';2Y.k.w=\'S\';5g();W.T=\'\';1h.T=\'\';D.B=O+\'2s.1b\';2h=A;2m=H;2U.k.R=H+(2*J)+\'q\';D.k.y=\'K\';2w.k.w=\'S\';4W.T=\'\';49();74();2j.k.w=\'S\';2l.k.w=\'S\';1S.k.y=\'K\';1U.k.y=\'K\';20.k.w=\'S\';4S();v}p 74(){59.1C(2V,0);2d=\'G\';l(2Q==\'o\'){6J()}l(2I==\'o\'){5D()}v}p 6f(){Y.1P=0;Y.1Q=0;l(Q.3J&&Q.4h){1P=Q.3J+Q.4h;1Q=Q.4y+Q.4z}t l(m.X.4I>m.X.2Z){1P=m.X.4I;1Q=m.X.5C}t{1P=m.X.2Z;1Q=m.X.7h}l(14.17.Z("2H")!=-1||14.17.Z("3k")!=-1){1P=m.X.4I;1Q=m.X.5C}l(14.17.Z("3R")!=-1||14.17.Z("6d")!=-1){1P=1z+Q.4h;1Q=1q+Q.4z}v}p 6g(){Y.1z=0;Y.1q=0;l(m.1J&&(m.1J.3a||m.1J.2L)){1z=m.1J.3a;1q=m.1J.2L}t l(3g(Q.3J)==\'5A\'){1z=Q.3J;1q=Q.4y}t l(m.X&&(m.X.3a||m.X.2L)){1z=m.X.3a;1q=m.X.2L;v}l(14.17.Z("3k")!=-1){1z=m.1J.3a;1q=m.1J.2L}l(m.5z!=3e){l(m.5z.6u(\'7f\')&&(14.17.Z("3R")!=-1||14.17.Z("3k")!=-1||14.17.Z("7e")!=-1)){1q=m.X.2L}}v}p 6e(){Y.2S=0;Y.2u=0;l(3g(Q.6s)==\'5A\'){2u=Q.6s;2S=Q.7d}t l(m.X&&(m.X.3L||m.X.3E)){2u=m.X.3E;2S=m.X.3L}t l(m.1J&&(m.1J.3L||m.1J.3E)){2u=m.1J.3E;2S=m.1J.3L}v}p 6i(){F s,i,j;F a=U 2v();a.1Z(m.r(\'4j\'));a.1Z(m.r(\'4c\'));a.1Z(m.r(\'4e\'));a.1Z(m.r(\'4g\'));a.1Z(m.r(\'4f\'));1x(i=0;i<a.C;i++){s=a[i].15(\'B\');l(s.7b().Z(".1e")!=-1){a[i].B=O+\'2s.1b\';a[i].k.1d+="1X:23.22.24(B=\'"+s+"\', 26=7a);"}}m.r(\'4n\').k.1d="1X:23.22.24(B=\'"+O+"/6z.1e\', 26=\'4b\');";m.r(\'4a\').k.1d="1X:23.22.24(B=\'"+O+"/6y.1e\', 26=\'3l\');";m.r(\'4d\').k.1d="1X:23.22.24(B=\'"+O+"/6x.1e\', 26=\'3l\');";m.r(\'2z\').k.1d="1X:23.22.24(B=\'"+O+"/6A.1e\', 26=\'4b\');";m.r(\'2y\').k.1d="1X:23.22.24(B=\'"+O+"/6B.1e\', 26=\'4b\');";m.r(\'5j\').k.1d="1X:23.22.24(B=\'"+O+"/6F.1e\', 26=\'3l\');";m.r(\'5l\').k.1d="1X:23.22.24(B=\'"+O+"/6D.1e\', 26=\'3l\');";m.r(\'5i\').k.1d="1X:23.22.24(B=\'"+O+"/6C.1e\', 26=\'3l\');";m.r(\'4n\').k.1T="K";m.r(\'4a\').k.1T="K";m.r(\'4d\').k.1T="K";m.r(\'2z\').k.1T="K";m.r(\'2y\').k.1T="K";m.r(\'5j\').k.1T="K";m.r(\'5l\').k.1T="K";m.r(\'5i\').k.1T="K"}p 4E(){F a=m.2b("5s");1x(i=0;i!=a.C;i++){a[i].k.w="S"}}p 6J(){F a=m.2b("5s");1x(i=0;i!=a.C;i++){a[i].k.w="19"}}p 4D(){F a=m.2b("5q");1x(i=0;i<a.C;i++){a[i].k.w="S"}F b=m.2b("6L");1x(i=0;i<b.C;i++){b[i].k.w="S"}}p 5D(){F a=m.2b("5q");1x(i=0;i<a.C;i++){a[i].k.w="19"}F b=m.2b("6L");1x(i=0;i<b.C;i++){b[i].k.w="19"}}p 6N(a){l(14.17.Z("3k")!=-1){a=-a}l(u.C>2){l(a>0&&x>1){l(1l==\'o\'){1y()}1n(x-1)}l(a<0&&x<u.C-1){l(1l==\'o\'){1y()}1n(x+1)}}}p 4U(a){F b=2d=="o";F c=0;l(!a)a=Q.4K;l(a.5o){c=a.5o/79;l(Q.78)c=-c}t l(a.6Z){c=-a.6Z/3}l(c&&b)6N(c);l(a.5m&&!2G)a.5m();a.77=2G}l(Q.2O)Q.2O(\'76\',4U,M);Q.72=m.72=4U;',62,510,'||||||||||||||||||||style|if|document||on|function|px|getElementById||else|CB_Gallery|return|visibility|CB_ActImgId|display|id|CB_ImgWidth|src|length|CB_Img|width|var|off|CB_ImgHeight|div|CB_ImgBorder|none|CB_Rel|false|CB_Links|CB_PicDir|parseInt|window|height|hidden|innerHTML|new|CB_RoundPix|CB_Txt1|body|this|indexOf|||||navigator|getAttribute|block|userAgent||visible|CB_HideContent|gif|td|filter|png|alt|opacity|CB_Txt2|CB_HTxt|CB_TextH|0px|CB_SSTimer|CB_Clicked|CB_LoadImage|CB_Padd|CB_ImgHd|BrSizeY|onclick|clearbox|CB_TxtL|class|appendChild|img|for|CB_SlideShowJump|BrSizeX|rel|CB_Animation|sajat|title|substring|CB_WinPadd|idotartam|temp|CB_effektek|documentElement|createTextNode|CB_iFr|CB_SlideB|CB_Txt|CB_SlideS|DocSizeX|DocSizeY|CB_PadT|CB_Prv|backgroundImage|CB_Nxt|halefutott|CB_SlideP|progid|null|push|CB_LoadingImg|split|Microsoft|DXImageTransform|AlphaImageLoader||sizingMethod||onmouseover|CB_AnimSpeed|CB_STi|getElementsByTagName|left|CB_ClearBox|CB_ImgTextFade|CB_AllThumbsWidth|CB_SS|CB_ImgWidthOld|href|CB_NavP|CB_ImgOpacitySpeed|CB_NavN|CB_ImgHeightOld|CB_HideOpacitySpeed|alpha|span|CB_ImgWidthOrig|CB_TextNav|blank|tnhref|DocScrY|Array|CB_Win|CB_AllowedToRun|CB_Left|CB_Right|CB_Cls|Atlatszosag|CB_Thm|tr|CB_ImgMinWidth|CB_ImgMinHeight|CB_ScrollEnabled|MSIE|CB_FlashHide|Image|CB_SlShowTime|clientHeight|start|CB_FontSize|addEventListener|CB_IsAnimating|CB_SelectsHide|CB_TextOpacitySpeed|DocScrX|CB_preImages|CB_ImgCont|CB_HideOpacity|elrejt|CB_ImgHeightOrig|CB_ShTh|offsetWidth||tempX||top|CB_AllowExtFunct|100|||CB_Preload||clientWidth|CB_ImgNum|CB_FontSize2|CB_SimpleDesign|undefined|CB_ActThumbSrc|typeof|CB_ShowImgURL|CB_Show|CB_ShowGalName|Opera|crop|CB_Footer|CB_Header|HTML|CB_BodyMarginBottom|CB_BodyMarginTop|CB_BodyMarginRight|CB_CloseOnHON|CB_Thm2|CB_BodyMarginLeft|CB_NavTextImgDL|CB_FullSize|round|CB_Sep|CB_preThumbs|CB_Break|true|CB_ScrollTimer|CB_animWidth|scrollTop|CB_CloseOnH|CB_CheckDuplicates|CB_PrevNext|CB_IEShowBug|innerWidth|CB_preThumbs2|scrollLeft|charAt|CB_NavTextFull|CB_NoThumbnails|CB_BtmNav|warp|Firefox|CB_HideThumbs|CB_ShowImage|CB_ImgLoadTimer|CB_Loaded|Math|CB_Count|CB_NavTextImgPrv|CB_BodyMarginX|CB_animHeight|CB_ImgRate|CB_Close|CB_SlideBW|FF_ScrollbarBug|CB_NavTextImgNxt|double|CB_BodyMarginY|CB_NavTextImgFull|CB_TxtLShow|CB_TopLeft|scale|CB_SlideShowS|CB_TopRight|CB_SlideShowP|CB_NavNext|CB_NavPrev|scrollMaxX|marginLeft|CB_CloseWindow|CB_ScrollText|CB_ImageFade|CB_ScrollT|CB_Top|CB_TxtLPos|szelesseg|clearTimeout|CB_Thumbs|CB_CheckLoaded|CB_ScrollTextStop|CB_NewAndLoad|iFrFadeEffect|CB_All|CB_SetMargins|innerHeight|scrollMaxY|CB_SSStart|CB_AfterResizeHTML|CB_HideDocument|CB_HideFlash|CB_HideSelect|CB_SetAllPositions|childNodes|CB_SlShowTimer|scrollWidth|CB_ClickURL|event|pause|CB_ClickIMG|CB_NavTextDL|CB_ShowTh|CB_NavTextNxt|createElement|CB_NavTextPrv|CB_CloseOnHOFF|CB_ieRPBug|scroll_wheel|TxtFadeEffect|CB_iFrC|IE|fontSize|CB_ie6RPBug||fontWeight||fontFamily||CB_WindowResizeXY|300|10000|CB_SSPause|HideDocumentFadeEffect2|HideDocumentFadeEffect|CB_AnimatePlease|HideDocumentFadeEffectiFr|CB_MarginT|CB_SlideShow|CB_MarginL|CB_SlideShowStop|ImgFadeEffect|CB_BtmRight|CB_Btm|CB_PrvNxt|CB_BtmLeft|preventDefault|CB_T2|wheelDelta|CB_Text|object|CB_Next|select|CB_Prev|CB_PictureStart|CB_NavTextStart|CB_PicturePause|CB_NavTextStop|CB_ImgHide|compatMode|number|CB_PicturePrev|scrollHeight|CB_ShowFlash|CB_Image|CB_PictureLoading|PreloadPrv|CB_Thumbs2|CB_ssbarWidth|CB_PictureClose|CB_NavTextClose|CB_ImgContainer|CB_Padding|CB_CheckThumbs|_blank|target|CB_ImgNumBracket|CB_iFrCont|CB_ImgFadeIn|textAlign|CB_ExternalFunction|CB_STii|CB_AfterLoadedHTML|magassag|CB_Window|CB_WindowResizeY|table|CB_FitToBrowser|setTimeout|CB_SlideShowBar|CB_ContentHide|CB_GetImageSize|CB_NewWindow|CB_HiddenText|setAttribute|CB_iFrame|iframe|PreloadNxt|CB_LoadingImage|Netscape|getScrollPosition|getDocumentSize|getBrowserSize|which|CB_pngFixIE|1000|CB_PictureNext|in|CB_Init|ERROR|attachEvent|ClearBox|alert|OnLoad|pageYOffset|btm_dl|match|btm_max|btm_next|s_topright|s_topleft|s_top|s_right|s_left|s_btmright|s_btmleft|btm_prev|s_btm|noprv|getMouseXY|normal|CB_ShowSelect|CB_ShowThumbs|embed|ImgFadeEffect2|scroll_handle|CB_KeyPress|CB_T1|color|600|CB_FontWeight|CB_Font|marginTop|onmouseout|url|CB_WindowResizeX|CB_TL|detail||CB_Content|onmousewheel|backgroundColor|CB_ShowDocument||DOMMouseScroll|returnValue|opera|120|image|toLowerCase|CB_ResizeTimer|pageXOffset|Safari|Back|CB_pngie|offsetHeight|loading|CB_ImgFadeNum|lt|pageX|clientX|CB_ThumbsImg|fromCharCode|align|_box|valign|CB_Body|center|String|cellpadding|cellspacing|complete|frameborder|item|screen|keyCode|while|gt|CB_version|Windows|attribute|REL|CB_RoundPixBugFix|Bad|click|CB_TnThumbs|static|className|position|be|onkeypress|cannot|name|gallery|nClearBox|load|CB_URL|white|onmousemove|MOUSEMOVE|Event|captureEvents|all|250|CB_FontColor2|CB_FontWeight2|CB_Font2|CB_FontColor|CB_ImgBorderColor|solid|border|CB_HideColor|fff|padding'.split('|'),0,{}));function hideElement(idElement){
		var tmpElement=window.document.getElementById(idElement);
		if(!tmpElement){
			//alert('Error 7004, Element: '+this.elementID+' not found!')
		}
		else{
			tmpElement.style.display="none";
		}
}
function showElement(idElement){
		var tmpElement=window.document.getElementById(idElement);
		if(!tmpElement){
			//alert('Error 7003, Element: '+idElement+' not found!')
		}
		else{
			tmpElement.style.display="block";
		}
}
function addInnerValue(idElement,value){
		var tmpElement=window.document.getElementById(idElement);
		if(!tmpElement){
			//alert('Error 7005, Element: '+idElement+' not found!')
		}
		else{
			var elementTxt=tmpElement.innerHTML;
			var newTxt=elementTxt+value;
			tmpElement.innerHTML=newTxt;
		}
}
function setValue(idElement,value){
		var tmpElement=window.document.getElementById(idElement);
		if(!tmpElement){
			alert('Error 7002, Element: '+idElement+' not found!')
		}
		else{
			tmpElement.value=value;
		}
}
function getValue(idElement){
		var tmpElement=window.document.getElementById(idElement);
		if(!tmpElement){
			//alert('Error 7009, Element: '+idElement+' not found!')
			return "";
		}
		else{
			return tmpElement.value;
		}
}
function getInnerValue(idElement){
		var tmpElement=window.document.getElementById(idElement);
		if(!tmpElement){
			document.location.reload();
		}
		else{
			return tmpElement.innerHTML;
		}
}
function setInnerValue(idElement,value){
		//alert(idElement);
		var tmpElement=window.document.getElementById(idElement);
		if(!tmpElement){
			alert('Error 7010, Element: '+idElement+' not found!');
		}
		else{
			//tmpElement.nodeValue=value;
//			while (tmpElement.hasChildNodes())
//			{
//				tmpElement.removeChild(tmpElement.firstChild);
//			}

			var newNode = document.createElement('div');
			newNode.innerHTML=value;
			newNode.setAttribute('id',idElement);
			//newNode.nodeValue=value;
			tmpElement.parentNode.replaceChild(newNode,tmpElement);
			//tmpElement.innerHTML=value;
		}
}
 // I create the class  
AjaxCaller.instance = null; // Will contain the one and only instance of the class  
AjaxCaller.elementID='';
AjaxCaller.pars='';
AjaxCaller.afterAction='';
AjaxCaller.form=null;
AjaxCaller.ajaxRequest=null;


function AC(form,elementID,actionName){
	var ac= AjaxCaller.getInstance();
	if(ac){
		ac.elementID=elementID;
		ac.form=form;
		ac.actionName=actionName;
		ac.serilizeForm();
		ac.getUpdate();
	}
}
function ACS(form,actionName){
	var ac= AjaxCaller.getInstance();
	if(ac){
		ac.form=form;
		ac.actionName=actionName;
		ac.serilizeForm();
		ac.sendData();
	}
}
function ACA(form,elementID,actionName,afterAction){
	var ac= AjaxCaller.getInstance();
	if(ac){
		ac.elementID=elementID;
		ac.form=form;
		ac.actionName=actionName;
		ac.afterAction=afterAction;
		ac.serilizeForm();
		ac.getUpdateAA();
	}
}
function ACEdit(form, acadID){
	var ac= AjaxCaller.getInstance();
	if(ac){
		var lang = document.getElementById('lang').value;
        ac.elementID='languages-'+acadID;
		ac.actionName='/academies/addLang/'+acadID+'/'+lang;
        ac.form=form;
		ac.serilizeForm();
		ac.getUpdate();
	}
}

function AjaxCaller(){
	this.elementID='';
	this.pars='';
	this.afterAction='';
	this.form=null;
	this.ajaxRequest=null;
	this.once=true;
}
 
 // This function ensures that I always use the same instance of the object  
AjaxCaller.getInstance = function() {  
     var ac=null;
	
     if (AjaxCaller.instance == null) {  
         AjaxCaller.instance = new AjaxCaller();
         ac=AjaxCaller.instance;  
     }
     else{
    	if(AjaxCaller.instance.ajaxRequest != null){
    		//alert(this.actionName)
    		alert('Request in progress, please wait...');
    		ac=false;
    	}
    	else{
    		ac=AjaxCaller.instance; 
    	}
     }
     return ac;  
 }
AjaxCaller.prototype.sendData = function(){
	this.loading();
	this.ajaxRequest = new Ajax.Request(
			this.actionName, 
				{
					method: 'post',
					onSuccess: this.displayMsg.bind(this),
					onFailure: this.reportError.bind(this),
					parameters: this.pars
				}
			);	
}
AjaxCaller.prototype.displayMsg = function(request)
{
		this.endLoading();
		alert(request.responseText);
}
AjaxCaller.prototype.getAdd = function(){
	this.loading()
	this.ajaxRequest = new Ajax.Request(
			this.actionName, 
				{
					method: 'post',
					onSuccess: this.elementAdd.bind(this),
					onFailure: this.reportError.bind(this),
					parameters: this.pars
				}
			);	
}
AjaxCaller.prototype.getUpdate = function(){
	this.loading()
	this.ajaxRequest = new Ajax.Request(
			this.actionName, 
				{
					method: 'post',
					onSuccess: this.elementReplace.bind(this),
					onFailure: this.reportError.bind(this),
					parameters: this.pars
				}
			);
}
AjaxCaller.prototype.getUpdateAA = function(){
	this.loading()
	this.ajaxRequest = new Ajax.Request(
			this.actionName, 
				{
					method: 'post',
					onSuccess: this.elementReplaceAA.bind(this),
					onFailure: this.reportError.bind(this),
					parameters: this.pars
				}
			);
}
AjaxCaller.prototype.getUpdateT = function(){
	this.loading()
	this.ajaxRequest = new Ajax.Request(
			this.actionName, 
				{
					method: 'post',
					onSuccess: this.elementReplaceT.bind(this),
					onFailure: this.reportError.bind(this),
					parameters: this.pars
				}
			);
}
AjaxCaller.prototype.elementReplace = function(request) {
		setInnerValue(this.elementID,request.responseText);
		this.endLoading();
}
AjaxCaller.prototype.elementReplaceAA = function(request) {
	setInnerValue(this.elementID,request.responseText);
	eval(this.afterAction);
}
AjaxCaller.prototype.elementReplaceT = function(request) {
		setInnerValue(this.elementID,request.responseText);
		this.endLoading();
		saveAllData();
}         
AjaxCaller.prototype.elementAdd = function(request) {
		addInnerValue(this.elementID,request.responseText);
		this.endLoading();
}
AjaxCaller.prototype.reportError = function(request){
	alert('Sorry. Not implemented.'+this.actionName);	
	this.endLoading();
}
AjaxCaller.prototype.serilizeForm=function(){
	if(this.pars=='' && this.form != null){
         	this.pars=Form.serialize(this.form);
      }
}
AjaxCaller.prototype.loading=function(){
	//setInnerValue('statusText',' loading...');
	//showElement('requestStatus');
	//this.serilizeForm();
}
AjaxCaller.prototype.endLoading=function(){
	//setInnerValue('statusText','');
	//hideElement('requestStatus');
	this.pars='';
	this.form=null;
	this.elementID='';
	//sorttable.init();
	this.ajaxRequest=null;
}

