


/*  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();

//***************************************************************************
// Set Global vars															*
//***************************************************************************

var IE				= document.all?true:false;
if(IE){
	try{
		document.execCommand("BackgroundImageCache", false, true);
	} catch(err){		
	}
}
var alertMsg		= new Array();
var errorMsg		= new Array();
var popup;

var a;
var anchorObject;
var tmpAnchor;
var selectedOption;
var dragableComponent;

var	refreshTimerSecs	= 2000; // 2 seconds between each refresh
var refreshKeyCodes		= new Array();
refreshKeyCodes[0]		= 116;
refreshKeyCodes[1]		= 82;
refreshKeyCodes[2]		= 114;

var backSpaceKeyCodes	= new Array();
backSpaceKeyCodes[0]	= 8;

// the defaultFilename can be changed in the globalProjectVars within your project

if(!defaultFilename) {
	var defaultFilename		= 'marcompro.php';
}
// base64 encoding vars
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

// wysiwyg
//var wysiwyg = null;
//var wysiwyg2 = null;

// IE7 detect

var IE7 = null;
var ua = navigator.userAgent;
var re  = new RegExp("MSIE ([7-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
  IE7 = parseFloat( RegExp.$1 );
}


//***************************************************************************
// SetAnchorEvents															*
// comments:	Set standard anchor events									*
//***************************************************************************
setAnchorEvents = function() {
	var anchors = document.getElementsByTagName('A');

	for(i=0;i<anchors.length;i++) {
		var anchor	= anchors[i];

		if(IE) {
			anchor.attachEvent("onfocus", focusEventAction);
			
			// for IE we need to use the onmouseup event!If we use the onclick event,
			// the onclick in the tag will always be triggerd first!
			// thats something that cannot happen
			anchor.onmouseup = lookForChanges;
			anchor.attachEvent("onmouseup", setAnchorObject);
			
		} else {
			
			anchor.addEventListener("focus", focusEventAction, true);
			
			anchor.addEventListener("click", setAnchorObject, true);
			
			anchor.addEventListener("click", lookForChanges, true);
			
			anchor.addEventListener("mouseover", checkMouseOvers, true);
			
		}
	}
}

//***************************************************************************
// checkMouseOvers															*
// @evt	'event'																*
// comments:	Look for default mouseover events 							*
//***************************************************************************
checkMouseOvers = function(evt) {
	var a = evt.currentTarget;

	// little hack
	// set the onclick in a temp var
	// so the onclick will not be triggered before we have checked for changes
	if(a.onclick != '') {
		a.onclick_tmp = a.onclick;
		a.onclick = '';
	}
}


//***************************************************************************
// focusEventAction															*
// @evt	'event'																*
// comments:	Give the focus event an action 								*
//***************************************************************************
focusEventAction = function(evt) {
	
	if(IE) {
		var obj = event.srcElement;
		obj.blur();
	} else {
		var obj = evt.currentTarget;
		obj.blur();
	}
}

//***************************************************************************
// lookForChanges															*
// @evt	'event'																*
// comments:	When a link is clicked, check if the link loads the page	*
//				If the page will reload, check if there a changes made in 	*
//				input fields.												*
//***************************************************************************
lookForChanges = function(evt) {
	if(IE) {
		
		var obj = event.srcElement;
		// stupid dumb IE bug for child Elements
		if(obj.tagName != 'A') {
			if (obj.parentNode) {
				while (obj.parentNode) {
					if(obj.tagName == 'A') {
						a = obj;

						break;
					} else {
						obj = obj.parentNode;
					}
				}
			}
		} else {
			a = obj;
		}
	} else {
		a = evt.currentTarget;
	}

	if(!IE) {
		a.onclick = a.onclick_tmp;
	}

	var link		= a.href;
	var type		= a.type;
	var map			= a.getAttribute('map');

	// return boolean
	// true if an external link is clicked, which means the page has to reload
	if(MARCOMPRO_MODE) {
		var check	= checkForExternalLink(link, type);
	
		if(check) {
			
			var changes = changedFieldValues.chechForChanges(a, 1);
			if(!changes) {
				if(IE) {
					a.onclick = '';
					event.returnValue = false;
					return;
				} else {
					if(evt.cancelable) {
						evt.preventDefault();
						return;
					}
				}
			}
		} 
	}

	// check for extra actions
	if(map && map != '') {
		doMap(map);

		// stop the event
		if(IE) {
			event.returnValue = false;
			return;
		} else {
			if(evt.cancelable) {
				evt.preventDefault();
				return;
			}
		}
	}

	// check selects of lists
	if(type == 'select_all' || type == 'deselect_all') {
		selectingList.doSelects(type);
	}

	if(!IE) {
		if(a.onclick) {
			a.onclick();
		}
		// stop bubbling
		// when an img tag is within an anchor tag, the onclick will be triggered twice
		evt.stopPropagation();
	} else {
		event.cancelBubble = true;
	}
}




//***************************************************************************
//checkForExternalLink														*
// @evt	'event'																*
// comments:	Give the focus event an action 								*
//***************************************************************************
checkForExternalLink = function(link, type) {

	if(link.length > 1) {
		var end		= link.length;
		var start	= end - 1;
		var extLink	= link.substring(start, end);
	} else if(link.length == 1){
		extLink	= link;
	} else {
		return false;
	}

	// a link can have a load as a type,
	// which means by an onclick="" the page will reload

	if(type == 'no_load') {

		// the link is forced to have a load but don't give a message that the content will be lost
		// for example when a popup will appear
		return false;
	} else if(extLink == '#' && type != 'load') {
		return false;
	} else if(extLink == '' && type != 'load') {
		return false;
	} else if(extLink == ';' && type != 'load') {
		return false;
	} else {
		return true;
	}

}


//***************************************************************************
// doMap															*
// @string	'definition'													*
// comments:	Check what kind of action the user is doing 				*
//				For example: if the user is deleting a person, show an 		*
//				important popup												*
//***************************************************************************
doMap = function(map) {
	loadingTemplatesWithAjax.loadTpl('?do=' + map);
	return false;
}

//***************************************************************************
// setAnchorObject															*
// @a	'obj'																*
// comments: 	set the anchor object 										*
//***************************************************************************
setAnchorObject = function (evt) {

	var a = '';
	if(IE) {
		if(typeof(evt) == 'object') {
			a = evt;
		} else {
			
			var obj = event.srcElement;
		
			// stupid dumb IE bug for child Elements
			if(obj.tagName != 'A') {
				
				if (obj.parentNode) {
					while (obj.parentNode) {
						if(obj.tagName == 'A') {
							a = obj;
							break;
						} else {
							obj = obj.parentNode;
						}
					}
				}
				
			} else {
				
				a = obj;
			}
		}
	} else {
		
		if(typeof(evt) == 'object') {
			a = evt;
		} else {
			a = evt.currentTarget;
		}
	}
	

	anchorObject = a;
	return;
}


//***************************************************************************
// getAnchorObject															*
// comments: 	call this function when the anchor event is lost 			*
//***************************************************************************
getAnchorObject = function () {
	return anchorObject;
}









/**
 * setFormEvents
 * comments:	Set standard submit events
**/
setFormEvents = function() {

	var forms = document.getElementsByTagName('FORM');
	for(i=0;i<forms.length;i++) {
		form	= forms[i];

		if(IE) {
			form.onsubmit = submitAction;
		} else {
			form.addEventListener("submit", submitAction, false);
		}
	}
}


/**
 * submitAction
 * comments:	Give the form a submit
 * @param evt	'event'
**/
submitAction = function(evt) {
	
	//var synchWysiwyg= saveFormWithAjax.synchWysiwyg();
	
	if(IE) {
		var form 	= event.srcElement;
	} else {
		var form 	= evt.currentTarget;
	}
	
	var check	= formControl.checkFormFields(form);
	
	//first check all the fields
	if(!check) {
		if(IE) {
			event.returnValue = false;
		} else {
			
			evt.preventDefault();
		}
	} else {

		var submit	= formControl.setSubmit(form);

		// do this so we do not see the popup of changed field values
		// everytime a user presses a link
		var reset	= changedFieldValues.checkSubmit();

		//then check if the page has to reload on a submit
		//if not, the page will be loaded with ajax, so kill the submit event
		if(!submit) {
			if(IE) {
				event.returnValue = false;
			} else {
				evt.preventDefault();
			}
		}
	}


}

/**
 * submitAction
 * Give the form, selected by id, a submit
 * @param evt	'event'

**/
enableSubmit = function(evt) {
	
	if(IE) {
		var field 	= event.srcElement;
	} else {
		var field 	= evt.currentTarget;
	}
	
	if(field.checked) {
		var form 	= find.findObjectByTagName(field, 'FORM');
		var elems 	= form.elements;
		var len		= elems.length;
		for(i=0;i<len;i++) {
			var elem	= elems[i];
			if(elem.type == 'submit' && elem.disabled) {
				elem.disabled = false;
				field 	= null;
				form	= null;
				elem	= null;
				return;
			}
		}
	}
}

/**
 * submitAction
 * Give the form, selected by id, a submit
 * @param evt	'event'

**/
disableSubmit = function(field) {
	
	var form 	= find.findObjectByTagName(field, 'FORM');
	var elems 	= form.elements;
	var len		= elems.length;
	for(i=0;i<len;i++) {
		var elem	= elems[i];

		if(elem.type == 'submit' && !field.checked) {
			elem.disabled = true;
			field 	= null;
			form	= null;
			elem	= null;
			return;
		}
	}
	
}

/**
 * submitAction
 * Give the form, selected by id, a submit
 * @param evt	'event'

**/
submitActionById = function(id) {
	try {
		//var synchWysiwyg= saveFormWithAjax.synchWysiwyg();
	 	var form		= document.getElementById(id);
	 	if(form) {
			var check	= formControl.checkFormFields(form);
			
			//first check all the fields
			if(!check) {
				//form.onsubmit = false;
				return false;
			} else {
	
				var submit	= formControl.setSubmit(form);
	
				// do this so we do not see the popup of changed field values
				// everytime a user presses a link
	
				changedFieldValues.checkSubmit();
	
	
			}
	 	}
	
	 	return true;
	} catch(e) {
		alert(e);
	}
}

/**
 * setInputFieldsCSS
 * Coz IE does not support selectors, we have to write a little
 * event to set a class to input fields
 *
 * @param param evt	'event'
**/
setInputFieldsCSS = function(evt) {
	// we do not want to slow down all the other browsers
	// so only use this for IE
	if(IE) {
		var inputFields = document.getElementsByTagName('INPUT');

		for(i=0;i<inputFields.length;i++) {
			var inputField = inputFields[i];

			if(inputField.type == 'text' || inputField.type == 'password') {
				inputField.className = 'input_type_text';
			} else if(inputField.type == 'submit' || inputField.type == 'reset' || inputField.type == 'button') {
				inputField.className = 'input_type_buttons';
			} else if(inputField.type == 'radio') {
				inputField.className = 'input_type_radio';
			}
		}
	}

}




//***************************************************************************
// Set Global vars															*	
//***************************************************************************


//***************************************************************************
// ChangedFieldValues Constructor											*	
// Comment:	use the this.onFocusNewValues for changed values of the fields	*
//			use the this.onFocusFirstValues to save the original values of 	*
//			the fields														*
//***************************************************************************
function ChangedFieldValues() {
	this.onFocusNewValues		= new Object();
	this.onFocusFirstValues		= new Object();
	this.onclick				= false;
	this.popupCancel			= false;
	this.popupSubmit			= false;
}


//***************************************************************************
// ChangedFieldValues setFieldFirstValue									*
// @id	'string'															*
// @value	'string'														*
// comments:	Sets an array of all the first  values of the fields that 	*
//				are editted													*
//				Use the id of the field as a reference so we can check for 	*
//				changes later												*
//***************************************************************************
ChangedFieldValues.prototype.setFieldFirstValue = function (id, value) {
		this.onFocusFirstValues[id] 		= new Object();
		this.onFocusFirstValues[id][0]  	= value;
}


//***************************************************************************
// ChangedFieldValues setFieldsFirstValuesLoad								*
// @id	'string'															*
// comments:	
//***************************************************************************
ChangedFieldValues.prototype.setFieldsFirstValuesLoad = function (id) {
	
	try{
		var obj 	= document.getElementById(id);
		var form	= find.findObjectByTagName(obj, 'FORM');
		var len		= form.elements.length;
		
		for(var i=0; i<len; i++) {
			var elem	=  form.elements[i];
			if(elem.id) {
				var fieldId = elem.id;
				var value	= elem.value
				
				this.setFieldFirstValue(fieldId, value);
			}
			
		}
		
	} catch(e) {
		errorMsg.push(e + ' (ChangedFieldValues.js)');
		debugWindow.handleAjaxError(errorMsg);
	}
	
}

//***************************************************************************
// ChangedFieldValues setFieldsFirstValues									*
// @id	'string'															*
// comments:	Sometimes fields in a form will be filled by ajax			*
//				Normally we use the onfocus to set the first field values	*
//				But when fields are filled with ajax, no onfucus occures
//***************************************************************************
ChangedFieldValues.prototype.setFieldsFirstValues = function (id) {
	
	this.setFieldsFirstValuesId = id;
	try {
		var obj 		= document.getElementById(id);
		
		var inputs		= obj.getElementsByTagName('INPUT');
		var textareas	= obj.getElementsByTagName('TEXTAREA');
		var selects		= obj.getElementsByTagName('SELECT');
		var images		= obj.getElementsByTagName('IMG');

		var lenInputs	= inputs.length;
		var lenTextareas= textareas.length;
		var lenSelects	= selects.length;
		var lenImages	= images.length;
		
		// find the inputs
		for(var i=0; i<lenInputs; i++) {
			
			var elem = 	inputs[i];
			if(elem.id) {
				var fieldId = elem.id;
				var value	= elem.value
				this.setFieldFirstValue(fieldId, value);
			}
			
		}
		// find the images
		for(var i=0; i<lenImages; i++) {
			
			var elem = 	images[i];
			if(elem.id) {
				var fieldId = elem.id;
				var value	= elem.src
				this.setFieldFirstValue(fieldId, value);
			}
			
		}
		
		// find the textareas
		for(var i=0; i<lenTextareas; i++) {
			
			var elem = 	Textareas[i];
			if(elem.id) {
				var fieldId = elem.id;
				var value	= elem.value
				this.setFieldFirstValue(fieldId, value);
			}
			
		}
		
		// find the selects
		for(var i=0; i<lenSelects; i++) {
			
			selected	= selects.selectedIndex;
			for(a=0; a<select.length; a++) {
				if(selected == a) {
					
					if(elem.id) {
						var fieldId = elem.id;
						var value	= elem.value
						this.setFieldFirstValue(fieldId, value);
					}
	
				}
			}
			
		}
		
		obj = null;
		
	} catch(e) {
		errorMsg.push(e + ' (ChangedFieldValues.js)');
		debugWindow.handleAjaxError(errorMsg);
	}
}

//***************************************************************************
// ChangedFieldValues setFieldNewValue										*
// @id	'string'															*
// @value	'string'														*
// comments:	Sets an array of all the fields that are editted			*
//				Use the id of the field as a reference						*
//***************************************************************************
ChangedFieldValues.prototype.setFieldNewValue = function (id, value) {
	try{
		var obj = document.getElementById(id);
		if(obj) {
			this.onFocusNewValues[id] 			= new Object();
			this.onFocusNewValues[id][0]  		= value;
		}
		
	} catch (e) {
	
		errorMsg.push(e + ' (ChangedFieldValues.js)');
		debugWindow.handleAjaxError(errorMsg);
	}
	
	
}

//***************************************************************************
// ChangedFieldValues chechForChanges										*
// @obj	'object'															*
// @showPopup 'bool'														* 
// @onclick	'function'	temp onclick action									*
// comments:	Sets an array of all the fields that are editted			*
//				Use the id of the field as a reference						*
//***************************************************************************
ChangedFieldValues.prototype.chechForChanges = function (obj, showPopup) {
	
	var link		= '';
	var newValues	= this.onFocusNewValues;
	var firstValues	= this.onFocusFirstValues;
	this.obj		= obj;
	
	if(obj != '') {
		link		= this.setLink(obj);
	} else {
		link		= this.link;	
	}
	
	var fields		= '';
	
	var b = 0;
	for(var i in newValues) {
		
		try {
			var id 			= i;
			var newValue 	= newValues[i][0];
		
			var firstValue	= firstValues[i][0];

			if(newValue != firstValue) {
				var obj 	= document.getElementById(i);
				if(obj) {
					var title	= obj.title;
					
					if(title == 'undefined' || title == '') {
						title	= 'onbekend veld met id: ' + i;
						fields	+= '&field[' + b + ']=' + i;
					} else {
						title	= title;
						fields	+= '&field[' + b + ']=' + title;
					}
				
				}
			}
			b++;
		} catch(e) {
			errorMsg.push(e + ' (changedFieldValues.js)');
			debugWindow.handleAjaxError(errorMsg);
		}
	}
	

	if(fields != '') {
		rExp 			= /&/gi;
		replaceInUrl 	= new String("%26");
		
		newLink 		= link.replace(rExp, replaceInUrl);
		
		rExp3 			= /(\'.*\')/gi;
		rExp4 			= /\'/gi;
		rExp5 			= /\'.*\'/gi;
		
		// first get the right template
		if(newLink.match(rExp3)) {
			
			newLink 	= new String(newLink.match(rExp3));
			var first	= newLink.charAt(0);
			var len		= (newLink.length) -1;
			var last	= newLink.charAt(len);
			
			// check if there are still ' at the front and back of the tpl
			if(first.match(rExp4) && last.match(rExp4)) {
				
				newLink 		= newLink.replace(rExp4, '');
			}
		}
	
		var get = fields + '&redirect=' + newLink;
		
		// load the popup template
		if(showPopup) {
			
			loadingTemplatesWithAjax.loadTplPost('?do=popupchangedfields', get);

			popup.checkSubmit('changedFieldValues.checkSubmit()');
		}
		return false;
		
	}
	return true;
}

//***************************************************************************
// ChangedFieldValues setLink												*
// @str_obj	'object || string'												*
// comments:	Sets the link for the popup									*
//***************************************************************************
ChangedFieldValues.prototype.setLink = function (str_obj) {
	
	if(typeof str_obj == 'object') {
		var obj		= str_obj;
		var link 	= obj.href;
		
		var end		= link.length;
		var start	= end - 1;
		var extLink	= link.substring(start, end);

		if(extLink == '' || extLink == '#') {
			this.onclick	= true;
			var click		= obj.getAttribute('onclick').toString();
			
			rExp 			= /;/g;
			rExp2 			= /loadingTemplatesWithAjax/g;
			//ie creates an anonymous function, we have to remove it to get to the string within
			rExp3 			= /function anonymous()/g;
			
			if(click.match(rExp)) {
				
				var splittedClick 	= click.split(rExp);
				var len				= splittedClick.length;
				
				for(var i=0; i<len; i++) {
					if(splittedClick[i].match(rExp2)) {
						if(IE) {
							// remove the anonymous function wrapper 
							if(splittedClick[i].match(rExp3)) {
								var link 	= splittedClick[i].split('{');
								link		= link[1];
							}
						} else {
							var link = splittedClick[i];
						}
					
						break;
					}
				}

						
			} else if(click.match(rExp2)){
				if(IE) {
					// remove the anonymous function wrapper 
					if(click.match(rExp3)) {
						var link 	= click.split('{');
						link		= link[1].split('}');
						link		= link[0];
						
					}
				} else {
					var link = click;
				}
				
				

			} else {
				errorMsg.push('No link could be set from var click: ' + click + ' (Popup_v0.1.js)');
			}
			
		
		}

	} else if(typeof str_obj == 'string') {
		var string		= str_obj;
		this.onclick	= true;
		
		this.link		= string
	}
	
	if(link) {
		if(link.match('tmi=')) {
			var tmi = link.split('&');
			var len = tmi.length;
			var re 		= /tmi=/g;
			for(var i=0; i<len; i++) {
				if(tmi[i].match(re)) {
					var theTmi = tmi[i];
					break;
				}
			}
			
			tmi 	= theTmi.split('=')[1];
			var re 	= /\'\)/g;
			if(re.test(tmi)) {
				tmi = tmi.replace(re,'');
			}
			
			eval('marcomproMenu.setSelectedItemsById(\'menuId'+tmi+'\')');
		}
		
		return link;
	}

	
}

//***************************************************************************
// ChangedFieldValues checkCancel											*
// comments:	Check if the user pressed cancel in the popup				*
//***************************************************************************
ChangedFieldValues.prototype.checkCancel = function () {
	this.popupCancel = true;
}

//***************************************************************************
// ChangedFieldValues checkSubmit											*
// comments:	Check if the user pressed cancel in the submit button		*
//				if he has, all the values of the fields must be the set to	*
//				the first field values										*
//***************************************************************************
ChangedFieldValues.prototype.checkSubmit = function () {
	try {
		obj				= this.obj;
		var newValues	= this.onFocusNewValues;
		var firstValues	= this.onFocusFirstValues;
		var link		= this.setLink(obj);
		var msg			= '';
	
		for(var i in newValues) {
		
			var id 			= i;
			var newValue 	= newValues[i][0];
			var firstValue	= firstValues[i][0];
			
			if(newValue != firstValue) {
	
				var obj 	= document.getElementById(i);
				if(obj) {
	
					this.setFieldFirstValue(i, firstValue);
					this.setFieldNewValue(i, firstValue)
				}
			}
		}
	} catch(e) {
		errorMsg.push(e + ' (ChangedFieldValues.js: method checkSubmit())');
		debugWindow.handleAjaxError(errorMsg);
	}

}

var changedFieldValues = new ChangedFieldValues();

/**
 * Set Global vars
**/

var required		= 'required';
var minlength		= 'minlength';
var definition		= 'definition';
var formpopup		= 'popupref';
var link			= 'link';

var definitiontypes	= new Array();
definitiontypes[0]	= 'email';
definitiontypes[1]	= 'postalcode';
definitiontypes[2]	= 'zipcode';
definitiontypes[3]	= 'int';
definitiontypes[4]	= 'nospecialchars'; // for directories etc.
definitiontypes[5]	= 'phone';

var submittypes	= new Array();
submittypes[0]	= 'ajax';

/**
 * FormControl Constructor
 * @constructor
**/
function FormControl() {
	this.reset();
}

/**
 * Clear all vars
 **/
FormControl.prototype.reset = function(){
	this.errorMsgRequired	= new Object();
	this.errorMsgTypes		= new Object();
	this.errors				= 0;
	this.onFocusFirstValues	= new Object();
	this.showPopup			= false;
	this.linkAtt			= false;
	this.fieldserror		= '?do=popupfieldserror';
}
/**
 * setFormObject
 * @member FormControl
 * @param obj	'object'	The form object
 * @param saveType	'string'	(ajax)
 * @comment:	The saveType is the type in which the form has to save stuff
 *				For example: a for can be saved with ajax, when all the form
 *				fields are filled in correctly, save the form with ajax
**/
FormControl.prototype.checkAjaxFormObject = function (obj) {

}

/**
 * checkFormFields
 * @member FormControl
 * @param obj	'object'	The form object
 * @comment:	check the form field values
 *
**/
FormControl.prototype.checkFormFields = function (obj) {

	var count			= 0;
	var elements		= obj.elements;
	var len				= elements.length;
	for(i=0;i<len;i++) {

		var elem	= elements[i];

		var fieldId	= elem.id;
		var title	= elem.title;

		this.checkRequired(elem, title, obj);
		this.checkDefinitions(elem, title);
		this.checkMinLength(elem, title);

	}

	for(var i in this.errorMsgRequired) {
		count++;
	}

	for(var i in this.errorMsgTypes) {
		count++;
	}

	if(count > 0) {
		this.errors = 1;
		this.setTheMessage();
		return false;
	} else {
		this.errors = 0;
		return true;
	}
}
/**
 * checkOnly
 * @member FormControl
 * @param obj	'object'	The form object
 * @comment:	check the form field values
 *
**/
FormControl.prototype.checkOnly = function (obj) {

	var count			= 0;
	var elements		= obj.elements;
	var len				= elements.length;
	for(i=0;i<len;i++) {

		var elem	= elements[i];

		var fieldId	= elem.id;
		var title	= elem.title;

		this.checkRequired(elem, title, obj);
		this.checkDefinitions(elem, title);
		this.checkMinLength(elem, title);

	}

	for(var i in this.errorMsgRequired) {
		count++;
	}

	for(var i in this.errorMsgTypes) {
		count++;
	}

	if(count > 0) {
		this.errors = 1;
		return false;
	}
	
	this.errors = 0;
	return true;
}
/**
 * setSubmit
 * @member FormControl
 * @param obj	'object'	The form object
**/
FormControl.prototype.setSubmit = function (obj) {
	
	var definitionAtt 	= obj.getAttribute(definition);
	var showPopupAtt 	= obj.getAttribute(formpopup);
	if(obj.getAttribute('fieldserror')) {
		this.fieldserror 	= obj.getAttribute('fieldserror');
	}
	if(showPopupAtt) {
		this.showPopup = showPopupAtt;

		// check for a link

		var linkAtt 	= obj.getAttribute(link);
		if(linkAtt) {
			this.linkAtt = linkAtt;
		}
	}

	saveFormWithAjax.send(obj);
	return false;
}


/**
 * showSavePopup - to open a confirm popup in the template that is loaded,
 * return this function in a true <br/>
 * this.showPopup is set in setSubmit function when the <strong>formpopup</strong> attribute<br />
 * in the form tag is set to true
 * @member FormControl
**/
FormControl.prototype.showSavePopup = function () {
	return this.showPopup;
}


/**
 * savePopupLink
 * Sets a link for the extra button (besides the cancel button) <br/>
 * in the popup. If no link is set the value will be false
 * @member FormControl
**/
FormControl.prototype.savePopupLink = function () {
	return this.linkAtt;
}


/**
 * FormControl getRedirectLink
 * Set a link for the extra button (besides the cancel button)<br />
 * in the popup. If no link is set the value will be false
 * @member FormControl
**/
FormControl.prototype.getRedirectLink = function () {
	return this.linkAtt;
}

/**
 * FormControl resetSavePopup
 * When popup is shown, reset the values, otherwise we will stay in a loop
 * @member FormControl
**/
FormControl.prototype.resetSavePopup = function () {
	this.showPopup = false;
}

/**
 * FormControl resetSavePopup
 * Set the url to which the error message has to be send
 * @member FormControl
**/
FormControl.prototype.setFieldsErrorUrl = function (value) {
	this.fieldserror = value;
}

/**
 * FormControl checkrequired
 * @param elem	'object'	the field object
 * @param title	'string'	the field title
 * @param obj	'object'	the form obj
 * @comment:	Look for required form elements
 * @member FormControl
**/
FormControl.prototype.checkRequired = function (elem, title, obj) {

	var id			= elem.id;
	var value		= elem.value;
	var requiredAtt	= elem.getAttribute(required);
	var count		= 0;

	if(requiredAtt && requiredAtt == 'required') {

		if(elem.type == 'radio' || elem.type == 'checkbox') {
			var name	= elem.name;
			var check 	= this.getRadioCheckboxItems(obj, name);
		} else{
			var check	= 1;
		}


		if(value == '' || !check) {

			if(!title || title == '') {
				//errorMsg.push(e + ' (FormControl.js)');
				//debugWindow.handleAjaxError(errorMsg);
				return count;
			}

			this.errorMsgRequired[title] 		= new Object();
			this.errorMsgRequired[title].id		= id;
			count++;
		}
	}

	return count;
}

/**
 * FormControl getRadioItems
 * @param obj	'object'	the form obj
 * @param name	'string'	the radio btn name
 * @comment:	Look for required form elements
 * @member FormControl
**/
FormControl.prototype.getRadioCheckboxItems = function (obj, name) {
	var elements	= obj.elements;
	var len			= elements.length;

	for(var i=0; i<len; i++) {
		var elem	= elements[i];
		var type	= elem.type;
		if(type == 'radio' || type == 'checkbox') {

			var elemName	= elem.name;
			if(elemName == name) {
				if(elem.checked) {
					return 1;
				}
			}
		}
	}

	return 0;
}


/**
 * FormControl checkdefinitions
 * @param obj	'elem'	the field object
 * @param title	'string'	the field title
 * @comment:	Look for correct values in the form fields
 * @member FormControl
**/
FormControl.prototype.checkDefinitions = function (elem, title) {
	var definitionAtt	= elem.getAttribute(definition);
	var count			= 0;
	var id				= elem.id;
	var value			= elem.value;

	if(definitionAtt) {
		if(definitionAtt == definitiontypes[0]) {
			if(elem.value != '') {
				var emailCheck	= this.checkEmail(elem);
				if(!emailCheck) {
					count++;
					this.errorMsgTypes[title] 		= new Object();
					this.errorMsgTypes[title].id	= id;
				}
			}
		} else if(definitionAtt == definitiontypes[1]) {
			if(elem.value != '') {
				var postalcodeCheck	= this.checkPostalcode(elem);
				if(!postalcodeCheck) {
					count++;
					this.errorMsgTypes[title] 		= new Object();
					this.errorMsgTypes[title].id	= id;
				}
			}
		} else if(definitionAtt == definitiontypes[2]) {
			if(elem.value != '') {
				var zipcodeCheck	= this.checkZipcode(elem);
				if(!zipcodeCheck) {
					count++;
					this.errorMsgTypes[title] 		= new Object();
					this.errorMsgTypes[title].title	= id;
				}
			}
		} else if(definitionAtt == definitiontypes[3]) {
			if(elem.value != '') {
				var intCheck	= this.checkInt(elem);
				if(!intCheck) {
					count++;
					this.errorMsgTypes[title] 		= new Object();
					this.errorMsgTypes[title].id	= id;
				}
			}
		} else if(definitionAtt == definitiontypes[4]) {
			if(elem.value != '') {
				var intCheck	= this.noSpecialChars(elem);
				if(!intCheck) {
					count++;
					this.errorMsgTypes[title] 		= new Object();
					this.errorMsgTypes[title].id	= id;
				}
			}
		} else if(definitionAtt == definitiontypes[5]) {
			if(elem.value != '') {
				var phoneCheck	= this.checkPhone(elem);
				if(!phoneCheck) {
					count++;
					this.errorMsgTypes[title] 		= new Object();
					this.errorMsgTypes[title].id	= id;
				}
			}
		}
		
	}

	return count;
}

/**
 * FormControl checkMinLength
 * @param obj	'elem'	the field object
 * @param title	'string'	the field title
 * @comment:	check if the min length of content is reached
 * @member FormControl
**/
FormControl.prototype.checkMinLength = function (elem, title) {
	var minLengthAtt	= elem.getAttribute(minlength);
	if(minLengthAtt) {
		var count			= 0;
		var id				= elem.id;
		var value			= elem.value;
		var strlen			= value.length;

		if(strlen < minLengthAtt) {
			count++;
			this.errorMsgTypes[title] 		= new Object();
			this.errorMsgTypes[title].id	= id;
		}
	}
	return count;
}

/**
 * FormControl checkEmail
 * @param elem	'object'	the field object
 * @member FormControl
**/
FormControl.prototype.checkEmail = function (elem) {

	//var validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
	var validRegExp = new RegExp("^([a-zA-Z0-9\\-\\.\\_]+)(\\@)([a-zA-Z0-9\\-\\.]+)(\\.)([a-zA-Z]{2,4})$");
	var strEmail = elem.value;
	if (strEmail.search(validRegExp) == -1)
	{
		return false;
	}
	return true;

}

/**
 * FormControl checkInt
 * @param elem	'object'	the field object
 * @member FormControl
**/
FormControl.prototype.checkInt = function (elem) {
	if(isNaN(elem.value)) {
		return false;
	}
	return true;
}

/**
 * FormControl checkPhone
 * @param elem	'object'	the field object
 * @member FormControl
**/
FormControl.prototype.checkPhone = function (elem) {
	var validChars = "0123456789";
	var character;
	
	for (var z=0;z<elem.value.length;z++) { 
		character = elem.value.charAt(z); 
		if (validChars.indexOf(character) == -1 || elem.value.length < 10) {
			return false;
		}
	}
	return true;

}


/**
 * FormControl noSpecialChars
 * @param elem	'object'	the field object
 * @member FormControl
**/
FormControl.prototype.noSpecialChars = function (elem) {

	var validRegExp = /[^$A-Za-z0-9_]/;
	var value		= elem.value;

	if (value.match(validRegExp) == -1) {
		return false;
	}
	return true;
}

/**
 * FormControl checkPostalcode
 * @param elem	'object'	the field object
 * @member FormControl
**/
FormControl.prototype.checkPostalcode = function (elem) {

	var validRegExp_1 = /^[1-9][0-9]{3} [A-Za-z]{2}$/;
	var validRegExp_2 = /^[1-9][0-9]{3}[A-Za-z]{2}$/;
	var strZipcode 	= elem.value;
	if (strZipcode.search(validRegExp_1) == -1 && strZipcode.search(validRegExp_2) == -1)
	{
		return false;
	}
	return true;

}


/**
 * FormControl checkZipcode
 * @param elem	'object'	the field object
 * @member FormControl
**/
FormControl.prototype.checkZipcode = function (elem) {

	var validRegExp_1 = /^[1-9][0-9]{3} [a-z|A-Z]{2}$/;
	var validRegExp_2 = /^[1-9][0-9]{3}[a-z|A-Z]{2}$/;
	var strZipcode = elem.value;
	if (strZipcode.search(validRegExp_1) == -1 && strZipcode.search(validRegExp_2) == -1)
	{
		return false;
	}
	return true;

}

/**
 * FormControl setTheMessage
 * Set the message fields and pass them to the template loader as a post. An error popup will be opened
 * @requires LoadingTemplatesWithAjax loads the popupfieldserror-map containing the form-validationerrors
 * @requires XmlHTTPObject resets the loader
 * @member FormControl
**/
FormControl.prototype.setTheMessage = function () {
	var msg		= '';
	msgRequired	= this.errorMsgRequired;

	for(var i in msgRequired) {
		msg		+= '&requiredContent[' + i + ']=' + msgRequired[i].id;
	}

	msgTypes	= this.errorMsgTypes;
	for(var i in msgTypes) {
		msg		+= '&wrongContent[' + i + ']=' + msgTypes[i].id;
	}


	// load the popup template
	loadingTemplatesWithAjax.loadTplPost(this.fieldserror, msg);

	// make sure the loader will apear
	// its just a check
	xmlHttpObject.resetLoader();

	// reset
	this.errorMsgRequired	= new Object();
	this.errorMsgTypes		= new Object();

	return true;
}

var formControl	= new FormControl();

// remove the /] in the header of the document
// it comes from the dtd include

//<![CDATA[
if(!IE) {
	try {
		var len = document.body.childNodes.length;
		with (window.document.body) 
		for (var i=0;i<len;++i) {
			if (/]>/.test(childNodes[i].data)) {
				removeChild(childNodes[i]);
				break;
			}
		} 
	} catch(e) {}
}
//]]>


//***************************************************************************
// Set Global vars															*	
//***************************************************************************
var popupId;
//********************
// Popup Constructor *
//********************
function ShowPopup() {
	this.content			= '';
	this.title				= '';
	this.link				= '';
	this.onclick			= '';
	popupClose				= true;
	callCancelFunction		= null;
	callSubmitFunction		= null;
	popupOnclick			= '';
	method					= null;
}

ShowPopup.prototype.setMessage = function(content) {
	this.content	= content;
}

ShowPopup.prototype.setTitle = function(title) {
	this.title	= title;
}


ShowPopup.prototype.resetContent = function() {
	this.title		= '';
	this.content	= '';
	popupClose		= true;
}

ShowPopup.prototype.disabled = function(disabled) {
	// do not close the popup after an onclick
	if(disabled == 'false') {
		popupClose = false;
	}
}

ShowPopup.prototype.setMethod = function(methodType) {
	method = methodType;
	
}

ShowPopup.prototype.getMethod = function() {
	return method;
}

ShowPopup.prototype.setOnclick = function(link) {
	popupOnclick = link;
}

ShowPopup.prototype.getOnclick = function() {
	return popupOnclick;
}

ShowPopup.prototype.setGoBtnName = function(id, name) {
	obj			= document.getElementById(id);
	var buttons	= obj.getElementsByTagName('INPUT');
	for(i=0;i<buttons.length;i++) {
		if(buttons[i].name == 'go') {
			buttons[i].name = name;
		}
	}
}

ShowPopup.prototype.setCancelBtnName = function(id, name) {
	obj			= document.getElementById(id);
	var buttons	= obj.getElementsByTagName('INPUT');
	for(i=0;i<buttons.length;i++) {
		if(buttons[i].name == 'cancel') {
			buttons[i].name = name;
		}
	}
}

ShowPopup.prototype.setLink = function(link) {
	var newLink	= link.split('/');
	if(newLink) {
		var size	= (newLink.length) -1;
		this.link	= newLink[size];
	} else {
		this.link	= link;
	}
}

ShowPopup.prototype.checkCancel = function(callFunction) {
	callCancelFunction = callFunction;
}

ShowPopup.prototype.checkSubmit = function(callFunction) {
	callSubmitFunction = callFunction;
}

ShowPopup.prototype.getCancelFunc = function() {
	return callCancelFunction;
}

ShowPopup.prototype.getSubmitFunc = function() {
	return callSubmitFunction;
}

ShowPopup.prototype.checkBtns = function(id) {
	try {
		obj			= document.getElementById(id);
		var count	= new Array;
		
		var buttons	= obj.getElementsByTagName('INPUT');
		for(i=0;i<buttons.length;i++) {
			if(buttons[i].name == 'cancel') {
				count[i] = 'cancel';
			} else if(buttons[i].name == 'go') {
				count[i] = 'go';
			}
		}
		return count;
	} catch(e) {
		errorMsg.push(e + ' (Popup_v0.1.js)');
	}
}

//********************
ShowPopup.prototype.position = function(id) {
	
	if(IE) {
		checkDocumentSelectBoxes('hidden');
	}
	
	try {
		this.popupFilter	= document.getElementById('popupFilter');
		this.obj			= document.getElementById(id);
		
		this.popupFilter.className       = 'show';
		this.obj.className				 = 'show';
	} catch(e) {
		errorMsg.push(e + ' (Popup_v0.1.js)');
	}
	
	setPopupId(id);

	//this.setContent();
	
}

ShowPopup.prototype.setContent = function() {
	try {
		var spans			= this.obj.getElementsByTagName('SPAN');
		var buttons			= this.obj.getElementsByTagName('INPUT');
		
		_this				= this;
	
		for(i=0;i<buttons.length;i++) {
			var button	= buttons[i];
			if(button.name == 'go') {
				if(IE) {
					button.onclick = setPopupGoEvent;
				} else {
					button.addEventListener("click", setPopupGoEvent, false);
				}
			} else if(button.name == 'cancel') {
				if(IE) {
					button.onclick = setPopupNoEvent;
				} else {
					button.addEventListener("click", setPopupNoEvent, false);
				}
			}
			
			//buttons[i] = null;
		}
		
		if(this.content != '' && this.content != '') {
		
			for(i=0;i<spans.length;i++) {
				if(spans[i].className == 'content') {
					if(this.content != '') {
						spans[i].innerHTML = this.content;
					}
				} else if(spans[i].className == 'title') {
					if(this.title != '') {
						spans[i].innerHTML = this.title;
					}
				}
			}
		}
		
		button	= null;
		buttons = null;
		spans	= null;
		return;
	} catch(e) {
		alert(e);
	}

}



setPopupGoEvent = function(evt) {
	
	if(click) {
		return;
	}
	
	
	var click 	= showPopup.getOnclick();
		
	var method 	= showPopup.getMethod();
	
	// call to an extra function by a submit
	if(showPopup.getSubmitFunc()) {
		eval(showPopup.getSubmitFunc());
	}
	
	if(click != '') {
		if(IE) {
			var btn			= event.srcElement;
		} else {
			var btn 		= evt.currentTarget;
		}
		
		
		btn.onclick = click;
		var type	= typeof(btn.onclick);
		
		if(type == 'function') {
			// first close the popup
			// otherwise the objects are gone
			closePopup();
			// do the event when the var is a function
			btn.onclick();
		} else if(method == 'function') {
			eval(click);
		} else {
			closePopup();
			
			try {

				// else, when the var is a string, load the string in the template loader
				if(method == 'post') {
					btn.onclick = loadingTemplatesWithAjax.loadTplPost(click, 1);
				} else if(method == 'get') {
					
					btn.onclick = loadingTemplatesWithAjax.loadTpl(click);
				} else if(!method)  {
					// temp hack
					// we need to re-write this class soon
					
					if(click.charAt(0) == '?') {
						btn.onclick = loadingTemplatesWithAjax.loadTpl(click);
					} else {
						errorMsg.push('the var click is not an url, but probably a function (Popup_v0.1.js.js)');
						debugWindow.handleAjaxError(errorMsg);	
					}
				} 
			} catch (e) {
				errorMsg.push(e + ' (Popup_v0.1.js.js)');
				debugWindow.handleAjaxError(errorMsg);
			}
			
		} 

	} else {
		document.location.href = _this.link;
	}

	// clean the method, otherwise it will be remembered!	
	method			= null;
	_this.method 	= null;
	btn 			= null;
	click			= null;
	type			= null;
	return;
	
}

setPopupNoEvent = function(evt) {
	// call to an extra function
	
	if(callCancelFunction) {
		eval(callCancelFunction);
	}
	popupClose = 1;
	closePopup();
}

setPopupId = function(id) {
	popupId	= id;
}

closePopup = function() {

	
	if(popupClose) {
		if(IE) {
			checkDocumentSelectBoxes('visible');
		}
		
		try {
			var popupFilter			= document.getElementById('popupFilter');
			var popups				= document.getElementById('popups');
			var popup				= document.getElementById('popup');
			var obj					= document.getElementById(popupId);
			
			obj.className			= 'hide';	
			popupFilter.className	= 'hide';
			// clean up the mess
			
			$('popups').setStyle({height:0, margin:0, padding: 0});
			$('popups').innerHTML = '';
		} catch(e) {
			errorMsg.push(e + ' (Popup_v0.1.js)');
			
		}
	}
	
	// clean the method, otherwise it will be remembered!	
	_this.method 	= null;
	method			= null;
	
	
}

// hide select boxes for IE
checkDocumentSelectBoxes = function(type) {
	var selects	= document.getElementsByTagName('SELECT');
	var len		= selects.length;
	
	for(var i=0;i<len;i++) {
		var select	= selects[i];
		select.style.visibility = type;
	}

}

var showPopup = new ShowPopup();


//***************************************************************************
// StatusErrors Constructor  												*
// comments:	Class wich returns all the errors that can occure			*
//***************************************************************************

function StatusErrors() {
	
}

//***************************************************************************
// XMLHttpObject post														*
// comments:
//***************************************************************************
StatusErrors.prototype.statusCheck = function(status, url) {

	try {
		rExp 			= /&/gi;
		replaceInUrl 	= new String("{{||}}");
		newUrl 			= url.replace(rExp, replaceInUrl);
		
		switch(status) {
		// bad request ( Impossible request or syntax error)
		case 400:
			loadingTemplatesWithAjax.loadTpl('marcompro.php?do=popuploaderror&errorType=' + status + '&url=' + newUrl);
			
			return false;
			break;
		// Unauthorized (Request should be retried with proper authorization header.)
		case 401:
			loadingTemplatesWithAjax.loadTpl('marcompro.php?do=popuploaderror&errorType=' + status + '&url=' + newUrl);
			
			return false;
			break;
		// Payment Required ( Request should be retried with proper charge-to header)
		case 402:
			loadingTemplatesWithAjax.loadTpl('marcompro.php?do=popuploaderror&errorType=' + status + '&url=' + newUrl);
			
			return false;
			break;
		// Forbidden ( Authorization will not help)
		case 403:
			loadingTemplatesWithAjax.loadTpl('marcompro.php?do=popuploaderror&errorType=' + status + '&url=' + newUrl);
			
			return false;
			break;
		// page not found (A document with that URL doesn't exist)
		case 404:
			loadingTemplatesWithAjax.loadTpl('marcompro.php?do=popuploaderror&errorType=' + status + '&url=' + newUrl);
			
			return false;
			break;
		// No such group ( (NCSA httpd) the newsgroup in news:newsgroup doesn't exist.)
		case 411:
			loadingTemplatesWithAjax.loadTpl('marcompro.php?do=popuploaderror&errorType=' + status + '&url=' + newUrl);
			
			return false;
			break;
		// Internal Error
		case 500:
			loadingTemplatesWithAjax.loadTpl('marcompro.php?do=popuploaderror&errorType=' + status + '&url=' + newUrl);
			
			return false;
			break;
		// Not implemented
		case 501:
			loadingTemplatesWithAjax.loadTpl('marcompro.php?do=popuploaderror&errorType=' + status + '&url=' + newUrl);
			
			return false;
			break;
		// Timed out
		case 502:
			loadingTemplatesWithAjax.loadTpl('marcompro.php?do=popuploaderror&errorType=' + status + '&url=' + newUrl);
			
			return false;
			break;	
			
		default:
			return true;
			break;
		}
	} catch(e) {
		
	}
}

var statusErrors = new StatusErrors();



/**
 * Set Global vars
**/
var returnValue;

/**
 * XMLHttpObject Constructor
**/
function XMLHttpObject() {
	this.errorMsg		= new Array();
	this.connectionSecs = 10000; // 10 seconds
	this.loader			= true;
	this.initializer	= 1;
	this.replaceAnchors	= false;
	this.project_http	= "";
}

/**
 * XMLHttpObject post
 * @comments:
**/
XMLHttpObject.prototype.post = function(file, url) {
	if (window.XMLHttpRequest) this._xmlhttp = new XMLHttpRequest();
	else if (window.ActiveXObject) this._xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

	this.requesting();
	var instance = this;

	this._xmlhttp.open('POST', file, true);
	this._xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset:UTF-8');
	this._xmlhttp.onreadystatechange = function() {
		switch(instance._xmlhttp.readyState) {
		
		case 1:
			instance.loading();
			break;
		// loaded
		case 2:
			//instance.loaded();
			break;
		// interactive
		case 3:
			instance.interactive();
			break;
		//complete
		case 4:
		var status = 1;
		
			if(MARCOMPRO_MODE) {
				status = statusErrors.statusCheck(instance._xmlhttp.status, url);
			}
			
			if(status) {
				var result = instance._xmlhttp.responseText;
				instance.response(result);
			}

			break;
		}
	}

	this._xmlhttp.send(url);
}

/**
 * XMLHttpObject get
 * @comments:
**/
XMLHttpObject.prototype.get = function(url) {

	if (window.XMLHttpRequest) this._xmlhttp = new XMLHttpRequest();
	else if (window.ActiveXObject) this._xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	this.url 		= url;
	var instance 	= this;

	this._xmlhttp.open('GET', url, true);
	this._xmlhttp.onreadystatechange = function() {
		switch(instance._xmlhttp.readyState) {
			case 1:
				instance.loading();
				break;
			// loaded
			case 2:
				//instance.loaded();
				break;
			// interactive
			case 3:
				instance.interactive();
				break;
			//complete
			case 4:
				var status = 1;
				if(MARCOMPRO_MODE) {
					var status = statusErrors.statusCheck(instance._xmlhttp.status, url);
				}
				
				if(status) {
					var result 			= instance._xmlhttp.responseText;
					instance.response(result);
				}
	
				break;
		}
	}
	this._xmlhttp.send(null);
}

XMLHttpObject.prototype.loading = function() {
	this.requesting();
}

XMLHttpObject.prototype.loaded = function() {
	this.endRequesting();
}

XMLHttpObject.prototype.interactive = function() {

}

/**
 * XMLHttpObject unsetInit
 * @comments: 	set the initializer to false, so not always will the init()
 *				be triggered
**/
XMLHttpObject.prototype.unsetInit = function() {
	this.initializer = 0;
}

/**
 * XMLHttpObject setInit
 * @comments: 	reset the this.initializer so the init() will be triggerd
 *				again after a tpl load
**/
XMLHttpObject.prototype.setInit = function() {
	this.initializer = 1;
}

/**
 * XMLHttpObject unsetLoader
 * @comments: 	When the this.loader = false, do not disable the anchor tags
 *				and don't show the sandglass :-)
**/
XMLHttpObject.prototype.unsetLoader = function() {
	this.loader	 = false;
}

/**
 * XMLHttpObject resetLoader
 * @comments:
**/
XMLHttpObject.prototype.resetLoader = function() {
	this.loader	= true;
}

/**
 * XMLHttpObject requesting
 * @comments:	When the loader is false, show a sandglass and make
 *				users can not click when the templates are loading
**/
XMLHttpObject.prototype.requesting = function () {
	

	if(this.loader == true) {

		// disable all the possible clicks
		showAppLayer();
		
		if(IE) {
			document.body.attachEvent("onclick", disableClick, false);
		} else {
			document.body.addEventListener("click", disableClick, false);
		}


		// show the loader
		document.body.style.cursor = 'wait';
		
		
		if(document.getElementById('page-busy-loading')) {
			this.endRequest = 0;
			this.pageLoading();
		}

	}

}

/**
 * XMLHttpObject pageLoading
 * @comments:
**/
XMLHttpObject.prototype.pageLoading = function () {
	
	var loading = new YAHOO.util.Anim("page-busy-loading", {
		width: {from: 0, to:100}
	}, 1.3);
	
	loading.animate();
	
	loading.onComplete.subscribe(function() {
		if(!xmlHttpObject.endRequest) {
			xmlHttpObject.pageLoading();
		} else {
			document.getElementById('page-busy-loading').setStyle({width:0});
		}
	});
}

/**
 * XMLHttpObject requesting
 * @comments:	When the loader is false, show a sandglass and make
 *				users can not click when the templates are loading
**/
XMLHttpObject.prototype.endRequesting = function () {

	if(this.loader == true) {

		document.body.style.cursor = 'default';
		var anchor = getAnchorObject();
		
		if(anchor) {
			
			if(anchor.style) {

				// IE
				anchor.style.cursor = 'hand';
				// other
				anchor.style.cursor = 'pointer';
			}
		} else {
			errorMsg.push('No anchor tag is found (XMLHttpObject.js method endRequesting())');
		}

		if(errorMsg.length) {
			debugWindow.handleAjaxError(errorMsg);
		}
		// template is loaded, so kill the rest
		/*
		timer.stop();
		*/
		hideAppLayer();
		
		if(document.getElementById('page-busy-loading')) {
			
			this.endRequest = 1;
		
		}
	}

}

/**
 * XMLHttpObject tplStatus
 * @param string func 		the function to be evaluated
 * @param int 	 delay 		delay for re-invoking the function
 * @comments:	U can call this method from everywhere, so you can keep on
 *				checking the status when the template is loading
 *				returns true when the template is loaded completely
 *				You can also give a method name as a parameter
**/
/*
XMLHttpObject.prototype.tplStatus = function (func, delay) {
	
	if(!delay) {
		var delay = 1000;
	}

	if(this._xmlhttp.readyState == 4 && this._xmlhttp.responseText != '') {
		// do something with a method
		
		if(func && func != '') {
			
			eval(func);
		}
		return true;
	} else {

		setTimeout("xmlHttpObject.tplStatus('" + func + "', '" + delay + "')", delay);
	}

}
*/
XMLHttpObject.prototype.tplStatus = function (func, delay, emptyResponse) {
	
	if(!delay) {
		var delay = 1000;
	}
	
	if(this._xmlhttp.readyState == 4) {
		// do something with a method
		
		if(emptyResponse) {
			if(func && func != '') {
				eval(func);
			}
		} else if(this._xmlhttp.responseText != '') {
			if(func && func != '') {
				eval(func);
			}
		}
		
		return true;
	} else {
		setTimeout("xmlHttpObject.tplStatus('" + func + "', '" + delay + "', '" + emptyResponse + "')", delay);
	}

}

/**
 * XMLHttpObject checkContent
 * @param string result
 * @comments:	Check the result. If the result starts with an xml tag, we
 *				cannot convert the content in the loadingTemplatesWithAjax
 *				class. Redirect to the login, probably the session has ended
**/
XMLHttpObject.prototype.checkContent = function (result) {

	var content = result;
	if(content.match('xml version="1.0" encoding="utf-8"')) {
		return false;
	}

	return true;

}

/**
 * XMLHttpObject abort
 * @comments:	U can call this method from everywhere, so you can keep on
 *				checking the status when te template is loading
 *				returns true when the template is loaded completely
 *				You can also give a method name as a parameter
**/
XMLHttpObject.prototype.abort = function () {
	this._xmlhttp.abort();
}

/**
 * response
 * @comments:
**/
XMLHttpObject.prototype.response = function(result) {

	if(result) {
		var checkContent 	= this.checkContent(result);

		if(checkContent) {
			// set the response
			
			if(this.replaceAnchors){
				//result = result.replace(/href='#'/g, "href='javascript:void(0);'");
				//result = result.replace(/href="#"/g, 'href="javascript:void(0);"');				
				
				result = result.replace( new RegExp( 'href="#"', 'g' ), 'href="javascript:void(0);"' );
				result = result.replace( new RegExp( "href='#'", "g" ), "href='javascript:void(0);'" );
				
				if(this.project_http!=""){					
					result = result.replace( new RegExp( 'href="' + this.project_http + '#"', 'g' ), 'href="javascript:void(0);"' );
					result = result.replace( new RegExp( "href='" + this.project_http + "#'", "g" ), "href='javascript:void(0);'" );
				}
			}
			
			loadingTemplatesWithAjax.setResponse(result);
			
			this.rawResponse = result;
			// the template is loaded correctly, now we can save the last url that was used
			loadingTemplatesWithAjax.setLastLoadedTpl();

			if(this.initializer && MARCOMPRO_MODE) {
				init();
			}
			
			this.loaded();
			/*if(MARCOMPRO_MODE) {
				
				//initCB();
			}*/
		} else {
			// probably the users session has ended!Give a notice
			loadingTemplatesWithAjax.loadTpl('?do=sessionEnded');
		}

	} else {
		errorMsg.push('Resultset was empty or not set (url: ' + xmlHttpObject.url + ' in file: XMLHttpObject.js)');
		debugWindow.handleAjaxError(errorMsg);
	}

	return;
}


/**
 * getRawResponse
 * @comments: get the raw response before it is being converted
**/
XMLHttpObject.prototype.getRawResponse = function() {

	return this.rawResponse;
}


/**
 * disableClick
 * @comments: 	When templates are loaded disable the clicks. When the
 *				req.status == 200 (templates are completely loaded) remove
 *				the event
**/
disableClick = function(evt) {
	if(returnValue == 200) {
		this.removeEventListener("click", arguments.callee, false);
	}
}

/**
 * showAppLayer
 * @comments: 	Showing the application layer means that a layer will be on
 *				top of the application,so nothing can be clicked while
 *				templates are being loaded
**/
showAppLayer = function() {
	var appLayer = document.getElementById('appLayer');

	if(appLayer) {
		appLayer.className = 'show';
	}
}

/**
 * showAppLayer
 * @comments: 	Hide the application layer
**/
hideAppLayer = function() {
	var appLayer = document.getElementById('appLayer');

	if(appLayer) {
		appLayer.className = 'hide';
	}
}

var xmlHttpObject = new XMLHttpObject();

/**
 * SaveFormWithAjax Constructor
 * @param 	popupObj	'object'
 * @param 	XMLHttpObject	'object'
 * @return	'bool'
 * @comments: 	use popup object when errors occure
 *				when there's a response needed, set the response to true
**/
function SaveFormWithAjax() {
	this.loop 	= 0;
	this.count 	= 0;
	// popup.position('downloadPDF')
}

/**
 * SaveFormWithAjax send
 * @param obj	'object' the form object
 * @comments: 	loop through the form, only fields with an id will be saved
 **/
SaveFormWithAjax.prototype.send = function (obj) {
	
	try {
		if(typeof(obj) == 'string') {
			// if an id isset instead of an object
			obj = document.getElementById(obj);
		}


		var url			= '';
		var action		= obj.action;
		var file		= this.getFile(action);

		//var synchWysiwyg= this.synchWysiwyg();
		var form		= obj;
		var fields		= form.elements;
		var len			= fields.length;

		for(var i=0;i<len;i++) {
			var field = fields[i];
			if(field.id) {
				if(field.type != 'submit' && field.type != 'button' && field.type != 'label') {

					if(field.type == 'checkbox' || field.type == 'radio') {
						
						var value	= field.value;
						var name	= field.name;

						if(field.checked) {

							if(name != '') {
								
								url			+= '&' + name + '=' + encodeURIComponent(value);
								
							}

						} else if (field.type == 'checkbox') {

							if(name != '') {
								var submitempty = field.getAttribute('submitempty');
								
								if(!submitempty) {
									url			+= '&' + name + '=0';
								}
							}
						}
					} else if(field.type == 'file') {
						var upload = this.upload(form);
						if(upload) {
							// prevent form submitting twice
							return false;
						}
					} else if(field.type == 'textarea') {
						
					
						var txt = field.value;
						field.value = txt.replace(/<br>/g,'');	//Now we replace the <br> tag, since the editor combines a <br> with a newline, we do not need to place it ourself
						field.value = txt.replace(/<br \/>/g,'');	//Now we replace the <br> tag, since the editor combines a <br> with a newline, we do not need to place it ourself


						var value	= field.value;
						var name	= field.name;
						
						if(name != '') {
							
							url			+= '&' + name + '=' + encodeURIComponent(value);
						
						} else {
							if(IE) {
								// ons zorgen kindje IE
								a
								if(field.getAttribute('hack_ie')) {
									var name = field.getAttribute('hack_ie');
									
									url			+= '&' + name + '=' + encodeURIComponent(value);
								
								}
							}								
						}
					} else {

						if(field.value) {
							var value	= field.value;
						} else {
							var value	= '';
						}

						var name	= field.name;
						if(name != '') {
							
							url			+= '&' + name + '=' + encodeURIComponent(value);
						
						} else {
							if(IE) {
								// ons zorgen kindje IE
								if(field.getAttribute('hack_ie')) {
									var name = field.getAttribute('hack_ie');
									url			+= '&' + name + '=' + encodeURIComponent(value);
								}
							}
						}
					}
				}
			}
		}
		
		
		

		
		if(IE) {
			file = loadingTemplatesWithAjax.checkFilename(file);
		}

		var submit	= this.sendForm(file, url);
		if(submit) {


			return true;
		}

		return false;
	} catch(e) {
		
		errorMsg.push(e + 'saveformWithAjax.js (method: send())');
		debugWindow.handleAjaxError(errorMsg);
	}
}


/**
 * SaveFormWithAjax upload
 * @param field	'object'
 * @comments:
**/
SaveFormWithAjax.prototype.upload = function (form) {

	if(this.iFrame) {
		form.submit();

		return true;
	} else {
		errorMsg.push('No iframe to save the form in!When we want to upload a file, we need an iframe! (SaveFormWithAjax.js)');
		debugWindow.handleAjaxError(errorMsg);
		return false;
	}
}

/**
 * SaveFormWithAjax setUpload
 * @obj	'object'	iFrame object
 * @comments:
**/
SaveFormWithAjax.prototype.setUpload = function (obj) {
	this.iFrame	= obj;
}

/**
 * SaveFormWithAjax sendForm
 * @param file	'string' the marcompro.php?do=something
 * @param url	'string' The post values
 * @comments: 	Sending the url as a post to the action	using the
 *				XMLHttpObject
 *				return true if everything went ok
 *				return false if an error occures
**/
SaveFormWithAjax.prototype.sendForm = function (file, url) {
	xmlHttpObject.post(file, url);
	return true;
}


/**
 * SaveFormWithAjax getFile
 * @action	'string' the absolute path
 * @comments: 	Return the relative action path
**/
SaveFormWithAjax.prototype.getFile = function (action) {
	var newFile	= action.split('/');
	var size	= (newFile.length) -1;
	var file	= newFile[size];
	return file;
}

var saveFormWithAjax = new SaveFormWithAjax();

/**
 * Set Global vars
*/
	var popup		= new ShowPopup();
/*
 * LoadingTemplatesWithAjax Constructor
 * @comments:
**/
function LoadingTemplatesWithAjax() {
	this.errorMsg			= new Array();
	this.lastLoadedTpl		= new Array();
	this.newStr				= new Object();
	this.url				= '';
	this.sendType			= '';
}

/**
 * LoadingTemplatesWithAjax loadTpl
 * @param url	'string'
 * @comments: 	Sending the url as a get to the action	using the
 *				XMLHttpObject
 *				return true if everything went ok
 *				return false if an error occures
**/

LoadingTemplatesWithAjax.prototype.loadTpl = function (url) {
	// if there are any loopings, stop them so we do not have multiple requests
	if(typeof(timer) == 'object') {
		timer.stop();
	}
	if(IE) {
		url = this.checkFilename(url);
	}

	this.sendType	= 'get';
	this.url 		= this.checkUrl(url);

	xmlHttpObject.get(url);
	return true;
}

/**
 * LoadingTemplatesWithAjax loadTplPost
 * @param file	'string' (example: marcompro.php?do=popup)
 * @param get	'bool || string'	treat the post as a get	using the & as params
 * @param obj	'object'	Whem the clicked element is not an anchor tag, whe can use this object as a reference
 * @comments: 	Sending the file as a post to the action	using the
 *				XMLHttpObject
 *				return true if everything went ok
 *				return false if an error occures
 *				By setting the get, means that a url is already set
 *				the get can be a part of a url or a boolean
 *				2 examples @ Popup_v0.1.js and Refresh.js
 *				Otherwise we have to look for the right fields and make a url
**/
LoadingTemplatesWithAjax.prototype.loadTplPost = function (file, get, obj) {
	
	// if there are any loopings, stop them so we do not have multiple requests
	if(typeof(timer) == 'object') {
		timer.stop();
	}
	
	if(get == '' && get != 0) {
		errorMsg.push(' The post your are sending is empty (LoadingTemplatesWithAjax.js)');
		debugWindow.handleAjaxError(errorMsg);
		this.loadTpl(file);
		return;
	}

	var url = false;
	// first set the post values
	// if we already know the postvalues, use them as a get
	if(get) {
		if(get == 1) {
			var url = file;
		} else {
			var url = get;
		}
	} else {
		
		// else find the post values within the document
		postValues.setPostValues(obj);
		// then get the post values as a url string
		
		if(postValues.fieldErrors) {
			return;
		}
		
		var url	= postValues.getPostValues();
	}

	if(IE) {
		file = this.checkFilename(file);
	}

	if(file) {
		this.sendType	= 'post';
		this.file		= this.checkUrl(file);
		
		if(url != '') {
			this.url 		= this.checkUrl(url);
		}
		
		xmlHttpObject.post(file, url);

		return true;
	}
}

/**
 *LoadingTemplatesWithAjax preloadImgWait
 *@param url	'string'
 *@comments: 	Wait till all images are preloaded before we show the content
**/
LoadingTemplatesWithAjax.prototype.preloadImgWait = function (id, count) {
	
	try {
		if(!count) {
			var count			= 0;
		}
		var contentObj 		= document.getElementById(id);
		var docImages 		= contentObj.getElementsByTagName('img');
		
		if(docImages) {
			var len = docImages.length;
			var c	= 0;
			for(var i=0; i<len; i++) {
				var img	= docImages[i];
			
				if(img && img.complete) {
					c++;
					var loaderObj 	= find.findPreviousSibling(img, 'IMG');
				
					if(loaderObj) {
						
						var definition = '';
						if(loaderObj.getAttribute('definition')) {
						
							definition	= loaderObj.getAttribute('definition');
							
							if(definition == 'loader') {
								
								loaderObj.className = 'marcompro_hide';
								loaderObj = null;
								
							}
							
						}
						
					}
					
					img.className			= 'marcompro_show';
					
				}
			}
			
			if (c == len) {
				var obj					= document.getElementById('temp_preloader');
				if(obj) {
					obj.remove(obj);
				}
				
				this.show = '';

			} else { 	
				if(this.show == 'false' && count == 0) {
					this.preloadContent(contentObj);
				}
				count++;
				setTimeout("loadingTemplatesWithAjax.preloadImgWait('"+id+"','"+count+"')", 700); 
			}
		}
		
		contentObj 	= null;
		img			= null;
		docImages	= null;
		obj			= null;
		
	} catch(e) {
		
	}
}

/**
 *LoadingTemplatesWithAjax preloadContent
 *@param url	'string'
 *@comments: 	Wait till all images are preloaded before we show the content
**/
LoadingTemplatesWithAjax.prototype.preloadContent = function (contentObj) {
	var div				= document.createElement('div');
	div.id	 			= 'temp_preloader';
	div.innerHTML		= this.imagepreload;
	contentObj.parentNode.insertBefore(div, contentObj);
}

/**
 *LoadingTemplatesWithAjax checkParams
 *@param url	'string'
 *@comments: 	Check if a &amp; isset within the link...if there is/are replace them with only a &
 *				when sending an &amp; the get/post result will be for example [amp;menu_id] => 1
**/
LoadingTemplatesWithAjax.prototype.checkUrl = function (url) {
	
	try {
		if(url.match('&amp;')) {
			url = url.replace('amp;', '');
		}

		return url;
	} catch(e) {
		errorMsg.push(e + ' (LoadingTemplatesWithAjax.js) method: checkUrl');
		debugWindow.handleAjaxError(errorMsg);
	}
}

/**
 *LoadingTemplatesWithAjax checkFilename
 *@param file	'string'
 *@comments: 	Only for IE to check if a filename isset in the url, like
 *				marcompro.php? instead of only a ?
**/
LoadingTemplatesWithAjax.prototype.checkFilename = function (file) {

	var check = /^\?/;
	// we have to check wheather a filename has been put in the url
	if(file.match(check)) {
		file = defaultFilename + file;
	}

	return file;
}
/**
 *LoadingTemplatesWithAjax setResponse
 *@param str	'string'
 *@comments:	Handles the response of the view-class
**/
LoadingTemplatesWithAjax.prototype.setResponse = function (str) {
	
	// check for fatal errors within the response
	this.checkFatalError(str);

	try {
		
		this.errorMsg		= new Array();
		var strXml 			= '<?xml version="1.0"?>\n<templates>\n';
		strXml				+= str + '\n';
		strXml				+= '</templates>';

		var xml 			= this.stringToXMLParser(strXml);
		var xmlDocRoot		= xml.documentElement;
		
		var nodes			= xmlDocRoot.getElementsByTagName('ajax');

		var len				= nodes.length;

		var placeContent	= 'innerHTML';
		this.placeContent	= placeContent;
		var disabled		= false;
		
		for(var i=0;i<len;i++) {				
				// first reset all attributes
				var id 				= '';
				var type 			= '';
				var definition 		= '';
				var imagepreload 	= '';
				var placeContent	= '';
				var action 			= '';
				var doAction 		= '';
				var disabled 		= '';
				var show			= ''; // bool
				var method			= '';
				var init			= '';
				var func			= '';

				// get the nodes
				var node 	= nodes[i];

				// get the attributes
				var attr	= true;

				if(attr) {
					
					if(node.getAttribute('id')) {
						var id			= node.getAttribute('id');
						this.id			= id;
					}

					if(node.getAttribute('type')) {
						var type		= node.getAttribute('type');
					}

					if(node.getAttribute('definition')) {
						var definition	= node.getAttribute('definition');
					}
					
					if(node.getAttribute('imagepreload')) {
						var imagepreload	= node.getAttribute('imagepreload');
						this.imagepreload	= imagepreload;
					}

					if(node.getAttribute('content')) {
						placeContent		= node.getAttribute('content');
						this.placeContent 	= placeContent;
					}

					if(node.getAttribute('action')) {
						var action		= node.getAttribute('action');
					}

					if(node.getAttribute('do')) {
						var doAction	= node.getAttribute('do');
					}

					if(node.getAttribute('disabled')) {
						var disabled	= node.getAttribute('disabled');
					}

					if(node.getAttribute('show')) {
						var show		= node.getAttribute('show');
						this.show		= show;
					}

					if(node.getAttribute('function')) {
						var func		= node.getAttribute('function');
					}

					if(node.getAttribute('init')) {
						var init		= node.getAttribute('init');
						this.init		= node.getAttribute('init');
					}

					if(node.getAttribute('method')) {
						var method		= node.getAttribute('method');
						this.method		= node.getAttribute('method');
					}

				} else {
					this.errorMsg.push('No attribute was set in the <ajax> tag. No reference to any id!');
				}
				
				// get the content
				
				if(node.childNodes[0]) {
					var content	= node.childNodes[0].nodeValue;
					this.content= content;
					
					if(id && id != '') {
						var contentToDoc	= document.getElementById(id);
						
						if(id == 'admin-content-indent' && !contentToDoc) {
							id		= 'admin-content';
							this.id = 'admin-content';
							contentToDoc	= document.getElementById(id);
						} else if(id == 'admin-content' && !contentToDoc) {
							id		= 'admin-content-indent';
							this.id = 'admin-content-indent';
							contentToDoc	= document.getElementById(id);
						}
						
						if(show && show != '') {
							if(show == 'true') {
								contentToDoc.className = 'marcompro_show';
							} else {
								contentToDoc.className = 'marcompro_hide';
							}
						}

						
						if(contentToDoc) {
							this.contentToDoc = contentToDoc;
						
							if(imagepreload && imagepreload != '') {
								//contentToDoc.className = 'hidden';
							}
							
							switch(placeContent){
								case 'value':
									contentToDoc.value	= content;
									break;
								case 'src':
									contentToDoc.src	= content;
									break;
								case 'none':
									break;
								default:

									contentToDoc.innerHTML = content;
									break;
							}
							
							if(imagepreload && imagepreload != '') {
								this.preloadImgWait(id);
								
							}

						} else {
							this.errorMsg.push('The id with value ' + id + ' is not in use in the document');
						}

					} else {
						this.errorMsg.push('One or more id\'s are not set. No reference possible!');
					}

					
					this.checkJS = content.evalScripts();
					//this.checkJS = triggerJavascript(content);

				}


				if(func && func != '') {
					eval(func);
					func = 0;
				}

				// do the attributes
				// only when the correct type is set
				if(type && type != '') {
					this.doAttr(type, definition, action, doAction, disabled, func);
				}

				// with this we can set and unset the init()
				if(init  == 'false') {
					xmlHttpObject.unsetInit();
				} else if(init == 'true') {
					xmlHttpObject.setInit();
				}

		}

		// after loading the templates look for extra's
		var formSavedPopup 	= this.checkFormSavedPopup();

		// when all is loaded check for errors
		var errorLength	= this.errorMsg.length;

		if(errorLength) {
			debugWindow.handleAjaxError(this.errorMsg);
		}
	
	} catch(e) {
		
		errorMsg.push(e + ' (LoadingTemplatesWithAjax.setResponse)');
		debugWindow.handleAjaxError(errorMsg);
	}
		
		
}

/**
 *LoadingTemplatesWithAjax checkFatalError									*
 *@param xml	'str'														*
 *@comments: 	Check if there are any fatal errors within the response 	*
 *				If there are, show them in the debugger						*
**/
LoadingTemplatesWithAjax.prototype.checkFatalError = function (str) {
	if(str.match('<b>Fatal error</b>')) {
		errorMsg.push('A fatal error has encountered within the response!Check the firebug response code to track the error! (LoadingTemplatesWithAjax.checkFatalError)');
		debugWindow.handleAjaxError(errorMsg);
	}
}

/**
 *LoadingTemplatesWithAjax StringToXMLParser								*
 *@param xml	'str'														*
 *@comments: 	Parse the string content into xml object 					*
**/
LoadingTemplatesWithAjax.prototype.stringToXMLParser = function (str) {

	if(IE) {
		var myDocument;
   	// Internet Explorer, create a new XML document using ActiveX
  	 // and use loadXML as a DOM parser.
   		myDocument = new ActiveXObject("Microsoft.XMLDOM")
   		myDocument.async= "false";


   		var parsed_xml = myDocument.loadXML(str);

   		return myDocument;
	} else {
		var xml = new DOMParser().parseFromString(str, 'text/xml');
		return xml;
	}


}

/**
 * LoadingTemplatesWithAjax parseStrToXml				*
 * @param xml	'str'									*
 * @comments: 	Parse the xml content into a string 	*
**/
LoadingTemplatesWithAjax.prototype.parseStrToXml = function (xml) {
	var str = (new XMLSerializer()).serializeToString(xml);
	return str;
}


/**
 * LoadingTemplatesWithAjax lastLoadedTpl									*
 * @comments: 	sets an array of the last loaded template url and its method*
 *				the method can only be a post or a get						*
**/
LoadingTemplatesWithAjax.prototype.setLastLoadedTpl = function () {
	this.lastLoadedTpl[0] = this.sendType;
	this.lastLoadedTpl[1] = this.url;
	this.lastLoadedTpl[2] = this.file;
}

/**
 *LoadingTemplatesWithAjax lastLoadedTpl									*
 *@comments: 	returns an array of the last loaded template url and its 	*
 *				method														*
**/
LoadingTemplatesWithAjax.prototype.getLastLoadedTpl = function () {
	return this.lastLoadedTpl;
}

/**
 * LoadingTemplatesWithAjax checkFormSavedPopup								*
 * @comments: 	Open the formControl class  and check if a form is saved and*
 *				if it is, check if a popup has to open						*
 *				the formControl.showSavePopup() returns a true or false		*
**/
LoadingTemplatesWithAjax.prototype.checkFormSavedPopup = function () {

	var formSavedPopup 	= formControl.showSavePopup();
	var btnLink			= formControl.savePopupLink();

	if(formSavedPopup) {
		var popupObj	= document.getElementById(formSavedPopup);

		if(popupObj) {
			if(btnLink) {
				popup.setOnclick(btnLink);
			}

			popup.position(formSavedPopup);

			//reset the savepopup otherwise we stay in a loop
			formControl.resetSavePopup();
		} else {
			this.errorMsg.push('The popup object ' + formSavedPopup + ' does not exist!(LoadingTemplatesWithAjax.js method: checkFormSavedPopup())');
		}
	}
}

/**
 * LoadingTemplatesWithAjax openPopup
 * @param id  'string' 		the ID of the element where the popup should be placed
 * @param action 'string' 	the action to be coupled to the corresponding buttons
 * @param doAction	'string' onclick-event to be coupled
 * @comments: 	Opens a selected popup if the definition is set	and the type
 *				is set to openpopup
**/
LoadingTemplatesWithAjax.prototype.openPopup = function (id, action, doAction) {

	var popupObj	= document.getElementById(id);

	if(popupObj) {
		// set the actions of the buttons
		// if there is only a cancel button in the popup, but you still want
		// to do an action, change the button into a 'go' button
		if(action && action != '') {
			var checkPopupBtns	= popup.checkBtns(id);
			var len				= checkPopupBtns.length;

			// if the popup has only one button and the button is a cancel button,
			// change the button name to 'go',
			// a new event will be added to the button
			if(len == 1 && checkPopupBtns[0] == 'cancel') {
				popup.setCancelBtnName(id, 'go');
			}

			if(action == 'url') {
				// make sure the onclick is not in use
				popup.setOnclick('');

				popup.setLink(doAction);
			} else if(action == 'onclick') {
				if(this.method) {
					if(this.method != 'post' || this.method != 'get') {
						this.errorMsg.push('The values of the method attribute do not match "post" or "get"!');
					} else if(this.method == 'post') {
						popup.setMethod(this.method);
					}
				}
				// make sure the link is not in use
				popup.setLink('');
				// we have our own link to trigger, so disable all the other links that are set
				formControl.resetSavePopup();
				popup.setOnclick(doAction);
			} else {
				this.errorMsg.push('The values of the action attribute do not match "url" or "onclick"!');
			}
		}

		// first reset cache content
		popup.resetContent();
		popup.position(id);
		popup.setContent();
	} else {
		this.errorMsg.push('The popup object ' + id + ' does not exist!(LoadingTemplatesWithAjax.js method: openPopup())');
	}
}

/**
 * LoadingTemplatesWithAjax isopenPopup
 * @param id 'string' the id of the open popup
 * @param action 'string' the type action
 * @param doAction 'string'
 * @param disabled 'boolean'
 * @comments: 	If a popup is already open, change the content of the popup
 **/
LoadingTemplatesWithAjax.prototype.isopenPopup = function (id, action, doAction, disabled, func) {

	/**
	* set the actions of the buttons
	* if there is only a cancel button in the popup, but you still want
	* to do an action, change the button into a 'go' button
	**/
	if(disabled ==  'true') {

		obj				= document.getElementById(id);

		if(IE) {
			// somehow IE doesn't want to change the className :S
			obj.style.display	= 'none';
		} else {
			obj.className	= 'hide';
		}
	} else {

		if(action && action != '') {
			var checkPopupBtns	= popup.checkBtns(id);
			var len				= checkPopupBtns.length;
			/**
			 * if the popup has only one button and the button is a cancel button,
			 * change the button name to 'go',
			 *  a new event will be added to the button
			 **/
			if(len == 1 && checkPopupBtns[0] == 'cancel') {
				popup.setCancelBtnName(id, 'go');
			}

			if(action == 'url') {
				// make sure the onclick is not in use
				popup.setOnclick('');

				popup.setLink(doAction);
			} else if(action == 'onclick') {
				if(this.method) {

					if(this.method != 'post' && this.method != 'get' && this.method != 'function') {
						this.errorMsg.push('The values of the method attribute do not match "post", "get" or "function"!');

					} else if(this.method == 'post' || this.method == 'function') {

						popup.setMethod(this.method);
					}
				}

				// make sure the link is not in use
				popup.setLink('');
				// we have our own link to trigger, so disable all the other links that are set
				formControl.resetSavePopup();

				popup.setOnclick(doAction);
			} else if(action == 'saveform') {

				// check if the popup is triggered by saving a form

				// look for the link to redirect to
				var doAction = formControl.getRedirectLink();

				if(doAction) {

					if(this.method) {
						method = this.method;
					} else {
						method = 'get';
					}

					popup.setMethod(method);
					// we have our own link to trigger, so disable all the other links that are set
					formControl.resetSavePopup();
					popup.setOnclick(doAction);

				} else {

					popup.setMethod('function');
					popup.setOnclick('closePopup()');

				}
			} else {
				this.errorMsg.push('The values of the action attribute do not match "url" or "onclick"!');
			}
		}

		if(func && func != 'undefined') {
			if(action == 'onclick') {
				popup.checkSubmit(func);
			} else {
				popup.checkCancel(func);
			}
		}

		// first reset cache content
		popup.resetContent();

		popup.setContent();
	}
}

/**
 * LoadingTemplatesWithAjax doAttr
 * if the attribute type exists, doi something with the	attributes
 *
 * @param type			'string'
 * @param definition	'string'
 * @param action		'string'
 * @param doAction		'string'
 * @param disabled		'string'
 * @param func			'string'
 *
 * @requires changedFieldValues
 * @requires adproJobStatus
 * @requires projectAttributes
**/
LoadingTemplatesWithAjax.prototype.doAttr = function (type, definition, action, doAction, disabled, func) {
	switch (type){
		case 'steps':
			
			if(definition == 'setFieldNewValue' && this.placeContent == 'value') {
				changedFieldValues.setFieldNewValue(this.id, this.content);
			}
			
			var containerObj	= document.getElementById('admin-content');
			if(!containerObj) {
				var containerObj	= document.getElementById('admin-content-indent');
			}
			
			if(containerObj) {
				var div				= document.createElement('div');
				div.className	 	= 'navbox-tabs-hor-pageTopIndent';
				containerObj.insertBefore(div, containerObj.childNodes[0]);
			}
			break;
		case 'important':
			important.doAction(disabled);
			break;
		
		case 'openpopup':

			if(definition) {
				this.openPopup(definition, action, doAction);
			} else {
				this.errorMsg.push('Don\'t know which popup to show! The definition is not set');
			}
			break;
		case 'isopenpopup':
			this.isopenPopup(definition, action, doAction, disabled, func);
			break;
		case 'pdf':
			adproJobStatus.getStatus(definition, action, func);
			break;
		default:

			projectAttributes.doAttr(type, definition, action, doAction, disabled, func);
			break;
	}
}

var loadingTemplatesWithAjax = new LoadingTemplatesWithAjax();


//***************************************************************************
// Set Global vars															*	
//***************************************************************************

//***************************************************************************
// DebugWindow Constructor													*	
//***************************************************************************
function DebugWindow() {
	
}

DebugWindow.prototype.initDebugger = function () {
	this.debug			= document.getElementById('debugWindow');
	this.debugValue		= new Array();
	
	if(IE) {
		document.attachEvent("onclick", errorHandler);
	} else {
		document.addEventListener("click", errorHandler, false);
	}
}

//***************************************************************************
// DebugWindow setDebugValue												*
// @values:	'string'														*
// comments: 	Set a debug array											*
//***************************************************************************
DebugWindow.prototype.setDebugValue = function (value) {
	this.debugValue.push(value);
}

//***************************************************************************
// DebugWindow showDebug													*
// @time:	'integer'														*
// comments:																*
//***************************************************************************
DebugWindow.prototype.showDebug = function () {
	if(this.debugValue.length) {
		
		this.debug.innerHTML	= '';
		this.debug.innerHTML	+= '<h2>Debug window</h2><hr /><br />';
		this.debug.innerHTML	+= '<p>';
		for(i=0;i<this.debugValue.length;i++) {
			this.debug.innerHTML	+= (i +1) + '. ' + this.debugValue[i] + '<br />';
		}
		this.debug.innerHTML	+= '</p>';
		
		this.debug.className	= 'show';
	}
}

DebugWindow.prototype.handleAjaxError = function (errorMsg) {
	var errorLength	= errorMsg.length;

	if(errorLength) {
		
		var errorXmlStr = '<errors>\n';	
		
		for(a=0;a<errorLength;a++) {
			errorXmlStr	+= '\t<error>\n\t\t' + errorMsg[a] + '\n\t</error>\n';
		}
			
		errorXmlStr += '</errors>\n';
		var obj		= document.getElementById('ajax_debugger');
		if(obj) {
			obj.innerHTML = errorXmlStr;
		}
	}
}
	

errorHandler = function(evt) {
	if(errorMsg.length) {
		debugWindow.handleAjaxError(errorMsg);
	}
}

var debugWindow = new DebugWindow();

//***************************************************************************
// PostValues Constructor													*
// Comment:
//***************************************************************************
function PostValues() {
	this.errorMsg		= new Array();
	this.types			= new Array();
	this.url			= '';
	this.formId			= null;
}


//***************************************************************************
// PostValues setPostValues													*
// @id	'string'															*
// comments:
//***************************************************************************
PostValues.prototype.setPostValues = function (obj) {
	
	if(obj) {
		var anchor 		= obj;
	} else {
		var anchor  	= getAnchorObject();
	}

	// check if the anchor isn't an event object
	// if it its, make it an anchor object
	if(IE) {
		
		if(anchor.srcElement) {
			// check if the evtn didn't bubble
			if(anchor.srcElement.nodeName != 'A') {
				var anchor	= find.findObjectByTagName(anchor.srcElement, 'A');
			} else {
				var anchor = anchor.srcElement;
			}
		}
	} else {
		if(anchor.currentTarget) {
			var anchor = anchor.currentTarget;
		}
	}
	
	this.url		= false;
	
	try {
		
		if(!this.reference) {
		
			var reference 	= anchor.getAttribute('reference');
			
		} else {

			var reference	= this.reference;
		}
		
	} catch (e) {
	
		errorMsg.push(e + ' (PostValues.js)');
		debugWindow.handleAjaxError(errorMsg);
	}

	if(reference) {
		var formObj	= find.findObjectByTagName(anchor, 'FORM');
		if(formObj) {
			var fieldserror 	= formObj.getAttribute('fieldserror');
			if(fieldserror) {
				formControl.setFieldsErrorUrl(fieldserror);
			}
			
			// now we got the form object we can search for the correct fields
			// and their values
			
			var url	= this.formFields(formObj, 'reference', reference);
			
			if(url != '') {
				// set the url as a global var
				this.url = url;
			} else {
				this.errorMsg.push('Notice: the url is empty, so no request is sent! (PostValues.js)');
				
			}
		} else {
			
			var formId	= this.getPostFormId();
			var formObj	= document.getElementById(formId);

			if(formObj) {
				var url	= this.formFields(formObj, 'reference', reference);
				
				if(url != '') {
					// set the url as a global var
					this.url = url;


				} else {
					this.errorMsg.push('Notice: the url is empty, so no request is send! (PostValues.js)');
				}

			} else {
				// serach the document for form tags with elements reference
				var formObj	= this.findFormObjectsInDocument(reference);

				if(!formObj) {
					this.errorMsg.push('Could not find a form object! (PostValues.js)');
				}
				
			}
		}

	} else {
		
		this.errorMsg.push('A reference must be set to the anchor tag to find the fields you want to post! (PostValues.js)');
	}

	if(this.errorMsg.length > 0) {
		debugWindow.handleAjaxError(this.errorMsg);
	}

	return true;
}


//***************************************************************************
// PostValues setPostFormId													*
// comments: sets an id of a form											*
//***************************************************************************
PostValues.prototype.setPostFormId = function (id) {
	this.formId = id;
}

//***************************************************************************
// PostValues getPostFormId													*
// comments: get a form id
//***************************************************************************
PostValues.prototype.getPostFormId = function () {
	return this.formId;
}


//***************************************************************************
// PostValues getPostValues													*
// comments: return the post url
//***************************************************************************
PostValues.prototype.getPostValues = function () {
	return this.url;
}

//***************************************************************************
// PostValues getPostValues													*
// comments: return the post url
//***************************************************************************
PostValues.prototype.createReference = function (reference) {
	this.reference = reference;
}

//***************************************************************************
// PostValues formFields													*
// @obj	'object'															*
// @attr	'string'	the attribute to look for							*
// @reference	'string'	the correct ones								*
// comments:	Search the fields and check there values					*
//***************************************************************************
PostValues.prototype.formFields = function (obj, attr, reference) {
	
	var elements	= obj.elements;
	var len			= elements.length;
	var count		= 0;
	var url			= '';

	for(var i=0;i<len;i++) {
		var checkDef= 0;
		var checkReq= 0;
		var elem	= elements[i];

		if(elem.getAttribute(attr)) {
			if(elem.getAttribute(attr) == reference) {
				var fieldId	= elem.id;
				var title	= elem.title;

				var checkReq		= formControl.checkRequired(elem, title, obj);
				var checkDef		= formControl.checkDefinitions(elem, title);
				var checkMinLength	= formControl.checkMinLength(elem, title);

				if(checkReq) {
					count++;
				}

				if(checkDef) {
					count++;
				}
				
				if(checkMinLength) {
					count++;
				}

				// if the field is validated
				// create the url
				if(checkDef == 0 && checkReq == 0) {
					
					var value	= elem.value;
					var name	= elem.name;
					
					if(elem.type == 'radio') {
						if(elem.checked) {
							url			+= '&' + name + '=' + encodeURIComponent(value);
						}
					} else if(elem.type == 'checkbox' && !elem.checked) {
						var submitempty = elem.getAttribute('submitempty');
						
						if(!submitempty) {
							url			+= '&' + name + '=0';
						}
					} else {
						
						
						if(name != '') {
							
							url			+= '&' + name + '=' + encodeURIComponent(value);
						
						} else {
							if(IE) {
								// ons zorgen kindje IE
								if(elem.getAttribute('hack_ie')) {
									var name = elem.getAttribute('hack_ie');
									url			+= '&' + name + '=' + encodeURIComponent(value);
									
								}
							}
						}
					}
				}
			}
		}
		

	}

	if(count) {
		this.fieldErrors = 1;
		formControl.setTheMessage();
		url = '';
	} else {
		this.fieldErrors = 0;
	}

	return url;

}

//***************************************************************************
// PostValues findFormObjectsInDocument										*
// comments: 	find all form objects in the document, then look for 		*
//				elements with a reference									*
//***************************************************************************
PostValues.prototype.findFormObjectsInDocument = function (reference) {
	var objects 	= document.getElementsByTagName('FORM');
	var len			= objects.length;
	var url			= '';
	this.url		= false;
	for(var i=0; i<len; i++) {
		var formObj	= objects[i];
		// create the url
		var url	=+ this.formFields(formObj, 'reference', reference);
	}

	if(url != '') {
		// set the url as a global var
		this.url = url;

	} else {
		this.errorMsg.push('Notice: the url is empty, so no request is send! (PostValues.js)');
	}
}

var postValues				= new PostValues();

//***************************************************************************
// Find Constructor															*		
// comments: 	Class to find all kind of stuff, like finding the left or 	*
//				top position of an object or a parent object				*
//***************************************************************************

function Find() {
	this.errorMsg		= new Array();
}

//***************************************************************************
// Searchbox findPosX														*
// @obj	'object'															*
// comments:	find the left position of the selected object				*
//***************************************************************************
Find.prototype.findPosX = function (obj) {
	var curleft = 0;
	
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
	}
	
	return curleft;
	
}

//***************************************************************************
// Searchbox findPosY														*
// @obj	'object'															*
// comments:	find the top position of the selected object				*
//***************************************************************************
Find.prototype.findPosY = function (obj) {
	var curtop = 0;
	
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		curtop += obj.y;
	}
	
	obj = null;
	
	return curtop;
	
}
//***************************************************************************
// Searchbox findObjectByTagName											*
// @obj 'object' Current object												*
// @tagName	'string'														*
// comments:	find a parent object by tagname								*
//***************************************************************************
Find.prototype.findObjectByTagName = function (obj, tagName) {
	checkObj = this.isObj(obj);
	if(!checkObj) {
		return false;
	}
	
	var newObject = null;
	if (obj.parentNode) {
		while (obj.parentNode) {
			if(obj.nodeName == tagName) {
				newObject	= obj;
				break;
			} else {
				obj = obj.parentNode;
			}
		}
	}
	
	obj = null;
	
	if(newObject) {
		return newObject;
	} else {
		this.errorMsg.push('No parent tag ' + tagName + ' was found');
		
		debugWindow.handleAjaxError(this.errorMsg);
		return false;
	}
}

//***************************************************************************
// Searchbox findObjectById													*
// @id	'string'															*
// @obj 'object' Current object												*
// comments:	find a parent object by tagname								*
//***************************************************************************
Find.prototype.findObjectById = function (obj, id) {
	checkObj = this.isObj(obj);
	if(!checkObj) {
		return false;
	}
	var newObject = null;
	if (obj.parentNode) {
		while (obj.parentNode) {
			if(obj.id == id) {
				newObject	= obj;
				break;
			} else {
				obj = obj.parentNode;
			}
		}
	}
	
	obj = null;
	
	if(newObject) {
		return newObject;
	} else {
		this.errorMsg.push('No parent object with id ' + id + ' was found');
		
		debugWindow.handleAjaxError(this.errorMsg);
		return false;
	}
}

//***************************************************************************
// Searchbox findObjectByClassName											*
// @id	'string'															*
// @obj 'object' Current object												*
// comments:	find a parent object by tagname								*
//***************************************************************************
Find.prototype.findObjectByClassName = function (obj, name) {
	
	checkObj = this.isObj(obj);
	if(!checkObj) {
		return false;
	}

	var newObject = null;
	if (obj.parentNode) {
		while (obj.parentNode) {
			if(obj.className == name) {
				newObject	= obj;
				break;
			} else {
				obj = obj.parentNode;
			}
		}
	}
	
	obj = null;
	
	if(newObject) {
		return newObject;
	} else {
		this.errorMsg.push('No parent object with className ' + name + ' was found');
		
		debugWindow.handleAjaxError(this.errorMsg);
		return false;
	}
}

//***************************************************************************
// Searchbox findNextSibling												*
// @id	'string'															*
// @obj 'object' Current object												*
// comments:	find a next sibling by its tag name							*
//***************************************************************************
Find.prototype.findNextSibling = function (obj, name) {
	checkObj = this.isObj(obj);
	if(!checkObj) {
		return false;
	}

	var newObject = null;
	if (obj.nextSibling) {
		while (obj.nextSibling) {
			if(obj.nextSibling.nodeName == name) {
				newObject	= obj.nextSibling;
				break;
			} else {
				obj = obj.nextSibling;
			}
		}
	}
	
	obj = null;
	
	if(newObject) {
		return newObject;
	} else {
		this.errorMsg.push('No parent object with className ' + name + ' was found');
		
		debugWindow.handleAjaxError(this.errorMsg);
		return false;
	}
}

//***************************************************************************
// Searchbox findPreviousSibling											*
// @id	'string'															*
// @obj 'object' Current object												*
// comments:	find a previous sibling by its tag name						*
//***************************************************************************
Find.prototype.findPreviousSibling = function (obj, name) {
	checkObj = this.isObj(obj);
	if(!checkObj) {
		return false;
	}

	var newObject = null;
	if (obj.previousSibling) {
		while (obj.previousSibling) {
			if(obj.previousSibling.nodeName == name) {
				newObject	= obj.previousSibling;
				break;
			} else {
				obj = obj.previousSibling;
			}
		}
	}
	
	obj = null;
	
	if(newObject) {
		return newObject;
	} else {
		this.errorMsg.push('No parent object with className ' + name + ' was found');
		
		debugWindow.handleAjaxError(this.errorMsg);
		return false;
	}
}


//***************************************************************************
// Find findObjectByTitle													*
// @obj 'object' Current object												*
// comments:	find a parent object by title								*
//***************************************************************************
Find.prototype.findObjectByTitle = function (obj, value) {
	checkObj = this.isObj(obj);
	if(!checkObj) {
		return false;
	}

	var newObject = null;
	if (obj.parentNode) {
		while (obj.parentNode) {
			if(obj.title == value) {
				newObject	= obj;
				break;
			} else {
				obj = obj.parentNode;
			}
		}
	}
	
	obj = null;
	
	if(newObject) {
		return newObject;
	} else {
		this.errorMsg.push('No parent object with title ' + value + ' was found');
		
		debugWindow.handleAjaxError(this.errorMsg);
		return false;
	}
}


//***************************************************************************
// Find findObjectByDefinition												*
// @obj 'object' Current object												*
// comments:	find a parent object by its definition						*
//***************************************************************************
Find.prototype.findObjectByDefinition = function (obj, value) {
	checkObj = this.isObj(obj);
	if(!checkObj) {
		return false;
	}

	var newObject = null;
	if (obj.parentNode) {
		while (obj.parentNode) {
			var definition = obj.getAttribute('definition');
			if(definition == value) {
				newObject	= obj;
				break;
			} else {
				obj = obj.parentNode;
			}
		}
	}
	
	obj = null;
	
	if(newObject) {
		return newObject;
	} else {
		this.errorMsg.push('No parent object with title ' + value + ' was found');
		
		debugWindow.handleAjaxError(this.errorMsg);
		return false;
	}
}
//***************************************************************************
// Searchbox selectedOption													*
// @obj 'object' Selectbox													*
// comments:	find the selected option object within a selectbox			*
//***************************************************************************
Find.prototype.selectedOption = function (obj) {
	var options 		= obj.getElementsByTagName('option');
	var sel				= obj.selectedIndex;
	var option			= options[sel];
	
	if(option) {
		return option;
	} else {
		errorMsg.push('Could not find a selected option');
		debugWindow.handleAjaxError(errorMsg);
		return false;
	}

}

//***************************************************************************
// Find isObj																*
// @obj 'object' 															*
// comments:	check if the object is indeed an object						*
//***************************************************************************
Find.prototype.isObj = function (obj) {
	
	if(typeof(obj) != 'object') {
		errorMsg.push('Could not find a selected option');
		debugWindow.handleAjaxError(errorMsg);
		return false;
	} 
	
	return true;
}	

var find= new Find();


/**
 * Set Global vars
*/

/**
 * alertDebugger
 * @message	'string'
 * @comments: You can call this function wherever you like to create a alert box.
 * @comments: Call the executeAlert() method to display the alert
*/
function alertDebugger(message) {
	alertMsg.push(message);
}

/**
 * executeAlert
 */
function executeAlert() {
	var len 		= alertMsg.length;
	var alertWindow	= document.getElementById('alert');
	var	msg			= '';

	try {
		if(len) {
			alertWindow.className 	= 'show';
			for(var i=0; i<len; i++) {
				msg += alertMsg[i] + '<br />';
			}

			var divs	= alertWindow.getElementsByTagName('DIV');
			var divsLen	= divs.length;
			for(var i=0; i<divsLen; i++) {
				var div	= divs[i];
				if(div.className == 'alertMessage') {
					div.innerHTML = msg;
				}
			}
		}

	} catch(e) {
		errorMsg.push(e + ' (Alert.js)');
	}
}

/**
 * closeAlert
 * 	@comments gets the element by id 'alert'
*/
function closeAlert() {
	var alertWindow	= document.getElementById('alert');

	try {
		alertWindow.className 	= 'hide';

		var divs	= alertWindow.getElementsByTagName('DIV');
		var divsLen	= divs.length;

		// make sure we don't leave a mess
		alertMsg = new Array();
		for(var i=0; i<divsLen; i++) {
			var div	= divs[i];
			if(div.className == 'alertMessage') {
				div.innerHTML = '';
			}
		}

	} catch(e) {
		errorMsg.push(e + ' (Alert.js)');
	}
}



/**
 * UserAgent constructor
 * @comments: 	find out what the users platform and browser is
**/

function BrowserPlatform() {
	this.browserPlatform	= navigator.userAgent;
}

/**
 * UserAgent getPlatform
 * @comments: 	get the platform!
**/
BrowserPlatform.prototype.getPlatform = function() {
	if(this.browserPlatform.indexOf("Win") != -1) {
		var platform = 'Win';
	} else if(this.browserPlatform.indexOf("Mac") != -1) {
		var platform = 'Mac';
	} else if(this.browserPlatform.indexOf("Lin") != -1) {
		var platform = 'Lin';
	} else {
		var platform = false;
	}

	return platform;
}

/**
 * UserAgent getBrowser
 * @comments: 	get the browser!
 */
BrowserPlatform.prototype.getBrowser = function() {

	if(navigator.userAgent.indexOf("Safari/3") != -1) {
		var browser = false; // in the future marcompro has t run under Safari
	} else if(navigator.userAgent.indexOf("Safari/4") != -1) {
		var browser = false; // in the future marcompro has t run under Safari
	} else if(navigator.userAgent.indexOf("Firefox/1.5") != -1) {
		var browser = 'Firefox/1.5';
	} else if(navigator.userAgent.indexOf("Firefox/2.0") != -1) {
		var browser = 'Firefox/2.0';
	} else if (navigator.userAgent.indexOf("MSIE 6.0") != -1) {
		var browser = 'MSIE 6.0';
	} else if (navigator.userAgent.indexOf("MSIE 7.0") != -1) {
		var browser = 'MSIE 7.0';
	} else {
		var browser = false;
	}

	return browser;
}

BrowserPlatform.prototype.checkBrowserCompatibility = function(type) {
	var browser = this.getBrowser();

	if(!browser) {
		if(type == 'alert') {
			var msg = 'Marcompro does not (yet) support this browser!\nBrowser information:' + navigator.userAgent + '\n\nBrowsers that are available for Marcompro are: Mozilla Firefox 1.5 on Windows, Linux and Macintosh\nInternet explorer 6.0 on Windows';
//			alert(msg);
		}
	}
}

var browserPlatform	= new BrowserPlatform();

// Trigger javascripts
triggerJavascript = function(value) {

	// triggering javascripts
	// the scripts have to be in a single line
	var content = value;

	var re =/<script.*>\s*(.*)<\/script>\s*/gi
	var i = 0;

	while(script = re.exec(content)) {
		var sc	= script[1];
		if(sc.match('<script>')) {
			sc = sc.replace('<script>', '');
		}

		if(sc.match('</script>')) {
			sc = sc.replace('</script>', '');
		}

		if(sc.match('<script type="text/javascript">')) {
			sc = sc.replace('<script type="text/javascript">', '');
		}

		eval(sc);
		i++;
	}

	if(i) {
		return true;
	} else {
		return false;
	}
}

//***************************************************************************
// Set Global vars															*	
//***************************************************************************

//***************************************************************************
// Timer Constructor														*		
// comments: 	Starts a timer
//***************************************************************************
function Timer() {
	this.loop 		= 0;
	this.count		= 0;
	this.status 	= 0;
	this.tStart  	= null;
	this.maxCount	= null;
	this.func		= null;
	// set default in sec
	this.delay		= 1000;
}

//***************************************************************************
// Timer updateTimer														*
// comments: 	Loop through the timer, untill a max is reached (if a max is*
//				set)	 													*
//***************************************************************************
Timer.prototype.updateTimer = function() {
	
	/*
	if(this.status == 1) {
		return true;
	}
	*/
	
	if(this.maxCount && this.maxCount <= this.count) {   
   		
   		// if a function is set, execute it
   		if(this.func) {
   			
   			// first check if the method(s) are in an object
   			var check = eval(this.func);
   		
   			if(typeof check == 'function') {
   				eval(this.func);
   			} else if(typeof check == 'object') {
   				var len = check.length;
   				
   				for(var i=0;i<len; i++) {
   					eval(check[i]);
   				}
   			}
   			
   		}
		this.stop();
		
		return true;
   	}

   	this.count = this.count + this.delay;
   	this.loop = setTimeout("timer.updateTimer()", this.delay);
  
   	return false;
}

//***************************************************************************
// Timer start																*	
// comments: 	Start the loop here 										*
//***************************************************************************
Timer.prototype.start = function(func) {
	this.loop = setTimeout("timer.updateTimer()", 1);
	
	if(func) {
   			
		// first check if the method(s) are in an object
		var check = eval(func);
	
		if(typeof check == 'function') {
			eval(func);
		} else if(typeof check == 'object') {
			var len = check.length;
			
			for(var i=0;i<len; i++) {
				eval(check[i]);
			}
		}
	}
}

//***************************************************************************
// Timer max																*	
// @sec 'int' set the max mili seconds										*
// @func 'string' set a return function when the max is reached				*
// comments: 	Set a max when the loop has to stop 						*
//***************************************************************************
Timer.prototype.max = function(sec, func) {
	if(isNaN(sec)) {
		return false;
	}
	

	this.maxCount = sec;
	this.status 	= 0;
	// when the max is reached, call a function
	this.func = func;
	return true;
}

//***************************************************************************
// Timer stop																*	
// comments: 	Stops the timer												*
//***************************************************************************
Timer.prototype.stop = function() {
	this.count 		= 0;
	//this.status 	= 1;
	//this.func		= null;
	clearTimeout(this.loop);
}


//***************************************************************************
// Timer setDelay															*	
// comments: 	sets a delay, default delay is 1 sec						*
//***************************************************************************
Timer.prototype.setDelay = function(delay) {
 	this.delay = delay;
}

var timer	= new Timer();

//-->


/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.4.0
*/
if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C<A.length;C=C+1){D=A[C].split(".");E=YAHOO;for(B=(D[0]=="YAHOO")?1:0;B<D.length;B=B+1){E[D[B]]=E[D[B]]||{};E=E[D[B]];}}return E;};YAHOO.log=function(D,A,C){var B=YAHOO.widget.Logger;if(B&&B.log){return B.log(D,A,C);}else{return false;}};YAHOO.register=function(A,E,D){var I=YAHOO.env.modules;if(!I[A]){I[A]={versions:[],builds:[]};}var B=I[A],H=D.version,G=D.build,F=YAHOO.env.listeners;B.name=A;B.version=H;B.build=G;B.versions.push(H);B.builds.push(G);B.mainClass=E;for(var C=0;C<F.length;C=C+1){F[C](B);}if(E){E.VERSION=H;E.BUILD=G;}else{YAHOO.log("mainClass is undefined for module "+A,"warn");}};YAHOO.env=YAHOO.env||{modules:[],listeners:[]};YAHOO.env.getVersion=function(A){return YAHOO.env.modules[A]||null;};YAHOO.env.ua=function(){var C={ie:0,opera:0,gecko:0,webkit:0,mobile:null};var B=navigator.userAgent,A;if((/KHTML/).test(B)){C.webkit=1;}A=B.match(/AppleWebKit\/([^\s]*)/);if(A&&A[1]){C.webkit=parseFloat(A[1]);if(/ Mobile\//.test(B)){C.mobile="Apple";}else{A=B.match(/NokiaN[^\/]*/);if(A){C.mobile=A[0];}}}if(!C.webkit){A=B.match(/Opera[\s\/]([^\s]*)/);if(A&&A[1]){C.opera=parseFloat(A[1]);A=B.match(/Opera Mini[^;]*/);if(A){C.mobile=A[0];}}else{A=B.match(/MSIE\s([^;]*)/);if(A&&A[1]){C.ie=parseFloat(A[1]);}else{A=B.match(/Gecko\/([^\s]*)/);if(A){C.gecko=1;A=B.match(/rv:([^\s\)]*)/);if(A&&A[1]){C.gecko=parseFloat(A[1]);}}}}}return C;}();(function(){YAHOO.namespace("util","widget","example");if("undefined"!==typeof YAHOO_config){var B=YAHOO_config.listener,A=YAHOO.env.listeners,D=true,C;if(B){for(C=0;C<A.length;C=C+1){if(A[C]==B){D=false;break;}}if(D){A.push(B);}}}})();YAHOO.lang=YAHOO.lang||{isArray:function(B){if(B){var A=YAHOO.lang;return A.isNumber(B.length)&&A.isFunction(B.splice);}return false;},isBoolean:function(A){return typeof A==="boolean";},isFunction:function(A){return typeof A==="function";},isNull:function(A){return A===null;},isNumber:function(A){return typeof A==="number"&&isFinite(A);},isObject:function(A){return(A&&(typeof A==="object"||YAHOO.lang.isFunction(A)))||false;},isString:function(A){return typeof A==="string";},isUndefined:function(A){return typeof A==="undefined";},hasOwnProperty:function(A,B){if(Object.prototype.hasOwnProperty){return A.hasOwnProperty(B);}return !YAHOO.lang.isUndefined(A[B])&&A.constructor.prototype[B]!==A[B];},_IEEnumFix:function(C,B){if(YAHOO.env.ua.ie){var E=["toString","valueOf"],A;for(A=0;A<E.length;A=A+1){var F=E[A],D=B[F];if(YAHOO.lang.isFunction(D)&&D!=Object.prototype[F]){C[F]=D;}}}},extend:function(D,E,C){if(!E||!D){throw new Error("YAHOO.lang.extend failed, please check that all dependencies are included.");}var B=function(){};B.prototype=E.prototype;D.prototype=new B();D.prototype.constructor=D;D.superclass=E.prototype;if(E.prototype.constructor==Object.prototype.constructor){E.prototype.constructor=E;}if(C){for(var A in C){D.prototype[A]=C[A];}YAHOO.lang._IEEnumFix(D.prototype,C);}},augmentObject:function(E,D){if(!D||!E){throw new Error("Absorb failed, verify dependencies.");}var A=arguments,C,F,B=A[2];if(B&&B!==true){for(C=2;C<A.length;C=C+1){E[A[C]]=D[A[C]];}}else{for(F in D){if(B||!E[F]){E[F]=D[F];}}YAHOO.lang._IEEnumFix(E,D);}},augmentProto:function(D,C){if(!C||!D){throw new Error("Augment failed, verify dependencies.");}var A=[D.prototype,C.prototype];for(var B=2;B<arguments.length;B=B+1){A.push(arguments[B]);}YAHOO.lang.augmentObject.apply(this,A);},dump:function(A,G){var C=YAHOO.lang,D,F,I=[],J="{...}",B="f(){...}",H=", ",E=" => ";if(!C.isObject(A)){return A+"";}else{if(A instanceof Date||("nodeType" in A&&"tagName" in A)){return A;}else{if(C.isFunction(A)){return B;}}}G=(C.isNumber(G))?G:3;if(C.isArray(A)){I.push("[");for(D=0,F=A.length;D<F;D=D+1){if(C.isObject(A[D])){I.push((G>0)?C.dump(A[D],G-1):J);}else{I.push(A[D]);}I.push(H);}if(I.length>1){I.pop();}I.push("]");}else{I.push("{");for(D in A){if(C.hasOwnProperty(A,D)){I.push(D+E);if(C.isObject(A[D])){I.push((G>0)?C.dump(A[D],G-1):J);}else{I.push(A[D]);}I.push(H);}}if(I.length>1){I.pop();}I.push("}");}return I.join("");},substitute:function(Q,B,J){var G,F,E,M,N,P,D=YAHOO.lang,L=[],C,H="dump",K=" ",A="{",O="}";for(;;){G=Q.lastIndexOf(A);if(G<0){break;}F=Q.indexOf(O,G);if(G+1>=F){break;}C=Q.substring(G+1,F);M=C;P=null;E=M.indexOf(K);if(E>-1){P=M.substring(E+1);M=M.substring(0,E);}N=B[M];if(J){N=J(M,N,P);}if(D.isObject(N)){if(D.isArray(N)){N=D.dump(N,parseInt(P,10));}else{P=P||"";var I=P.indexOf(H);if(I>-1){P=P.substring(4);}if(N.toString===Object.prototype.toString||I>-1){N=D.dump(N,parseInt(P,10));}else{N=N.toString();}}}else{if(!D.isString(N)&&!D.isNumber(N)){N="~-"+L.length+"-~";L[L.length]=C;}}Q=Q.substring(0,G)+N+Q.substring(F+1);}for(G=L.length-1;G>=0;G=G-1){Q=Q.replace(new RegExp("~-"+G+"-~"),"{"+L[G]+"}","g");}return Q;},trim:function(A){try{return A.replace(/^\s+|\s+$/g,"");}catch(B){return A;}},merge:function(){var D={},B=arguments;for(var C=0,A=B.length;C<A;C=C+1){YAHOO.lang.augmentObject(D,B[C],true);}return D;},later:function(H,B,I,D,E){H=H||0;B=B||{};var C=I,G=D,F,A;if(YAHOO.lang.isString(I)){C=B[I];}if(!C){throw new TypeError("method undefined");}if(!YAHOO.lang.isArray(G)){G=[D];}F=function(){C.apply(B,G);};A=(E)?setInterval(F,H):setTimeout(F,H);return{interval:E,cancel:function(){if(this.interval){clearInterval(A);}else{clearTimeout(A);}}};},isValue:function(B){var A=YAHOO.lang;return(A.isObject(B)||A.isString(B)||A.isNumber(B)||A.isBoolean(B));}};YAHOO.util.Lang=YAHOO.lang;YAHOO.lang.augment=YAHOO.lang.augmentProto;YAHOO.augment=YAHOO.lang.augmentProto;YAHOO.extend=YAHOO.lang.extend;YAHOO.register("yahoo",YAHOO,{version:"2.4.0",build:"733"});

/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.4.0
*/
YAHOO.util.CustomEvent=function(D,B,C,A){this.type=D;this.scope=B||window;this.silent=C;this.signature=A||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var E="_YUICEOnSubscribe";if(D!==E){this.subscribeEvent=new YAHOO.util.CustomEvent(E,this,true);}this.lastError=null;};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(B,C,A){if(!B){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}if(this.subscribeEvent){this.subscribeEvent.fire(B,C,A);}this.subscribers.push(new YAHOO.util.Subscriber(B,C,A));},unsubscribe:function(D,F){if(!D){return this.unsubscribeAll();}var E=false;for(var B=0,A=this.subscribers.length;B<A;++B){var C=this.subscribers[B];if(C&&C.contains(D,F)){this._delete(B);E=true;}}return E;},fire:function(){var D=this.subscribers.length;if(!D&&this.silent){return true;}var G=[],F=true,C,H=false;for(C=0;C<arguments.length;++C){G.push(arguments[C]);}if(!this.silent){}for(C=0;C<D;++C){var K=this.subscribers[C];if(!K){H=true;}else{if(!this.silent){}var J=K.getScope(this.scope);if(this.signature==YAHOO.util.CustomEvent.FLAT){var A=null;if(G.length>0){A=G[0];}try{F=K.fn.call(J,A,K.obj);}catch(E){this.lastError=E;}}else{try{F=K.fn.call(J,this.type,G,K.obj);}catch(E){this.lastError=E;}}if(false===F){if(!this.silent){}return false;}}}if(H){var I=[],B=this.subscribers;for(C=0,D=B.length;C<D;C=C+1){I.push(B[C]);}this.subscribers=I;}return true;},unsubscribeAll:function(){for(var B=0,A=this.subscribers.length;B<A;++B){this._delete(A-1-B);}this.subscribers=[];return B;},_delete:function(A){var B=this.subscribers[A];if(B){delete B.fn;delete B.obj;}this.subscribers[A]=null;},toString:function(){return"CustomEvent: '"+this.type+"', scope: "+this.scope;}};YAHOO.util.Subscriber=function(B,C,A){this.fn=B;this.obj=YAHOO.lang.isUndefined(C)?null:C;this.override=A;};YAHOO.util.Subscriber.prototype.getScope=function(A){if(this.override){if(this.override===true){return this.obj;}else{return this.override;}}return A;};YAHOO.util.Subscriber.prototype.contains=function(A,B){if(B){return(this.fn==A&&this.obj==B);}else{return(this.fn==A);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", override: "+(this.override||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var H=false;var I=[];var J=[];var G=[];var E=[];var C=0;var F=[];var B=[];var A=0;var D={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9};return{POLL_RETRYS:4000,POLL_INTERVAL:10,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:YAHOO.env.ua.ie,_interval:null,_dri:null,DOMReady:false,startInterval:function(){if(!this._interval){var K=this;var L=function(){K._tryPreloadAttach();};this._interval=setInterval(L,this.POLL_INTERVAL);}},onAvailable:function(P,M,Q,O,N){var K=(YAHOO.lang.isString(P))?[P]:P;for(var L=0;L<K.length;L=L+1){F.push({id:K[L],fn:M,obj:Q,override:O,checkReady:N});}C=this.POLL_RETRYS;this.startInterval();},onContentReady:function(M,K,N,L){this.onAvailable(M,K,N,L,true);},onDOMReady:function(K,M,L){if(this.DOMReady){setTimeout(function(){var N=window;if(L){if(L===true){N=M;}else{N=L;}}K.call(N,"DOMReady",[],M);},0);}else{this.DOMReadyEvent.subscribe(K,M,L);}},addListener:function(M,K,V,Q,L){if(!V||!V.call){return false;}if(this._isValidCollection(M)){var W=true;for(var R=0,T=M.length;R<T;++R){W=this.on(M[R],K,V,Q,L)&&W;}return W;}else{if(YAHOO.lang.isString(M)){var P=this.getEl(M);if(P){M=P;}else{this.onAvailable(M,function(){YAHOO.util.Event.on(M,K,V,Q,L);});return true;}}}if(!M){return false;}if("unload"==K&&Q!==this){J[J.length]=[M,K,V,Q,L];return true;}var Y=M;if(L){if(L===true){Y=Q;}else{Y=L;}}var N=function(Z){return V.call(Y,YAHOO.util.Event.getEvent(Z,M),Q);};var X=[M,K,V,N,Y,Q,L];var S=I.length;I[S]=X;if(this.useLegacyEvent(M,K)){var O=this.getLegacyIndex(M,K);if(O==-1||M!=G[O][0]){O=G.length;B[M.id+K]=O;G[O]=[M,K,M["on"+K]];E[O]=[];M["on"+K]=function(Z){YAHOO.util.Event.fireLegacyEvent(YAHOO.util.Event.getEvent(Z),O);};}E[O].push(X);}else{try{this._simpleAdd(M,K,N,false);}catch(U){this.lastError=U;this.removeListener(M,K,V);return false;}}return true;},fireLegacyEvent:function(O,M){var Q=true,K,S,R,T,P;S=E[M];for(var L=0,N=S.length;L<N;++L){R=S[L];if(R&&R[this.WFN]){T=R[this.ADJ_SCOPE];P=R[this.WFN].call(T,O);Q=(Q&&P);}}K=G[M];if(K&&K[2]){K[2](O);}return Q;},getLegacyIndex:function(L,M){var K=this.generateId(L)+M;if(typeof B[K]=="undefined"){return -1;}else{return B[K];}},useLegacyEvent:function(L,M){if(this.webkit&&("click"==M||"dblclick"==M)){var K=parseInt(this.webkit,10);if(!isNaN(K)&&K<418){return true;}}return false;},removeListener:function(L,K,T){var O,R,V;if(typeof L=="string"){L=this.getEl(L);}else{if(this._isValidCollection(L)){var U=true;for(O=0,R=L.length;O<R;++O){U=(this.removeListener(L[O],K,T)&&U);}return U;}}if(!T||!T.call){return this.purgeElement(L,false,K);}if("unload"==K){for(O=0,R=J.length;O<R;O++){V=J[O];if(V&&V[0]==L&&V[1]==K&&V[2]==T){J[O]=null;return true;}}return false;}var P=null;var Q=arguments[3];if("undefined"===typeof Q){Q=this._getCacheIndex(L,K,T);}if(Q>=0){P=I[Q];}if(!L||!P){return false;}if(this.useLegacyEvent(L,K)){var N=this.getLegacyIndex(L,K);var M=E[N];if(M){for(O=0,R=M.length;O<R;++O){V=M[O];if(V&&V[this.EL]==L&&V[this.TYPE]==K&&V[this.FN]==T){M[O]=null;break;}}}}else{try{this._simpleRemove(L,K,P[this.WFN],false);}catch(S){this.lastError=S;return false;}}delete I[Q][this.WFN];delete I[Q][this.FN];I[Q]=null;return true;},getTarget:function(M,L){var K=M.target||M.srcElement;return this.resolveTextNode(K);},resolveTextNode:function(K){if(K&&3==K.nodeType){return K.parentNode;}else{return K;}},getPageX:function(L){var K=L.pageX;if(!K&&0!==K){K=L.clientX||0;if(this.isIE){K+=this._getScrollLeft();}}return K;},getPageY:function(K){var L=K.pageY;if(!L&&0!==L){L=K.clientY||0;if(this.isIE){L+=this._getScrollTop();}}return L;},getXY:function(K){return[this.getPageX(K),this.getPageY(K)];
},getRelatedTarget:function(L){var K=L.relatedTarget;if(!K){if(L.type=="mouseout"){K=L.toElement;}else{if(L.type=="mouseover"){K=L.fromElement;}}}return this.resolveTextNode(K);},getTime:function(M){if(!M.time){var L=new Date().getTime();try{M.time=L;}catch(K){this.lastError=K;return L;}}return M.time;},stopEvent:function(K){this.stopPropagation(K);this.preventDefault(K);},stopPropagation:function(K){if(K.stopPropagation){K.stopPropagation();}else{K.cancelBubble=true;}},preventDefault:function(K){if(K.preventDefault){K.preventDefault();}else{K.returnValue=false;}},getEvent:function(M,K){var L=M||window.event;if(!L){var N=this.getEvent.caller;while(N){L=N.arguments[0];if(L&&Event==L.constructor){break;}N=N.caller;}}return L;},getCharCode:function(L){var K=L.keyCode||L.charCode||0;if(YAHOO.env.ua.webkit&&(K in D)){K=D[K];}return K;},_getCacheIndex:function(O,P,N){for(var M=0,L=I.length;M<L;++M){var K=I[M];if(K&&K[this.FN]==N&&K[this.EL]==O&&K[this.TYPE]==P){return M;}}return -1;},generateId:function(K){var L=K.id;if(!L){L="yuievtautoid-"+A;++A;K.id=L;}return L;},_isValidCollection:function(L){try{return(L&&typeof L!=="string"&&L.length&&!L.tagName&&!L.alert&&typeof L[0]!=="undefined");}catch(K){return false;}},elCache:{},getEl:function(K){return(typeof K==="string")?document.getElementById(K):K;},clearCache:function(){},DOMReadyEvent:new YAHOO.util.CustomEvent("DOMReady",this),_load:function(L){if(!H){H=true;var K=YAHOO.util.Event;K._ready();K._tryPreloadAttach();}},_ready:function(L){var K=YAHOO.util.Event;if(!K.DOMReady){K.DOMReady=true;K.DOMReadyEvent.fire();K._simpleRemove(document,"DOMContentLoaded",K._ready);}},_tryPreloadAttach:function(){if(this.locked){return false;}if(this.isIE){if(!this.DOMReady){this.startInterval();return false;}}this.locked=true;var P=!H;if(!P){P=(C>0);}var O=[];var Q=function(S,T){var R=S;if(T.override){if(T.override===true){R=T.obj;}else{R=T.override;}}T.fn.call(R,T.obj);};var L,K,N,M;for(L=0,K=F.length;L<K;++L){N=F[L];if(N&&!N.checkReady){M=this.getEl(N.id);if(M){Q(M,N);F[L]=null;}else{O.push(N);}}}for(L=0,K=F.length;L<K;++L){N=F[L];if(N&&N.checkReady){M=this.getEl(N.id);if(M){if(H||M.nextSibling){Q(M,N);F[L]=null;}}else{O.push(N);}}}C=(O.length===0)?0:C-1;if(P){this.startInterval();}else{clearInterval(this._interval);this._interval=null;}this.locked=false;return true;},purgeElement:function(O,P,R){var M=(YAHOO.lang.isString(O))?this.getEl(O):O;var Q=this.getListeners(M,R),N,K;if(Q){for(N=0,K=Q.length;N<K;++N){var L=Q[N];this.removeListener(M,L.type,L.fn,L.index);}}if(P&&M&&M.childNodes){for(N=0,K=M.childNodes.length;N<K;++N){this.purgeElement(M.childNodes[N],P,R);}}},getListeners:function(M,K){var P=[],L;if(!K){L=[I,J];}else{if(K==="unload"){L=[J];}else{L=[I];}}var R=(YAHOO.lang.isString(M))?this.getEl(M):M;for(var O=0;O<L.length;O=O+1){var T=L[O];if(T&&T.length>0){for(var Q=0,S=T.length;Q<S;++Q){var N=T[Q];if(N&&N[this.EL]===R&&(!K||K===N[this.TYPE])){P.push({type:N[this.TYPE],fn:N[this.FN],obj:N[this.OBJ],adjust:N[this.OVERRIDE],scope:N[this.ADJ_SCOPE],index:Q});}}}}return(P.length)?P:null;},_unload:function(R){var Q=YAHOO.util.Event,O,N,L,K,M;for(O=0,K=J.length;O<K;++O){L=J[O];if(L){var P=window;if(L[Q.ADJ_SCOPE]){if(L[Q.ADJ_SCOPE]===true){P=L[Q.UNLOAD_OBJ];}else{P=L[Q.ADJ_SCOPE];}}L[Q.FN].call(P,Q.getEvent(R,L[Q.EL]),L[Q.UNLOAD_OBJ]);J[O]=null;L=null;P=null;}}J=null;if(YAHOO.env.ua.IE&&I&&I.length>0){N=I.length;while(N){M=N-1;L=I[M];if(L){L[Q.EL].clearAttributes();}N=N-1;}L=null;}G=null;Q._simpleRemove(window,"unload",Q._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var K=document.documentElement,L=document.body;if(K&&(K.scrollTop||K.scrollLeft)){return[K.scrollTop,K.scrollLeft];}else{if(L){return[L.scrollTop,L.scrollLeft];}else{return[0,0];}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(M,N,L,K){M.addEventListener(N,L,(K));};}else{if(window.attachEvent){return function(M,N,L,K){M.attachEvent("on"+N,L);};}else{return function(){};}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(M,N,L,K){M.removeEventListener(N,L,(K));};}else{if(window.detachEvent){return function(L,M,K){L.detachEvent("on"+M,K);};}else{return function(){};}}}()};}();(function(){var A=YAHOO.util.Event;A.on=A.addListener;if(A.isIE){YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);A._dri=setInterval(function(){var C=document.createElement("p");try{C.doScroll("left");clearInterval(A._dri);A._dri=null;A._ready();C=null;}catch(B){C=null;}},A.POLL_INTERVAL);}else{if(A.webkit){A._dri=setInterval(function(){var B=document.readyState;if("loaded"==B||"complete"==B){clearInterval(A._dri);A._dri=null;A._ready();}},A.POLL_INTERVAL);}else{A._simpleAdd(document,"DOMContentLoaded",A._ready);}}A._simpleAdd(window,"load",A._load);A._simpleAdd(window,"unload",A._unload);A._tryPreloadAttach();})();}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(A,C,F,E){this.__yui_events=this.__yui_events||{};var D=this.__yui_events[A];if(D){D.subscribe(C,F,E);}else{this.__yui_subscribers=this.__yui_subscribers||{};var B=this.__yui_subscribers;if(!B[A]){B[A]=[];}B[A].push({fn:C,obj:F,override:E});}},unsubscribe:function(C,E,G){this.__yui_events=this.__yui_events||{};var A=this.__yui_events;if(C){var F=A[C];if(F){return F.unsubscribe(E,G);}}else{var B=true;for(var D in A){if(YAHOO.lang.hasOwnProperty(A,D)){B=B&&A[D].unsubscribe(E,G);}}return B;}return false;},unsubscribeAll:function(A){return this.unsubscribe(A);},createEvent:function(G,D){this.__yui_events=this.__yui_events||{};var A=D||{};var I=this.__yui_events;if(I[G]){}else{var H=A.scope||this;var E=(A.silent);var B=new YAHOO.util.CustomEvent(G,H,E,YAHOO.util.CustomEvent.FLAT);I[G]=B;if(A.onSubscribeCallback){B.subscribeEvent.subscribe(A.onSubscribeCallback);}this.__yui_subscribers=this.__yui_subscribers||{};
var F=this.__yui_subscribers[G];if(F){for(var C=0;C<F.length;++C){B.subscribe(F[C].fn,F[C].obj,F[C].override);}}}return I[G];},fireEvent:function(E,D,A,C){this.__yui_events=this.__yui_events||{};var G=this.__yui_events[E];if(!G){return null;}var B=[];for(var F=1;F<arguments.length;++F){B.push(arguments[F]);}return G.fire.apply(G,B);},hasEvent:function(A){if(this.__yui_events){if(this.__yui_events[A]){return true;}}return false;}};YAHOO.util.KeyListener=function(A,F,B,C){if(!A){}else{if(!F){}else{if(!B){}}}if(!C){C=YAHOO.util.KeyListener.KEYDOWN;}var D=new YAHOO.util.CustomEvent("keyPressed");this.enabledEvent=new YAHOO.util.CustomEvent("enabled");this.disabledEvent=new YAHOO.util.CustomEvent("disabled");if(typeof A=="string"){A=document.getElementById(A);}if(typeof B=="function"){D.subscribe(B);}else{D.subscribe(B.fn,B.scope,B.correctScope);}function E(J,I){if(!F.shift){F.shift=false;}if(!F.alt){F.alt=false;}if(!F.ctrl){F.ctrl=false;}if(J.shiftKey==F.shift&&J.altKey==F.alt&&J.ctrlKey==F.ctrl){var G;if(F.keys instanceof Array){for(var H=0;H<F.keys.length;H++){G=F.keys[H];if(G==J.charCode){D.fire(J.charCode,J);break;}else{if(G==J.keyCode){D.fire(J.keyCode,J);break;}}}}else{G=F.keys;if(G==J.charCode){D.fire(J.charCode,J);}else{if(G==J.keyCode){D.fire(J.keyCode,J);}}}}}this.enable=function(){if(!this.enabled){YAHOO.util.Event.addListener(A,C,E);this.enabledEvent.fire(F);}this.enabled=true;};this.disable=function(){if(this.enabled){YAHOO.util.Event.removeListener(A,C,E);this.disabledEvent.fire(F);}this.enabled=false;};this.toString=function(){return"KeyListener ["+F.keys+"] "+A.tagName+(A.id?"["+A.id+"]":"");};};YAHOO.util.KeyListener.KEYDOWN="keydown";YAHOO.util.KeyListener.KEYUP="keyup";YAHOO.util.KeyListener.KEY={ALT:18,BACK_SPACE:8,CAPS_LOCK:20,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,META:224,NUM_LOCK:144,PAGE_DOWN:34,PAGE_UP:33,PAUSE:19,PRINTSCREEN:44,RIGHT:39,SCROLL_LOCK:145,SHIFT:16,SPACE:32,TAB:9,UP:38};YAHOO.register("event",YAHOO.util.Event,{version:"2.4.0",build:"733"});

/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.4.0
*/
(function(){var B=YAHOO.util,L,J,H=0,K={},F={},N=window.document;var C=YAHOO.env.ua.opera,M=YAHOO.env.ua.webkit,A=YAHOO.env.ua.gecko,G=YAHOO.env.ua.ie;var E={HYPHEN:/(-[a-z])/i,ROOT_TAG:/^body|html$/i};var O=function(Q){if(!E.HYPHEN.test(Q)){return Q;}if(K[Q]){return K[Q];}var R=Q;while(E.HYPHEN.exec(R)){R=R.replace(RegExp.$1,RegExp.$1.substr(1).toUpperCase());}K[Q]=R;return R;};var P=function(R){var Q=F[R];if(!Q){Q=new RegExp("(?:^|\\s+)"+R+"(?:\\s+|$)");F[R]=Q;}return Q;};if(N.defaultView&&N.defaultView.getComputedStyle){L=function(Q,T){var S=null;if(T=="float"){T="cssFloat";}var R=N.defaultView.getComputedStyle(Q,"");if(R){S=R[O(T)];}return Q.style[T]||S;};}else{if(N.documentElement.currentStyle&&G){L=function(Q,S){switch(O(S)){case"opacity":var U=100;try{U=Q.filters["DXImageTransform.Microsoft.Alpha"].opacity;}catch(T){try{U=Q.filters("alpha").opacity;}catch(T){}}return U/100;case"float":S="styleFloat";default:var R=Q.currentStyle?Q.currentStyle[S]:null;return(Q.style[S]||R);}};}else{L=function(Q,R){return Q.style[R];};}}if(G){J=function(Q,R,S){switch(R){case"opacity":if(YAHOO.lang.isString(Q.style.filter)){Q.style.filter="alpha(opacity="+S*100+")";if(!Q.currentStyle||!Q.currentStyle.hasLayout){Q.style.zoom=1;}}break;case"float":R="styleFloat";default:Q.style[R]=S;}};}else{J=function(Q,R,S){if(R=="float"){R="cssFloat";}Q.style[R]=S;};}var D=function(Q,R){return Q&&Q.nodeType==1&&(!R||R(Q));};YAHOO.util.Dom={get:function(S){if(S&&(S.tagName||S.item)){return S;}if(YAHOO.lang.isString(S)||!S){return N.getElementById(S);}if(S.length!==undefined){var T=[];for(var R=0,Q=S.length;R<Q;++R){T[T.length]=B.Dom.get(S[R]);}return T;}return S;},getStyle:function(Q,S){S=O(S);var R=function(T){return L(T,S);};return B.Dom.batch(Q,R,B.Dom,true);},setStyle:function(Q,S,T){S=O(S);var R=function(U){J(U,S,T);};B.Dom.batch(Q,R,B.Dom,true);},getXY:function(Q){var R=function(S){if((S.parentNode===null||S.offsetParent===null||this.getStyle(S,"display")=="none")&&S!=S.ownerDocument.body){return false;}return I(S);};return B.Dom.batch(Q,R,B.Dom,true);},getX:function(Q){var R=function(S){return B.Dom.getXY(S)[0];};return B.Dom.batch(Q,R,B.Dom,true);},getY:function(Q){var R=function(S){return B.Dom.getXY(S)[1];};return B.Dom.batch(Q,R,B.Dom,true);},setXY:function(Q,T,S){var R=function(W){var V=this.getStyle(W,"position");if(V=="static"){this.setStyle(W,"position","relative");V="relative";}var Y=this.getXY(W);if(Y===false){return false;}var X=[parseInt(this.getStyle(W,"left"),10),parseInt(this.getStyle(W,"top"),10)];if(isNaN(X[0])){X[0]=(V=="relative")?0:W.offsetLeft;}if(isNaN(X[1])){X[1]=(V=="relative")?0:W.offsetTop;}if(T[0]!==null){W.style.left=T[0]-Y[0]+X[0]+"px";}if(T[1]!==null){W.style.top=T[1]-Y[1]+X[1]+"px";}if(!S){var U=this.getXY(W);if((T[0]!==null&&U[0]!=T[0])||(T[1]!==null&&U[1]!=T[1])){this.setXY(W,T,true);}}};B.Dom.batch(Q,R,B.Dom,true);},setX:function(R,Q){B.Dom.setXY(R,[Q,null]);},setY:function(Q,R){B.Dom.setXY(Q,[null,R]);},getRegion:function(Q){var R=function(S){if((S.parentNode===null||S.offsetParent===null||this.getStyle(S,"display")=="none")&&S!=N.body){return false;}var T=B.Region.getRegion(S);return T;};return B.Dom.batch(Q,R,B.Dom,true);},getClientWidth:function(){return B.Dom.getViewportWidth();},getClientHeight:function(){return B.Dom.getViewportHeight();},getElementsByClassName:function(U,Y,V,W){Y=Y||"*";V=(V)?B.Dom.get(V):null||N;if(!V){return[];}var R=[],Q=V.getElementsByTagName(Y),X=P(U);for(var S=0,T=Q.length;S<T;++S){if(X.test(Q[S].className)){R[R.length]=Q[S];if(W){W.call(Q[S],Q[S]);}}}return R;},hasClass:function(S,R){var Q=P(R);var T=function(U){return Q.test(U.className);};return B.Dom.batch(S,T,B.Dom,true);},addClass:function(R,Q){var S=function(T){if(this.hasClass(T,Q)){return false;}T.className=YAHOO.lang.trim([T.className,Q].join(" "));return true;};return B.Dom.batch(R,S,B.Dom,true);},removeClass:function(S,R){var Q=P(R);var T=function(U){if(!this.hasClass(U,R)){return false;}var V=U.className;U.className=V.replace(Q," ");if(this.hasClass(U,R)){this.removeClass(U,R);}U.className=YAHOO.lang.trim(U.className);return true;};return B.Dom.batch(S,T,B.Dom,true);},replaceClass:function(T,R,Q){if(!Q||R===Q){return false;}var S=P(R);var U=function(V){if(!this.hasClass(V,R)){this.addClass(V,Q);return true;}V.className=V.className.replace(S," "+Q+" ");if(this.hasClass(V,R)){this.replaceClass(V,R,Q);}V.className=YAHOO.lang.trim(V.className);return true;};return B.Dom.batch(T,U,B.Dom,true);},generateId:function(Q,S){S=S||"yui-gen";var R=function(T){if(T&&T.id){return T.id;}var U=S+H++;if(T){T.id=U;}return U;};return B.Dom.batch(Q,R,B.Dom,true)||R.apply(B.Dom,arguments);},isAncestor:function(Q,R){Q=B.Dom.get(Q);R=B.Dom.get(R);if(!Q||!R){return false;}if(Q.contains&&R.nodeType&&!M){return Q.contains(R);}else{if(Q.compareDocumentPosition&&R.nodeType){return !!(Q.compareDocumentPosition(R)&16);}else{if(R.nodeType){return !!this.getAncestorBy(R,function(S){return S==Q;});}}}return false;},inDocument:function(Q){return this.isAncestor(N.documentElement,Q);},getElementsBy:function(X,R,S,U){R=R||"*";S=(S)?B.Dom.get(S):null||N;if(!S){return[];}var T=[],W=S.getElementsByTagName(R);for(var V=0,Q=W.length;V<Q;++V){if(X(W[V])){T[T.length]=W[V];if(U){U(W[V]);}}}return T;},batch:function(U,X,W,S){U=(U&&(U.tagName||U.item))?U:B.Dom.get(U);if(!U||!X){return false;}var T=(S)?W:window;if(U.tagName||U.length===undefined){return X.call(T,U,W);}var V=[];for(var R=0,Q=U.length;R<Q;++R){V[V.length]=X.call(T,U[R],W);}return V;},getDocumentHeight:function(){var R=(N.compatMode!="CSS1Compat")?N.body.scrollHeight:N.documentElement.scrollHeight;var Q=Math.max(R,B.Dom.getViewportHeight());return Q;},getDocumentWidth:function(){var R=(N.compatMode!="CSS1Compat")?N.body.scrollWidth:N.documentElement.scrollWidth;var Q=Math.max(R,B.Dom.getViewportWidth());return Q;},getViewportHeight:function(){var Q=self.innerHeight;var R=N.compatMode;if((R||G)&&!C){Q=(R=="CSS1Compat")?N.documentElement.clientHeight:N.body.clientHeight;
}return Q;},getViewportWidth:function(){var Q=self.innerWidth;var R=N.compatMode;if(R||G){Q=(R=="CSS1Compat")?N.documentElement.clientWidth:N.body.clientWidth;}return Q;},getAncestorBy:function(Q,R){while(Q=Q.parentNode){if(D(Q,R)){return Q;}}return null;},getAncestorByClassName:function(R,Q){R=B.Dom.get(R);if(!R){return null;}var S=function(T){return B.Dom.hasClass(T,Q);};return B.Dom.getAncestorBy(R,S);},getAncestorByTagName:function(R,Q){R=B.Dom.get(R);if(!R){return null;}var S=function(T){return T.tagName&&T.tagName.toUpperCase()==Q.toUpperCase();};return B.Dom.getAncestorBy(R,S);},getPreviousSiblingBy:function(Q,R){while(Q){Q=Q.previousSibling;if(D(Q,R)){return Q;}}return null;},getPreviousSibling:function(Q){Q=B.Dom.get(Q);if(!Q){return null;}return B.Dom.getPreviousSiblingBy(Q);},getNextSiblingBy:function(Q,R){while(Q){Q=Q.nextSibling;if(D(Q,R)){return Q;}}return null;},getNextSibling:function(Q){Q=B.Dom.get(Q);if(!Q){return null;}return B.Dom.getNextSiblingBy(Q);},getFirstChildBy:function(Q,S){var R=(D(Q.firstChild,S))?Q.firstChild:null;return R||B.Dom.getNextSiblingBy(Q.firstChild,S);},getFirstChild:function(Q,R){Q=B.Dom.get(Q);if(!Q){return null;}return B.Dom.getFirstChildBy(Q);},getLastChildBy:function(Q,S){if(!Q){return null;}var R=(D(Q.lastChild,S))?Q.lastChild:null;return R||B.Dom.getPreviousSiblingBy(Q.lastChild,S);},getLastChild:function(Q){Q=B.Dom.get(Q);return B.Dom.getLastChildBy(Q);},getChildrenBy:function(R,T){var S=B.Dom.getFirstChildBy(R,T);var Q=S?[S]:[];B.Dom.getNextSiblingBy(S,function(U){if(!T||T(U)){Q[Q.length]=U;}return false;});return Q;},getChildren:function(Q){Q=B.Dom.get(Q);if(!Q){}return B.Dom.getChildrenBy(Q);},getDocumentScrollLeft:function(Q){Q=Q||N;return Math.max(Q.documentElement.scrollLeft,Q.body.scrollLeft);},getDocumentScrollTop:function(Q){Q=Q||N;return Math.max(Q.documentElement.scrollTop,Q.body.scrollTop);},insertBefore:function(R,Q){R=B.Dom.get(R);Q=B.Dom.get(Q);if(!R||!Q||!Q.parentNode){return null;}return Q.parentNode.insertBefore(R,Q);},insertAfter:function(R,Q){R=B.Dom.get(R);Q=B.Dom.get(Q);if(!R||!Q||!Q.parentNode){return null;}if(Q.nextSibling){return Q.parentNode.insertBefore(R,Q.nextSibling);}else{return Q.parentNode.appendChild(R);}},getClientRegion:function(){var S=B.Dom.getDocumentScrollTop(),R=B.Dom.getDocumentScrollLeft(),T=B.Dom.getViewportWidth()+R,Q=B.Dom.getViewportHeight()+S;return new B.Region(S,T,Q,R);}};var I=function(){if(N.documentElement.getBoundingClientRect){return function(R){var S=R.getBoundingClientRect();var Q=R.ownerDocument;return[S.left+B.Dom.getDocumentScrollLeft(Q),S.top+B.Dom.getDocumentScrollTop(Q)];};}else{return function(S){var T=[S.offsetLeft,S.offsetTop];var R=S.offsetParent;var Q=(M&&B.Dom.getStyle(S,"position")=="absolute"&&S.offsetParent==S.ownerDocument.body);if(R!=S){while(R){T[0]+=R.offsetLeft;T[1]+=R.offsetTop;if(!Q&&M&&B.Dom.getStyle(R,"position")=="absolute"){Q=true;}R=R.offsetParent;}}if(Q){T[0]-=S.ownerDocument.body.offsetLeft;T[1]-=S.ownerDocument.body.offsetTop;}R=S.parentNode;while(R.tagName&&!E.ROOT_TAG.test(R.tagName)){if(B.Dom.getStyle(R,"display").search(/^inline|table-row.*$/i)){T[0]-=R.scrollLeft;T[1]-=R.scrollTop;}R=R.parentNode;}return T;};}}();})();YAHOO.util.Region=function(C,D,A,B){this.top=C;this[1]=C;this.right=D;this.bottom=A;this.left=B;this[0]=B;};YAHOO.util.Region.prototype.contains=function(A){return(A.left>=this.left&&A.right<=this.right&&A.top>=this.top&&A.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(E){var C=Math.max(this.top,E.top);var D=Math.min(this.right,E.right);var A=Math.min(this.bottom,E.bottom);var B=Math.max(this.left,E.left);if(A>=C&&D>=B){return new YAHOO.util.Region(C,D,A,B);}else{return null;}};YAHOO.util.Region.prototype.union=function(E){var C=Math.min(this.top,E.top);var D=Math.max(this.right,E.right);var A=Math.max(this.bottom,E.bottom);var B=Math.min(this.left,E.left);return new YAHOO.util.Region(C,D,A,B);};YAHOO.util.Region.prototype.toString=function(){return("Region {top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+"}");};YAHOO.util.Region.getRegion=function(D){var F=YAHOO.util.Dom.getXY(D);var C=F[1];var E=F[0]+D.offsetWidth;var A=F[1]+D.offsetHeight;var B=F[0];return new YAHOO.util.Region(C,E,A,B);};YAHOO.util.Point=function(A,B){if(YAHOO.lang.isArray(A)){B=A[1];A=A[0];}this.x=this.right=this.left=this[0]=A;this.y=this.top=this.bottom=this[1]=B;};YAHOO.util.Point.prototype=new YAHOO.util.Region();YAHOO.register("dom",YAHOO.util.Dom,{version:"2.4.0",build:"733"});

/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.4.0
*/
YAHOO.widget.LogMsg=function(A){if(A&&(A.constructor==Object)){for(var B in A){this[B]=A[B];}}};YAHOO.widget.LogMsg.prototype.msg=null;YAHOO.widget.LogMsg.prototype.time=null;YAHOO.widget.LogMsg.prototype.category=null;YAHOO.widget.LogMsg.prototype.source=null;YAHOO.widget.LogMsg.prototype.sourceDetail=null;YAHOO.widget.LogWriter=function(A){if(!A){YAHOO.log("Could not instantiate LogWriter due to invalid source.","error","LogWriter");return ;}this._source=A;};YAHOO.widget.LogWriter.prototype.toString=function(){return"LogWriter "+this._sSource;};YAHOO.widget.LogWriter.prototype.log=function(A,B){YAHOO.widget.Logger.log(A,B,this._source);};YAHOO.widget.LogWriter.prototype.getSource=function(){return this._sSource;};YAHOO.widget.LogWriter.prototype.setSource=function(A){if(!A){YAHOO.log("Could not set source due to invalid source.","error",this.toString());return ;}else{this._sSource=A;}};YAHOO.widget.LogWriter.prototype._source=null;YAHOO.widget.LogReader=function(B,A){this._sName=YAHOO.widget.LogReader._index;YAHOO.widget.LogReader._index++;this._buffer=[];this._filterCheckboxes={};this._lastTime=YAHOO.widget.Logger.getStartTime();if(A&&(A.constructor==Object)){for(var C in A){this[C]=A[C];}}this._initContainerEl(B);if(!this._elContainer){YAHOO.log("Could not instantiate LogReader due to an invalid container element "+B,"error",this.toString());return ;}this._initHeaderEl();this._initConsoleEl();this._initFooterEl();this._initDragDrop();this._initCategories();this._initSources();YAHOO.widget.Logger.newLogEvent.subscribe(this._onNewLog,this);YAHOO.widget.Logger.logResetEvent.subscribe(this._onReset,this);YAHOO.widget.Logger.categoryCreateEvent.subscribe(this._onCategoryCreate,this);YAHOO.widget.Logger.sourceCreateEvent.subscribe(this._onSourceCreate,this);this._filterLogs();YAHOO.log("LogReader initialized",null,this.toString());};YAHOO.widget.LogReader.prototype.logReaderEnabled=true;YAHOO.widget.LogReader.prototype.width=null;YAHOO.widget.LogReader.prototype.height=null;YAHOO.widget.LogReader.prototype.top=null;YAHOO.widget.LogReader.prototype.left=null;YAHOO.widget.LogReader.prototype.right=null;YAHOO.widget.LogReader.prototype.bottom=null;YAHOO.widget.LogReader.prototype.fontSize=null;YAHOO.widget.LogReader.prototype.footerEnabled=true;YAHOO.widget.LogReader.prototype.verboseOutput=true;YAHOO.widget.LogReader.prototype.newestOnTop=true;YAHOO.widget.LogReader.prototype.outputBuffer=100;YAHOO.widget.LogReader.prototype.thresholdMax=500;YAHOO.widget.LogReader.prototype.thresholdMin=100;YAHOO.widget.LogReader.prototype.isCollapsed=false;YAHOO.widget.LogReader.prototype.isPaused=false;YAHOO.widget.LogReader.prototype.draggable=true;YAHOO.widget.LogReader.prototype.toString=function(){return"LogReader instance"+this._sName;};YAHOO.widget.LogReader.prototype.pause=function(){this.isPaused=true;this._btnPause.value="Resume";this._timeout=null;this.logReaderEnabled=false;};YAHOO.widget.LogReader.prototype.resume=function(){this.isPaused=false;this._btnPause.value="Pause";this.logReaderEnabled=true;this._printBuffer();};YAHOO.widget.LogReader.prototype.hide=function(){this._elContainer.style.display="none";};YAHOO.widget.LogReader.prototype.show=function(){this._elContainer.style.display="block";};YAHOO.widget.LogReader.prototype.collapse=function(){this._elConsole.style.display="none";if(this._elFt){this._elFt.style.display="none";}this._btnCollapse.value="Expand";this.isCollapsed=true;};YAHOO.widget.LogReader.prototype.expand=function(){this._elConsole.style.display="block";if(this._elFt){this._elFt.style.display="block";}this._btnCollapse.value="Collapse";this.isCollapsed=false;};YAHOO.widget.LogReader.prototype.getCheckbox=function(A){return this._filterCheckboxes[A];};YAHOO.widget.LogReader.prototype.getCategories=function(){return this._categoryFilters;};YAHOO.widget.LogReader.prototype.showCategory=function(B){var D=this._categoryFilters;if(D.indexOf){if(D.indexOf(B)>-1){return ;}}else{for(var A=0;A<D.length;A++){if(D[A]===B){return ;}}}this._categoryFilters.push(B);this._filterLogs();var C=this.getCheckbox(B);if(C){C.checked=true;}};YAHOO.widget.LogReader.prototype.hideCategory=function(B){var D=this._categoryFilters;for(var A=0;A<D.length;A++){if(B==D[A]){D.splice(A,1);break;}}this._filterLogs();var C=this.getCheckbox(B);if(C){C.checked=false;}};YAHOO.widget.LogReader.prototype.getSources=function(){return this._sourceFilters;};YAHOO.widget.LogReader.prototype.showSource=function(A){var D=this._sourceFilters;if(D.indexOf){if(D.indexOf(A)>-1){return ;}}else{for(var B=0;B<D.length;B++){if(A==D[B]){return ;}}}D.push(A);this._filterLogs();var C=this.getCheckbox(A);if(C){C.checked=true;}};YAHOO.widget.LogReader.prototype.hideSource=function(A){var D=this._sourceFilters;for(var B=0;B<D.length;B++){if(A==D[B]){D.splice(B,1);break;}}this._filterLogs();var C=this.getCheckbox(A);if(C){C.checked=false;}};YAHOO.widget.LogReader.prototype.clearConsole=function(){this._timeout=null;this._buffer=[];this._consoleMsgCount=0;var A=this._elConsole;while(A.hasChildNodes()){A.removeChild(A.firstChild);}};YAHOO.widget.LogReader.prototype.setTitle=function(A){this._title.innerHTML=this.html2Text(A);};YAHOO.widget.LogReader.prototype.getLastTime=function(){return this._lastTime;};YAHOO.widget.LogReader.prototype.formatMsg=function(D){var E=D.category;var L=E.substring(0,4).toUpperCase();var I=D.time;var J;if(I.toLocaleTimeString){J=I.toLocaleTimeString();}else{J=I.toString();}var B=I.getTime();var F=YAHOO.widget.Logger.getStartTime();var C=B-F;var N=B-this.getLastTime();var A=D.source;var M=D.sourceDetail;var K=(M)?A+" "+M:A;var H=this.html2Text(YAHOO.lang.dump(D.msg));var G=(this.verboseOutput)?["<pre class=\"yui-log-verbose\"><p><span class='",E,"'>",L,"</span> ",C,"ms (+",N,") ",J,": ","</p><p>",K,": </p><p>",H,"</p></pre>"]:["<pre><p><span class='",E,"'>",L,"</span> ",C,"ms (+",N,") ",J,": ",K,": ",H,"</p></pre>"];return G.join("");};YAHOO.widget.LogReader.prototype.html2Text=function(A){if(A){A+="";return A.replace(/&/g,"&#38;").replace(/</g,"&#60;").replace(/>/g,"&#62;");
}return"";};YAHOO.widget.LogReader._index=0;YAHOO.widget.LogReader.prototype._sName=null;YAHOO.widget.LogReader.prototype._buffer=null;YAHOO.widget.LogReader.prototype._consoleMsgCount=0;YAHOO.widget.LogReader.prototype._lastTime=null;YAHOO.widget.LogReader.prototype._timeout=null;YAHOO.widget.LogReader.prototype._filterCheckboxes=null;YAHOO.widget.LogReader.prototype._categoryFilters=null;YAHOO.widget.LogReader.prototype._sourceFilters=null;YAHOO.widget.LogReader.prototype._elContainer=null;YAHOO.widget.LogReader.prototype._elHd=null;YAHOO.widget.LogReader.prototype._elCollapse=null;YAHOO.widget.LogReader.prototype._btnCollapse=null;YAHOO.widget.LogReader.prototype._title=null;YAHOO.widget.LogReader.prototype._elConsole=null;YAHOO.widget.LogReader.prototype._elFt=null;YAHOO.widget.LogReader.prototype._elBtns=null;YAHOO.widget.LogReader.prototype._elCategoryFilters=null;YAHOO.widget.LogReader.prototype._elSourceFilters=null;YAHOO.widget.LogReader.prototype._btnPause=null;YAHOO.widget.LogReader.prototype._btnClear=null;YAHOO.widget.LogReader.prototype._initContainerEl=function(B){B=YAHOO.util.Dom.get(B);if(B&&B.tagName&&(B.tagName.toLowerCase()=="div")){this._elContainer=B;YAHOO.util.Dom.addClass(this._elContainer,"yui-log");}else{this._elContainer=document.body.appendChild(document.createElement("div"));YAHOO.util.Dom.addClass(this._elContainer,"yui-log");YAHOO.util.Dom.addClass(this._elContainer,"yui-log-container");var A=this._elContainer.style;if(this.width){A.width=this.width;}if(this.right){A.right=this.right;}if(this.top){A.top=this.top;}if(this.left){A.left=this.left;A.right="auto";}if(this.bottom){A.bottom=this.bottom;A.top="auto";}if(this.fontSize){A.fontSize=this.fontSize;}if(navigator.userAgent.toLowerCase().indexOf("opera")!=-1){document.body.style+="";}}};YAHOO.widget.LogReader.prototype._initHeaderEl=function(){var A=this;if(this._elHd){YAHOO.util.Event.purgeElement(this._elHd,true);this._elHd.innerHTML="";}this._elHd=this._elContainer.appendChild(document.createElement("div"));this._elHd.id="yui-log-hd"+this._sName;this._elHd.className="yui-log-hd";this._elCollapse=this._elHd.appendChild(document.createElement("div"));this._elCollapse.className="yui-log-btns";this._btnCollapse=document.createElement("input");this._btnCollapse.type="button";this._btnCollapse.className="yui-log-button";this._btnCollapse.value="Collapse";this._btnCollapse=this._elCollapse.appendChild(this._btnCollapse);YAHOO.util.Event.addListener(A._btnCollapse,"click",A._onClickCollapseBtn,A);this._title=this._elHd.appendChild(document.createElement("h4"));this._title.innerHTML="Logger Console";};YAHOO.widget.LogReader.prototype._initConsoleEl=function(){if(this._elConsole){YAHOO.util.Event.purgeElement(this._elConsole,true);this._elConsole.innerHTML="";}this._elConsole=this._elContainer.appendChild(document.createElement("div"));this._elConsole.className="yui-log-bd";if(this.height){this._elConsole.style.height=this.height;}};YAHOO.widget.LogReader.prototype._initFooterEl=function(){var A=this;if(this.footerEnabled){if(this._elFt){YAHOO.util.Event.purgeElement(this._elFt,true);this._elFt.innerHTML="";}this._elFt=this._elContainer.appendChild(document.createElement("div"));this._elFt.className="yui-log-ft";this._elBtns=this._elFt.appendChild(document.createElement("div"));this._elBtns.className="yui-log-btns";this._btnPause=document.createElement("input");this._btnPause.type="button";this._btnPause.className="yui-log-button";this._btnPause.value="Pause";this._btnPause=this._elBtns.appendChild(this._btnPause);YAHOO.util.Event.addListener(A._btnPause,"click",A._onClickPauseBtn,A);this._btnClear=document.createElement("input");this._btnClear.type="button";this._btnClear.className="yui-log-button";this._btnClear.value="Clear";this._btnClear=this._elBtns.appendChild(this._btnClear);YAHOO.util.Event.addListener(A._btnClear,"click",A._onClickClearBtn,A);this._elCategoryFilters=this._elFt.appendChild(document.createElement("div"));this._elCategoryFilters.className="yui-log-categoryfilters";this._elSourceFilters=this._elFt.appendChild(document.createElement("div"));this._elSourceFilters.className="yui-log-sourcefilters";}};YAHOO.widget.LogReader.prototype._initDragDrop=function(){if(YAHOO.util.DD&&this.draggable&&this._elHd){var A=new YAHOO.util.DD(this._elContainer);A.setHandleElId(this._elHd.id);this._elHd.style.cursor="move";}};YAHOO.widget.LogReader.prototype._initCategories=function(){this._categoryFilters=[];var C=YAHOO.widget.Logger.categories;for(var A=0;A<C.length;A++){var B=C[A];this._categoryFilters.push(B);if(this._elCategoryFilters){this._createCategoryCheckbox(B);}}};YAHOO.widget.LogReader.prototype._initSources=function(){this._sourceFilters=[];var C=YAHOO.widget.Logger.sources;for(var B=0;B<C.length;B++){var A=C[B];this._sourceFilters.push(A);if(this._elSourceFilters){this._createSourceCheckbox(A);}}};YAHOO.widget.LogReader.prototype._createCategoryCheckbox=function(B){var A=this;if(this._elFt){var E=this._elCategoryFilters;var D=E.appendChild(document.createElement("span"));D.className="yui-log-filtergrp";var C=document.createElement("input");C.id="yui-log-filter-"+B+this._sName;C.className="yui-log-filter-"+B;C.type="checkbox";C.category=B;C=D.appendChild(C);C.checked=true;YAHOO.util.Event.addListener(C,"click",A._onCheckCategory,A);var F=D.appendChild(document.createElement("label"));F.htmlFor=C.id;F.className=B;F.innerHTML=B;this._filterCheckboxes[B]=C;}};YAHOO.widget.LogReader.prototype._createSourceCheckbox=function(A){var D=this;if(this._elFt){var F=this._elSourceFilters;var E=F.appendChild(document.createElement("span"));E.className="yui-log-filtergrp";var C=document.createElement("input");C.id="yui-log-filter"+A+this._sName;C.className="yui-log-filter"+A;C.type="checkbox";C.source=A;C=E.appendChild(C);C.checked=true;YAHOO.util.Event.addListener(C,"click",D._onCheckSource,D);var B=E.appendChild(document.createElement("label"));B.htmlFor=C.id;B.className=A;B.innerHTML=A;this._filterCheckboxes[A]=C;
}};YAHOO.widget.LogReader.prototype._filterLogs=function(){if(this._elConsole!==null){this.clearConsole();this._printToConsole(YAHOO.widget.Logger.getStack());}};YAHOO.widget.LogReader.prototype._printBuffer=function(){this._timeout=null;if(this._elConsole!==null){var B=this.thresholdMax;B=(B&&!isNaN(B))?B:500;if(this._consoleMsgCount<B){var A=[];for(var C=0;C<this._buffer.length;C++){A[C]=this._buffer[C];}this._buffer=[];this._printToConsole(A);}else{this._filterLogs();}if(!this.newestOnTop){this._elConsole.scrollTop=this._elConsole.scrollHeight;}}};YAHOO.widget.LogReader.prototype._printToConsole=function(J){var B=J.length;var O=this.thresholdMin;if(isNaN(O)||(O>this.thresholdMax)){O=0;}var L=(B>O)?(B-O):0;var C=this._sourceFilters.length;var M=this._categoryFilters.length;for(var I=L;I<B;I++){var F=false;var K=false;var N=J[I];var A=N.source;var D=N.category;for(var H=0;H<C;H++){if(A==this._sourceFilters[H]){K=true;break;}}if(K){for(var G=0;G<M;G++){if(D==this._categoryFilters[G]){F=true;break;}}}if(F){var E=this.formatMsg(N);if(this.newestOnTop){this._elConsole.innerHTML=E+this._elConsole.innerHTML;}else{this._elConsole.innerHTML+=E;}this._consoleMsgCount++;this._lastTime=N.time.getTime();}}};YAHOO.widget.LogReader.prototype._onCategoryCreate=function(D,C,A){var B=C[0];A._categoryFilters.push(B);if(A._elFt){A._createCategoryCheckbox(B);}};YAHOO.widget.LogReader.prototype._onSourceCreate=function(D,C,A){var B=C[0];A._sourceFilters.push(B);if(A._elFt){A._createSourceCheckbox(B);}};YAHOO.widget.LogReader.prototype._onCheckCategory=function(A,B){var C=this.category;if(!this.checked){B.hideCategory(C);}else{B.showCategory(C);}};YAHOO.widget.LogReader.prototype._onCheckSource=function(A,B){var C=this.source;if(!this.checked){B.hideSource(C);}else{B.showSource(C);}};YAHOO.widget.LogReader.prototype._onClickCollapseBtn=function(A,B){if(!B.isCollapsed){B.collapse();}else{B.expand();}};YAHOO.widget.LogReader.prototype._onClickPauseBtn=function(A,B){if(!B.isPaused){B.pause();}else{B.resume();}};YAHOO.widget.LogReader.prototype._onClickClearBtn=function(A,B){B.clearConsole();};YAHOO.widget.LogReader.prototype._onNewLog=function(D,C,A){var B=C[0];A._buffer.push(B);if(A.logReaderEnabled===true&&A._timeout===null){A._timeout=setTimeout(function(){A._printBuffer();},A.outputBuffer);}};YAHOO.widget.LogReader.prototype._onReset=function(C,B,A){A._filterLogs();};if(!YAHOO.widget.Logger){YAHOO.widget.Logger={loggerEnabled:true,_browserConsoleEnabled:false,categories:["info","warn","error","time","window"],sources:["global"],_stack:[],maxStackEntries:2500,_startTime:new Date().getTime(),_lastTime:null,_windowErrorsHandled:false,_origOnWindowError:null};YAHOO.widget.Logger.log=function(B,F,G){if(this.loggerEnabled){if(!F){F="info";}else{F=F.toLocaleLowerCase();if(this._isNewCategory(F)){this._createNewCategory(F);}}var C="global";var A=null;if(G){var D=G.indexOf(" ");if(D>0){C=G.substring(0,D);A=G.substring(D,G.length);}else{C=G;}if(this._isNewSource(C)){this._createNewSource(C);}}var H=new Date();var J=new YAHOO.widget.LogMsg({msg:B,time:H,category:F,source:C,sourceDetail:A});var I=this._stack;var E=this.maxStackEntries;if(E&&!isNaN(E)&&(I.length>=E)){I.shift();}I.push(J);this.newLogEvent.fire(J);if(this._browserConsoleEnabled){this._printToBrowserConsole(J);}return true;}else{return false;}};YAHOO.widget.Logger.reset=function(){this._stack=[];this._startTime=new Date().getTime();this.loggerEnabled=true;this.log("Logger reset");this.logResetEvent.fire();};YAHOO.widget.Logger.getStack=function(){return this._stack;};YAHOO.widget.Logger.getStartTime=function(){return this._startTime;};YAHOO.widget.Logger.disableBrowserConsole=function(){YAHOO.log("Logger output to the function console.log() has been disabled.");this._browserConsoleEnabled=false;};YAHOO.widget.Logger.enableBrowserConsole=function(){this._browserConsoleEnabled=true;YAHOO.log("Logger output to the function console.log() has been enabled.");};YAHOO.widget.Logger.handleWindowErrors=function(){if(!YAHOO.widget.Logger._windowErrorsHandled){if(window.error){YAHOO.widget.Logger._origOnWindowError=window.onerror;}window.onerror=YAHOO.widget.Logger._onWindowError;YAHOO.widget.Logger._windowErrorsHandled=true;YAHOO.log("Logger handling of window.onerror has been enabled.");}else{YAHOO.log("Logger handling of window.onerror had already been enabled.");}};YAHOO.widget.Logger.unhandleWindowErrors=function(){if(YAHOO.widget.Logger._windowErrorsHandled){if(YAHOO.widget.Logger._origOnWindowError){window.onerror=YAHOO.widget.Logger._origOnWindowError;YAHOO.widget.Logger._origOnWindowError=null;}else{window.onerror=null;}YAHOO.widget.Logger._windowErrorsHandled=false;YAHOO.log("Logger handling of window.onerror has been disabled.");}else{YAHOO.log("Logger handling of window.onerror had already been disabled.");}};YAHOO.widget.Logger.categoryCreateEvent=new YAHOO.util.CustomEvent("categoryCreate",this,true);YAHOO.widget.Logger.sourceCreateEvent=new YAHOO.util.CustomEvent("sourceCreate",this,true);YAHOO.widget.Logger.newLogEvent=new YAHOO.util.CustomEvent("newLog",this,true);YAHOO.widget.Logger.logResetEvent=new YAHOO.util.CustomEvent("logReset",this,true);YAHOO.widget.Logger._createNewCategory=function(A){this.categories.push(A);this.categoryCreateEvent.fire(A);};YAHOO.widget.Logger._isNewCategory=function(B){for(var A=0;A<this.categories.length;A++){if(B==this.categories[A]){return false;}}return true;};YAHOO.widget.Logger._createNewSource=function(A){this.sources.push(A);this.sourceCreateEvent.fire(A);};YAHOO.widget.Logger._isNewSource=function(A){if(A){for(var B=0;B<this.sources.length;B++){if(A==this.sources[B]){return false;}}return true;}};YAHOO.widget.Logger._printToBrowserConsole=function(C){if(window.console&&console.log){var E=C.category;var D=C.category.substring(0,4).toUpperCase();var G=C.time;var F;if(G.toLocaleTimeString){F=G.toLocaleTimeString();}else{F=G.toString();}var H=G.getTime();var B=(YAHOO.widget.Logger._lastTime)?(H-YAHOO.widget.Logger._lastTime):0;
YAHOO.widget.Logger._lastTime=H;var A=F+" ("+B+"ms): "+C.source+": "+C.msg;console.log(A);}};YAHOO.widget.Logger._onWindowError=function(A,C,B){try{YAHOO.widget.Logger.log(A+" ("+C+", line "+B+")","window");if(YAHOO.widget.Logger._origOnWindowError){YAHOO.widget.Logger._origOnWindowError();}}catch(D){return false;}};YAHOO.widget.Logger.log("Logger initialized");}YAHOO.register("logger",YAHOO.widget.Logger,{version:"2.4.0",build:"733"});

// set the Mcfront objects

var MARCOMPRO_MODE			= 0;
var errorMsg				= new Array();

init = function() {
	try {
		setAnchorEvents();
		setFormEvents();
		debugWindow.initDebugger();
		if(window.document.getElementById('debugWindow')) {
			window.document.getElementById('debugWindow').style.display = "none";
		}

		// load project functions by a window onload
		projectInit();
	} catch (e) {
		errorMsg.push(e + ' (InitSiteview.js)');
		debugWindow.handleAjaxError(errorMsg);
	}
}

window.onload = init;

//***************************************************************************
// ProjectAttributes Constructor											*
// comments:																*
//***************************************************************************
function ProjectAttributes() {
	
}

//***************************************************************************
// ProjectAttributes doAttr													*
// @type	'string'														*
// @definition	'string'													*
// @action	'string'														*
// @doAction	'string'													*
// @disabled	'string'													*
// comments: 	if the attribute type exists, do something with the 		*
//				attributes
//***************************************************************************
ProjectAttributes.prototype.doAttr = function (type, definition, action, doAction, disabled) {

}

var projectAttributes = new ProjectAttributes();


setParentChecked = function(subCatObj, mainCatObjId){
	
	if(subCatObj.checked){
		if(!$(mainCatObjId).checked){
			$(mainCatObjId).checked = true;

			try {
				if($("search_category1")) {
					$("search_category1")	= $(mainCatObjId).value;
				}

				var subId	= subCatObj.id;
				if($(subId)) {
					$("search_category2")	= $(subId).value;
				}
			} catch (e) {
				
			}
		}
	} else {
		var subs 	= $$('input.' + subCatObj.className);
		var len 	= subs.length;
		var checked	= false;
		
		for(var i = 0; i < len; i++){
			if(subs[i].checked){
				checked = true;
				break;
			}
		}
		
		$(mainCatObjId).checked = checked;
	}
}

setElementsClickAction = function(){
	
	var elements 	= document.getElementsByTagName('a');
	var imgElms		= document.getElementsByTagName('img');		
	
	elements 		= mergeNodeLists(elements, imgElms); 
		
	var eLen = elements.length;	
	
	for(var i = 0; i < eLen; i++){
				
		if(document.addEventListener){				
			if(elements[i].getAttribute('onclick')){
				var onclick = elements[i].getAttribute('onclick');
				elements[i].setAttribute('onclick', 'browserBackButton = false; ' + onclick);
			} else {
				elements[i].addEventListener('click', setBrowserBackButton, false);
			}
		} else {
			if(elements[i].getAttribute('onclick')){
				var onclick = elements[i].getAttribute('onclick');
				onclick = onclick.toString();								
				onclick = onclick.substring((onclick.indexOf('{') + 1), onclick.lastIndexOf('}'));
				for(var j = 0; j < elements[i].attributes.length; j++){					
					if(elements[i].attributes[j].name == 'onclick'){
						elements[i].attributes[j].value = 'browserBackButton = false; ' + onclick;
					}
				}
				alert()
			} else {
				elements[i].attachEvent('onclick', setBrowserBackButton);
			}
		}					
	}
}

mergeNodeLists = function(list1, list2){		
		
	var len 	= (list1.length > list2.length) ? list1.length : list2.length;	
	var arr		= new Array();
	
	for(var i = 0; i < len; i++){
		if(list1[i]){
			arr[arr.length] = list1[i];			
		}
		if(list2[i]){
			arr[arr.length] = list2[i];
		}				
	}		
	
	return arr;	
}

confirmBrowseAway = function(evt){	 
		
	/*
	if(browserBackButton){
		var str = "WAARSCHUWING!\n\r";
		str += "----------------------------------------------\n\r";
		str += "Het gebruik van de 'terug'-knop van de browser heeft niet het gewenste effect op deze pagina!\r\n";
		str += "Gebruik alstublieft onze eigen (oranje gekleurde) 'terug'-knop boven de artikelafbeelding.\r\n";
		str += "----------------------------------------------";
    	return str;	  
	}
	*/
}	

setBrowserBackButton = function(evt){		
	if(!evt){
		var evt = window.event;
	}
	var element = (evt.target) ? evt.target : evt.srcElement;
	var click 	= element.getAttribute('onclick');
	var href 	= element.getAttribute('href');
	var pClick 	= element.parentNode.getAttribute('onclick');
	var pHref 	= element.parentNode.getAttribute('href');
		
	if(click || href || pClick || pHref){
		browserBackButton = false;
	}
}

calculateDisplayPrice = function(priceId, marginId){
	
	var price 	= parseFloat($(priceId).value.replace(',', '.'));
	var margin	= parseFloat($(marginId).value.replace(',', '.'));
	
	if(isNaN(price) || isNaN(margin)){
		
		alert('Either the price or the margin was invalid. Try different values.');
	} else {
	
		$('spn_calc_price').innerHTML = Math.round((price * margin) * 100) / 100;
	}
}

var mb_register = null;
var OverlayDisplay = null;

projectInit = function() {		
	mb_register = $H();
}

updateStatuses = function() {
	var asset_id = $('catstatus_asset_id').value;				
	var statusvalue = $('catstatus_value').value;					
	var statuscat = $('catstatus_category').value;
	
	// Basename: for the button in the popupbox 
	var basename = 'status_' + asset_id + '_' + statuscat + '_';
	// Anchorbase: for the tiny little icons above the thumbs
	var anchorbase = 'anchor_' + asset_id + '_' + statuscat + '_';
	
	// Show all icons and links
	var active_anchor = $(anchorbase + '10');
	var passive_anchor = $(anchorbase + '1');

	$(basename + '1').className = 'left';
	$(basename + '10').className = 'left';
	
	active_anchor.removeClassName('hide');
	passive_anchor.removeClassName('hide');
	
	// Get the status, and show only the correct button or icon
	statusvalue = (statusvalue == 10 ? 1 : 10);
	
	$(basename + statusvalue).addClassName('hide');
	$(anchorbase + statusvalue).addClassName('hide');
}

updateWebshop = function(){
	var asset_id = $('webshopstatus_asset_id').value;
	var statusvalue = $('webshopstatus_status').value;
	var anchorbase = 'anchor_'+asset_id+'_shop_';
	var active_anchor =$(anchorbase + '10');
	var passive_anchor =$(anchorbase + '1');
	
	if (active_anchor.className.match('hide')){
		active_anchor.removeClassName('hide');
	}
	if (passive_anchor.className.match('hide')){
		passive_anchor.removeClassName('hide');
	}
	
	statusvalue = (statusvalue == 10 ? 1 : 10);
	$(anchorbase + statusvalue).addClassName('hide');
}

function clearSearch(){
	var form = $('category_switch');
	var els = form.getElements();
	els.each(function(el){
		if (el.id != 'assetpro_search_bank_id'){
			el.value = '';
		}
	});
	
	if($("assetpro_search_category")) $("assetpro_search_category").value="";
	if($("assetpro_search_subcategory")) $("assetpro_search_subcategory").value="";
}

function checkQuickSearch(titleFieldId, artnrFieldId){
	
	//check if fields have values and if so, if they have other values than default values
	var titleValid = ($(titleFieldId).value == '' || $(titleFieldId).value == 'op naam') ? false : true;
	var artnrValid = ($(artnrFieldId).value == '' || $(artnrFieldId).value == 'op artikelnummer') ? false : true;
	
	//if the value is not valid empty title field before submit
	//so no invalid value will be passed to the actual search field
	if(!titleValid){
		$(titleFieldId).value = '';
	}
	
	//if the value is not valid empty artnr field before submit
	//so no invalid value will be passed to the actual search field
	if(!artnrValid){
		$(artnrFieldId).value = '';
	}
	
	return (titleValid || artnrValid);
}


/**
 * FormValidation 
 * Uses formControl-class from mcfront
 * 
 * @param string formid
 * @param string feedbackdiv
 **/
function validateForm(formid, feedbackdiv, noSubmit){
	var form = $(formid);
	var fbd = $(feedbackdiv);
	var msg		= '';
	formControl.reset();		
	
	var res = formControl.checkOnly(form);
	if (res){
		fbd.className = 'hide'; 
		fbd.innerHTML = '';
		if(!noSubmit){						
			form.submit();
			return true;			
		} else {
			return true;
		}
	}
	var msgRequired	= formControl.errorMsgRequired;
	var msgfirst = true;
	for(var i in msgRequired) {
		if (msgfirst) {
			msg += '<h3>De volgende velden zijn vereist, maar niet ingevuld:</h3>';
			msgfirst = false;			
		}
		msg		+= msgRequired[i].id +'<br/>';
	}
	
	var msgTypes	= formControl.errorMsgTypes;
	var msgfirst = true;
		
	for(var i in msgTypes) {
		if (msgfirst){
			msg += '<h3>De volgende velden zijn onjuist ingevuld:</h3>';
			msgfirst = false;	
		}
		msg		+= msgTypes[i].id +'<br/>';
	}
	
	fbd.innerHTML = msg;
	fbd.className = 'show fieldsError';
	return false;
}


function isIntVal(link){
	var inputvalue = link.parentNode.getElementsByTagName('input')[0].value
	var value = inputvalue.match(/^[0-9]+$/);
	if (!value){
		return false;
	}
	if (value > 0 ){
		return true;
	}
	return false;
}


/*
*/

function toggleEL(elementID){
	if(typeof(elementID)!="undefined"){
		var el=$(elementID);
		if(el){
			el.style.display = (el.style.display=="") ? el.style.display="none" : el.style.display="";
		}
	}
}

function deToggleElements(elementsArray){
	if(typeof(elementsArray)=="undefined") elementsArray=new Array();
	var len=elementsArray.length;
	for(var i=0;i<len;i++){
		var elItem	= elementsArray[i];
		var el;
		
		if(el=$(elItem)){
			el.style.display = "none";
		}
	}
}

function toggleElements(elementsArray){
	if(typeof(elementsArray)=="undefined") elementsArray=new Array();
	var len=elementsArray.length;
	for(var i=0;i<len;i++){
		var elItem	= elementsArray[i];
		var el;
		
		if(el=$(elItem)){
			el.style.display = "";
		}
	}
}


var blinkIntervalID	= 0;
var blinkSteps		= 0;
var blinkMaxSteps	= 8;
function animateOffertemandje() {
	if($("shoppingcartWrapper")) {
		$("shoppingcartWrapper").removeClassName("groen");
		blinkSteps			= 0;
		blinkIntervalID		= setInterval("blinkOfferteMandje()",250);
	}
}

function blinkOfferteMandje() {

	var status	= blinkSteps % 2;

	if(status == 0) {
		$("shoppingcartWrapper").addClassName("groen");
	} else {
		$("shoppingcartWrapper").removeClassName("groen");
	}

	blinkSteps++;
	if(blinkSteps > blinkMaxSteps) {
		clearInterval(blinkIntervalID);
		$("shoppingcartWrapper").removeClassName("groen");
		$("shoppingcartWrapper").addClassName("groen");
	}
}


OverlayDisplay = Class.create({
	initialize: function(){
		this.overlay = $('overlay');
		this.container = $('overlay_container');
	 	this.items = [];
	},
	
	display: function(id){
		var selects = document.getElementsByTagName('select');
		for (i = 0; i < selects.length; i++) {
			var sel = $(selects[i]);
			sel.addClassName('hide'); 
		}

		this.items.each(function(s){
			$(s).className = 'hide';
		});
		$(id).className = "show";
		this.overlay.className = 'show';
		this.container.className = 'show';
	},
	
	hide: function(){
		var selects = document.getElementsByTagName('select');
		for (i = 0; i < selects.length; i++) {
			var sel = $(selects[i]);
			sel.removeClassName('hide'); 
		}
		this.overlay.className = 'hide';
		this.container.className = 'hide';
	},
	
	addItem: function(id){
		if (this.items.indexOf(id) != -1){
			return;
		}
		var obj = $(id).cloneNode(true);
		this.container.appendChild(obj);
		this.items.push(id);
	},
	
	removeItem: function(id){
		var newarr = this.items.without(id);
		if (newarr.length == this.items.length){
			return;
		}
		// eigenlijk moet dat element heir ook nog removed worden
		this.items = newarr;
	}
});

/**
 * Caroussel is an array, which can be looped
 * You can call next and previous, and when you've reached the end, you'll start at the beginning again
 */
var Caroussel = Class.create({

	/**
	 * The items of the Caroussel
	 * @var array
	 */
	items: [],

	/**
	 * The active index of the caroussel
	 * @var int
	 */
	activeIndex: 0,

	initialize: function(){
		this.activeIndex = 0;
	}, 
	/**
	 * Add an item to the Caroussel. 
	 * Will do only unique vals
	 * @param string val
	 */
	addItem: function(val){
		if (this.items.indexOf(val) != -1){
			return;
		}
		this.items.push(val);	
	},
	
	/**
	 * Remove an item to the Caroussel. 
	 * @param string val
	 */
	removeItem: function(val){
		var newarr = this.items.without(index_id);
		if (newarr.length == this.items.length){
			return;
		}
		this.items = newarr;
	},
		
	/**
	 * Return the active item
	 */
	current: function(){
		return this.items[this.activeIndex];
	}, 
		
	/**
	 * Return the previous item
	 */
	previous: function(){
		if (this.activeIndex == 0){
			this.activeIndex = this.items.length;
		}
		this.activeIndex--;
		return this.items[this.activeIndex];
	},
			
	/**
	 * Return the next item
	 */
	next: function(){
		if (this.activeIndex ==  (this.items.length -1)){
			this.activeIndex = -1;
		}
		this.activeIndex++;
		return this.items[this.activeIndex];
	}
});