

/*  Prototype JavaScript framework, version 1.6.0
 *  (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',

  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;

if (Prototype.Browser.WebKit)
  Prototype.BrowserFeatures.XPath = 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 === undefined) 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 (value !== undefined)
        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 && arguments[0] === undefined) 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 = count === undefined ? 1 : count;

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

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

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : 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.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 = fillWith === undefined ? 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 == undefined || 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 == undefined || 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, 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, 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 (value !== undefined) 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() {
  if (function() {
    var i = 0, Test = function(value) { this.key = value };
    Test.prototype.key = 'foo';
    for (var property in new Test('bar')) i++;
    return i > 1;
  }()) {
    function each(iterator) {
      var cache = [];
      for (var key in this._object) {
        var value = this._object[key];
        if (cache.include(key)) continue;
        cache.push(key);
        var pair = [key, value];
        pair.key = key;
        pair.value = value;
        iterator(pair);
      }
    }
  } else {
    function each(iterator) {
      for (var key in this._object) {
        var value = this._object[key], pair = [key, value];
        pair.key = key;
        pair.value = value;
        iterator(pair);
      }
    }
  }

  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: each,

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

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);
    } 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  = xml === undefined ? 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')))
        return null;
    try {
      return this.transport.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 = options || { };
    var onComplete = options.onComplete;
    options.onComplete = (function(response, param) {
      this.updateContent(response.responseText);
      if (Object.isFunction(onComplete)) onComplete(response, param);
    }).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);
    }

    if (this.success()) {
      if (this.onComplete) this.onComplete.bind(this).defer();
    }
  }
});

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, t, range;

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

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

      content = Object.toHTML(content);

      range = element.ownerDocument.createRange();
      t.initializeRange(element, range);
      t.insert(element, range.createContextualFragment(content.stripScripts()));

      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 $A($(element).getElementsByTagName('*')).each(Element.extend);
  },

  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 expression ? Selector.findElement(ancestors, expression, index) :
      ancestors[index || 0];
  },

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

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

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

  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] = value === undefined ? true : value;

    for (var attr in attributes) {
      var 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);

    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 == ancestor) 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') ?
          (elementStyle.styleFloat === undefined ? '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 (!document.createRange || Prototype.Browser.Opera) {
  Element.Methods.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 t = Element._insertionTranslations, content, position, pos, tagName;

    for (position in insertions) {
      content  = insertions[position];
      position = position.toLowerCase();
      pos      = t[position];

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

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

      if (t.tags[tagName]) {
        var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
        if (position == 'top' || position == 'after') fragments.reverse();
        fragments.each(pos.insert.curry(element));
      }
      else element.insertAdjacentHTML(pos.adjacency, content.stripScripts());

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

    return element;
  };
}

if (Prototype.Browser.Opera) {
  Element.Methods._getStyle = Element.Methods.getStyle;
  Element.Methods.getStyle = function(element, style) {
    switch(style) {
      case 'left':
      case 'top':
      case 'right':
      case 'bottom':
        if (Element._getStyle(element, 'position') == 'static') return null;
      default: return Element._getStyle(element, style);
    }
  };
  Element.Methods._readAttribute = Element.Methods.readAttribute;
  Element.Methods.readAttribute = function(element, attribute) {
    if (attribute == 'title') return element.title;
    return Element._readAttribute(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) {
          var 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 Position.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];
  div.innerHTML = t[0] + html + t[1];
  t[2].times(function() { div = div.firstChild });
  return $A(div.childNodes);
};

Element._insertionTranslations = {
  before: {
    adjacency: 'beforeBegin',
    insert: function(element, node) {
      element.parentNode.insertBefore(node, element);
    },
    initializeRange: function(element, range) {
      range.setStartBefore(element);
    }
  },
  top: {
    adjacency: 'afterBegin',
    insert: function(element, node) {
      element.insertBefore(node, element.firstChild);
    },
    initializeRange: function(element, range) {
      range.selectNodeContents(element);
      range.collapse(true);
    }
  },
  bottom: {
    adjacency: 'beforeEnd',
    insert: function(element, node) {
      element.appendChild(node);
    }
  },
  after: {
    adjacency: 'afterEnd',
    insert: function(element, node) {
      element.parentNode.insertBefore(node, element.nextSibling);
    },
    initializeRange: function(element, range) {
      range.setStartAfter(element);
    }
  },
  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() {
  this.bottom.initializeRange = this.top.initializeRange;
  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 = { };
    $w('width height').each(function(d) {
      var D = d.capitalize();
      dimensions[d] = self['inner' + D] ||
       (document.documentElement['client' + D] || document.body['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();
  },

  compileMatcher: function() {
    // Selectors with namespaced attributes can't use the XPath version
    if (Prototype.BrowserFeatures.XPath && !(/(\[[\w-]*?:|:checked)/).test(this.expression))
      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: "[@#{1}]",
    attr: function(m) {
      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, m, 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, children = [], 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) {
      tagName = 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() == tagName) 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;
  }
});

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 (options.hash === undefined) 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 (value === undefined) return element.checked ? element.value : null;
    else element.checked = !!value;
  },

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

  select: function(element, index) {
    if (index === undefined)
      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);
      return element.match(expression) ? element : element.up(expression);
    },

    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;

      if (document.createEvent) {
        var event = document.createEvent("HTMLEvents");
        event.initEvent("dataavailable", true, true);
      } else {
        var 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;
    }
  };
})());

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

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

  var timer, fired = false;

  function fireContentLoadedEvent() {
    if (fired) return;
    if (timer) window.clearInterval(timer);
    document.fire("dom:loaded");
    fired = 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();

﻿/*  
	Animator.js 1.1.9
	
	This library is released under the BSD license:

	Copyright (c) 2006, Bernard Sumption. All rights reserved.
	
	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:
	
	Redistributions of source code must retain the above copyright notice, this
	list of conditions and the following disclaimer. Redistributions in binary
	form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials
	provided with the distribution. Neither the name BernieCode nor
	the names of its contributors may be used to endorse or promote products
	derived from this software without specific prior written permission. 
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
	ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
	DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
	CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
	LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
	OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
	DAMAGE.

*/


// Applies a sequence of numbers between 0 and 1 to a number of subjects
// construct - see setOptions for parameters
function Animator(options) {
	this.setOptions(options);
	var _this = this;
	this.timerDelegate = function(){_this.onTimerEvent()};
	this.subjects = [];
	this.target = 0;
	this.state = 0;
	this.lastTime = null;
};
Animator.prototype = {
	// apply defaults
	setOptions: function(options) {
		this.options = Animator.applyDefaults({
			interval: 20,  // time between animation frames
			duration: 400, // length of animation
			onComplete: function(){},
			onStep: function(){},
			transition: Animator.tx.easeInOut
		}, options);
	},
	// animate from the current state to provided value
	seekTo: function(to) {
		this.seekFromTo(this.state, to);
	},
	// animate from the current state to provided value
	seekFromTo: function(from, to) {
		this.target = Math.max(0, Math.min(1, to));
		this.state = Math.max(0, Math.min(1, from));
		this.lastTime = new Date().getTime();
		if (!this.intervalId) {
			this.intervalId = window.setInterval(this.timerDelegate, this.options.interval);
		}
	},
	// animate from the current state to provided value
	jumpTo: function(to) {
		this.target = this.state = Math.max(0, Math.min(1, to));
		this.propagate();
	},
	// seek to the opposite of the current target
	toggle: function() {
		this.seekTo(1 - this.target);
	},
	// add a function or an object with a method setState(state) that will be called with a number
	// between 0 and 1 on each frame of the animation
	addSubject: function(subject) {
		this.subjects[this.subjects.length] = subject;
		return this;
	},
	// remove all subjects
	clearSubjects: function() {
		this.subjects = [];
	},
	// forward the current state to the animation subjects
	propagate: function() {
		var value = this.options.transition(this.state);
		for (var i=0; i<this.subjects.length; i++) {
			if (this.subjects[i].setState) {
				this.subjects[i].setState(value);
			} else {
				this.subjects[i](value);
			}
		}
	},
	// called once per frame to update the current state
	onTimerEvent: function() {
		var now = new Date().getTime();
		var timePassed = now - this.lastTime;
		this.lastTime = now;
		var movement = (timePassed / this.options.duration) * (this.state < this.target ? 1 : -1);
		if (Math.abs(movement) >= Math.abs(this.state - this.target)) {
			this.state = this.target;
		} else {
			this.state += movement;
		}
		
		try {
			this.propagate();
		} finally {
			this.options.onStep.call(this);
			if (this.target == this.state) {
				window.clearInterval(this.intervalId);
				this.intervalId = null;
				this.options.onComplete.call(this);
			}
		}
	},
	// shortcuts
	play: function() {this.seekFromTo(0, 1)},
	reverse: function() {this.seekFromTo(1, 0)},
	// return a string describing this Animator, for debugging
	inspect: function() {
		var str = "#<Animator:\n";
		for (var i=0; i<this.subjects.length; i++) {
			str += this.subjects[i].inspect();
		}
		str += ">";
		return str;
	}
}
// merge the properties of two objects
Animator.applyDefaults = function(defaults, prefs) {
	prefs = prefs || {};
	var prop, result = {};
	for (prop in defaults) result[prop] = prefs[prop] !== undefined ? prefs[prop] : defaults[prop];
	return result;
}
// make an array from any object
Animator.makeArray = function(o) {
	if (o == null) return [];
	if (!o.length) return [o];
	var result = [];
	for (var i=0; i<o.length; i++) result[i] = o[i];
	return result;
}
// convert a dash-delimited-property to a camelCaseProperty (c/o Prototype, thanks Sam!)
Animator.camelize = function(string) {
	var oStringList = string.split('-');
	if (oStringList.length == 1) return oStringList[0];
	
	var camelizedString = string.indexOf('-') == 0
		? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
		: oStringList[0];
	
	for (var i = 1, len = oStringList.length; i < len; i++) {
		var s = oStringList[i];
		camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
	}
	return camelizedString;
}
// syntactic sugar for creating CSSStyleSubjects
Animator.apply = function(el, style, options) {
	if (style instanceof Array) {
		return new Animator(options).addSubject(new CSSStyleSubject(el, style[0], style[1]));
	}
	return new Animator(options).addSubject(new CSSStyleSubject(el, style));
}
// make a transition function that gradually accelerates. pass a=1 for smooth
// gravitational acceleration, higher values for an exaggerated effect
Animator.makeEaseIn = function(a) {
	return function(state) {
		return Math.pow(state, a*2); 
	}
}
// as makeEaseIn but for deceleration
Animator.makeEaseOut = function(a) {
	return function(state) {
		return 1 - Math.pow(1 - state, a*2); 
	}
}
// make a transition function that, like an object with momentum being attracted to a point,
// goes past the target then returns
Animator.makeElastic = function(bounces) {
	return function(state) {
		state = Animator.tx.easeInOut(state);
		return ((1-Math.cos(state * Math.PI * bounces)) * (1 - state)) + state; 
	}
}
// make an Attack Decay Sustain Release envelope that starts and finishes on the same level
// 
Animator.makeADSR = function(attackEnd, decayEnd, sustainEnd, sustainLevel) {
	if (sustainLevel == null) sustainLevel = 0.5;
	return function(state) {
		if (state < attackEnd) {
			return state / attackEnd;
		}
		if (state < decayEnd) {
			return 1 - ((state - attackEnd) / (decayEnd - attackEnd) * (1 - sustainLevel));
		}
		if (state < sustainEnd) {
			return sustainLevel;
		}
		return sustainLevel * (1 - ((state - sustainEnd) / (1 - sustainEnd)));
	}
}
// make a transition function that, like a ball falling to floor, reaches the target and/
// bounces back again
Animator.makeBounce = function(bounces) {
	var fn = Animator.makeElastic(bounces);
	return function(state) {
		state = fn(state); 
		return state <= 1 ? state : 2-state;
	}
}
 
// pre-made transition functions to use with the 'transition' option
Animator.tx = {
	easeInOut: function(pos){
		return ((-Math.cos(pos*Math.PI)/2) + 0.5);
	},
	linear: function(x) {
		return x;
	},
	easeIn: Animator.makeEaseIn(1.5),
	easeOut: Animator.makeEaseOut(1.5),
	strongEaseIn: Animator.makeEaseIn(2.5),
	strongEaseOut: Animator.makeEaseOut(2.5),
	elastic: Animator.makeElastic(1),
	veryElastic: Animator.makeElastic(3),
	bouncy: Animator.makeBounce(1),
	veryBouncy: Animator.makeBounce(3)
}

// animates a pixel-based style property between two integer values
function NumericalStyleSubject(els, property, from, to, units) {
	this.els = Animator.makeArray(els);
	if (property == 'opacity' && window.ActiveXObject) {
		this.property = 'filter';
	} else {
		this.property = Animator.camelize(property);
	}
	this.from = parseFloat(from);
	this.to = parseFloat(to);
	this.units = units != null ? units : 'px';
}
NumericalStyleSubject.prototype = {
	setState: function(state) {
		var style = this.getStyle(state);
		var visibility = (this.property == 'opacity' && state == 0) ? 'hidden' : '';
		var j=0;
		for (var i=0; i<this.els.length; i++) {
			try {
				this.els[i].style[this.property] = style;
			} catch (e) {
				// ignore fontWeight - intermediate numerical values cause exeptions in firefox
				if (this.property != 'fontWeight') throw e;
			}
			if (j++ > 20) return;
		}
	},
	getStyle: function(state) {
		state = this.from + ((this.to - this.from) * state);
		if (this.property == 'filter') return "alpha(opacity=" + Math.round(state*100) + ")";
		if (this.property == 'opacity') return state;
		return Math.round(state) + this.units;
	},
	inspect: function() {
		return "\t" + this.property + "(" + this.from + this.units + " to " + this.to + this.units + ")\n";
	}
}

// animates a colour based style property between two hex values
function ColorStyleSubject(els, property, from, to) {
	this.els = Animator.makeArray(els);
	this.property = Animator.camelize(property);
	this.to = this.expandColor(to);
	this.from = this.expandColor(from);
	this.origFrom = from;
	this.origTo = to;
}

ColorStyleSubject.prototype = {
	// parse "#FFFF00" to [256, 256, 0]
	expandColor: function(color) {
		var hexColor, red, green, blue;
		hexColor = ColorStyleSubject.parseColor(color);
		if (hexColor) {
			red = parseInt(hexColor.slice(1, 3), 16);
			green = parseInt(hexColor.slice(3, 5), 16);
			blue = parseInt(hexColor.slice(5, 7), 16);
			return [red,green,blue]
		}
		if (window.DEBUG) {
			alert("Invalid colour: '" + color + "'");
		}
	},
	getValueForState: function(color, state) {
		return Math.round(this.from[color] + ((this.to[color] - this.from[color]) * state));
	},
	setState: function(state) {
		var color = '#'
				+ ColorStyleSubject.toColorPart(this.getValueForState(0, state))
				+ ColorStyleSubject.toColorPart(this.getValueForState(1, state))
				+ ColorStyleSubject.toColorPart(this.getValueForState(2, state));
		for (var i=0; i<this.els.length; i++) {
			this.els[i].style[this.property] = color;
		}
	},
	inspect: function() {
		return "\t" + this.property + "(" + this.origFrom + " to " + this.origTo + ")\n";
	}
}

// return a properly formatted 6-digit hex colour spec, or false
ColorStyleSubject.parseColor = function(string) {
	var color = '#', match;
	if(match = ColorStyleSubject.parseColor.rgbRe.exec(string)) {
		var part;
		for (var i=1; i<=3; i++) {
			part = Math.max(0, Math.min(255, parseInt(match[i])));
			color += ColorStyleSubject.toColorPart(part);
		}
		return color;
	}
	if (match = ColorStyleSubject.parseColor.hexRe.exec(string)) {
		if(match[1].length == 3) {
			for (var i=0; i<3; i++) {
				color += match[1].charAt(i) + match[1].charAt(i);
			}
			return color;
		}
		return '#' + match[1];
	}
	return false;
}
// convert a number to a 2 digit hex string
ColorStyleSubject.toColorPart = function(number) {
	if (number > 255) number = 255;
	var digits = number.toString(16);
	if (number < 16) return '0' + digits;
	return digits;
}
ColorStyleSubject.parseColor.rgbRe = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;
ColorStyleSubject.parseColor.hexRe = /^\#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;

// Animates discrete styles, i.e. ones that do not scale but have discrete values
// that can't be interpolated
function DiscreteStyleSubject(els, property, from, to, threshold) {
	this.els = Animator.makeArray(els);
	this.property = Animator.camelize(property);
	this.from = from;
	this.to = to;
	this.threshold = threshold || 0.5;
}

DiscreteStyleSubject.prototype = {
	setState: function(state) {
		var j=0;
		for (var i=0; i<this.els.length; i++) {
			this.els[i].style[this.property] = state <= this.threshold ? this.from : this.to; 
		}
	},
	inspect: function() {
		return "\t" + this.property + "(" + this.from + " to " + this.to + " @ " + this.threshold + ")\n";
	}
}

// animates between two styles defined using CSS.
// if style1 and style2 are present, animate between them, if only style1
// is present, animate between the element's current style and style1
function CSSStyleSubject(els, style1, style2) {
	els = Animator.makeArray(els);
	this.subjects = [];
	if (els.length == 0) return;
	var prop, toStyle, fromStyle;
	if (style2) {
		fromStyle = this.parseStyle(style1, els[0]);
		toStyle = this.parseStyle(style2, els[0]);
	} else {
		toStyle = this.parseStyle(style1, els[0]);
		fromStyle = {};
		for (prop in toStyle) {
			fromStyle[prop] = CSSStyleSubject.getStyle(els[0], prop);
		}
	}
	// remove unchanging properties
	var prop;
	for (prop in fromStyle) {
		if (fromStyle[prop] == toStyle[prop]) {
			delete fromStyle[prop];
			delete toStyle[prop];
		}
	}
	// discover the type (numerical or colour) of each style
	var prop, units, match, type, from, to;
	for (prop in fromStyle) {
		var fromProp = String(fromStyle[prop]);
		var toProp = String(toStyle[prop]);
		if (toStyle[prop] == null) {
			if (window.DEBUG) alert("No to style provided for '" + prop + '"');
			continue;
		}
		
		if (from = ColorStyleSubject.parseColor(fromProp)) {
			to = ColorStyleSubject.parseColor(toProp);
			type = ColorStyleSubject;
		} else if (fromProp.match(CSSStyleSubject.numericalRe)
				&& toProp.match(CSSStyleSubject.numericalRe)) {
			from = parseFloat(fromProp);
			to = parseFloat(toProp);
			type = NumericalStyleSubject;
			match = CSSStyleSubject.numericalRe.exec(fromProp);
			var reResult = CSSStyleSubject.numericalRe.exec(toProp);
			if (match[1] != null) {
				units = match[1];
			} else if (reResult[1] != null) {
				units = reResult[1];
			} else {
				units = reResult;
			}
		} else if (fromProp.match(CSSStyleSubject.discreteRe)
				&& toProp.match(CSSStyleSubject.discreteRe)) {
			from = fromProp;
			to = toProp;
			type = DiscreteStyleSubject;
			units = 0;   // hack - how to get an animator option down to here
		} else {
			if (window.DEBUG) {
				alert("Unrecognised format for value of "
					+ prop + ": '" + fromStyle[prop] + "'");
			}
			continue;
		}
		this.subjects[this.subjects.length] = new type(els, prop, from, to, units);
	}
}

CSSStyleSubject.prototype = {
	// parses "width: 400px; color: #FFBB2E" to {width: "400px", color: "#FFBB2E"}
	parseStyle: function(style, el) {
		var rtn = {};
		// if style is a rule set
		if (style.indexOf(":") != -1) {
			var styles = style.split(";");
			for (var i=0; i<styles.length; i++) {
				var parts = CSSStyleSubject.ruleRe.exec(styles[i]);
				if (parts) {
					rtn[parts[1]] = parts[2];
				}
			}
		}
		// else assume style is a class name
		else {
			var prop, value, oldClass;
			oldClass = el.className;
			el.className = style;
			for (var i=0; i<CSSStyleSubject.cssProperties.length; i++) {
				prop = CSSStyleSubject.cssProperties[i];
				value = CSSStyleSubject.getStyle(el, prop);
				if (value != null) {
					rtn[prop] = value;
				}
			}
			el.className = oldClass;
		}
		return rtn;
		
	},
	setState: function(state) {
		for (var i=0; i<this.subjects.length; i++) {
			this.subjects[i].setState(state);
		}
	},
	inspect: function() {
		var str = "";
		for (var i=0; i<this.subjects.length; i++) {
			str += this.subjects[i].inspect();
		}
		return str;
	}
}
// get the current value of a css property, 
CSSStyleSubject.getStyle = function(el, property){
	var style;
	if(document.defaultView && document.defaultView.getComputedStyle){
		style = document.defaultView.getComputedStyle(el, "").getPropertyValue(property);
		if (style) {
			return style;
		}
	}
	property = Animator.camelize(property);
	if(el.currentStyle){
		style = el.currentStyle[property];
	}
	return style || el.style[property]
}


CSSStyleSubject.ruleRe = /^\s*([a-zA-Z\-]+)\s*:\s*(\S(.+\S)?)\s*$/;
CSSStyleSubject.numericalRe = /^-?\d+(?:\.\d+)?(%|[a-zA-Z]{2})?$/;
CSSStyleSubject.discreteRe = /^\w+$/;

// required because the style object of elements isn't enumerable in Safari
/*
CSSStyleSubject.cssProperties = ['background-color','border','border-color','border-spacing',
'border-style','border-top','border-right','border-bottom','border-left','border-top-color',
'border-right-color','border-bottom-color','border-left-color','border-top-width','border-right-width',
'border-bottom-width','border-left-width','border-width','bottom','color','font-size','font-size-adjust',
'font-stretch','font-style','height','left','letter-spacing','line-height','margin','margin-top',
'margin-right','margin-bottom','margin-left','marker-offset','max-height','max-width','min-height',
'min-width','orphans','outline','outline-color','outline-style','outline-width','overflow','padding',
'padding-top','padding-right','padding-bottom','padding-left','quotes','right','size','text-indent',
'top','width','word-spacing','z-index','opacity','outline-offset'];*/


CSSStyleSubject.cssProperties = ['azimuth','background','background-attachment','background-color','background-image','background-position','background-repeat','border-collapse','border-color','border-spacing','border-style','border-top','border-top-color','border-right-color','border-bottom-color','border-left-color','border-top-style','border-right-style','border-bottom-style','border-left-style','border-top-width','border-right-width','border-bottom-width','border-left-width','border-width','bottom','clear','clip','color','content','cursor','direction','display','elevation','empty-cells','css-float','font','font-family','font-size','font-size-adjust','font-stretch','font-style','font-variant','font-weight','height','left','letter-spacing','line-height','list-style','list-style-image','list-style-position','list-style-type','margin','margin-top','margin-right','margin-bottom','margin-left','max-height','max-width','min-height','min-width','orphans','outline','outline-color','outline-style','outline-width','overflow','padding','padding-top','padding-right','padding-bottom','padding-left','pause','position','right','size','table-layout','text-align','text-decoration','text-indent','text-shadow','text-transform','top','vertical-align','visibility','white-space','width','word-spacing','z-index','opacity','outline-offset','overflow-x','overflow-y'];


// chains several Animator objects together
function AnimatorChain(animators, options) {
	this.animators = animators;
	this.setOptions(options);
	for (var i=0; i<this.animators.length; i++) {
		this.listenTo(this.animators[i]);
	}
	this.forwards = false;
	this.current = 0;
}

AnimatorChain.prototype = {
	// apply defaults
	setOptions: function(options) {
		this.options = Animator.applyDefaults({
			// by default, each call to AnimatorChain.play() calls jumpTo(0) of each animator
			// before playing, which can cause flickering if you have multiple animators all
			// targeting the same element. Set this to false to avoid this.
			resetOnPlay: true
		}, options);
	},
	// play each animator in turn
	play: function() {
		this.forwards = true;
		this.current = -1;
		if (this.options.resetOnPlay) {
			for (var i=0; i<this.animators.length; i++) {
				this.animators[i].jumpTo(0);
			}
		}
		this.advance();
	},
	// play all animators backwards
	reverse: function() {
		this.forwards = false;
		this.current = this.animators.length;
		if (this.options.resetOnPlay) {
			for (var i=0; i<this.animators.length; i++) {
				this.animators[i].jumpTo(1);
			}
		}
		this.advance();
	},
	// if we have just play()'d, then call reverse(), and vice versa
	toggle: function() {
		if (this.forwards) {
			this.seekTo(0);
		} else {
			this.seekTo(1);
		}
	},
	// internal: install an event listener on an animator's onComplete option
	// to trigger the next animator
	listenTo: function(animator) {
		var oldOnComplete = animator.options.onComplete;
		var _this = this;
		animator.options.onComplete = function() {
			if (oldOnComplete) oldOnComplete.call(animator);
			_this.advance();
		}
	},
	// play the next animator
	advance: function() {
		if (this.forwards) {
			if (this.animators[this.current + 1] == null) return;
			this.current++;
			this.animators[this.current].play();
		} else {
			if (this.animators[this.current - 1] == null) return;
			this.current--;
			this.animators[this.current].reverse();
		}
	},
	// this function is provided for drop-in compatibility with Animator objects,
	// but only accepts 0 and 1 as target values
	seekTo: function(target) {
		if (target <= 0) {
			this.forwards = false;
			this.animators[this.current].seekTo(0);
		} else {
			this.forwards = true;
			this.animators[this.current].seekTo(1);
		}
	}
}

// an Accordion is a class that creates and controls a number of Animators. An array of elements is passed in,
// and for each element an Animator and a activator button is created. When an Animator's activator button is
// clicked, the Animator and all before it seek to 0, and all Animators after it seek to 1. This can be used to
// create the classic Accordion effect, hence the name.
// see setOptions for arguments
function Accordion(options) {
	this.setOptions(options);
	var selected = this.options.initialSection, current;
	if (this.options.rememberance) {
		current = document.location.hash.substring(1);
	}
	this.rememberanceTexts = [];
	this.ans = [];
	var _this = this;
	for (var i=0; i<this.options.sections.length; i++) {
		var el = this.options.sections[i];
		var an = new Animator(this.options.animatorOptions);
		var from = this.options.from + (this.options.shift * i);
		var to = this.options.to + (this.options.shift * i);
		an.addSubject(new NumericalStyleSubject(el, this.options.property, from, to, this.options.units));
		an.jumpTo(0);
		var activator = this.options.getActivator(el);
		activator.index = i;
		activator.onclick = function(){_this.show(this.index)};
		this.ans[this.ans.length] = an;
		this.rememberanceTexts[i] = activator.innerHTML.replace(/\s/g, "");
		if (this.rememberanceTexts[i] === current) {
			selected = i;
		}
	}
	this.show(selected);
}

Accordion.prototype = {
	// apply defaults
	setOptions: function(options) {
		this.options = Object.extend({
			// REQUIRED: an array of elements to use as the accordion sections
			sections: null,
			// a function that locates an activator button element given a section element.
			// by default it takes a button id from the section's "activator" attibute
			getActivator: function(el) {return document.getElementById(el.getAttribute("activator"))},
			// shifts each animator's range, for example with options {from:0,to:100,shift:20}
			// the animators' ranges will be 0-100, 20-120, 40-140 etc.
			shift: 0,
			// the first page to show
			initialSection: 0,
			// if set to true, document.location.hash will be used to preserve the open section across page reloads 
			rememberance: true,
			// constructor arguments to the Animator objects
			animatorOptions: {}
		}, options || {});
	},
	show: function(section) {
		for (var i=0; i<this.ans.length; i++) {
			this.ans[i].seekTo(i > section ? 1 : 0);
		}
		if (this.options.rememberance) {
			document.location.hash = this.rememberanceTexts[section];
		}
	}
}


/******************************************************************************
Name:    Basic Functions
Version: 0.9 (March 26 2008)
Author:  Sebastian Brink
Contact: http://www.quadrifolia.de

Licence:
Basic Functions is licensed under a Creative Commons Attribution-Noncommercial 
3.0 License (http://creativecommons.org/licenses/by-nc/3.0/).

You are free:
	* to copy, distribute and transmit the work
	* to adapt the work

Under the following conditions:
	* Attribution. You must attribute the work in the manner specified by 
	  the author or licensor.
	* Noncommercial. You may not use this work for commercial purposes.

* For any reuse or distribution, you must make clear to others the license 
  terms of this work. 
* Any of the above conditions can be waived if you get permission from the
  copyright holder.
* Nothing in this license impairs or restricts the author's moral rights.

Your fair dealing and other rights are in no way affected by the above.
******************************************************************************/

/******************************************************************************
  get the screensize
******************************************************************************/

function getScreenSize() {
	var x = y = 0;
	if (self.innerHeight) {
		// all except Explorer
		x = self.innerWidth;
		y = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		// Explorer 6 Strict Mode
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	} else if (document.body) {
		// other Explorers
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}

	return [x,y];
}

/******************************************************************************
  get the total site dimensions
******************************************************************************/

function getSiteDimensions() {
	
	var x = y = 0;
	var screensize = getScreenSize();
	
	if (window.innerHeight && window.scrollMaxY) {
		x = window.innerWidth + window.scrollMaxX;
		y = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight) {
		// all but Explorer Mac
		x = document.body.scrollWidth;
		y = document.body.scrollHeight;
	} else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight) {
		// Explorer 6 strict mode
		x = document.documentElement.scrollWidth;
		y = document.documentElement.scrollHeight;
	} else {
		// Explorer Mac...would also work in Mozilla and Safari
		x = document.body.offsetWidth;
		y = document.body.offsetHeight;
	}
	
	// for small pages with total height less then height of the viewport
	if(y < screensize[1]) {
		y = screensize[1];
	}

	// for small pages with total width less then width of the viewport
	if(x < screensize[0]) {
		x = screensize[0];
	}

	return [x,y];
}

/******************************************************************************
  find the position of an element (http://www.quirksmode.org/js/findpos.html)
******************************************************************************/

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/******************************************************************************
  disable selection of site elements
******************************************************************************/

function disableSelection(){
	if(window.getSelection){
		if(navigator.userAgent.indexOf('AppleWebKit/') > -1){
			if(window.devicePixelRatio) {
				window.getSelection().removeAllRanges();
			} else {
				window.getSelection().collapse();
			}
		}else{
			window.getSelection().removeAllRanges();
		}
	}else if(document.selection){
		if(document.selection.empty){
			document.selection.empty();
		}else if(document.selection.clear){
			document.selection.clear();
		}
	}

	var element = document.body;
	if(navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1){
		element.style.MozUserSelect = "none";
	}else if(navigator.userAgent.indexOf('AppleWebKit/') > -1){
		element.style.KhtmlUserSelect = "none"; 
	}else if(!!(window.attachEvent && !window.opera)){
		element.unselectable = "on";
		element.onselectstart = function() {
		        return false;
		};
	}
}

/******************************************************************************
  enable selection of site elements
******************************************************************************/

function enableSelection(){
	var element = document.body;
	if(navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1){ 
		element.style.MozUserSelect = "";
	}else if(navigator.userAgent.indexOf('AppleWebKit/') > -1){
		element.style.KhtmlUserSelect = "";
	}else if(!!(window.attachEvent && !window.opera)){
		element.unselectable = "off";
		element.onselectstart = function() {
		        return true;
		};
	}else{
		return false;
	}
	return true;
}

/******************************************************************************
  clear nodes
******************************************************************************/

function clearContent(id) {
    var content = $(id);
    while(content.hasChildNodes()){
        content.removeChild(content.childNodes[0]);
    }    
}

// --- END

/******************************************************************************
Name:    processXML
Version: 1.0 (December 20 2007)
Author:  Sebastian Brink
Contact: http://www.quadrifolia.de

Licence:
processXML is licensed under a Creative Commons Attribution-Noncommercial 
3.0 License (http://creativecommons.org/licenses/by-nc/3.0/).

You are free:
	* to copy, distribute and transmit the work
	* to adapt the work

Under the following conditions:
	* Attribution. You must attribute the work in the manner specified by 
	  the author or licensor.
	* Noncommercial. You may not use this work for commercial purposes.

* For any reuse or distribution, you must make clear to others the license 
  terms of this work. 
* Any of the above conditions can be waived if you get permission from the
  copyright holder.
* Nothing in this license impairs or restricts the author's moral rights.

Your fair dealing and other rights are in no way affected by the above.
******************************************************************************/

processXML = Class.create();

processXML.prototype = {

	initialize: function(options) {
		
		// vars
		var xml = this;
		var req;
		
		this.isIE = false;
		this.tags = new Array();
		this.tmpTags = '';
		this.result = new Array();
		
		this.options = options || {};
		this.initialized = true;

	},
	
	load: function(url) {
	    // native XMLHttpRequest object
	    if (window.XMLHttpRequest) {
	        req = new XMLHttpRequest();
	        req.onreadystatechange = this.process;
	        req.open("GET", url, true);
	        req.send(null);
	    // IE on Windows ActiveX version
	    } else if (window.ActiveXObject) {
	        this.isIE = true;
	        req = new ActiveXObject("Microsoft.XMLHTTP");
	        if (req) {
	            req.onreadystatechange = this.process;
	            req.open("GET", url, true);
	            req.send();
	        }
	    }
	},
	
	findTagNames: function(node) {
		if (node.tagName) {
			if (this.tmpTags.search(node.tagName) == -1) {	
				if (this.tmpTags == '') {
					this.tmpTags = node.tagName;
				} else {
					this.tmpTags = this.tmpTags + ' ' + node.tagName;
				}
			}
		}
		if (node.hasChildNodes()) {
			for (var i=0, j=node.childNodes.length; i<j; i+=1) {
				if (node.childNodes[i].tagName) {
					if (this.tmpTags.search(node.childNodes[i].tagName) == -1) {
						this.tmpTags = this.tmpTags + ' ' + node.childNodes[i].tagName;
					}
				}
				if (node.childNodes[i].hasChildNodes()) {
					this.findTagNames(node.childNodes[i]);
				}
			}
		}
	},
	
	process: function() {
	    // only if req shows "loaded"
	    if (req.readyState == 4) {
	        // only if "OK"
	        if (req.status == 200) {
				var type = req.responseXML.getElementsByTagName("type");
				var content = req.responseXML;
				if (content.hasChildNodes()) {
					myXML.tmpTags = '';
					for (var i=0, j=content.childNodes.length; i<j; i+=1) {
						myXML.findTagNames(content.childNodes[i]);
					}
					myXML.buildContent();
			    }
	         } else {
	            alert("There was a problem retrieving the XML data:\n" + req.statusText);
	         }
	    }
	},
	
	buildContent: function() {
		
		// all available content tags will be collected in this.result['tags']
		
		// vars
		var whiteSpace = new RegExp(/[\f\n\r\t\u00A0\u2028\u2029]/g);
		var resultTags = new Array();
		
		// tags
		this.tags = this.tmpTags.split(' ');
		
		// collect content
		for (var i=0, j=this.tags.length; i<j; i+=1) {		
			var items = req.responseXML.getElementsByTagName(this.tags[i]);
			var itemsArray = new Array();
			for (var x=0, y=items.length; x<y; x+=1) {
				if ((items[x].firstChild.nodeType == 3) && (!whiteSpace.test(items[x].firstChild.nodeValue))) {
					itemsArray.push(items[x].firstChild.nodeValue);
				}
			}
			if (itemsArray.length > 0) {
				resultTags.push(this.tags[i]);
				this.result[this.tags[i]] = itemsArray;
			}
		}
		this.result['tags'] = resultTags;
		
		if (this.initialized && this.options.onBuild) {
			this.options.onBuild(this.result);
		}

	}
	
}

// --- END

/******************************************************************************
Name:    Resize Control
Version: 1.0 (March 19 2008)
Author:  Sebastian Brink
Contact: http://www.quadrifolia.de

Licence:
Resize Control is licensed under a Creative Commons Attribution-Noncommercial 
3.0 License (http://creativecommons.org/licenses/by-nc/3.0/).

You are free:
	* to copy, distribute and transmit the work
	* to adapt the work

Under the following conditions:
	* Attribution. You must attribute the work in the manner specified by 
	  the author or licensor.
	* Noncommercial. You may not use this work for commercial purposes.

* For any reuse or distribution, you must make clear to others the license 
  terms of this work. 
* Any of the above conditions can be waived if you get permission from the
  copyright holder.
* Nothing in this license impairs or restricts the author's moral rights.

Your fair dealing and other rights are in no way affected by the above.
******************************************************************************/

// --- globals

var floorSize = 				0.25;
var ceilingSize = 				1.00;
var startSize =					0.25;

// --- class

Resize = Class.create();

Resize.prototype = {

	initialize: function(wrapper, options) {
		
		var resizer = this;
		
		// options
		this.options = options || {};
		this.listItem = this.options.listItem;
		this.images = this.options.images;
		this.reflections = this.options.reflections;
		this.titles = this.options.titles;
		this.startValues = this.options.startValues;
		
		this.wrapper = wrapper;
		
		// call this functions on slider change
		mySlider.options.onSlide = function(value) {
			myResize.draw(value);
		}
		
		this.initialized = true;
		
		this.draw(startSize);
		
	},
	
	draw: function(value) {
		
		// set start size
		startSize = value;
		
		// ratio
		this.ratio = floorSize + (value * (ceilingSize - floorSize));
		
		// area width
		this.thumbsAreaWidth = parseInt(Element.getStyle(this.wrapper, 'width'));
		
		// calculate new list item size
		this.newThumbsItemWidth = Math.round(this.ratio * thumbsMaxWidth);
		this.newThumbsItemHeight = Math.round(this.ratio * totalMaxHeight);
		
		if (reflection === true) {
			this.newThumbsItemHeight = this.newThumbsItemHeight + Math.round(this.ratio * reflectionHeight) + reflectionTopMargin;
		}
		
		// calculate new item margins
		this.itemsInLine = Math.floor(this.thumbsAreaWidth / (this.newThumbsItemWidth + thumbsMinMargin));
		if (this.itemsInLine > this.images.length) {
			this.itemsInLine = this.images.length;
		}
		this.itemsInLineWidth = this.itemsInLine * (this.newThumbsItemWidth + thumbsMinMargin);
		this.newThumbsItemMargin = Math.floor((this.thumbsAreaWidth - this.itemsInLineWidth) / (this.itemsInLine * 2)) + (thumbsMinMargin / 2);
		
		// calculate and set new thumbs area height
		this.linesInArea = Math.ceil(this.images.length / this.itemsInLine);
		this.newThumbsAreaHeight = Math.ceil(this.linesInArea * (this.newThumbsItemHeight + thumbsMarginTop));
		$(this.wrapper).style.height = this.newThumbsAreaHeight + 'px';

		// resize content
		for (var i=0, j=this.images.length; i<j; i+=1) {
		
			// calculate new image size
			this.newImageWidth = Math.floor(this.ratio * this.startValues[i][0]);
			this.newImageHeight = Math.floor(this.ratio * this.startValues[i][1]);
			
			// calculate new reflection size
			if (reflection === true) {
				this.newReflectionWidth = this.newImageWidth;
				this.newReflectionHeight = Math.floor(this.ratio * reflectionHeight);
			}
			
			// calculate new left margin
			this.newMarginLeft = Math.floor((this.newThumbsItemWidth - this.newImageWidth) / 2);
			
			// scale the images
			this.images[i].style.width = this.newImageWidth + 'px';
		    this.images[i].style.height = this.newImageHeight + 'px';
			this.images[i].style.marginLeft = this.newMarginLeft + 'px';
		
			// scale the reflection
			if (reflection === true) {
				this.reflections[i].style.width = this.newReflectionWidth + 'px';
		    	this.reflections[i].style.height = this.newReflectionHeight + 'px';
				this.reflections[i].style.marginTop = reflectionTopMargin + 'px';
				this.reflections[i].style.marginLeft = this.newMarginLeft + 'px';
			}
			
			// scale the title
			if (this.newThumbsItemWidth >= 150) {
				this.titles[i].style.marginTop = '-' + this.newReflectionHeight + 'px';
				this.titles[i].style.marginLeft = this.newMarginLeft + 'px';
				this.titles[i].style.width = this.newReflectionWidth + 'px';
				this.titles[i].style.display = 'block';
				if (this.newThumbsItemWidth >= 250) {
					this.titles[i].style.fontSize = '12px';
				} else if (this.newThumbsItemWidth >= 200) {
					this.titles[i].style.fontSize = '11px';
				} else {
					this.titles[i].style.fontSize = '10px';
				}
			} else {
				this.titles[i].style.display = 'none';
			}
			
			// scale the items
			this.listItem[i].style.width = this.newThumbsItemWidth + 'px';
		    this.listItem[i].style.height = this.newThumbsItemHeight + 'px';
		
			// set the new items margin
			this.listItem[i].style.marginLeft = this.newThumbsItemMargin + 'px';
			this.listItem[i].style.marginRight = this.newThumbsItemMargin + 'px';
			this.listItem[i].style.marginTop = thumbsMarginTop + 'px';
			
			// arrange the item to the frame bottom
			if (reflection === true) {
				this.images[i].style.marginTop = this.newThumbsItemHeight - this.newImageHeight - this.newReflectionHeight - reflectionTopMargin + 'px';
			} else {
				this.images[i].style.marginTop = this.newThumbsItemHeight - this.newImageHeight + 'px';
			}
			
			// resize scroller
			myScroller.resizeHandle();
			
		}
		
	}
	
}

// --- END

/******************************************************************************
Name:    Scroller Control
Version: 0.9 (March 27 2008)
Author:  Sebastian Brink
Contact: http://www.quadrifolia.de

Licence:
Scroller Control is licensed under a Creative Commons Attribution-Noncommercial 
3.0 License (http://creativecommons.org/licenses/by-nc/3.0/).

You are free:
	* to copy, distribute and transmit the work
	* to adapt the work

Under the following conditions:
	* Attribution. You must attribute the work in the manner specified by 
	  the author or licensor.
	* Noncommercial. You may not use this work for commercial purposes.

* For any reuse or distribution, you must make clear to others the license 
  terms of this work. 
* Any of the above conditions can be waived if you get permission from the
  copyright holder.
* Nothing in this license impairs or restricts the author's moral rights.

Your fair dealing and other rights are in no way affected by the above.
******************************************************************************/

// --- globals

var setting_scroller_arrow =			'both'; 		// top, bottom, both
var setting_track_position = 			'right'; 		// right, left
var setting_offset_top =				-7;				// the top handle offset (depends on the used graphics)
var setting_offset_bottom =				-7;				// the bottom handle offset (depends on the used graphics)
var setting_default_mousewhell_off = 	false;			// turns the default mousewhell actions for the whole page off
var setting_mousewhell_trigger = 		'container';	// document, container (container turns the default mousewhell actions off if the cursor is inside the container)

// --- nomenclature

var id_scroller_container =				'scroller_container';
var id_scroller_track = 				'scroller_track';
var id_scroller_up =					'scroller_up';
var id_scroller_down = 					'scroller_down';
var id_scroller_handle = 				'scroller_handle';
var id_scroller_handle_top =			'scroller_handle_top';
var id_scroller_handle_middle = 		'scroller_handle_middle';
var id_scroller_handle_bottom =			'scroller_handle_bottom';

// --- class

contentScroller = Class.create();

contentScroller.prototype = {
	
	initialize: function(container, content, options) {
		var scroller = this;
		
		// options
		this.options = options || {};
		
		this.arrowPosition = this.options.arrowPosition;
		this.trackPosition = this.options.trackPosition;
		this.offsetTop = this.options.offsetTop;
		this.offsetBottom = this.options.offsetBottom;
		this.contentLeftMargin = this.options.contentLeftMargin;
		this.contentRightMargin = this.options.contentRightMargin;
		
		// set content
		this.content = $(content);
		
		// create scroller
		if(!$(id_scroller_track)) {
			var objContainer = document.getElementById(container);
			
			var objTrack = new Element('div', { 'id': id_scroller_track });
			objContainer.appendChild(objTrack);
			
			var objArrowUp = new Element('div', { 'id': id_scroller_up });
			objTrack.appendChild(objArrowUp);
			
			var objArrowDown = new Element('div', { 'id': id_scroller_down });
			objTrack.appendChild(objArrowDown);
			
			var objHandle = new Element('div', { 'id': id_scroller_handle });
			objTrack.appendChild(objHandle);
			
			var objHandleTop = new Element('div', { 'id': id_scroller_handle_top });
			objHandle.appendChild(objHandleTop);
			
			var objHandleMiddle = new Element('div', { 'id': id_scroller_handle_middle });
			objHandle.appendChild(objHandleMiddle);
			
			var objHandleBottom = new Element('div', { 'id': id_scroller_handle_bottom });
			objHandle.appendChild(objHandleBottom);
			
			// set styles
			this.containerWidth = parseInt(Element.getStyle(objContainer, 'width'));
			this.trackHeight = parseInt(Element.getStyle(objContainer, 'height'));
			this.trackWidth = parseInt(Element.getStyle(objTrack, 'width'));
			this.handleCapTopHeight = parseInt(Element.getStyle(objHandleTop, 'height'));
			this.handleCapBottomHeight = parseInt(Element.getStyle(objHandleBottom, 'height'));
			this.handleHeight = this.handleCapTopHeight + this.handleCapBottomHeight;
			this.arrowUpHeight = parseInt(Element.getStyle(objArrowUp, 'height'));
			this.arrowDownHeight = parseInt(Element.getStyle(objArrowDown, 'height'));
			
			objTrack.setStyle({
				height: this.trackHeight + 'px',
				top: '0px'
			});
			
			if (this.trackPosition == 'left') {
				objTrack.setStyle({
					left: '0px'
				});
			} else if (this.trackPosition == 'right') {
				objTrack.setStyle({
					left: this.containerWidth - this.trackWidth + 'px'
				});
			}
			
			if (this.arrowPosition == 'top') {
				objHandle.setStyle({
					marginTop: this.arrowUpHeight + this.arrowDownHeight + this.offsetTop + 'px'
				});
				objArrowUp.setStyle({
					marginTop: '0px'
				});
				objArrowDown.setStyle({
					marginTop: this.arrowUpHeight + 'px'
				});
			} else if (this.arrowPosition == 'both') {
				objHandle.setStyle({
					marginTop: this.arrowUpHeight + this.offsetTop + 'px'
				});
				objArrowUp.setStyle({
					marginTop: '0px'
				});
				objArrowDown.setStyle({
					marginTop: this.trackHeight - this.arrowDownHeight + 'px'
				});
			} else if (this.arrowPosition == 'bottom') {
				objHandle.setStyle({
					marginTop: this.offsetTop + 'px'
				});
				objArrowUp.setStyle({
					marginTop: this.trackHeight - this.arrowUpHeight - this.arrowDownHeight + 'px'
				});
				objArrowDown.setStyle({
					marginTop: this.trackHeight - this.arrowDownHeight + 'px'
				});
			}
			
			// set elements
			this.handle = objHandle;
			this.handleMiddle = objHandleMiddle;
			this.track = objTrack;
			this.up = objArrowUp;
			this.down = objArrowDown;
			
			// set event listner
			this.eventMouseDownHandle = this.startDrag.bindAsEventListener(this);
			this.eventMouseDownTrack = this.setHandle.bindAsEventListener(this);
			this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
			this.eventMouseMove = this.moveHandle.bindAsEventListener(this);
			this.eventMouseDownArrowUp = this.startScroll.bindAsEventListener(this, 'up');
			this.eventMouseDownArrowDown = this.startScroll.bindAsEventListener(this, 'down');
			this.eventMouseUpArrow = this.endScroll.bindAsEventListener(this);
			this.eventMouseWheel = this.wheel.bindAsEventListener(this);

			Event.observe(this.handle, 'mousedown', this.eventMouseDownHandle);
			Event.observe(this.track, 'mousedown', this.eventMouseDownTrack);
			Event.observe(this.up, 'mousedown', this.eventMouseDownArrowUp);
			Event.observe(this.down, 'mousedown', this.eventMouseDownArrowDown);
			if (setting_mousewhell_trigger == 'container') {
				Event.observe(objContainer, 'mousewheel', this.eventMouseWheel);
				Event.observe(objContainer, "DOMMouseScroll", this.eventMouseWheel); // Firefox
			} else {
				Event.observe(document, 'mousewheel', this.eventMouseWheel);
				Event.observe(document, "DOMMouseScroll", this.eventMouseWheel); // Firefox
			}
			
		}
		
		// resize
		this.resizeHandle();
		
		this.active = false;
		this.scroll = false;
		this.initialized = true;
	},
	
	startDrag: function(e) {
		this.position = parseInt(this.handle.style.marginTop) || 0;
		this.startY = e.clientY - this.position;
		Event.observe(document, 'mousemove', this.eventMouseMove);
		Event.observe(document, 'mouseup', this.eventMouseUp);
		this.active = true;
		disableSelection();
	},
	
	endDrag: function(e) {
		if (this.active === true) {
			Event.stopObserving(document, 'mousedown', this.eventMouseMove);
			Event.stopObserving(document, 'mouseup', this.eventMouseUp);
			this.active = false;
			enableSelection();
		}
	},
	
	startScroll: function(e, direction) {
		this.scroll = true;
		Event.observe(document, 'mouseup', this.eventMouseUpArrow);
		this.moveArrow(direction);
	},
	
	endScroll: function(e) {
		this.scroll = false;
		Event.stopObserving(document, 'mouseup', this.eventMouseUpArrow);
	},
	
	wheel: function(event) {
		var delta = 0;
		if (!event) event = window.event;

		if (event.wheelDelta) {
			// IE / Opera
			delta = event.wheelDelta / 120;
			if (window.opera) {
				delta = -delta;
			}
		} else if (event.detail) {
			// Mozilla
			//delta = -event.detail/3;
			delta = -event.detail; // scroll faster
		}
		
		if (delta) {
			this.marginTop = (this.marginTop-=delta) || 0;
			this.draw('wheel');
		}
		
		// prevent default actions
		if ((setting_default_mousewhell_off === true) || (setting_mousewhell_trigger == 'container')) {
			if (event.preventDefault) {
				event.preventDefault();
			}
			event.returnValue = false;
		}
	},
	
	setHandle: function(e) {
		var element, offset;
		
		if (e.target) {
			element = e.target;
		} else if (e.srcElement) {
			element = e.srcElement;
		}
		
		// defeat Safari bug
		if (element.nodeType == 3) {
			element = element.parentNode;
		}
		
		if (element.id == this.track.getAttribute('id')) {
			if(e.layerY){
				this.marginTop = parseInt(e.layerY) - (this.handleHeight/2);
			} else if (e.offsetY) {
				this.marginTop = parseInt(e.offsetY) - (this.handleHeight/2);
			}
			
			this.draw('track');
		}
	},
	
	moveHandle: function(e) {
		if (this.active === true) {

			this.posY = e.clientY;
			this.marginTop = this.posY - this.startY;
			
			this.draw('handle');
		}
	},
	
	moveArrow: function(direction) {
		if (this.scroll === true) {
			
			var scrollStep = Math.round(this.scrollFactor);
			if (scrollStep < 1) {
				scrollStep = 1;
			}
			
			if (direction == 'up') {
				this.marginTop = (this.marginTop-=scrollStep) || 0;
			} else if (direction == 'down') {
				this.marginTop = (this.marginTop+=scrollStep) || 0;
			}
			this.draw('arrow');
			setTimeout('myScroller.moveArrow("'+direction+'")', 0);
		}
	},
	
	draw: function(element) {
		if (this.arrowPosition == 'top') {
			if (this.marginTop < (this.arrowUpHeight + this.arrowDownHeight + this.offsetTop)) {
				this.marginTop = this.arrowUpHeight + this.arrowDownHeight + this.offsetTop;
			}
			if (this.marginTop > (this.trackHeight - this.handleHeight - this.offsetBottom)) {
				this.marginTop = (this.trackHeight - this.handleHeight - this.offsetBottom);
			}
			this.options.scrollerValue = (this.marginTop - this.arrowUpHeight - this.arrowDownHeight - this.offsetTop) / (this.trackHeight - this.handleHeight - this.arrowUpHeight - this.arrowDownHeight - this.offsetTop - this.offsetBottom);
		} else if (this.arrowPosition == 'both') {
			if (this.marginTop < (this.arrowUpHeight + this.offsetTop)) {
				this.marginTop = this.arrowUpHeight + this.offsetTop;
			}
			if (this.marginTop > (this.trackHeight - this.handleHeight - this.arrowDownHeight - this.offsetBottom)) {
				this.marginTop = (this.trackHeight - this.handleHeight - this.arrowDownHeight - this.offsetBottom);
			}
			this.options.scrollerValue = (this.marginTop - this.arrowUpHeight - this.offsetTop) / (this.trackHeight - this.handleHeight - this.arrowUpHeight - this.arrowDownHeight - this.offsetTop - this.offsetBottom);
		} else if (this.arrowPosition == 'bottom') {
			if (this.marginTop < this.offsetTop) {
				this.marginTop = this.offsetTop;
			}
			if (this.marginTop > (this.trackHeight - this.handleHeight - this.arrowUpHeight - this.arrowDownHeight - this.offsetBottom)) {
				this.marginTop = (this.trackHeight - this.handleHeight - this.arrowUpHeight - this.arrowDownHeight - this.offsetBottom);
			}
			this.options.scrollerValue = (this.marginTop - this.offsetTop) / (this.trackHeight - this.handleHeight - this.arrowUpHeight - this.arrowDownHeight - this.offsetTop - this.offsetBottom);
		}
		
		// movement
		if(element == 'track') {
			window.scroller_move = new Animator({
				duration: 500
			}).addSubject(new CSSStyleSubject(
				this.handle, 'margin-top: '+this.marginTop+'px')
			).addSubject(new CSSStyleSubject(
				this.content, 'margin-top: -'+((this.marginTop - (this.arrowUpHeight + this.offsetTop)) * this.scrollFactor)+'px')
			);
		
			window.scroller_move.seekTo(1);
		} else {
			this.handle.style.marginTop = this.marginTop + 'px';
			this.content.style.marginTop = '-' + ((this.marginTop - (this.arrowUpHeight + this.offsetTop)) * this.scrollFactor) + 'px';
		}
		
		if (this.initialized && this.options.onScroll) {
			this.options.onScroll(this.options.scrollerValue);
		}
	},
	
	resizeHandle: function() {
		
		// reset top margins
		// TODO: resize without setting the margins back
		this.content.style.marginTop = '0px';
		
		if (this.arrowPosition == 'top') {
			this.handle.setStyle({
				marginTop: this.arrowUpHeight + this.arrowDownHeight + this.offsetTop + 'px'
			});
		} else if (this.arrowPosition == 'both') {
			this.handle.setStyle({
				marginTop: this.arrowUpHeight + this.offsetTop + 'px'
			});
		} else if (this.arrowPosition == 'bottom') {
			this.handle.setStyle({
				marginTop: this.offsetTop + 'px'
			});
		}
		
		
		// content horizontal position and track visibility
		this.contentHeight = parseInt(Element.getStyle(this.content, 'height'));
		if (this.contentHeight > this.trackHeight) {
			if (this.trackPosition == 'left') {
				this.content.setStyle({
					position: 'absolute',
					left: this.trackWidth + this.contentLeftMargin + 'px',
					width: this.containerWidth - this.trackWidth - this.contentLeftMargin - this.contentRightMargin + 'px'
				});
			} else if (this.trackPosition == 'right') {
				this.content.setStyle({
					position: 'absolute',
					left: this.contentLeftMargin + 'px',
					width: this.containerWidth - this.trackWidth - this.contentLeftMargin - this.contentRightMargin + 'px'
				});
			}
		} else {
			this.content.setStyle({
				position: 'absolute',
				left: this.contentLeftMargin + 'px',
				width: this.containerWidth - this.contentLeftMargin - this.contentRightMargin + 'px'
			});
		}
		
		// content height
		this.contentHeight = parseInt(Element.getStyle(this.content, 'height'));
		
		// handle height
		this.handleHeight = (this.trackHeight * (this.trackHeight - (this.arrowUpHeight + this.offsetTop) - (this.arrowDownHeight + this.offsetBottom))) / this.contentHeight;
		$(id_scroller_handle_middle).setStyle({
			height: (this.handleHeight - this.handleCapTopHeight - this.handleCapBottomHeight) + 'px'
		});
		
		// track visibilty
		if ((this.contentHeight > this.trackHeight) && (Element.getStyle(id_scroller_track, 'display') == 'none')) {
			this.track.setStyle({
				display: 'block'
			});
			
			// fix for thumbnail view on resize
			if ((Element.getStyle(id_thumbs, 'display') == 'block') && (Element.getStyle(id_overview, 'display') == 'none')) {
				this.resizeHandle();
				myResize.draw(startSize);
			}
		} else if (this.contentHeight <= this.trackHeight) {
			this.track.setStyle({
				display: 'none'
			});
		}
		
		// track scrolling space
		this.trackSpace = this.trackHeight - this.handleHeight - (this.arrowUpHeight + this.offsetTop) - (this.arrowDownHeight + this.offsetBottom);
		
		// content hidden height
		this.contentScroll = this.contentHeight - this.trackHeight;
		
		// scroll factor
		this.scrollFactor = this.contentScroll / this.trackSpace;
		
	},
	
	setContent: function(contentId) {
		// reset top margins
		this.content.setStyle({
			marginTop: '0px'
		});
		
		if (this.arrowPosition == 'top') {
			this.handle.setStyle({
				marginTop: this.arrowUpHeight + this.arrowDownHeight + this.offsetTop + 'px'
			});
		} else if (this.arrowPosition == 'both') {
			this.handle.setStyle({
				marginTop: this.arrowUpHeight + this.offsetTop + 'px'
			});
		} else if (this.arrowPosition == 'bottom') {
			this.handle.setStyle({
				marginTop: this.offsetTop + 'px'
			});
		}
		
		// new content
		this.content = $(contentId);
		this.content.setStyle({
			marginTop: '0px'
		});
		
		// set handle
		this.resizeHandle();
	}
	
}

// --- END

/******************************************************************************
Name:    Skimmer Control
Version: 1.0 (March 17 2008)
Author:  Sebastian Brink
Contact: http://www.quadrifolia.de

Licence:
Skimmer Control is licensed under a Creative Commons Attribution-Noncommercial 
3.0 License (http://creativecommons.org/licenses/by-nc/3.0/).

You are free:
	* to copy, distribute and transmit the work
	* to adapt the work

Under the following conditions:
	* Attribution. You must attribute the work in the manner specified by 
	  the author or licensor.
	* Noncommercial. You may not use this work for commercial purposes.

* For any reuse or distribution, you must make clear to others the license 
  terms of this work. 
* Any of the above conditions can be waived if you get permission from the
  copyright holder.
* Nothing in this license impairs or restricts the author's moral rights.

Your fair dealing and other rights are in no way affected by the above.
******************************************************************************/

// --- globals

var skimmerMaxWidth =			160;
var skimmerMaxHeight =			160;

// --- nomenclature

var class_Skimmer = 			'skimmer';
var class_SkimmerWrapper = 		'skimmerFrame';
var class_SkimmerMask = 		'skimmerMask';
var class_SkimmerTitle = 		'skimmerTitle';
var class_SkimmerCounter = 		'skimmerCounter';
var class_SkimmerMarker = 		'skimmerMarker';

// --- class

if(!Control) var Control = {};
Control.Skimmer = Class.create();

Control.Skimmer.prototype = {

	initialize: function(options) {
		
		var skimmer = this;
		
		// options
		this.options = options || {};
		this.marker = this.options.marker;
		this.indicator = this.options.indicator;
		this.size = this.options.size;
		
		// vars
		this.counter = 0;
		
		// collect the skimmers
		this.anchors = $$('div.'+this.marker);
		this.skimmerCounter = this.anchors.length;
			
		for (var i=0, j=this.anchors.length; i<j; i+=1) {
				
			// create listner
			Event.observe(this.anchors[i], 'mousemove', this.move.bindAsEventListener(this));
			Event.observe(this.anchors[i], 'mouseout', this.reset.bindAsEventListener(this));
			
			// create indicator
			if (this.indicator === true) {
				var skimmerMarker = new Element('div', { 'class': class_SkimmerMarker });
				this.anchors[i].appendChild(skimmerMarker);
			}

		}
		
	},
	
	move: function(e) {
		e = e||window.event;
		
		var activeSkimmer = $(Event.element(e)).up('.'+class_Skimmer);
		if (!activeSkimmer) {
			var activeSkimmer = Event.element(e);
		}
		
		// reset all other skimmers - fix for bubbling bug
		for (var i=0; i<this.skimmerCounter; i+=1) {
			var tmpSkimmerId = class_Skimmer + '_' + i;
			if ((activeSkimmer.id != tmpSkimmerId) && ($(tmpSkimmerId).lastChild.getStyle('display') != 'none')) {
				
				$(tmpSkimmerId).setStyle({
					backgroundPosition: '0px 0px'
				});
				
				$(tmpSkimmerId).lastChild.setStyle({
					display: 'none'
				});

				this.counter = 0;
			}
		}
		
		// get skimmer size
		if (this.counter == 0) {
			var imgSrc = activeSkimmer.getStyle('backgroundImage').split('url(');
			imgSrc = imgSrc[1].split(')');
			imgSrc = imgSrc[0];
		
			var image = new Image();
			image.src = imgSrc;
		
			this.counter = image.height / this.size;
		}
		
		// calc new position
		var mouseX = Event.pointerX(e)
		var offset = findPos(activeSkimmer);
		var imgPosition = Math.round((mouseX - offset[0]) / (this.size / (this.counter - 1)));
		
		// set indicator
		if (this.indicator === true) {
			activeSkimmer.lastChild.setStyle({
			  display: 'block'
			});
		}
		
		// move items
		this.moveImage(activeSkimmer, imgPosition);
	},
	
	moveImage: function(activeSkimmer, imgPosition) {
		
		// move indicator
		if (this.indicator === true) {
			if(imgPosition != (this.counter - 1)) {
				activeSkimmer.lastChild.setStyle({
				  width: Math.floor(this.size / this.counter) + 'px'
				});
			} else {
				activeSkimmer.lastChild.setStyle({
				  width: Math.floor(this.size / this.counter) + (this.size % Math.floor(this.size / this.counter)) + 'px'
				});
			}
			activeSkimmer.lastChild.setStyle({
			  left: (this.size / this.counter) * imgPosition + 'px'
			});
		}
	
		// move image
		activeSkimmer.setStyle({
		  backgroundPosition: '0px ' + (-this.size * imgPosition) + 'px'
		});
		
	},
	
	reset: function(e) {
		e = e||window.event;
		var eventTarget = e.relatedTarget || e.toElement;

		if ((eventTarget.getAttribute('class') != class_SkimmerMarker) && (eventTarget.getAttribute('class') != class_SkimmerMask)) {
			var activeSkimmer = $(Event.element(e)).up('.'+class_Skimmer);
			if (!activeSkimmer) {
				var activeSkimmer = Event.element(e);
			}
			this.moveImage(activeSkimmer, 0);
			this.counter = 0;
			if (this.indicator === true) {
				activeSkimmer.lastChild.setStyle({
				  display: 'none'
				});
			}
		}
	}
	
}

// --- END

/******************************************************************************
Name:    Slider Control
Version: 1.0 (March 18 2008)
Author:  Sebastian Brink
Contact: http://www.quadrifolia.de

Licence:
Slider Control is licensed under a Creative Commons Attribution-Noncommercial 
3.0 License (http://creativecommons.org/licenses/by-nc/3.0/).

You are free:
	* to copy, distribute and transmit the work
	* to adapt the work

Under the following conditions:
	* Attribution. You must attribute the work in the manner specified by 
	  the author or licensor.
	* Noncommercial. You may not use this work for commercial purposes.

* For any reuse or distribution, you must make clear to others the license 
  terms of this work. 
* Any of the above conditions can be waived if you get permission from the
  copyright holder.
* Nothing in this license impairs or restricts the author's moral rights.

Your fair dealing and other rights are in no way affected by the above.
******************************************************************************/

// --- nomenclature

var id_slider =					'slider';
var id_sliderTrack =			'slider_track';
var id_sliderHandle =			'slider_handle';
var id_sliderLeftIcon =			'slider_left_icon';
var id_sliderRightIcon =		'slider_right_icon';

// --- class

if(!Control) var Control = {};
Control.Slider = Class.create();

Control.Slider.prototype = {
	
	initialize: function(target, options) {
		
		var slider = this;
		
		// options
		this.options = options || {};
		
		this.id_slider = this.options.slider;
		this.id_sliderTrack = this.options.sliderTrack;
		this.id_sliderHandle = this.options.sliderHandle;
		this.id_sliderLeftIcon = this.options.sliderLeftIcon;
		this.id_sliderRightIcon = this.options.sliderRightIcon;
		
		this.target = $(target);
		
		// create DOM nodes
		if(!$(this.id_slider)) {
			
			var objSlider = new Element('div', { id: this.id_slider });
			this.target.appendChild(objSlider);
			
			var objSliderLeftIcon = new Element('div', { id: this.id_sliderLeftIcon });
			objSlider.appendChild(objSliderLeftIcon);
			
			var objSliderTrack = new Element('div', { id: this.id_sliderTrack });
			objSlider.appendChild(objSliderTrack);
			
			var objSliderHandle = new Element('div', { id: this.id_sliderHandle });
			objSliderTrack.appendChild(objSliderHandle);
			
			var objSliderRightIcon = new Element('div', { id: this.id_sliderRightIcon });
			objSlider.appendChild(objSliderRightIcon);
			
		}
		
		this.sliderWidth = parseInt(Element.getStyle(this.id_sliderTrack, 'width'));
		this.handleWidth = parseInt(Element.getStyle(this.id_sliderHandle, 'width'));
		this.iconsWidth = parseInt(Element.getStyle(this.id_sliderLeftIcon, 'width'));
		
		this.track = $(this.id_sliderTrack);
		this.handle = $(this.id_sliderHandle);
		
		// events
		this.eventMouseDownHandle = this.startDrag.bindAsEventListener(this);
		this.eventMouseDownTrack = this.setSlider.bindAsEventListener(this);
		this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
		this.eventMouseMove = this.moveSlider.bindAsEventListener(this);
			
		Event.observe(this.handle, 'mousedown', this.eventMouseDownHandle);
		Event.observe(this.track, 'mousedown', this.eventMouseDownTrack);
		
		this.active = false;
		this.initialized = true;
		
		this.draw(this.options.sliderValue);
	},
	
	startDrag: function(e) {
		this.position = parseInt(this.handle.style.marginLeft) || 0;
		this.startX = e.clientX - this.position;
		Event.observe(document, 'mousemove', this.eventMouseMove);
		Event.observe(document, 'mouseup', this.eventMouseUp);
		this.active = true;
	},
	
	endDrag: function(e) {
		if (this.active === true) {
			Event.stopObserving(document, 'mousedown', this.eventMouseMove);
			Event.stopObserving(document, 'mouseup', this.eventMouseUp);
			this.active = false;
		}
	},
	
	setSlider: function(e) {
		var element, offset;
		
		if (e.target) {
			element = e.target;
		} else if (e.srcElement) {
			element = e.srcElement;
		}
		
		// defeat Safari bug
		if (element.nodeType == 3) {
			element = element.parentNode;
		}
		
		if (element.id == this.id_sliderTrack) {
			if(e.layerX){
				offset = parseInt(e.layerX) - this.iconsWidth - (this.handleWidth/2);
			} else if (e.offsetX) {
				offset = parseInt(e.offsetX) - (this.handleWidth/2);
			}
			
			if (offset < 0) {
				offset = 0;
			}
			
			if (offset > (this.sliderWidth-this.handleWidth)) {
				offset = (this.sliderWidth-this.handleWidth);
			}
			
			this.options.sliderValue = offset / (this.sliderWidth-this.handleWidth);
			
			this.draw();
		}
	},
	
	moveSlider: function(e) {
		if (this.active === true) {
			disableSelection();

			this.posX = e.clientX;
			this.marginLeft = this.posX - this.startX;
			
			if (this.marginLeft < 0) {
				this.marginLeft = 0;
			}
			
			if (this.marginLeft > (this.sliderWidth-this.handleWidth)) {
				this.marginLeft = (this.sliderWidth-this.handleWidth);
			}
			
			this.options.sliderValue = this.marginLeft / (this.sliderWidth-this.handleWidth);
			
			this.draw();
		}
	},
	
	draw: function() {
		
		this.handle.setStyle({
			marginLeft: this.options.sliderValue * (this.sliderWidth-this.handleWidth) + 'px'
		});
		
		if (this.initialized && this.options.onSlide) {
			this.options.onSlide(this.options.sliderValue);
		}
	}
	
}

// --- END

/******************************************************************************
Name:    Image Viewer
Version: 0.9 (March 30 2008)
Author:  Sebastian Brink
Contact: http://www.quadrifolia.de

Licence:
Image Viewer is licensed under a Creative Commons Attribution-Noncommercial 
3.0 License (http://creativecommons.org/licenses/by-nc/3.0/).

You are free:
	* to copy, distribute and transmit the work
	* to adapt the work

Under the following conditions:
	* Attribution. You must attribute the work in the manner specified by 
	  the author or licensor.
	* Noncommercial. You may not use this work for commercial purposes.

* For any reuse or distribution, you must make clear to others the license 
  terms of this work. 
* Any of the above conditions can be waived if you get permission from the
  copyright holder.
* Nothing in this license impairs or restricts the author's moral rights.

Your fair dealing and other rights are in no way affected by the above.
******************************************************************************/

// --- globals

var lightbox_marker =				'lightbox';
var lightbox_close = 				'left';
var lightbox_listner =				true;
var lightbox_space = 				100;
var lightbox_border = 				10;
var lightbox_title_lineheight = 	30;
var lightbox_title_opacity = 		0.8;
var lightbox_overlay_opacity = 		0.8;
var lightbox_processing_opacity = 	0.6;

// --- nomenclature

var id_viewer = 					'imgViewer';
var id_viewer_overlay =				'imgViewer_overlay';
var id_viewer_loading =				'imgViewer_loading';
var id_viewer_processing =			'imgViewer_processing';
var id_viewer_container =			'imgViewer_container';
var id_viewer_image =				'imgViewer_image';
var id_viewer_title =				'imgViewer_title';
var id_viewer_closebox =			'imgViewer_closebox';
var id_viewer_navi_left =			'imgViewer_naviLeft';
var id_viewer_navi_right =			'imgViewer_naviRight';

// --- initialize
//------------------------------------------------------------------------------------------------------------------------
// function initViewer() { 
// 	myViewer = new imgViewer({
// 		marker: 'lightbox',
// 		close: 'left',
// 		listner: true
// 	});
// }
// 
// Event.observe(window, 'load', initViewer, false);
//------------------------------------------------------------------------------------------------------------------------

// --- class

imgViewer = Class.create();

imgViewer.prototype = {

	initialize: function(options) {
		
		var viewer = this;
		
		// options
		this.options = options || {};
		this.marker = this.options.marker;
		this.closePosition = this.options.close;
		this.listner = this.options.listner;
		
		// vars
		this.position = 0;
		this.firstRun = true;
		
		// add event listner
		if (this.listner === true) {
			this.anchors = $$('a.'+this.marker);
		
			for (var i=0, j=this.anchors.length; i<j; i+=1) {
				Event.observe(this.anchors[i], 'click', this.load.bindAsEventListener(this));
			}
		} else {
			this.anchors = $$('a.'+this.marker);
		}
		
		// create DOM nodes
		if(!$(id_viewer_overlay)) {
			var objBody = $$('body')[0];
			
			var objOverlay = new Element('div', { id: id_viewer_overlay }).setStyle({
				display: 'none'
			});
			objBody.appendChild(objOverlay);
			
			var objLoading = new Element('div', { id: id_viewer_loading });
			objOverlay.appendChild(objLoading);
			
			var objViewer = new Element('div', { id: id_viewer }).setStyle({
				display: 'none'
			});
			objBody.appendChild(objViewer);
			
			var objProcessing = new Element('div', { id: id_viewer_processing }).setStyle({
				display: 'none'
			});
			objBody.appendChild(objProcessing);

			// build animations
			this.basicAnimations();
		}

	},
	
	load: function(e) {
		
		// event
		if (!e.type) {
			var element = e;
		} else {
			e = e||window.event;
			var element = $(Event.element(e)).up('.'+this.marker);
			if (!element) {
				var element = Event.element(e);
			}
		}
		
		if (this.firstRun === true) {
			
			// lightbox space
			this.lightbox_fullSpace = ((lightbox_space + lightbox_border) * 2);
		
			// get dimensions
			this.viewport = document.viewport.getDimensions();
			this.siteDimensions = getSiteDimensions();
			this.scrollOffset = document.viewport.getScrollOffsets();
		
			// set overlay
			$(id_viewer_overlay).setStyle({ width: this.siteDimensions[0] + 'px' });
			$(id_viewer_overlay).setStyle({ height: this.siteDimensions[1] + 'px' });
			
			// set loading animation
			var id_viewer_loading_width = parseInt($(id_viewer_loading).getStyle('width'));
			var id_viewer_loading_height = parseInt($(id_viewer_loading).getStyle('height'));
			
			$(id_viewer_loading).setStyle({ marginLeft: Math.floor(this.scrollOffset['left'] + (this.viewport['width'] / 2) - (id_viewer_loading_width / 2)) + 'px' });
			$(id_viewer_loading).setStyle({ marginTop: Math.floor(this.scrollOffset['top'] + (this.viewport['height'] / 2) - (id_viewer_loading_height / 2)) + 'px' });
			
			// set processing animation
			var id_viewer_processing_width = parseInt($(id_viewer_processing).getStyle('width'));
			var id_viewer_processing_height = parseInt($(id_viewer_processing).getStyle('height'));
			
			$(id_viewer_processing).setStyle({ marginLeft: Math.floor( this.scrollOffset['left'] + (this.viewport['width'] / 2) - (id_viewer_processing_width / 2)) + 'px' });
			$(id_viewer_processing).setStyle({ marginTop: Math.floor(this.scrollOffset['top'] + (this.viewport['height'] / 2) - (id_viewer_processing_height / 2)) + 'px' });
		
			// show overlay
			window.imgViewer_aniOverlay.seekTo(lightbox_overlay_opacity);
		
			// build image
			if (element.href) {
				this.src = element.href;
			} else {
				this.src = element;
			}
		
			this.image = new Image();
			this.image.src = this.src;
		
		}
		
		// build DOM
		if (this.image.complete === true) {
			
			// get image position
			this.srcSource = this.src.split('/');
			this.srcSource = this.srcSource[this.srcSource.length-1];
			this.srcSource = this.srcSource.replace(/\?/g, '_');
			
			for (var i=0, j=this.anchors.length; i<j; i+=1) {
				
				this.srcCheck = this.anchors[i].readAttribute('href').split('/');
				this.srcCheck = this.srcCheck[this.srcCheck.length-1];
				this.srcCheck = this.srcCheck.replace(/\?/g, '_');
				
				if (this.srcSource.match(this.srcCheck)) {
					this.position = i;
					if (this.anchors[i].readAttribute('title') != null) {
						this.imgTitle = this.anchors[i].readAttribute('title');
					} else {
						this.imgTitle = this.anchors[i].readAttribute('alt');
					}
				}
			}

			// check if image is larger then screen
			if ((this.image.width + this.lightbox_fullSpace) > this.viewport['width']) {
				this.imgWidth = this.viewport['width'] - this.lightbox_fullSpace;
				this.imgHeight = (this.image.height * this.imgWidth) / this.image.width;
			} else {
				this.imgWidth = this.image.width;
				this.imgHeight = this.image.height;
			}

			if ((this.imgHeight + this.lightbox_fullSpace) > this.viewport['height']) {
				this.imgWidth = (this.imgWidth * (this.viewport['height'] - this.lightbox_fullSpace)) / this.imgHeight;
				this.imgHeight = this.viewport['height'] - this.lightbox_fullSpace;
			}
			
			// build
			var objImgFrame = new Element('div', { id: id_viewer_container }).setStyle({
				position: 'absolute',
				width: this.imgWidth + (lightbox_border * 2) + 'px',
				height: this.imgHeight + (lightbox_border * 2) + 'px',
				marginLeft: Math.floor(this.scrollOffset['left'] + (this.viewport['width'] / 2) - ((this.imgWidth + (lightbox_border * 2)) / 2)) + 'px',
				marginTop: Math.floor(this.scrollOffset['top'] + (this.viewport['height'] / 2) - ((this.imgHeight + (lightbox_border * 2)) / 2)) + 'px'
			});
			$(id_viewer).appendChild(objImgFrame);
			
			var objImg = new Element('img', { id: id_viewer_image, src: this.image.src }).setStyle({
				width: this.imgWidth + 'px',
				height: this.imgHeight + 'px',
				marginLeft: lightbox_border + 'px',
				marginTop: lightbox_border + 'px'
			});
			objImgFrame.appendChild(objImg);
			
			var objTitle = new Element('div', { id: id_viewer_title }).setStyle({
				position: 'absolute',
				display: 'block',
				width: (this.imgWidth - lightbox_border) + 'px',
				height: '0px',
				top: (this.imgHeight + lightbox_border) + 'px',
				left: '0px',
				marginLeft: lightbox_border + 'px',
				marginTop: '0px',
				paddingLeft: (lightbox_border / 2) + 'px',
				paddingRight: (lightbox_border / 2) + 'px',
				lineHeight: lightbox_title_lineheight + 'px',
				opacity: lightbox_title_opacity,
				overflow: 'hidden'
			}).update(this.imgTitle);
			objImgFrame.appendChild(objTitle);
			
			var objClosebox = new Element('div', { id: id_viewer_closebox });
			$(id_viewer).appendChild(objClosebox);
			
			if (this.closePosition == 'left') {
				$(id_viewer_closebox).setStyle({
					marginLeft: Math.floor(this.scrollOffset['left'] + (this.viewport['width'] / 2) - ((this.imgWidth + (lightbox_border * 2)) / 2) - (parseInt($(id_viewer_closebox).getStyle('width')) / 2)) + 'px',
					marginTop: Math.floor(this.scrollOffset['top'] + (this.viewport['height'] / 2) - ((this.imgHeight + (lightbox_border * 2)) / 2) - (parseInt($(id_viewer_closebox).getStyle('height')) / 2)) + 'px'
				});
			} else {
				$(id_viewer_closebox).setStyle({
					marginLeft: Math.floor(this.scrollOffset['left'] + (this.viewport['width'] / 2) + ((this.imgWidth + (lightbox_border * 2)) / 2) - (parseInt($(id_viewer_closebox).getStyle('width')) / 2)) + 'px',
					marginTop: Math.floor(this.scrollOffset['top'] + (this.viewport['height'] / 2) - ((this.imgHeight + (lightbox_border * 2)) / 2) - (parseInt($(id_viewer_closebox).getStyle('height')) / 2)) + 'px'
				});
			}
			
			var objNaviLeft = new Element('div', { id: id_viewer_navi_left });
			$(id_viewer).appendChild(objNaviLeft);
			
			var id_viewer_navi_left_width = parseInt($(id_viewer_navi_left).getStyle('width'));
			var id_viewer_navi_left_height = parseInt($(id_viewer_navi_left).getStyle('height'));
			$(id_viewer_navi_left).setStyle({
				marginLeft: Math.floor(this.scrollOffset['left'] + (this.viewport['width'] / 2)) - id_viewer_navi_left_width + 'px',
				marginTop: Math.floor(this.scrollOffset['top'] + this.viewport['height'] - (this.lightbox_fullSpace / 2) + (((this.lightbox_fullSpace / 2) - id_viewer_navi_left_height) / 2)) + 'px'
			});
			
			var objNaviRight = new Element('div', { id: id_viewer_navi_right });
			$(id_viewer).appendChild(objNaviRight);
			
			var id_viewer_navi_right_width = parseInt($(id_viewer_navi_right).getStyle('width'));
			var id_viewer_navi_right_height = parseInt($(id_viewer_navi_right).getStyle('height'));
			$(id_viewer_navi_right).setStyle({
				marginLeft: Math.floor(this.scrollOffset['left'] + (this.viewport['width'] / 2)) + 'px',
				marginTop: Math.floor(this.scrollOffset['top'] + this.viewport['height'] - (this.lightbox_fullSpace / 2) + (((this.lightbox_fullSpace / 2) - id_viewer_navi_right_height) / 2)) + 'px'
			});
			
			// event listner
			Event.observe(objImg, 'mouseover', new Function('fx_Img_TitleIn', 'window.imgViewer_aniTitle.seekTo(1)'));
			Event.observe(objImg, 'mouseout', new Function('fx_Img_TitleOut', 'window.imgViewer_aniTitle.seekTo(0)'));
			Event.observe(objTitle, 'mouseover', new Function('fx_Title_TitleIn', 'window.imgViewer_aniTitle.seekTo(1)'));
			Event.observe(objTitle, 'mouseout', new Function('fx_Title_TitleOut', 'window.imgViewer_aniTitle.seekTo(0)'));
			Event.observe(objClosebox, 'click', new Function('fx_closeBox', 'myViewer.hide()'));
			Event.observe(objNaviLeft, 'click', new Function('fx_naviLeft', 'myViewer.prev()'));
			Event.observe(objNaviRight, 'click', new Function('fx_naviRight', 'myViewer.next()'));

			// build animations
			this.imgAnimations();
			
			// set firstRun back
			this.firstRun = true;

			// display the first image
			this.show();
		} else {
			this.firstRun = false;
			setTimeout("myViewer.load('"+element+"')",50);
		}
		
	},
	
	next: function() {
		
		// vars
		var positionNext, src, image, imgWidth, imgHeight, imgTitle;
		
		// show img loading
		window.imgViewer_aniProcessing.seekTo(lightbox_processing_opacity);
		
		// next image
		positionNext = this.position + 1;
		if (positionNext >= this.anchors.length) {
			positionNext = 0;
		}
		
		// image title
		if (this.anchors[positionNext].getAttribute('title') != null) {
			this.imgTitle = this.anchors[positionNext].getAttribute('title');
		} else {
			this.imgTitle = this.anchors[positionNext].getAttribute('alt');
		}

		// build image
		src = this.anchors[positionNext].getAttribute('href');
		image = new Image();
		image.src = src;

		if (image.complete === true) {
			
			window.imgViewer_aniImage.seekTo(0);
			window.imgViewer_aniTitle.seekTo(0);

			// check if image is larger then screen
			if ((image.width + this.lightbox_fullSpace) > this.viewport['width']) {
				imgWidth = this.viewport['width'] - this.lightbox_fullSpace;
				imgHeight = (image.height * imgWidth) / image.width;
			} else {
				imgWidth = image.width;
				imgHeight = image.height;
			}

			if ((imgHeight + this.lightbox_fullSpace) > this.viewport['height']) {
				imgWidth = (imgWidth * (this.viewport['height'] - this.lightbox_fullSpace)) / imgHeight;
				imgHeight = this.viewport['height'] - this.lightbox_fullSpace;
			}

			// set title
			$(id_viewer_title).setStyle({
				top: (imgHeight + lightbox_border) + 'px',
				width: (imgWidth - lightbox_border) + 'px'
			}).update(this.imgTitle);;
			
			// hide img loading
			window.imgViewer_aniProcessing.seekTo(0);

			// resize box
			this.resize(image.src, imgWidth, imgHeight);

			// set position
			this.position = positionNext;
		} else {
			setTimeout("myViewer.next()",50);
		}
		
	},
	
	prev: function() {
		
		// vars
		var positionPrev, src, image, imgWidth, imgHeight, imgTitle;
		
		// show img loading
		window.imgViewer_aniProcessing.seekTo(lightbox_overlay_opacity);
		
		// next image
		positionPrev = this.position - 1;
		if (positionPrev < 0) {
			positionPrev = this.anchors.length - 1;
		}
		
		// image title
		if (this.anchors[positionPrev].getAttribute('title') != null) {
			this.imgTitle = this.anchors[positionPrev].getAttribute('title');
		} else {
			this.imgTitle = this.anchors[positionPrev].getAttribute('alt');
		}

		// build image
		src = this.anchors[positionPrev].getAttribute('href');
		image = new Image();
		image.src = src;

		if (image.complete === true) {
			window.imgViewer_aniImage.seekTo(0);
			window.imgViewer_aniTitle.seekTo(0)

			// check if image is larger then screen
			if ((image.width + this.lightbox_fullSpace) > this.viewport['width']) {
				var imgWidth = this.viewport['width'] - this.lightbox_fullSpace;
				var imgHeight = (image.height * imgWidth) / image.width;
			} else {
				var imgWidth = image.width;
				var imgHeight = image.height;
			}

			if ((imgHeight + this.lightbox_fullSpace) > this.viewport['height']) {
				imgWidth = (imgWidth * (this.viewport['height'] - this.lightbox_fullSpace)) / imgHeight;
				imgHeight = this.viewport['height'] - this.lightbox_fullSpace;
			}

			// set title
			$(id_viewer_title).setStyle({
				top: (imgHeight + lightbox_border) + 'px',
				width: (imgWidth - lightbox_border) + 'px'
			}).update(this.imgTitle);;
			
			// hide img loading
			window.imgViewer_aniProcessing.seekTo(0);

			// resize box
			this.resize(image.src, imgWidth, imgHeight);

			// set position
			this.position = positionPrev;
		} else {
			setTimeout("myViewer.prev()",50);
		}
		
	},
	
	show: function() {
		if ($(id_viewer_overlay).style.display == 'block') {
			window.imgViewer_aniViewer.seekTo(1);
			window.imgViewer_aniLoading.seekTo(0);
		} else {
			setTimeout("myViewer.show()",50);
		}
	},
	
	hide: function() {
		window.imgViewer_aniViewer.seekTo(0);
		window.imgViewer_aniOverlay.seekTo(0);
		window.imgViewer_aniProcessing.seekTo(0);
		this.clear();
	},
	
	clear: function() {
		if ($(id_viewer_overlay).style.display == 'none') {
			// removes all child nodes
			while ($(id_viewer).firstChild) {
				$(id_viewer).removeChild($(id_viewer).firstChild);
			}
			window.imgViewer_aniLoading.seekTo(1);
		} else {
			setTimeout("myViewer.clear()",50);
		}
	},
	
	resize: function(img, x, y) {
		if ($(id_viewer_image).style.display == 'none') {
			
			x = parseInt(x);
			y = parseInt(y);
			
			var imgWidth = x + 'px';
			var imgHeight = y + 'px';
			
			var boxWidth = x + (lightbox_border * 2) + 'px';
			var boxHeight = y + (lightbox_border * 2) + 'px';
			
			var marginLeft = Math.floor(this.scrollOffset['left'] + (this.viewport['width'] / 2) - ((x + (lightbox_border * 2)) / 2)) + 'px';
			var marginTop = Math.floor(this.scrollOffset['top'] + (this.viewport['height'] / 2) - ((y + (lightbox_border * 2)) / 2)) + 'px';
			
			if (this.closePosition == 'left') {
				var marginLeftClose = Math.floor(this.scrollOffset['left'] + (this.viewport['width'] / 2) - ((x + (lightbox_border * 2)) / 2)  - (parseInt($(id_viewer_closebox).getStyle('width')) / 2)) + 'px';
			} else {
				var marginLeftClose = Math.floor(this.scrollOffset['left'] + (this.viewport['width'] / 2) + ((x + (lightbox_border * 2)) / 2)  - (parseInt($(id_viewer_closebox).getStyle('width')) / 2)) + 'px';
			}
			var marginTopClose = Math.floor(this.scrollOffset['top'] + (this.viewport['height'] / 2) - ((y + (lightbox_border * 2)) / 2)  - (parseInt($(id_viewer_closebox).getStyle('height')) / 2)) + 'px';

			$(id_viewer_image).setAttribute('src', img);
			$(id_viewer_image).style.width = imgWidth;
			$(id_viewer_image).style.height = imgHeight;

			// resize animation
			this.resizeAnimations(boxWidth, boxHeight, marginLeft, marginTop, marginLeftClose, marginTopClose);
			window.imgViewer_aniResize.seekTo(1);

		} else {
			setTimeout("myViewer.resize('"+img+"', '"+x+"', '"+y+"')",50);
		}
	},

// --- animations (Documentation: http://berniecode.com/writing/animator.html)	
	
	basicAnimations: function() {
		
		// visibilty of the viewer
		window.imgViewer_aniViewer = new Animator({
			duration: 250
		}).addSubject(new NumericalStyleSubject(
		    $(id_viewer), 'opacity', 0, 1)
		).addSubject(this.setVisibilityViewer);
	
		// visibilty of the overlay
		window.imgViewer_aniOverlay = new Animator({
			duration: 250
		}).addSubject(new NumericalStyleSubject(
		    $(id_viewer_overlay), 'opacity', 0, 1)
		).addSubject(this.setVisibiltyOverlay);
	
		// visibility of the loading indicator
		window.imgViewer_aniLoading = new Animator({
			duration: 250
		}).addSubject(new NumericalStyleSubject(
		    $(id_viewer_loading), 'opacity', 0, 1)
		).addSubject(this.setVisibiltyLoading);
		
		// visibility of the img loading indicator
		window.imgViewer_aniProcessing = new Animator({
			duration: 250
		}).addSubject(new NumericalStyleSubject(
		    $(id_viewer_processing), 'opacity', 0, 1)
		).addSubject(this.setVisibiltyProcessing);
	},
	
	resizeAnimations: function(boxWidth, boxHeight, marginLeft, marginTop, marginLeftClose, marginTopClose) {
		window.imgViewer_aniResize = new Animator().addSubject(new CSSStyleSubject(
			$(id_viewer_container), 'width: '+boxWidth+'; height: '+boxHeight+'; margin-left: '+marginLeft+'; margin-top: '+marginTop+';')
		).addSubject(new CSSStyleSubject(
			$(id_viewer_closebox), 'margin-left: '+marginLeftClose+'; margin-top: '+marginTopClose+';')
		).addSubject(this.showImage);
	},
	
	imgAnimations: function() {
		
		// visibilty of the image
		window.imgViewer_aniImage = new Animator({
			duration: 250
		}).addSubject(new NumericalStyleSubject(
		    $(id_viewer_image), 'opacity', 0, 1)
		).addSubject(new NumericalStyleSubject(
			$(id_viewer_navi_left), 'opacity', 0.2, 1)
		).addSubject(new NumericalStyleSubject(
			$(id_viewer_navi_right), 'opacity', 0.2, 1)
		).addSubject(
			this.setVisibiltyImage
		);
		
		// visibilty of the title
		window.imgViewer_aniTitle = new Animator({
			duration: 250
		}).addSubject(	new CSSStyleSubject(
			$(id_viewer_title), 'height: '+lightbox_title_lineheight+'px; margin-top: -'+lightbox_title_lineheight+'px')
		);
		
	},
	
	showImage: function(value) {
		if(value == 1) {
			window.imgViewer_aniImage.seekTo(1);
		}
	},
	
	setVisibilityViewer: function(value) {
		if(value == 0) {
			$(id_viewer).setStyle({ display: 'none' });
		} else {
			$(id_viewer).setStyle({ display: 'block' });
		}
	},
	
	setVisibiltyOverlay: function(value) {
		if(value == 0) {
			$(id_viewer_overlay).setStyle({ display: 'none' });
		} else {
			$(id_viewer_overlay).setStyle({ display: 'block' });
		}
	},
	
	setVisibiltyLoading: function(value) {
		if(value == 0) {
			$(id_viewer_loading).setStyle({ display: 'none' });
		} else {
			$(id_viewer_loading).setStyle({ display: 'block' });
		}
	},
	
	setVisibiltyProcessing: function(value) {
		if(value == 0) {
			$(id_viewer_processing).setStyle({ display: 'none' });
		} else {
			$(id_viewer_processing).setStyle({ display: 'block' });
		}
	},
	
	setVisibiltyImage: function(value) {
		if(value == 0) {
			$(id_viewer_image).setStyle({ display: 'none' });
		} else {
			$(id_viewer_image).setStyle({ display: 'block' });
		}
	}
	
}

// --- END

/******************************************************************************
Name:    Carousel Viewer
Version: 0.8 (March 30 2008)
Author:  Sebastian Brink
Contact: http://www.quadrifolia.de

Licence:
Carousel Viewer is licensed under a Creative Commons Attribution-Noncommercial 
3.0 License (http://creativecommons.org/licenses/by-nc/3.0/).

You are free:
	* to copy, distribute and transmit the work
	* to adapt the work

Under the following conditions:
	* Attribution. You must attribute the work in the manner specified by 
	  the author or licensor.
	* Noncommercial. You may not use this work for commercial purposes.

* For any reuse or distribution, you must make clear to others the license 
  terms of this work. 
* Any of the above conditions can be waived if you get permission from the
  copyright holder.
* Nothing in this license impairs or restricts the author's moral rights.

Your fair dealing and other rights are in no way affected by the above.
******************************************************************************/

// --- nomenclature

var id_carousel = 						'carousel';
var id_carousel_item_title = 			'carousel_itemTitle';
var id_carousel_navi = 					'carousel_navi';
var id_carousel_navi_play = 			'carousel_naviPlay';
var id_carousel_list_item_prefix = 		'carousel_posItem_';
var id_carousel_image_prefix = 			'carousel_posImage_';
var id_carousel_reflection_prefix = 	'carousel_posReflection_';

var class_carousel_list = 				'carousel_list';
var class_carousel_list_item = 			'carousel_item';
var class_carousel_navi_play = 			'icon_play';
var class_carousel_navi_pause =			'icon_pause';
var class_carousel_navi_left =			'icon_left';
var class_carousel_navi_fastLeft =		'icon_fastLeft';
var class_carousel_navi_center =		'icon_center';
var class_carousel_navi_right = 		'icon_right';
var class_carousel_navi_fastRight = 	'icon_fastRight';

var class_opacity_100 = 				'opacity_100';
var class_opacity_30 = 					'opacity_30';
var class_opacity_15 = 					'opacity_15';
var class_opacity_0 = 					'opacity_0';

var folder_content = 					'content/';
var folder_cache = 						'cache/';
var file_reflection_prefix = 			'reflect_';

// --- class

Carousel = Class.create();

Carousel.prototype = {
	
	initialize: function(wrapper, options) {
		
		var carousel = this;
		
		this.wrapper = wrapper;
		
		// options
		this.options = options || {};
		this.animationTime = this.options.animationTime;
		this.waitTime = this.options.waitTime;
		this.fastAnimationTime = this.options.fastAnimationTime;
		this.fastWaitTime = this.options.fastWaitTime;
		this.saveTime = this.options.saveTime;
		this.displayTitle = this.options.displayTitle;
		this.carouselWidth = this.options.carouselWidth;
		this.carouselHeight = this.options.carouselHeight;
		this.reflectionHeight = this.options.reflectionHeight;
		this.reflectionTopMargin = this.options.reflectionTopMargin;
		this.imgSourceType = this.options.imgSourceType;
		this.imgSource = this.options.imgSource;
		
		// vars
		this.position = 0;
		this.elements = 0;
		this.imgArray = [];
		this.animationRunning = false;
		this.breakGoto = false;
		this.activeNavigation = true;
		this.direction = '';
		this.oldAnimationTime = this.animationTime;
		this.oldWaitTime = this.waitTime;
		this.timestamp = new Date().getTime();

		this.initialized = true;
		
		this.build();
		
	},
	
	build: function() {
		
		// vars
		var complete = 0;
		
		// get the content
		if (this.imgSourceType == 'href') {
			
			// vars
			var items = $(this.imgSource).getElementsByTagName('a');

			// set elements counter
			this.elements = items.length;
			
			// build array
			for (var i=0, j=items.length; i<j; i+=1) {
				this.imgArray[i] = new Image();
				this.imgArray[i].src = items[i].firstChild.getAttribute('src');
				this.imgArray[i].reflection = items[i].firstChild.getAttribute('src').replace('output=img','output=refl');
				this.imgArray[i].href = items[i].href;
				this.imgArray[i].title = items[i].title;

				if (this.imgArray[i].complete === true) {
					complete += 1;
				}
			}
			
		} else if (this.imgSourceType == 'array') {
			
			// set elements counter
			this.elements = this.imgSource.length;
			
			// img array
			this.imgArray = this.imgSource;
			
			// check if images are fully loaded
			for (var i=0, j=this.elements; i<j; i+=1) {
				if (this.imgArray[i].complete === true) {
					complete += 1;
				}
			}

		}
		
		// build elements
		if(!$(id_carousel)) {
			
			var objCarousel = new Element('div', { id: id_carousel }).setStyle({
				position: 'absolute',
				width: this.carouselWidth + 'px',
				height: this.carouselHeight + 'px',
				left: '0px',
				top: '0px'
			});
			$(this.wrapper).appendChild(objCarousel);	
			
		} else {
			clearContent(id_carousel);
			var objCarousel = $(id_carousel);
		}
		
		var objCarouselPlayButton = new Element('div', { 'class': class_carousel_navi_play, id: id_carousel_navi_play });
		objCarousel.appendChild(objCarouselPlayButton);
		
		var objCarouselImgTitle = new Element('div', { id: id_carousel_item_title });
		objCarousel.appendChild(objCarouselImgTitle);
		
		var objCarouselList = new Element('ul', { 'class': class_carousel_list });
		objCarousel.appendChild(objCarouselList);
		
		var objCarouselIcon = new Element('div', { id: id_carousel_navi }).setStyle({
			backgroundColor: 'transparent',
			backgroundRepeat: 'no-repeat',
			backgroundPosition: 'top left'
		});
		objCarousel.appendChild(objCarouselIcon);
		
		Event.observe(objCarouselPlayButton, 'mousedown', this.play.bindAsEventListener(this));
		Event.observe(objCarouselIcon, 'mousedown', this.click.bindAsEventListener(this));
		Event.observe(objCarouselIcon, 'mousemove', this.iconHover.bindAsEventListener(this));
		
		// write carousel content
		if(complete == this.elements) {
			for (var i=0, j=this.imgArray.length; i<j; i+=1) {
				
				// calculate image sizes
				var itemWidth = this.imgArray[i].width;
				var itemHeight = this.imgArray[i].height + this.reflectionHeight + this.reflectionTopMargin;

				var maxWidth = (this.carouselWidth / 10) * 4;
				var maxHeight = (maxWidth * itemHeight) / itemWidth;

				if (maxHeight > this.carouselHeight) {
					maxWidth = (maxWidth * this.carouselHeight) / maxHeight;
					maxHeight = this.carouselHeight;
				}

				var factor = maxHeight / itemHeight;

				this.imgArray[i].maxWidth = maxWidth;
				this.imgArray[i].maxHeight = maxHeight;
				this.imgArray[i].factor = factor;

				// set title
				if ((i == 0) && (this.displayTitle === true)) {
					$(id_carousel_item_title).setStyle({
						width: (maxWidth - 10) + 'px',
						height: '30px',
						lineHeight: '30px',
						marginTop: (this.imgArray[i].height * factor) + ((this.carouselHeight - maxHeight) / 2) + 'px',
						marginLeft: ((this.carouselWidth / 10) * 3) + Math.floor((((this.carouselWidth / 10) * 4) - maxWidth) / 2) + 5 + 'px'
					});
					var textTitle = document.createTextNode(this.imgArray[i].title);
					$(id_carousel_item_title).appendChild(textTitle);
				}
				
				// build carousel content
				if (i == 0) {
					
					var objCarouselListItem = new Element('li', { 'class': (class_carousel_list_item + ' ' + class_opacity_100), id: (id_carousel_list_item_prefix + i) }).setStyle({
						width: ((this.carouselWidth / 10) * 4) + 'px',
						height: maxHeight + 'px',
						marginTop: ((this.carouselHeight - maxHeight) / 2) + 'px',
						marginLeft: ((this.carouselWidth / 10) * 3) + Math.floor((((this.carouselWidth / 10) * 4) - maxWidth) / 2) + 'px',
						opacity: 1.0
					});
					objCarouselList.appendChild(objCarouselListItem);
					
					var objCarouselLink = new Element('a', { 'class': (lightbox_marker + '_' + this.timestamp), href: this.imgArray[i].href, alt: this.imgArray[i].title });
					objCarouselListItem.appendChild(objCarouselLink);
					objCarouselLink.onclick = function() {return false;};
					
					var objCarouselImg = new Element('img', { src: this.imgArray[i].src, id: (id_carousel_image_prefix + i) }).setStyle({
						width: maxWidth + 'px',
						height: (this.imgArray[i].height * factor) + 'px'
					});
					objCarouselLink.appendChild(objCarouselImg);
					
					var objCarouselReflection = new Element('img', { src: this.imgArray[i].reflection, id: (id_carousel_reflection_prefix + i) }).setStyle({
						width: maxWidth + 'px',
						height: (this.reflectionHeight * factor) + 'px',
						marginTop: this.reflectionTopMargin + 'px'
					});
					objCarouselListItem.appendChild(objCarouselReflection);

				} else if (i == (1)) {
					
					var objCarouselListItem = new Element('li', { 'class': (class_carousel_list_item + ' ' + class_opacity_30), id: (id_carousel_list_item_prefix + i) }).setStyle({
						width: ((this.carouselWidth / 10) * 2) + 'px',
						height: (maxHeight / 2) + 'px',
						marginTop: ((this.carouselHeight - (maxHeight / 2)) / 2) + 'px',
						marginLeft: (this.carouselWidth / 10) + Math.floor((((this.carouselWidth / 10) * 2) - (maxWidth / 2)) / 2) + 'px',
						opacity: 0.3
					});
					objCarouselList.appendChild(objCarouselListItem);
					
					var objCarouselLink = new Element('a', { 'class': (lightbox_marker + '_' + this.timestamp), href: this.imgArray[i].href, alt: this.imgArray[i].title });
					objCarouselListItem.appendChild(objCarouselLink);
					objCarouselLink.onclick = function() {return false;};
					
					var objCarouselImg = new Element('img', { src: this.imgArray[i].src, id: (id_carousel_image_prefix + i) }).setStyle({
						width: (maxWidth / 2) + 'px',
						height: ((this.imgArray[i].height * factor) / 2) + 'px'
					});
					objCarouselLink.appendChild(objCarouselImg);
					
					var objCarouselReflection = new Element('img', { src: this.imgArray[i].reflection, id: (id_carousel_reflection_prefix + i) }).setStyle({
						width: (maxWidth / 2) + 'px',
						height: ((this.reflectionHeight * factor) / 2) + 'px',
						marginTop: this.reflectionTopMargin + 'px'
					});
					objCarouselListItem.appendChild(objCarouselReflection);

				} else if (i == (2)) {
					
					var objCarouselListItem = new Element('li', { 'class': (class_carousel_list_item + ' ' + class_opacity_15), id: (id_carousel_list_item_prefix + i) }).setStyle({
						width: (this.carouselWidth / 10) + 'px',
						height: (maxHeight / 4) + 'px',
						marginTop: ((this.carouselHeight - (maxHeight / 4)) / 2) + 'px',
						marginLeft:  Math.floor(((this.carouselWidth / 10) - (maxWidth / 4)) / 2) + 'px',
						opacity: 0.15
					});
					objCarouselList.appendChild(objCarouselListItem);
					
					var objCarouselLink = new Element('a', { 'class': (lightbox_marker + '_' + this.timestamp), href: this.imgArray[i].href, alt: this.imgArray[i].title });
					objCarouselListItem.appendChild(objCarouselLink);
					objCarouselLink.onclick = function() {return false;};
					
					var objCarouselImg = new Element('img', { src: this.imgArray[i].src, id: (id_carousel_image_prefix + i) }).setStyle({
						width: (maxWidth / 4) + 'px',
						height: ((this.imgArray[i].height * factor) / 4) + 'px'
					});
					objCarouselLink.appendChild(objCarouselImg);
					
					var objCarouselReflection = new Element('img', { src: this.imgArray[i].reflection, id: (id_carousel_reflection_prefix + i) }).setStyle({
						width: (maxWidth / 4) + 'px',
						height: ((this.reflectionHeight * factor) / 4) + 'px',
						marginTop: this.reflectionTopMargin + 'px'
					});
					objCarouselListItem.appendChild(objCarouselReflection);

				} else {
					
					var objCarouselListItem = new Element('li', { 'class': (class_carousel_list_item + ' ' + class_opacity_0), id: (id_carousel_list_item_prefix + i) }).setStyle({
						width: '0px',
						height: '0px',
						marginTop: (this.carouselHeight / 2) + 'px',
						marginLeft: '0px',
						opacity: 0.0
					});
					objCarouselList.appendChild(objCarouselListItem);
					
					var objCarouselLink = new Element('a', { 'class': (lightbox_marker + '_' + this.timestamp), href: this.imgArray[i].href, alt: this.imgArray[i].title });
					objCarouselListItem.appendChild(objCarouselLink);
					objCarouselLink.onclick = function() {return false;};
					
					var objCarouselImg = new Element('img', { src: this.imgArray[i].src, id: (id_carousel_image_prefix + i) }).setStyle({
						width: '0px',
						height: '0px'
					});
					objCarouselLink.appendChild(objCarouselImg);
					
					var objCarouselReflection = new Element('img', { src: this.imgArray[i].reflection, id: (id_carousel_reflection_prefix + i) }).setStyle({
						width: '0px',
						height: '0px',
						marginTop: '0px'
					});
					objCarouselListItem.appendChild(objCarouselReflection);

				}
				
				// set event listner
				Event.observe(objCarouselListItem, 'mousemove', this.iconHover.bindAsEventListener(this));
				Event.observe(objCarouselListItem, 'mouseout', this.iconHide.bindAsEventListener(this));
				Event.observe(objCarouselLink, 'mousedown', this.click.bindAsEventListener(this));
				
			}
			
			// initialize the viewer
			myViewer = new imgViewer({
				marker: lightbox_marker + '_' + this.timestamp,
				close: lightbox_close,
				listner: false
			});
			
			// add some empty values for the animation
			this.imgArray[this.elements] = 0;
			this.imgArray[this.elements+1] = 0;
			this.imgArray[this.elements+2] = 0;
			this.imgArray[this.elements+3] = 0;
			this.imgArray[-1] = 0;
			this.imgArray[-2] = 0;
			this.imgArray[-3] = 0;

			// create animation effects
			this.buildAnimations();
			
		} else {
			setTimeout('myCarousel.build()',250);
		}
	},
	
	// -------------------------------------------------------------------------------------------------------
	// NAVIGATION
	// -------------------------------------------------------------------------------------------------------
	
	// play button
	play: function() {
		if (this.activeNavigation === true) {
			if (this.animationRunning === false) {
				if (this.position < this.elements-1) {
					this.doAnimation('forward');
				} else {
					this.doAnimation('backward');
				}
			} else {
				this.stopAnimation();
				this.breakGoto = true;
			}
		}
	},
	
	// play button status
	switchPlayButton: function(state) {
		if (state == 'play') {
			$(id_carousel_navi_play).className = class_carousel_navi_play;
		} else if (state == 'pause') {
			$(id_carousel_navi_play).className = class_carousel_navi_pause;
		}
	},
	
	// carousel items
	click: function(e) {
		
		e = e || window.event;
		Event.stop(e); // doesn't work in safai 2.0.3

		if (this.activeNavigation === true) {
			if (this.animationRunning === true) {
				this.stopAnimation();
			}

			var mouseX = this.getMouseX(e);
			var offset = $(id_carousel).viewportOffset();
			var mousePosition = mouseX-offset[0];

			if (mousePosition < (this.carouselWidth/10)) {
				this.gotoPosition(this.position+2, 'start');
			} else if (mousePosition < ((this.carouselWidth/10) * 3)) {
				this.moveForward();
			} else if (mousePosition < ((this.carouselWidth/10) * 7)) {
				myViewer.load($(id_carousel_list_item_prefix+this.position).firstChild);
			} else if (mousePosition < ((this.carouselWidth/10) * 9)) {
				this.moveBackward();
			} else {
				this.gotoPosition(this.position-2, 'start');
			}
			
		}
		
	},
	
	// carousel icons
	iconHover: function(e) {
		if (this.animationRunning === false) {
			
			e = e || window.event;
			
			var mouseX = this.getMouseX(e);
			var offset = $(id_carousel).viewportOffset();
			var mousePosition = mouseX - offset[0];
			var maxWidth = (this.carouselWidth / 10) * 4;
			var iconHeight = parseInt(Element.getStyle(id_carousel_navi, 'height'));
			var iconWidth = parseInt(Element.getStyle(id_carousel_navi, 'width'));

			if (mousePosition < (this.carouselWidth/10)) {
				if (this.position < this.elements-2) {
					$(id_carousel_navi).className = class_carousel_navi_fastLeft;
					$(id_carousel_navi).setStyle({
						marginTop: (this.carouselHeight / 2) - (((this.reflectionHeight * this.imgArray[this.position+2].factor) / 8) + (iconHeight / 2)) + 'px',
						marginLeft: (maxWidth / 8) - (iconWidth / 2) + 'px',
						display: 'block'
					});
				}
			} else if (mousePosition < ((this.carouselWidth/10) * 3)) {
				if (this.position < this.elements-1) {
					$(id_carousel_navi).className = class_carousel_navi_left;
					$(id_carousel_navi).setStyle({
						marginTop: (this.carouselHeight / 2) - (((this.reflectionHeight * this.imgArray[this.position+1].factor) / 4) + (iconHeight / 2)) + 'px',
						marginLeft: ((this.carouselWidth/10) * 3) - (maxWidth / 4) - (iconWidth / 2) + 'px',
						display: 'block'
					});
				}
			} else if (mousePosition < ((this.carouselWidth/10) * 7)) {
				$(id_carousel_navi).className = class_carousel_navi_center;
				$(id_carousel_navi).setStyle({
					marginTop: (this.carouselHeight / 2) - (((this.reflectionHeight * this.imgArray[this.position].factor) / 2) + (iconHeight / 2)) + 'px',
					marginLeft: ((this.carouselWidth/10) * 7) - (maxWidth / 2) - (iconWidth / 2) + 'px',
					display: 'block'
				});
			} else if (mousePosition < ((this.carouselWidth/10) * 9)) {
				if (this.position > 0) {
					$(id_carousel_navi).className = class_carousel_navi_right;
					$(id_carousel_navi).setStyle({
						marginTop: (this.carouselHeight / 2) - (((this.reflectionHeight * this.imgArray[this.position-1].factor) / 4) + (iconHeight / 2)) + 'px',
						marginLeft: ((this.carouselWidth/10) * 9) - (maxWidth / 4) - (iconWidth / 2) + 'px',
						display: 'block'
					});
				}
			} else {
				if (this.position > 1) {
					$(id_carousel_navi).className = class_carousel_navi_fastRight;
					$(id_carousel_navi).setStyle({
						marginTop: (this.carouselHeight / 2) - (((this.reflectionHeight * this.imgArray[this.position-2].factor) / 8) + (iconHeight / 2)) + 'px',
						marginLeft: this.carouselWidth - (maxWidth / 8) - (iconWidth / 2) + 'px',
						display: 'block'
					});
				}
			}
		}
	},
	
	iconHide: function() {
		$(id_carousel_navi).setStyle({
			display: 'none'
		});
	},

	// activate navigation
	activateNavigation: function() {
		this.activeNavigation = true;
		window.aniCarouselPlayButton.seekTo(1);
	},

	// deactivate navigation
	deactivateNavigation: function() {
		this.activeNavigation = false;
		window.aniCarouselPlayButton.seekTo(0.6);
	},
	
	getMouseX: function(e){
		
		e = e || window.event;
		
		var posX = 0;
		
		if (e.pageX != undefined) {
			posX = e.pageX;
		} else if (e.clientX != undefined) {
			posX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		}
		return posX;
	},
	
	// -------------------------------------------------------------------------------------------------------
	// TITLE
	// -------------------------------------------------------------------------------------------------------
	
	// hide image title
	aniImgTitle: function(action, speed) {
		if (speed == 'normal') {
			window.aniCarouselImgTitle.seekTo(0);
		} else {
			window.aniCarouselImgTitleFast.seekTo(0);
		}
		setTimeout('myCarousel.updateImgTitle("'+action+'","'+speed+'")', (this.animationTime+this.saveTime));
	},
	
	// change and display image title
	updateImgTitle: function(action, speed) {
		if (action == 'forward') {
			
			$(id_carousel_item_title).setStyle({
				width: this.imgArray[this.position+1].maxWidth - 10 + 'px',
				height: '30px',
				lineHeight: '30px',
				marginTop: (this.imgArray[this.position+1].height * this.imgArray[this.position+1].factor) + ((this.carouselHeight - this.imgArray[this.position+1].maxHeight) / 2) + 'px',
				marginLeft: ((this.carouselWidth / 10) * 3) + Math.floor((((this.carouselWidth / 10) * 4) - this.imgArray[this.position+1].maxWidth) / 2) + 5 + 'px'
			});

			while ($(id_carousel_item_title).firstChild) {
				$(id_carousel_item_title).removeChild($(id_carousel_item_title).firstChild);
			}

			var textTitle = document.createTextNode(this.imgArray[this.position+1].title);
			$(id_carousel_item_title).appendChild(textTitle);

		} else if (action == 'backward') {
			
			$(id_carousel_item_title).setStyle({
				width: this.imgArray[this.position-1].maxWidth - 10 + 'px',
				height: '30px',
				lineHeight: '30px',
				marginTop: (this.imgArray[this.position-1].height * this.imgArray[this.position-1].factor) + ((this.carouselHeight - this.imgArray[this.position-1].maxHeight) / 2) + 'px',
				marginLeft: ((this.carouselWidth / 10) * 3) + Math.floor((((this.carouselWidth / 10) * 4) - this.imgArray[this.position-1].maxWidth) / 2) + 5 + 'px'
			});

			while ($(id_carousel_item_title).firstChild) {
				$(id_carousel_item_title).removeChild($(id_carousel_item_title).firstChild);
			}

			var textTitle = document.createTextNode(this.imgArray[this.position-1].title);
			$(id_carousel_item_title).appendChild(textTitle);

		}

		if (speed == 'normal') {
			window.aniCarouselImgTitle.seekTo(1);
		} else {
			window.aniCarouselImgTitleFast.seekTo(1);
		}
	},
	
	// -------------------------------------------------------------------------------------------------------
	// ANIMATION
	// -------------------------------------------------------------------------------------------------------
	
	buildAnimations: function() {
		
		// rotate forward
		window.rotateForward = new Animator({
			duration: this.animationTime
		}
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+(this.position+3)), 'position: absolute; height: '+(this.imgArray[this.position+3].maxHeight / 4)+'px; width: '+(this.carouselWidth / 10)+'px; margin-top: '+((this.carouselHeight-(this.imgArray[this.position+3].maxHeight / 4))/2)+'px; margin-left: '+Math.floor(0 + (((this.carouselWidth / 10) - (this.imgArray[this.position+3].maxWidth / 4)) / 2))+'px; opacity: 0.15;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position+3)), 'height: '+((this.imgArray[this.position+3].height * this.imgArray[this.position+3].factor) / 4)+'px; width: '+(this.imgArray[this.position+3].maxWidth / 4)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_reflection_prefix+(this.position+3)), 'height: '+((this.reflectionHeight * this.imgArray[this.position+3].factor) / 4)+'px; margin-top: '+this.reflectionTopMargin+'px; width: '+(this.imgArray[this.position+3].maxWidth / 4)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+(this.position+2)), 'position: absolute; height: '+(this.imgArray[this.position+2].maxHeight / 2)+'px; width: '+((this.carouselWidth / 10) * 2)+'px; margin-top: '+((this.carouselHeight-(this.imgArray[this.position+2].maxHeight / 2))/2)+'px; margin-left: '+Math.floor((this.carouselWidth / 10) + ((((this.carouselWidth / 10) * 2) - (this.imgArray[this.position+2].maxWidth / 2)) / 2))+'px; opacity: 0.3;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position+2)), 'height: '+((this.imgArray[this.position+2].height * this.imgArray[this.position+2].factor) / 2)+'px; width: '+(this.imgArray[this.position+2].maxWidth / 2)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_reflection_prefix+(this.position+2)), 'height: '+((this.reflectionHeight * this.imgArray[this.position+2].factor) / 2)+'px; margin-top: '+this.reflectionTopMargin+'px; width: '+(this.imgArray[this.position+2].maxWidth / 2)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+(this.position+1)), 'position: absolute; height: '+this.imgArray[this.position+1].maxHeight+'px; width: '+((this.carouselWidth / 10) * 4)+'px; margin-top: '+((this.carouselHeight-this.imgArray[this.position+1].maxHeight)/2)+'px; margin-left: '+Math.floor(((this.carouselWidth / 10) * 3) + ((((this.carouselWidth / 10) * 4) - (this.imgArray[this.position+1].maxWidth)) / 2))+'px; opacity: 1.0;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position+1)), 'height: '+(this.imgArray[this.position+1].height * this.imgArray[this.position+1].factor)+'px; width: '+(this.imgArray[this.position+1].maxWidth)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_reflection_prefix+(this.position+1)), 'height: '+(this.reflectionHeight * this.imgArray[this.position+1].factor)+'px; margin-top: '+this.reflectionTopMargin+'px; width: '+(this.imgArray[this.position+1].maxWidth)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+this.position), 'position: absolute; height: '+(this.imgArray[this.position].maxHeight / 2)+'px; width: '+((this.carouselWidth / 10) * 2)+'px; margin-top: '+((this.carouselHeight-(this.imgArray[this.position].maxHeight / 2))/2)+'px; margin-left: '+Math.floor(((this.carouselWidth / 10) * 7) + ((((this.carouselWidth / 10) * 2) - (this.imgArray[this.position].maxWidth / 2)) / 2))+'px; opacity: 0.3;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position)), 'height: '+((this.imgArray[this.position].height * this.imgArray[this.position].factor) / 2)+'px; width: '+(this.imgArray[this.position].maxWidth / 2)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_reflection_prefix+(this.position)), 'height: '+((this.reflectionHeight * this.imgArray[this.position].factor) / 2)+'px; margin-top: '+this.reflectionTopMargin+'px; width: '+(this.imgArray[this.position].maxWidth / 2)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+(this.position-1)), 'position: absolute; height: '+(this.imgArray[this.position-1].maxHeight / 4)+'px; width: '+(this.carouselWidth / 10)+'px; margin-top: '+((this.carouselHeight-(this.imgArray[this.position-1].maxHeight / 4))/2)+'px; margin-left: '+Math.floor(((this.carouselWidth / 10) * 9) + (((this.carouselWidth / 10) - (this.imgArray[this.position-1].maxWidth / 4)) / 2))+'px; opacity: 0.15;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position-1)), 'height: '+((this.imgArray[this.position-1].height * this.imgArray[this.position-1].factor) / 4)+'px; width: '+(this.imgArray[this.position-1].maxWidth / 4)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_reflection_prefix+(this.position-1)), 'height: '+((this.reflectionHeight * this.imgArray[this.position-1].factor) / 4)+'px; margin-top: '+this.reflectionTopMargin+'px; width: '+(this.imgArray[this.position-1].maxWidth / 4)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+(this.position-2)), 'position: absolute; height: 0px; width: 0px; margin-top: '+(this.carouselHeight / 2)+'px; margin-left: '+this.carouselWidth+'px; opacity: 0.0;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position-2)), 'height: 0px; width: 0px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_reflection_prefix+(this.position-2)), 'height: 0px; margin-top: 0px; width: 0px;')
		);
		
		// rotate backward
		window.rotateBackward = new Animator({
			duration: this.animationTime
		}
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+(this.position+2)), 'position: absolute; height: 0px; width: 0px; margin-top: '+(this.carouselHeight / 2)+'px; margin-left: 0px; opacity: 0.0;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position+2)), 'height: 0px; width: 0px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_reflection_prefix+(this.position+2)), 'height: 0px; margin-top: 0px; width: 0px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+(this.position+1)), 'position: absolute; height: '+(this.imgArray[this.position+1].maxHeight / 4)+'px; width: '+(this.carouselWidth / 10)+'px; margin-top: '+((this.carouselHeight-(this.imgArray[this.position+1].maxHeight / 4))/2)+'px; margin-left: '+Math.floor(0 + (((this.carouselWidth / 10) - (this.imgArray[this.position+1].maxWidth / 4)) / 2))+'px; opacity: 0.15;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position+1)), 'height: '+((this.imgArray[this.position+1].height * this.imgArray[this.position+1].factor) / 4)+'px; width: '+(this.imgArray[this.position+1].maxWidth / 4)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_reflection_prefix+(this.position+1)), 'height: '+((this.reflectionHeight * this.imgArray[this.position+1].factor) / 4)+'px; margin-top: '+this.reflectionTopMargin+'px; width: '+(this.imgArray[this.position+1].maxWidth / 4)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+this.position), 'position: absolute; height: '+(this.imgArray[this.position].maxHeight / 2)+'px; width: '+((this.carouselWidth / 10) * 2)+'px; margin-top: '+((this.carouselHeight-(this.imgArray[this.position].maxHeight / 2))/2)+'px; margin-left: '+Math.floor((this.carouselWidth / 10) + ((((this.carouselWidth / 10) * 2) - (this.imgArray[this.position].maxWidth / 2)) / 2))+'px; opacity: 0.3;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position)), 'height: '+((this.imgArray[this.position].height * this.imgArray[this.position].factor) / 2)+'px; width: '+(this.imgArray[this.position].maxWidth / 2)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_reflection_prefix+(this.position)), 'height: '+((this.reflectionHeight * this.imgArray[this.position].factor) / 2)+'px; margin-top: '+this.reflectionTopMargin+'px; width: '+(this.imgArray[this.position].maxWidth / 2)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+(this.position-1)), 'position: absolute; height: '+this.imgArray[this.position-1].maxHeight+'px; width: '+((this.carouselWidth / 10) * 4)+'px; margin-top: '+((this.carouselHeight-this.imgArray[this.position-1].maxHeight)/2)+'px; margin-left: '+Math.floor(((this.carouselWidth / 10) * 3) + ((((this.carouselWidth / 10) * 4) - (this.imgArray[this.position-1].maxWidth)) / 2))+'px; opacity: 1.00;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position-1)), 'height: '+((this.imgArray[this.position-1].height * this.imgArray[this.position-1].factor))+'px; width: '+(this.imgArray[this.position-1].maxWidth)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_reflection_prefix+(this.position-1)), 'height: '+(this.reflectionHeight * this.imgArray[this.position-1].factor)+'px; margin-top: '+this.reflectionTopMargin+'px; width: '+(this.imgArray[this.position-1].maxWidth)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+(this.position-2)), 'position: absolute; height: '+(this.imgArray[this.position-2].maxHeight / 2)+'px; width: '+((this.carouselWidth / 10) * 2)+'px; margin-top: '+((this.carouselHeight-(this.imgArray[this.position-2].maxHeight / 2))/2)+'px; margin-left: '+Math.floor(((this.carouselWidth / 10) * 7) + ((((this.carouselWidth / 10) * 2) - (this.imgArray[this.position-2].maxWidth / 2)) / 2))+'px; opacity: 0.3;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_image_prefix+(this.position-2)), 'height: '+((this.imgArray[this.position-2].height * this.imgArray[this.position-2].factor) / 2)+'px; width: '+(this.imgArray[this.position-2].maxWidth / 2)+'px;')
		).addSubject(new CSSStyleSubject(	
			$(id_carousel_reflection_prefix+(this.position-2)), 'height: '+((this.reflectionHeight * this.imgArray[this.position-2].factor) / 2)+'px; margin-top: '+this.reflectionTopMargin+'px; width: '+(this.imgArray[this.position-2].maxWidth / 2)+'px;')
		).addSubject(new CSSStyleSubject(
			$(id_carousel_list_item_prefix+(this.position-3)), 'position: absolute; height: '+(this.imgArray[this.position-3].maxHeight / 4)+'px; width: '+(this.carouselWidth / 10)+'px; margin-top: '+((this.carouselHeight-(this.imgArray[this.position-3].maxHeight / 4))/2)+'px; margin-left: '+Math.floor(((this.carouselWidth / 10) * 9) + (((this.carouselWidth / 10) - (this.imgArray[this.position-3].maxWidth / 4)) / 2))+'px; opacity: 0.15;')
		).addSubject(new CSSStyleSubject(	
			$(id_carousel_image_prefix+(this.position-3)), 'height: '+((this.imgArray[this.position-3].height * this.imgArray[this.position-3].factor) / 4)+'px; width: '+(this.imgArray[this.position-3].maxWidth / 4)+'px;')
		).addSubject(new CSSStyleSubject(	
			$(id_carousel_reflection_prefix+(this.position-3)), 'height: '+((this.reflectionHeight * this.imgArray[this.position-3].factor) / 4)+'px; margin-top: '+this.reflectionTopMargin+'px; width: '+(this.imgArray[this.position-3].maxWidth / 4)+'px;')
		);
		
		// image title animation
		window.aniCarouselImgTitle = new Animator({
			duration: (this.animationTime / 2)
		}).addSubject(new NumericalStyleSubject(
		    $(id_carousel_item_title), 'opacity', 0, 1)
		);
	
		window.aniCarouselImgTitleFast = new Animator({
			duration: 50
		}).addSubject(new NumericalStyleSubject(
		    $(id_carousel_item_title), 'opacity', 0, 1)
		);
		
		// play button animation
		window.aniCarouselPlayButton = new Animator({
			duration: 50
		}).addSubject(new NumericalStyleSubject(
		    $(id_carousel_navi_play), 'opacity', 0, 1)
		);
		
	},
	
	// build the new animations for the next step
	update: function(action) {
		if (action == 'forward') {	
			this.position+=1;
		} else if (action == 'backward') {
			this.position-=1;
		}
		this.buildAnimations();
	},
	
	// animates the carousel forward or backward
	doAnimation: function(action) {
		if (this.animationRunning === false) {
			this.animationRunning = true;
			this.switchPlayButton('pause');
		}

		if (action == 'forward') {
			window.rotateForward.seekTo(1);
			this.aniImgTitle('forward', 'normal');
			setTimeout('myCarousel.update("forward")', this.animationTime+this.saveTime);
			if (this.position < this.elements-2) {
				this.animation = setTimeout('myCarousel.doAnimation("forward")', this.animationTime+this.waitTime+this.saveTime);
			} else {
				this.stopAnimation();
			}
		} else if (action == 'backward') {
			window.rotateBackward.seekTo(1);
			this.aniImgTitle('backward', 'normal');
			setTimeout('myCarousel.update("backward")', this.animationTime+this.saveTime);
			if (this.position > 1) {
				this.animation = setTimeout('myCarousel.doAnimation("backward")', this.animationTime+this.waitTime+this.saveTime);
			} else {
				this.stopAnimation();
			}
		}
	},
	
	// stops the animation
	stopAnimation: function() {
		this.animationRunning = false;
		clearTimeout(this.animation);
		setTimeout('myCarousel.switchPlayButton("play")', this.animationTime+this.saveTime);
	},
	
	// move the carousel one step forward
	moveForward: function() {
		if (this.animationRunning === true) {
			this.stopAnimation();
		}
		this.deactivateNavigation();
		this.iconHide();
		window.rotateForward.seekTo(1);
		this.aniImgTitle('forward', 'normal');
		setTimeout('myCarousel.update("forward")', this.animationTime+this.saveTime);
		setTimeout('myCarousel.activateNavigation()', this.animationTime+this.saveTime);
	},
	
	// move the carousel on step backward
	moveBackward: function() {
		if (this.animationRunning === true) {
			this.stopAnimation();
		}
		this.deactivateNavigation();
		this.iconHide();
		window.rotateBackward.seekTo(1);
		this.aniImgTitle('backward', 'normal');
		setTimeout('myCarousel.update("backward")', this.animationTime+this.saveTime);
		setTimeout('myCarousel.activateNavigation()', this.animationTime+this.saveTime);
	},
	
	// fast animation to position
	gotoPosition: function(targetPosition, status) {

		if (status == 'start') {

			if (this.animationRunning === false) {

				// deactivate navigation
				this.deactivateNavigation();

				// set times
				this.oldAnimationTime = this.animationTime;
				this.oldWaitTime = this.waitTime;
				this.animationTime = this.fastAnimationTime;
				this.waitTime = this.fastWaitTime;

				// build fast animations
				this.buildAnimations();

				// direction
				if(targetPosition < 0) {
					targetPosition = 0;
				}

				if(targetPosition > this.imgArray.length-5) {
					targetPosition = this.imgArray.length-5;
				}

				if(targetPosition > this.position) {
					direction = 'forward';
					this.animationRunning = true;
				} else if (targetPosition < this.position) {
					direction = 'backward';
					this.animationRunning = true;
				} else {
					this.animationTime = this.oldAnimationTime;
					this.waitTime = this.oldWaitTime;
					this.buildAnimations();
					this.activateNavigation();
					return false;
				}

			} else {

				// direction
				if(targetPosition < 0) {
					targetPosition = 0;
				}

				if(targetPosition > imgArray.length-5) {
					targetPosition = imgArray.length-5;
				}

				if(targetPosition > position) {
					direction = 'forward';
					this.breakGoto = true;
				} else if (targetPosition < position) {
					direction = 'backward';
					this.breakGoto = true;
				} else {
					this.breakGoto = true;
				}

			}

		}

		if (direction == 'forward') {
			window.rotateForward.seekTo(1);
			this.aniImgTitle('forward', 'fast');
			setTimeout('myCarousel.updateGoto("forward", '+ targetPosition +')', this.animationTime+this.saveTime);
		} else if (direction == 'backward') {
			window.rotateBackward.seekTo(1);
			this.aniImgTitle('backward', 'fast');
			setTimeout('myCarousel.updateGoto("backward", '+ targetPosition +')', this.animationTime+this.saveTime);
		}

	},
	
	updateGoto: function(action, targetPosition) {
		if (action == 'forward') {	
			this.position+=1;
		} else if (action == 'backward') {
			this.position-=1;
		}

		if (this.breakGoto === false) {
			if (this.position != targetPosition) {
				this.buildAnimations();
				this.gotoPosition(targetPosition, 'recall');
			} else {
				this.animationRunning = false;
				this.animationTime = this.oldAnimationTime;
				this.waitTime = this.oldWaitTime;
				this.activateNavigation();
				this.buildAnimations();
			}
		} else {
			this.breakGoto = false;
		}
	}
	
}

// --- END

/******************************************************************************
Name:    qGallery
Version: 0.9 (March 31 2008)
Author:  Sebastian Brink
Contact: http://www.quadrifolia.de

Licence:
qGallery is licensed under a Creative Commons Attribution-Noncommercial 
3.0 License (http://creativecommons.org/licenses/by-nc/3.0/).

You are free:
	* to copy, distribute and transmit the work
	* to adapt the work

Under the following conditions:
	* Attribution. You must attribute the work in the manner specified by 
	  the author or licensor.
	* Noncommercial. You may not use this work for commercial purposes.

* For any reuse or distribution, you must make clear to others the license 
  terms of this work. 
* Any of the above conditions can be waived if you get permission from the
  copyright holder.
* Nothing in this license impairs or restricts the author's moral rights.

Your fair dealing and other rights are in no way affected by the above.
******************************************************************************/


/******************************************************************************
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
******************************************************************************/


/******************************************************************************
CREDITS: Bernard Sumption (berniecode.com), Peter-Paul Koch (quirksmode.org),
Lokesh Dhakar (huddletogether.com), Apple (apple.com), and others.
******************************************************************************/



//------------------------------------------------------------------------------------------------------------------------
// globals
//------------------------------------------------------------------------------------------------------------------------

var contentFolder = 			'content';		// folder containing the images

var wrapper = 					'gallery'; 		// id of the element that should contain the gallery
var fullscreen = 				false;			// not implemented yet
var reflection =				true;			// image reflections - false / true
var showThumbs = 				true;
var showMosaic = 				false;			// not implemented yet
var showCarousel =				true;

var contentRightMargin =		10;
var contentLeftMargin =			10;

var thumbsMaxWidth = 			400;
var thumbsMaxHeight = 			400;
var thumbsMinMargin =			20;
var thumbsMarginTop =			10;

var reflectionHeight = 			50;
var reflectionTopMargin = 		2;
var reflectionColor =			'000000';
var reflectionStartAlpha =		80;
var reflectionEndAlpha =		0;

// imgLoader
var imgCounter =				0;

// error
var errorBreak = 				false;

var totalMaxHeight, totalMaxWidth, errorType, errorValue, checkObj;

//------------------------------------------------------------------------------------------------------------------------
// files
//------------------------------------------------------------------------------------------------------------------------

var xml_overview =				contentFolder+'/overview.xml';

//------------------------------------------------------------------------------------------------------------------------
// nomenclature
//------------------------------------------------------------------------------------------------------------------------

// main parts
var id_header = 				'gallery_header';
var id_content = 				'gallery_content';
var id_footer = 				'gallery_footer';
var id_title = 					'gallery_title';
var id_overview = 				'gallery_overview';

// animation parts
var id_loader = 				'gallery_loader';
var id_loader_ani = 			'gallery_loader_animation';

// thumbnail-view elements
var id_thumbs = 				'thumbs';
var id_thumbsList =				'thumbs_list';
var class_thumbsListItem =		'thumbs_item';
var class_thumbsImage =			'thumbs_img';
var class_thumbsReflection =	'thumbs_reflection';
var class_thumbsTitle =			'thumbs_title';

// button elements
var id_buttons =				'buttons';
var id_button_thumbs =			'viewGrid';
var id_button_mosaic =			'viewMosaic';
var id_button_carousel =		'viewCarousel';
var id_button_overview = 		'viewOverview';

//------------------------------------------------------------------------------------------------------------------------
// translations
//------------------------------------------------------------------------------------------------------------------------

if ((navigator.userLanguage) && (navigator.userLanguage.indexOf('de') > -1)) {
	var user_language = 'de';
} else if (navigator.language.indexOf('de') > -1) {
	var user_language = 'de';
}

if (user_language == 'de') {
	var lang_pictures = 'Bilder';
} else {
	var lang_pictures = 'images';
}

//------------------------------------------------------------------------------------------------------------------------
// initialize the gallery
//------------------------------------------------------------------------------------------------------------------------

function initGallery() { 
	myXML = new processXML({});
	
	myGallery = new Gallery({
		wrapper: wrapper,
		reflection: reflection,
		fullscreen: fullscreen
	});
}

Event.observe(window, 'load', initGallery, false);

//------------------------------------------------------------------------------------------------------------------------




//------------------------------------------------------------------------------------------------------------------------
// CLASS Galery
//
// initialize the gallery parts
//------------------------------------------------------------------------------------------------------------------------

Gallery = Class.create();

Gallery.prototype = {

	initialize: function(options) {
		
		var gallery = this;
		
		// options
		this.options = options || {};
		this.wrapper = this.options.wrapper;
		this.reflection = this.options.reflection;
		this.fullscreen = this.options.fullscreen;
		
		// ini builder
		myBuilder = new Builder({
			wrapper: this.wrapper,
			reflection: this.reflection
		});
		
		// start
		this.gallery();
		
	},
	
	gallery: function() {
		myBuilder.gallery();
		this.overview();
	},
	
	overview: function() {
		myBuilder.overview(xml_overview);
	},
	
	thumbs: function(xml, recall) {
		
		if (recall === false) {
			
			window.aniLoader.seekTo(1);
			setTimeout(function() {myBuilder.thumbs(xml);}, 500);
		
		} else if ((recall === true) && (errorBreak === false)) {
			
			// vars
			var imgReady = true;
			var imgElements = $$('#'+id_thumbs+' img');
			
			var imgArray = new Array();
			var startValues = new Array();
			
			// check if all images are loaded
			for (var i=0, j=imgElements.length; i<j; i+=1) {
				if (imgElements[i].complete != true) {
					imgReady = false;
				}
			}
				
			if(imgReady === false) {
				
				setTimeout(function() {myGallery.thumbs('', true);}, 250);
				
			} else {
				
				// get size of images
				imgArray = new Array();
				this.zeroTrigger = false;
				this.images = $$('.'+class_thumbsImage);
				this.titles = $$('.'+class_thumbsTitle);
				this.listItem = $$('.'+class_thumbsListItem);
				for (var i=0, j=this.images.length; i<j; i+=1) {
					imgArray[i] = new Image();
					imgArray[i].src = this.images[i].src;
					
					// safari image width and height = 0 bug
					if ((imgArray[i].width == 0) || (imgArray[i].height == 0)) {
						this.zeroTrigger = true;
					}
				}
				
				if (this.zeroTrigger === true) {
					
					setTimeout(function() {myGallery.thumbs('', true);}, 50);
					
				} else {
					
					for (var i=0; i<imgArray.length; i+=1) {
						startValues[i] = new Array(imgArray[i].width, imgArray[i].height);
					
						// img max values
						if (typeof totalMaxWidth == 'undefined' || imgArray[i].width > totalMaxWidth) {
							totalMaxWidth = imgArray[i].width;
						}
						if (typeof totalMaxHeight == 'undefined' || imgArray[i].height > totalMaxHeight) {
							totalMaxHeight = imgArray[i].height;
						}
					}
				
					// set reflections
					if (this.reflection === true) {
						this.reflectionImages = document.getElementsByClassName(class_thumbsReflection);
						for (var i=0, j=this.reflectionImages.length; i<j; i+=1) {
							this.reflectionImages[i].setStyle({ display: 'block' });
						}
					} else {
						this.reflectionImages = 'empty';
					}

					// ini slider
				    mySlider = new Control.Slider(id_footer, {
				        sliderValue: startSize, slider: id_slider, sliderTrack: id_sliderTrack, sliderHandle: id_sliderHandle, sliderLeftIcon: id_sliderLeftIcon, sliderRightIcon: id_sliderRightIcon
				    });
			
					// ini scroller
					if(!$(id_scroller_track)) {
						myScroller = new contentScroller(id_scroller_container, id_thumbs, {
							arrowPosition: setting_scroller_arrow,
							trackPosition: setting_track_position,
							offsetTop: setting_offset_top,
							offsetBottom: setting_offset_bottom,
							contentRightMargin: contentRightMargin,
							contentLeftMargin: contentLeftMargin
						});
					} else {
						myScroller.setContent(id_thumbs);
					}
				
					// ini buttons
					myButtons = new Control.Buttons(id_footer, {
						showThumbs: showThumbs, showMosaic: showMosaic, showCarousel: showCarousel, idButtons: id_buttons, idThumbs: id_button_thumbs, idMosaic: id_button_mosaic, idCarousel: id_button_carousel
					});
			
					// ini resize
				    myResize = new Resize(id_thumbs, {
						listItem: this.listItem,
						images: this.images,
						reflections: this.reflectionImages,
						titles: this.titles,
						startValues: startValues
					});
				
					// ini viewer
					myViewer = new imgViewer({
						marker: lightbox_marker,
						close: lightbox_close,
						listner: lightbox_listner
					});
				
					// show thumbnails
					switchView(id_thumbs);
				}

			}
		
		} else {
			if (errorType == '404') {
				alert('ERROR: image "'+errorValue+'" is missing!')
			} else if (errorType == 'failure') {
				alert('ERROR: something went wrong!')
			}
			return true;
		}
	
	},
	
	carousel: function() {
		
		if(typeof myCarousel == 'object') {
			myCarousel.stopAnimation();
		}

		myCarousel = new Carousel(id_content, {
			animationTime: 800,
			waitTime: 1000,
			fastAnimationTime: 50,
			fastWaitTime: 0,
			saveTime: 0,
			displayTitle: true,
			carouselWidth: parseInt(Element.getStyle(id_content, 'width')) - (contentLeftMargin + contentRightMargin),
			carouselHeight: parseInt(Element.getStyle(id_content, 'height')),
			reflectionHeight: 50,
			reflectionTopMargin: 2,
			imgSourceType: 'href',
			imgSource: id_thumbs
		});
		
	}
		
}

//------------------------------------------------------------------------------------------------------------------------





//------------------------------------------------------------------------------------------------------------------------
// CLASS Builder
//
// build the gallery parts
//------------------------------------------------------------------------------------------------------------------------

Builder = Class.create();

Builder.prototype = {
	
	initialize: function(options) {
		
		var builder = this;
		
		// options
		this.options = options || {};
		this.wrapper = this.options.wrapper;
		this.reflection = this.options.reflection;
		
		// vars
		this.wrapperWidth = parseInt(Element.getStyle(wrapper, 'width'));
		this.wrapperHeight = parseInt(Element.getStyle(wrapper, 'height'));
		
		this.initialized = true;
		
	},
	
	gallery: function() {
		
		// build elements
		
		var objHeader = new Element('div', { id: id_header });
		$(this.wrapper).appendChild(objHeader);
		
		var objContent = new Element('div', { id: id_content });
		$(this.wrapper).appendChild(objContent);
		
		var objFooter = new Element('div', { id: id_footer });
		$(this.wrapper).appendChild(objFooter);
		
		var objTitle = new Element('div', { id: id_title });
		objHeader.appendChild(objTitle);
		
		var objButton = new Element('a', { id: id_button_overview, href: '#' });
		objHeader.appendChild(objButton);
		
		Event.observe(objButton, 'click', new Function('fx', 'myButtons.show_overview()'));
		
		var objLoader = new Element('div', { id: id_loader });
		$(this.wrapper).appendChild(objLoader);
		
		var objLoaderAni = new Element('div', { id: id_loader_ani });
		objLoader.appendChild(objLoaderAni);
		
		// set styles
		this.headerHeight = parseInt(Element.getStyle(id_header, 'height'));
		this.footerHeight = parseInt(Element.getStyle(id_footer, 'height'));
		this.contentHeight = this.wrapperHeight - this.headerHeight - this.footerHeight;
		
		$(id_header).setStyle({
			width: this.wrapperWidth + 'px',
			top: '0px',
			left: '0px'
		});
		
		$(id_content).setStyle({
			width: this.wrapperWidth + 'px',
			height: this.contentHeight + 'px',
			top: this.headerHeight + 'px',
			left: '0px'
		});
		
		$(id_footer).setStyle({
			width: this.wrapperWidth + 'px',
			top: (this.headerHeight + this.contentHeight) + 'px',
			left: '0px'
		});
		
		$(id_button_overview).setStyle({
			display: 'none'
		});
		
		$(id_loader).setStyle({
			width: this.wrapperWidth + 'px',
			height: this.contentHeight + 'px',
			top: this.headerHeight + 'px',
			left: '0px'
		});
		
		// build animations
		buildAnimation_loader();
		
	},
	
	overview: function(xml_file) {
		
		// load xml file
		myXML.load(xml_file);
		
		// call this functions on xml load
		myXML.options.onBuild = function(value) {
			
			// build elements
			
			var objHeadline = new Element('h1', {}).update(value['name'][0]);
			$(id_title).appendChild(objHeadline);
			
			var objButtonSpan = new Element('span', {}).update(value['name'][0]);
			$(id_button_overview).appendChild(objButtonSpan);
			
			var objOverview = new Element('div', { id: id_overview });
			$(id_content).appendChild(objOverview);

			for (var i=0, j=value['id'].length; i<j; i+=1) {
				
				var objSkimmerWrapper = new Element('div', { 'class': class_SkimmerWrapper, id: (class_SkimmerWrapper + '_' + i) });
				objOverview.appendChild(objSkimmerWrapper);
				
				var objSkimmer = new Element('div', { 'class': class_Skimmer, id: (class_Skimmer + '_' + i) }).setStyle({
					backgroundColor: 'transparent',
					background: 'url(skimmer.php?mode=xml&id=' + value['id'][i] + '&dir='+contentFolder+'&xml=' + value['xml'][i] + '&sWidth=' + skimmerMaxWidth + '&sHeight=' + skimmerMaxHeight + ')',
					backgroundRepeat: 'no-repeat',
					backgroundPosition: 'top left'
				});
				objSkimmerWrapper.appendChild(objSkimmer);
				
				Event.observe(objSkimmer, 'click', new Function('fx', 'myGallery.thumbs("'+contentFolder+'/'+value['xml'][i]+'", false)'));
				
				var objSkimmerMask = new Element('div', { 'class': class_SkimmerMask });
				objSkimmer.appendChild(objSkimmerMask);
				
				var objSkimmerTitle = new Element('p', { 'class': class_SkimmerTitle }).update(value['title'][i]);
				objSkimmerWrapper.appendChild(objSkimmerTitle);
				
				var objSkimmerCounter = new Element('p', { 'class': class_SkimmerCounter }).update(value['img_count'][i] + ' ' + lang_pictures);
				objSkimmerWrapper.appendChild(objSkimmerCounter);

			}
			
			// calculate margins
			var skimmerWidth = parseInt(Element.getStyle((class_SkimmerWrapper + '_0'), 'width'));
			var skimmerHeight = parseInt(Element.getStyle((class_SkimmerWrapper + '_0'), 'height'));
			var skimmerTopMargin = parseInt(Element.getStyle((class_SkimmerWrapper + '_0'), 'marginTop'));
			var skimmerMinMargin = parseInt(Element.getStyle((class_SkimmerWrapper + '_0'), 'marginLeft'));
			var skimmerFrames = document.getElementsByClassName(class_SkimmerWrapper);
			var skimmerCounter = value['id'].length;
			var skimmerMaxInLine = Math.floor( parseInt(Element.getStyle(id_overview, 'width')) / (skimmerWidth + skimmerMinMargin) );
			var skimmerNewMargin = Math.floor( ( parseInt(Element.getStyle(id_overview, 'width')) - (skimmerMaxInLine * (skimmerWidth + skimmerMinMargin)) - skimmerMinMargin ) / (skimmerMaxInLine + 1) );
				
			// calculate overview height
			var lineCount = Math.ceil(skimmerCounter / skimmerMaxInLine);
			var newOverviewHeight = (lineCount * (skimmerHeight + skimmerTopMargin));
			$(id_overview).setStyle({
				height: newOverviewHeight + 'px'
			});
			
			// init the scrollbar
			myScroller = new contentScroller("gallery_content", "gallery_overview", {
				arrowPosition: setting_scroller_arrow,
				trackPosition: setting_track_position,
				offsetTop: setting_offset_top,
				offsetBottom: setting_offset_bottom,
				contentRightMargin: contentRightMargin,
				contentLeftMargin: contentLeftMargin
			});
			
			// recalculate everything
			skimmerMaxInLine = Math.floor( parseInt(Element.getStyle(id_overview, 'width')) / (skimmerWidth + skimmerMinMargin) );
			skimmerNewMargin = Math.floor( ( parseInt(Element.getStyle(id_overview, 'width')) - (skimmerMaxInLine * (skimmerWidth + skimmerMinMargin)) - skimmerMinMargin ) / (skimmerMaxInLine + 1) );
			lineCount = Math.ceil(skimmerCounter / skimmerMaxInLine);
			newOverviewHeight = (lineCount * (skimmerHeight + skimmerTopMargin));
			$(id_overview).setStyle({
				height: newOverviewHeight + 'px'
			});
			
			// set scrollbar
			myScroller.resizeHandle();
			
			// set the new skimmer margin
			for (var i=0, j=skimmerFrames.length; i<j; i+=1) {
				skimmerFrames[i].style.marginLeft = skimmerMinMargin + skimmerNewMargin +'px';
			}
			
			// init the skimmer function
			mySkimmer = new Control.Skimmer({
				marker: class_Skimmer,
				indicator: true,
				size: 160
			});
			
			// loading screen
			if ($(id_loader).getStyle('display') != 'none') {
				window.aniLoader.seekTo(0);
			}
		}
	},
	
	thumbs: function(xml_file) {
			
		// load xml file
		myXML.load(xml_file);

		// call this functions on xml load
		myXML.options.onBuild = function(value) {
			
			// get dimensions
			this.viewport = document.viewport.getDimensions();
		
			// build elements
			if(!$(id_thumbs)) {
				var objThumbs = new Element('div', { id: id_thumbs });
				$(id_content).appendChild(objThumbs);
			} else {
				clearContent(id_thumbs);
				var objThumbs = $(id_thumbs);
			}
		
			var objList = new Element('ul', { 'class': id_thumbsList });
			objThumbs.appendChild(objList);
		
			// build list elements
			for (var i=0, j=value['title'].length; i<j; i+=1) {
				
				// check if file exists (with javascript)
				// javascript method disabled, because it loads the file				
				// checkObj = new Ajax.Request(contentFolder+'/'+value['file'][i], {
				// 	onSuccess: function(response) {
				// 		checkObj.transport.abort();
				// 	},
				// 	on404: function(response) {
				// 		errorBreak = true;
				// 		errorType = '404';
				// 	},
				// 	onFailure: function(response) {
				// 		errorBreak = true;
				// 		errorType = 'failure';
				// 	}
				// });
				
				// check if file exists (with php)
				checkObj = new Ajax.Request('image.php?check=true&dir='+contentFolder+'&img='+value['file'][i], {
					onSuccess: function(response) {
						var responseMessage = new Array();
						responseMessage = response.responseText.split('|');
						if (responseMessage[0] == 404) {
							errorBreak = true;
							errorType = '404';
							errorValue = responseMessage[1];
						}
					},
					onFailure: function(response) {
						errorBreak = true;
						errorType = 'failure';
					}
				});
				
				// build
				var objListElement = new Element('li', { 'class': class_thumbsListItem });
				objList.appendChild(objListElement);
				
				var objLink = new Element('a', { 'class': lightbox_marker, href: 'viewer.php?dir='+contentFolder+'&img=' + value['file'][i] + '&width=' + this.viewport['width'] + '&height=' + this.viewport['height'], title: value['title'][i] });
				objLink.onclick = function() {return false;};
				objListElement.appendChild(objLink);
				
				var objThumb = new Element('img', { 'class': class_thumbsImage, src: 'image.php?dir='+contentFolder+'&img=' + value['file'][i] + '&width=' + thumbsMaxWidth + '&height=' + thumbsMaxHeight + '&sWidth=' + skimmerMaxWidth + '&sHeight=' + skimmerMaxHeight + '&rHeight=' + reflectionHeight + '&color=' + reflectionColor + '&sAlpha=' + reflectionStartAlpha + '&eAlpha=' + reflectionEndAlpha + '&output=img' });
				objLink.appendChild(objThumb);

				if (myBuilder.reflection === true) {
					var objReflection = new Element('img', { 'class': class_thumbsReflection, src: 'image.php?dir='+contentFolder+'&img=' + value['file'][i] + '&width=' + thumbsMaxWidth + '&height=' + thumbsMaxHeight + '&sWidth=' + skimmerMaxWidth + '&sHeight=' + skimmerMaxHeight + '&rHeight=' + reflectionHeight + '&color=' + reflectionColor + '&sAlpha=' + reflectionStartAlpha + '&eAlpha=' + reflectionEndAlpha + '&output=refl' });
					objListElement.appendChild(objReflection);
				}

				var objTitle = new Element('div', { 'class': class_thumbsTitle });
				objListElement.appendChild(objTitle);
				
				var objTitleSpan = new Element('span', {}).update(value['title'][i]);
				objTitle.appendChild(objTitleSpan);
		
			}
			
			// recall
			myGallery.thumbs('', true);
			
		}
	}
	
}

//------------------------------------------------------------------------------------------------------------------------





//------------------------------------------------------------------------------------------------------------------------
// CLASS CONTROL BUTTONS
//
// controls the navigation buttons
//------------------------------------------------------------------------------------------------------------------------

if(!Control) var Control = {};
Control.Buttons = Class.create();

Control.Buttons.prototype = {
	
	initialize: function(target, options) {
		
		var buttons = this;
		
		// options
		this.options = options || {};
		
		this.showThumbs = this.options.showThumbs;
		this.showMosaic = this.options.showMosaic;
		this.showCarousel = this.options.showCarousel;
		this.id_buttonWrapper = this.options.idButtons;
		this.id_thumbs = this.options.idThumbs;
		this.id_mosaic = this.options.idMosaic;
		this.id_carousel = this.options.idCarousel;
		
		this.target = $(target);
		
		// create DOM nodes
		if(!$(this.id_buttonWrapper)) {			
			var objButtons = document.createElement('div');
			objButtons.setAttribute('id', this.id_buttonWrapper);
			objButtons.style.display = 'none';
			this.target.appendChild(objButtons);
			
			if (this.showThumbs === true) {
				var objButtonThumbs = document.createElement('div');
				objButtonThumbs.setAttribute('id', this.id_thumbs);
				objButtons.appendChild(objButtonThumbs);
				
				Event.observe($(this.id_thumbs), 'click', this.show_thumbOverview.bindAsEventListener(this));
			}
			
			if (this.showMosaic === true) {
				var objButtonMosaic = document.createElement('div');
				objButtonMosaic.setAttribute('id', this.id_mosaic);
				objButtons.appendChild(objButtonMosaic);
				
				Event.observe($(this.id_mosaic), 'click', this.show_mosaicOverview.bindAsEventListener(this));
				
			}
			
			if (this.showCarousel === true) {
				var objButtonCarousel = document.createElement('div');
				objButtonCarousel.setAttribute('id', this.id_carousel);
				objButtons.appendChild(objButtonCarousel);
				
				Event.observe($(this.id_carousel), 'click', this.show_carouselOverview.bindAsEventListener(this));
			}
		}
		
		this.initialized = true;
		
		this.draw();
	},
	
	show_thumbOverview: function(e) {
		if (Element.getStyle(id_thumbs, 'display') != 'block') {
			window.aniLoader.seekTo(1);
			setTimeout(function() {switchView(id_thumbs);}, 500);
		}
	},
	
	show_mosaicOverview: function(e) {
		alert('switch to mosaic');
	},
	
	show_carouselOverview: function(e) {
		window.aniLoader.seekTo(1);
		setTimeout(function() {switchView(id_carousel);}, 500);
	},
	
	show_overview: function(e) {
		window.aniLoader.seekTo(1);
		setTimeout(function() {switchView(id_overview);}, 500);
	},
	
	draw: function() {
		$(this.id_buttonWrapper).setStyle({
			display: 'block'
		});
	}
	
}

//------------------------------------------------------------------------------------------------------------------------





//------------------------------------------------------------------------------------------------------------------------
// ANIMATIONS
//
// some more basic animations
//------------------------------------------------------------------------------------------------------------------------

// animation of overlay layer

function buildAnimation_loader() {
	if (typeof window.aniLoader == 'undefined') {
		window.aniLoader = new Animator({
			duration: 500
		}).addSubject(new NumericalStyleSubject(
		    $(id_loader), 'opacity', 0, 1)
		).addSubject(updateAnimation_loader);
	}
}

function updateAnimation_loader(value) {
	if(value == 0) {
		$(id_loader).setStyle({
			display: 'none'
		});
	} else {
		$(id_loader).setStyle({
			display: 'block'
		});
	}
}

// switch visibilty of gallery elements

function switchView(element) {
	
	if(element == id_thumbs) {
		
		$(id_overview, id_title).invoke('hide');
		$(id_thumbs, id_slider, id_button_overview, id_buttons).invoke('show');
		
		if ($(id_carousel)) {
			$(id_carousel).setStyle({
				display: 'none'
			});
		}
		
		if($('scroller_track')) {
			myScroller.setContent(id_thumbs);
		}
		
		window.aniLoader.seekTo(0);
		
	} else if(element == id_carousel) {
		
		myGallery.carousel();
		
		$(id_overview, id_thumbs, id_slider, id_title).invoke('hide');
		$(id_carousel, id_button_overview, id_buttons).invoke('show');
		
		if($('scroller_track')) {
			myScroller.setContent(id_carousel);
		}
		
		window.aniLoader.seekTo(0);
		
	} else if(element == id_overview) {
		
		$(id_thumbs, id_slider, id_button_overview, id_buttons).invoke('hide');
		$(id_overview, id_title).invoke('show');
		
		if ($(id_carousel)) {
			$(id_carousel).setStyle({
				display: 'none'
			});
		}
		
		if($('scroller_track')) {
			myScroller.setContent(id_overview);
		}
		
		window.aniLoader.seekTo(0);
		
	}
	
}

//------------------------------------------------------------------------------------------------------------------------

