/****************************************************************/
/*  original filename prototype.js                        */
/****************************************************************/


/*  Prototype JavaScript framework, version 1.6.1_rc2
 *  (c) 2005-2009 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.1_rc2',

  Browser: {
    IE:     !!(window.attachEvent &&
      navigator.userAgent.indexOf('Opera') === -1),
    Opera:  navigator.userAgent.indexOf('Opera') > -1,
    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,
    SelectorsAPI: !!document.querySelector,
    ElementExtensions: (function() {
      if (window.HTMLElement && window.HTMLElement.prototype)
        return true;
      if (window.Element && window.Element.prototype)
        return true;
    })(),
    SpecificElementExtensions: (function() {
      if (typeof window.HTMLDivElement !== 'undefined')
        return true;

      var div = document.createElement('div');
      if (div['__proto__'] && div['__proto__'] !==
       document.createElement('form')['__proto__']) {
        return true;
      }

      return false;
    })()
  },

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

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

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


var Abstract = { };


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

/* Based on Alex Arnell's inheritance implementation. */

var Class = (function() {
  function create() {
    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;
  }

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

    if (!Object.keys({ toString: true }).length) {
      if (source.toString != Object.prototype.toString)
        properties.push("toString");
      if (source.valueOf != Object.prototype.valueOf)
        properties.push("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 = (function(m) {
          return function() { return ancestor[m].apply(this, arguments); };
        })(property).wrap(method);

        value.valueOf = method.valueOf.bind(method);
        value.toString = method.toString.bind(method);
      }
      this.prototype[property] = value;
    }

    return this;
  }

  return {
    create: create,
    Methods: {
      addMethods: addMethods
    }
  };
})();
(function() {

  function getClass(object) {
    return Object.prototype.toString.call(object)
     .match(/^\[object\s(.*)\]$/)[1];
  }

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

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

  function toJSON(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 (isElement(object)) return;

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

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

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

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

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

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

  function clone(object) {
    return extend({ }, object);
  }

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

  function isArray(object) {
    return getClass(object) === "Array";
  }


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

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

  function isString(object) {
    return getClass(object) === "String";
  }

  function isNumber(object) {
    return getClass(object) === "Number";
  }

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

  extend(Object, {
    extend:        extend,
    inspect:       inspect,
    toJSON:        toJSON,
    toQueryString: toQueryString,
    toHTML:        toHTML,
    keys:          keys,
    values:        values,
    clone:         clone,
    isElement:     isElement,
    isArray:       isArray,
    isHash:        isHash,
    isFunction:    isFunction,
    isString:      isString,
    isNumber:      isNumber,
    isUndefined:   isUndefined
  });
})();
Object.extend(Function.prototype, (function() {
  var slice = Array.prototype.slice;

  function update(array, args) {
    var arrayLength = array.length, length = args.length;
    while (length--) array[arrayLength + length] = args[length];
    return array;
  }

  function merge(array, args) {
    array = slice.call(array, 0);
    return update(array, args);
  }

  function argumentNames() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
      .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
      .replace(/\s+/g, '').split(',');
    return names.length == 1 && !names[0] ? [] : names;
  }

  function bind(context) {
    if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
    var __method = this, args = slice.call(arguments, 1);
    return function() {
      var a = merge(args, arguments);
      return __method.apply(context, a);
    }
  }

  function bindAsEventListener(context) {
    var __method = this, args = slice.call(arguments, 1);
    return function(event) {
      var a = update([event || window.event], args);
      return __method.apply(context, a);
    }
  }

  function curry() {
    if (!arguments.length) return this;
    var __method = this, args = slice.call(arguments, 0);
    return function() {
      var a = merge(args, arguments);
      return __method.apply(this, a);
    }
  }

  function delay(timeout) {
    var __method = this, args = slice.call(arguments, 1);
    timeout = timeout * 1000
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  }

  function defer() {
    var args = update([0.01], arguments);
    return this.delay.apply(this, args);
  }

  function wrap(wrapper) {
    var __method = this;
    return function() {
      var a = update([__method.bind(this)], arguments);
      return wrapper.apply(this, a);
    }
  }

  function methodize() {
    if (this._methodized) return this._methodized;
    var __method = this;
    return this._methodized = function() {
      var a = update([this], arguments);
      return __method.apply(null, a);
    };
  }

  return {
    argumentNames:       argumentNames,
    bind:                bind,
    bindAsEventListener: bindAsEventListener,
    curry:               curry,
    delay:               delay,
    defer:               defer,
    wrap:                wrap,
    methodize:           methodize
  }
})());


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"';
};


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();
      } catch(e) {
        /* empty catch for clients that don't support try/finally */
      }
      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, (function() {

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

  function gsub(pattern, replacement) {
    var result = '', source = this, match;
    replacement = prepareReplacement(replacement);

    if (Object.isString(pattern))
      pattern = RegExp.escape(pattern);

    if (!(pattern.length || pattern.source)) {
      replacement = replacement('');
      return replacement + source.split('').join(replacement) + 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;
  }

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

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

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

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

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

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

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

  function extractScripts() {
    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];
    });
  }

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

  function escapeHTML() {
    escapeHTML.text.data = this;
    return escapeHTML.div.innerHTML;
  }

  function unescapeHTML() {
    var div = document.createElement('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) : '';
  }

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

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

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

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

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

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

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

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

  function inspect(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, '\\\'') + "'";
  }

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

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

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

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

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

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

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

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

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

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

  return {
    gsub:           gsub,
    sub:            sub,
    scan:           scan,
    truncate:       truncate,
    strip:          strip,
    stripTags:      stripTags,
    stripScripts:   stripScripts,
    extractScripts: extractScripts,
    evalScripts:    evalScripts,
    escapeHTML:     escapeHTML,
    unescapeHTML:   unescapeHTML,
    toQueryParams:  toQueryParams,
    parseQuery:     toQueryParams,
    toArray:        toArray,
    succ:           succ,
    times:          times,
    camelize:       camelize,
    capitalize:     capitalize,
    underscore:     underscore,
    dasherize:      dasherize,
    inspect:        inspect,
    toJSON:         toJSON,
    unfilterJSON:   unfilterJSON,
    isJSON:         isJSON,
    evalJSON:       evalJSON,
    include:        include,
    startsWith:     startsWith,
    endsWith:       endsWith,
    empty:          empty,
    blank:          blank,
    interpolate:    interpolate
  };
})());

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

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

if ('<\n>'.escapeHTML() !== '&lt;\n&gt;') {
  String.prototype.escapeHTML = function() {
    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  }
}

if ('&lt;\n&gt;'.unescapeHTML() !== '<\n>') {
  String.prototype.unescapeHTML = function() {
    return this.stripTags().replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
  }
}
var Template = Class.create({
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern = pattern || Template.Pattern;
  },

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

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

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

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

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

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

var $break = { };

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

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

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

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

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

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

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

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

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

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

  function include(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;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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









  return {
    each:       each,
    eachSlice:  eachSlice,
    all:        all,
    every:      all,
    any:        any,
    some:       any,
    collect:    collect,
    map:        collect,
    detect:     detect,
    findAll:    findAll,
    select:     findAll,
    filter:     findAll,
    grep:       grep,
    include:    include,
    member:     include,
    inGroupsOf: inGroupsOf,
    inject:     inject,
    invoke:     invoke,
    max:        max,
    min:        min,
    partition:  partition,
    pluck:      pluck,
    reject:     reject,
    sortBy:     sortBy,
    toArray:    toArray,
    entries:    toArray,
    zip:        zip,
    size:       size,
    inspect:    inspect,
    find:       detect
  };
})();
function $A(iterable) {
  if (!iterable) return [];
  if ('toArray' in iterable) return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

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

Array.from = $A;


(function() {
  var arrayProto = Array.prototype,
      slice = arrayProto.slice,
      _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available

  function each(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  }
  if (!_each) _each = each;

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

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

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

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

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

  function without() {
    var values = slice.call(arguments, 0);
    return this.select(function(value) {
      return !values.include(value);
    });
  }

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

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

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


  function clone() {
    return slice.call(this, 0);
  }

  function size() {
    return this.length;
  }

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

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

  function indexOf(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;
  }

  function lastIndexOf(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;
  }

  function concat() {
    var array = slice.call(this, 0), item;
    for (var i = 0, length = arguments.length; i < length; i++) {
      item = arguments[i];
      if (Object.isArray(item) && !('callee' in item)) {
        for (var j = 0, arrayLength = item.length; j < arrayLength; j++)
          array.push(item[j]);
      } else {
        array.push(item);
      }
    }
    return array;
  }

  Object.extend(arrayProto, Enumerable);

  if (!arrayProto._reverse)
    arrayProto._reverse = arrayProto.reverse;

  Object.extend(arrayProto, {
    _each:     _each,
    clear:     clear,
    first:     first,
    last:      last,
    compact:   compact,
    flatten:   flatten,
    without:   without,
    reverse:   reverse,
    uniq:      uniq,
    intersect: intersect,
    clone:     clone,
    toArray:   clone,
    size:      size,
    inspect:   inspect,
    toJSON:    toJSON
  });

  var CONCAT_ARGUMENTS_BUGGY = (function() {
    return [].concat(arguments)[0][0] !== 1;
  })(1,2)

  if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat;

  if (!arrayProto.indexOf) arrayProto.indexOf = indexOf;
  if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf;
})();
function $H(object) {
  return new Hash(object);
};

var Hash = Class.create(Enumerable, (function() {
  function initialize(object) {
    this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
  }

  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 set(key, value) {
    return this._object[key] = value;
  }

  function get(key) {
    if (this._object[key] !== Object.prototype[key])
      return this._object[key];
  }

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

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

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

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

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

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

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

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

  function toQueryString() {
    return this.inject([], function(results, pair) {
      var key = encodeURIComponent(pair.key), values = pair.value;

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

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

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

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

  return {
    initialize:             initialize,
    _each:                  _each,
    set:                    set,
    get:                    get,
    unset:                  unset,
    toObject:               toObject,
    toTemplateReplacements: toObject,
    keys:                   keys,
    values:                 values,
    index:                  index,
    merge:                  merge,
    update:                 update,
    toQueryString:          toQueryString,
    inspect:                inspect,
    toJSON:                 toJSON,
    clone:                  clone
  };
})());

Hash.from = $H;
Object.extend(Number.prototype, (function() {
  function toColorPart() {
    return this.toPaddedString(2, 16);
  }

  function succ() {
    return this + 1;
  }

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

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

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

  function abs() {
    return Math.abs(this);
  }

  function round() {
    return Math.round(this);
  }

  function ceil() {
    return Math.ceil(this);
  }

  function floor() {
    return Math.floor(this);
  }

  return {
    toColorPart:    toColorPart,
    succ:           succ,
    times:          times,
    toPaddedString: toPaddedString,
    toJSON:         toJSON,
    abs:            abs,
    round:          round,
    ceil:           ceil,
    floor:          floor
  };
})());

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

var ObjectRange = Class.create(Enumerable, (function() {
  function initialize(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  }

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

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

  return {
    initialize: initialize,
    _each:      _each,
    include:    include
  };
})());



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

  activeRequestCount: 0
};

Ajax.Responders = {
  responders: [],

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

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

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

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

Object.extend(Ajax.Responders, Enumerable);

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

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

    if (Object.isString(this.options.parameters))
      this.options.parameters = this.options.parameters.toQueryParams();
    else if (Object.isHash(this.options.parameters))
      this.options.parameters = this.options.parameters.toObject();
  }
});
Ajax.Request = Class.create(Ajax.Base, {
  _complete: false,

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

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

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

    this.parameters = params;

    if (params = Object.toQueryString(params)) {
      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';
    }

    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

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

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

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

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

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

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

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

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

    if (state == 'Complete') {
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

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

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

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

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

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








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

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

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

  status:      0,

  statusText: '',

  getStatus: Ajax.Request.prototype.getStatus,

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

  getHeader: Ajax.Request.prototype.getHeader,

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

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

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

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

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

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

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

    $super(url, options);
  },

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

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

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

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

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

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

    this.start();
  },

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

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

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

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

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});



function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

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

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

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

if (!Node.ELEMENT_NODE) {
  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(global) {

  var SETATTRIBUTE_IGNORES_NAME = (function(){
    var elForm = document.createElement("form");
    var elInput = document.createElement("input");
    var root = document.documentElement;
    elInput.setAttribute("name", "test");
    elForm.appendChild(elInput);
    root.appendChild(elForm);
    var isBuggy = elForm.elements
      ? (typeof elForm.elements.test == "undefined")
      : null;
    root.removeChild(elForm);
    elForm = elInput = null;
    return isBuggy;
  })();

  var element = global.Element;
  global.Element = function(tagName, attributes) {
    attributes = attributes || { };
    tagName = tagName.toLowerCase();
    var cache = Element.cache;
    if (SETATTRIBUTE_IGNORES_NAME && 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(global.Element, element || { });
  if (element) global.Element.prototype = element.prototype;
})(this);

Element.cache = { };
Element.idCounter = 1;

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 = $(element);
    element.style.display = 'none';
    return element;
  },

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

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

  update: (function(){

    var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){
      var el = document.createElement("select"),
          isBuggy = true;
      el.innerHTML = "<option value=\"test\">test</option>";
      if (el.options && el.options[0]) {
        isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION";
      }
      el = null;
      return isBuggy;
    })();

    var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){
      try {
        var el = document.createElement("table");
        if (el && el.tBodies) {
          el.innerHTML = "<tbody><tr><td>test</td></tr></tbody>";
          var isBuggy = typeof el.tBodies[0] == "undefined";
          el = null;
          return isBuggy;
        }
      } catch (e) {
        return true;
      }
    })();

    var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () {
      var s = document.createElement("script"),
          isBuggy = false;
      try {
        s.appendChild(document.createTextNode(""));
        isBuggy = !s.firstChild ||
          s.firstChild && s.firstChild.nodeType !== 3;
      } catch (e) {
        isBuggy = true;
      }
      s = null;
      return isBuggy;
    })();

    function update(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 === 'SCRIPT' && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) {
        element.text = content;
        return element;
      }

      if (SELECT_ELEMENT_INNERHTML_BUGGY || TABLE_ELEMENT_INNERHTML_BUGGY) {
        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();
        }
      }
      else {
        element.innerHTML = content.stripScripts();
      }

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

    return update;
  })(),

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

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

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

    var content, insert, tagName, childNodes;

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

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

      content = Object.toHTML(content);

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

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

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

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

    return element;
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

  readAttribute: (function(){

    var iframeGetAttributeThrowsError = (function(){
      var el = document.createElement('iframe'),
          isBuggy = false;

      el.setAttribute('src', '/blank.html');
      document.documentElement.appendChild(el);
      try {
        el.getAttribute('type', 2);
      } catch(e) {
        isBuggy = true;
      }
      document.documentElement.removeChild(el);
      el = null;
      return isBuggy;
    })();

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

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

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

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

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

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

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

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

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

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

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

  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 (ancestor.contains)
      return ancestor.contains(element) && ancestor !== element;

    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 || value == 'auto') {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    }
    if (style == 'opacity') return value ? parseFloat(value) : 1.0;
    return value == 'auto' ? null : value;
  },

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

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

    return element;
  },

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

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

    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    if (originalPosition != 'fixed') // Switching fixed to absolute causes issues in Safari
      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';
      if (Prototype.Browser.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.toUpperCase() == 'BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p !== 'static') break;
      }
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

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

    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 element;

    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;

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

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == '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] || { });

    source = $(source);
    var p = source.viewportOffset();

    element = $(element);
    var delta = [0, 0];
    var parent = null;
    if (Element.getStyle(element, 'position') == 'absolute') {
      parent = element.getOffsetParent();
      delta = parent.viewportOffset();
    }

    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

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

Object.extend(Element.Methods, {
  getElementsBySelector: Element.Methods.select,

  childElements: Element.Methods.immediateDescendants
});

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

if (Prototype.Browser.Opera) {
  Element.Methods.getStyle = Element.Methods.getStyle.wrap(
    function(proceed, element, style) {
      switch (style) {
        case 'left': case 'top': case 'right': case 'bottom':
          if (proceed(element, 'position') === 'static') return null;
        case 'height': case 'width':
          if (!Element.visible(element)) return null;

          var dim = parseInt(proceed(element, style), 10);

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

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

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

else if (Prototype.Browser.IE) {
  Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
    function(proceed, element) {
      element = $(element);
      try { element.offsetParent }
      catch(e) { return $(document.body) }
      var position = element.getStyle('position');
      if (position !== 'static') return proceed(element);
      element.setStyle({ position: 'relative' });
      var value = proceed(element);
      element.setStyle({ position: position });
      return value;
    }
  );

  $w('positionedOffset viewportOffset').each(function(method) {
    Element.Methods[method] = Element.Methods[method].wrap(
      function(proceed, element) {
        element = $(element);
        try { element.offsetParent }
        catch(e) { return Element._returnOffset(0,0) }
        var position = element.getStyle('position');
        if (position !== 'static') return proceed(element);
        var offsetParent = element.getOffsetParent();
        if (offsetParent && offsetParent.getStyle('position') === 'fixed')
          offsetParent.setStyle({ zoom: 1 });
        element.setStyle({ position: 'relative' });
        var value = proceed(element);
        element.setStyle({ position: position });
        return value;
      }
    );
  });

  Element.Methods.cumulativeOffset = Element.Methods.cumulativeOffset.wrap(
    function(proceed, element) {
      try { element.offsetParent }
      catch(e) { return Element._returnOffset(0,0) }
      return proceed(element);
    }
  );

  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 = (function(){

    var classProp = 'className';
    var forProp = 'for';

    var el = document.createElement('div');

    el.setAttribute(classProp, 'x');

    if (el.className !== 'x') {
      el.setAttribute('class', 'x');
      if (el.className === 'x') {
        classProp = 'class';
      }
    }
    el = null;

    el = document.createElement('label');
    el.setAttribute(forProp, 'x');
    if (el.htmlFor !== 'x') {
      el.setAttribute('htmlFor', 'x');
      if (el.htmlFor === 'x') {
        forProp = 'htmlFor';
      }
    }
    el = null;

    return {
      read: {
        names: {
          'class':      classProp,
          'className':  classProp,
          'for':        forProp,
          'htmlFor':    forProp
        },
        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(){

            var el = document.createElement('div');
            el.onclick = Prototype.emptyFunction;
            var value = el.getAttribute('onclick');
            var f;

            if (String(value).indexOf('{') > -1) {
              f = function(element, attribute) {
                attribute = element.getAttribute(attribute);
                if (!attribute) return null;
                attribute = attribute.toString();
                attribute = attribute.split('{')[1];
                attribute = attribute.split('}')[0];
                return attribute.strip();
              }
            }
            else if (value === '') {
              f = function(element, attribute) {
                attribute = element.getAttribute(attribute);
                if (!attribute) return null;
                return attribute.strip();
              }
            }
            el = null;
            return f;
          })(),
          _flag: function(element, attribute) {
            return $(element).hasAttribute(attribute) ? attribute : null;
          },
          style: function(element) {
            return element.style.cssText.toLowerCase();
          },
          title: function(element) {
            return element.title;
          }
        }
      }
    }
  })();

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

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

  Element._attributeTranslations.has = {};

  $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
      'encType maxLength readOnly longDesc frameBorder').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);

  if (Prototype.BrowserFeatures.ElementExtensions) {
    (function() {
      function _descendants(element) {
        var nodes = element.getElementsByTagName('*'), results = [];
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.tagName !== "!") // Filter out comment nodes.
            results.push(node);
        return results;
      }

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

}

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.toUpperCase() == 'IMG' && element.width) {
        element.width++; element.width--;
      } else try {
        var n = document.createTextNode(' ');
        element.appendChild(n);
        element.removeChild(n);
      } catch (e) { }

    return element;
  };

  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 ('outerHTML' in document.documentElement) {
  Element.Methods.replace = function(element, content) {
    element = $(element);

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

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

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

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

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

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

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

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

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

Element.Methods.ByTag = { };

Object.extend(Element, Element.Methods);

(function(div) {

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

  div = null;

})(document.createElement('div'))

Element.extend = (function() {

  function checkDeficiency(tagName) {
    if (typeof window.Element != 'undefined') {
      var proto = window.Element.prototype;
      if (proto) {
        var id = '_' + (Math.random()+'').slice(2);
        var el = document.createElement(tagName);
        proto[id] = 'x';
        var isBuggy = (el[id] !== 'x');
        delete proto[id];
        el = null;
        return isBuggy;
      }
    }
    return false;
  }

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

  var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = checkDeficiency('object');
  var HTMLAPPLETELEMENT_PROTOTYPE_BUGGY = checkDeficiency('applet');

  if (Prototype.BrowserFeatures.SpecificElementExtensions) {
    if (HTMLOBJECTELEMENT_PROTOTYPE_BUGGY &&
        HTMLAPPLETELEMENT_PROTOTYPE_BUGGY) {
      return function(element) {
        if (element && element.tagName) {
          var tagName = element.tagName.toUpperCase();
          if (tagName === 'OBJECT' || tagName === 'APPLET') {
            extendElementWith(element, Element.Methods);
            if (tagName === 'OBJECT') {
              extendElementWith(element, Element.Methods.ByTag.OBJECT)
            }
            else if (tagName === 'APPLET') {
              extendElementWith(element, Element.Methods.ByTag.APPLET)
            }
          }
        }
        return element;
      }
    }
    return Prototype.K;
  }

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

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

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

    if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);

    extendElementWith(element, methods);

    element._extendedByPrototype = Prototype.emptyFunction;
    return element;

  }, {
    refresh: function() {
      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];

    var element = document.createElement(tagName);
    var proto = element['__proto__'] || element.constructor.prototype;
    element = null;
    return proto;
  }

  var elementPrototype = window.HTMLElement ? HTMLElement.prototype :
   Element.prototype;

  if (F.ElementExtensions) {
    copy(Element.Methods, elementPrototype);
    copy(Element.Methods.Simulated, elementPrototype, 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() {
    return { width: this.getWidth(), height: this.getHeight() };
  },

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

(function(viewport) {
  var B = Prototype.Browser, doc = document, element, property = {};

  function getRootElement() {
    if (B.WebKit && !doc.evaluate)
      return document;

    if (B.Opera && window.parseFloat(window.opera.version()) < 9.5)
      return document.body;

    return document.documentElement;
  }

  function define(D) {
    if (!element) element = getRootElement();

    property[D] = 'client' + D;

    viewport['get' + D] = function() { return element[property[D]] };
    return viewport['get' + D]();
  }

  viewport.getWidth  = define.curry('Width');

  viewport.getHeight = define.curry('Height');
})(document.viewport);


Element.Storage = {
  UID: 1
};

Element.addMethods({
  getStorage: function(element) {
    if (!(element = $(element))) return;

    var uid;
    if (element === window) {
      uid = 0;
    } else {
      if (typeof element._prototypeUID === "undefined")
        element._prototypeUID = [Element.Storage.UID++];
      uid = element._prototypeUID[0];
    }

    if (!Element.Storage[uid])
      Element.Storage[uid] = $H();

    return Element.Storage[uid];
  },

  store: function(element, key, value) {
    if (!(element = $(element))) return;

    if (arguments.length === 2) {
      element.getStorage().update(key);
    } else {
      element.getStorage().set(key, value);
    }

    return element;
  },

  retrieve: function(element, key, defaultValue) {
    if (!(element = $(element))) return;
    var hash = Element.getStorage(element), value = hash.get(key);

    if (Object.isUndefined(value)) {
      hash.set(key, defaultValue);
      value = defaultValue;
    }

    return value;
  },

  clone: function(element, deep) {
    if (!(element = $(element))) return;
    var clone = element.cloneNode(deep);
    clone._prototypeUID = void 0;
    if (deep) {
      var descendants = Element.select(clone, '*'),
          i = descendants.length;
      while (i--) {
        descendants[i]._prototypeUID = void 0;
      }
    }
    return Element.extend(clone);
  }
});
/* 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();

    if (this.shouldUseSelectorsAPI()) {
      this.mode = 'selectorsAPI';
    } else if (this.shouldUseXPath()) {
      this.mode = 'xpath';
      this.compileXPathMatcher();
    } else {
      this.mode = "normal";
      this.compileMatcher();
    }

  },

  shouldUseXPath: (function() {

    var IS_DESCENDANT_SELECTOR_BUGGY = (function(){
      var isBuggy = false;
      if (document.evaluate && window.XPathResult) {
        var el = document.createElement('div');
        el.innerHTML = '<ul><li></li></ul><div><ul><li></li></ul></div>';

        var xpath = ".//*[local-name()='ul' or local-name()='UL']" +
          "//*[local-name()='li' or local-name()='LI']";

        var result = document.evaluate(xpath, el, null,
          XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

        isBuggy = (result.snapshotLength !== 2);
        el = null;
      }
      return isBuggy;
    })();

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

      var e = this.expression;

      if (Prototype.Browser.WebKit &&
       (e.include("-of-type") || e.include(":empty")))
        return false;

      if ((/(\[[\w-]*?:|:checked)/).test(e))
        return false;

      if (IS_DESCENDANT_SELECTOR_BUGGY) return false;

      return true;
    }

  })(),

  shouldUseSelectorsAPI: function() {
    if (!Prototype.BrowserFeatures.SelectorsAPI) return false;

    if (Selector.CASE_INSENSITIVE_CLASS_NAMES) return false;

    if (!Selector._div) Selector._div = new Element('div');

    try {
      Selector._div.querySelector(this.expression);
    } catch(e) {
      return false;
    }

    return true;
  },

  compileMatcher: function() {
    var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
        c = Selector.criteria, le, p, m, len = ps.length, name;

    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 = 0; i<len; i++) {
        p = ps[i].re;
        name = ps[i].name;
        if (m = e.match(p)) {
          this.matcher.push(Object.isFunction(c[name]) ? c[name](m) :
            new Template(c[name]).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, len = ps.length, name;

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

    this.matcher = ['.//*'];
    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i = 0; i<len; i++) {
        name = ps[i].name;
        if (m = e.match(ps[i].re)) {
          this.matcher.push(Object.isFunction(x[name]) ? x[name](m) :
            new Template(x[name]).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;
    var e = this.expression, results;

    switch (this.mode) {
      case 'selectorsAPI':
        if (root !== document) {
          var oldId = root.id, id = $(root).identify();
          id = id.replace(/[\.:]/g, "\\$0");
          e = "#" + id + " " + e;
        }

        results = $A(root.querySelectorAll(e)).map(Element.extend);
        root.id = oldId;

        return results;
      case 'xpath':
        return document._getElementsByXPath(this.xpath, root);
      default:
       return this.matcher(root);
    }
  },

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

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

    while (e && le !== e && (/\S/).test(e)) {
      le = e;
      for (var i = 0; i<len; i++) {
        p = ps[i].re;
        name = ps[i].name;
        if (m = e.match(p)) {
          if (as[name]) {
            this.tokens.push([name, Object.clone(m)]);
            e = e.replace(m[0], '');
          } else {
            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() + ">";
  }
});

if (Prototype.BrowserFeatures.SelectorsAPI &&
 document.compatMode === 'BackCompat') {
  Selector.CASE_INSENSITIVE_CLASS_NAMES = (function(){
    var div = document.createElement('div'),
     span = document.createElement('span');

    div.id = "prototype_test_id";
    span.className = 'Test';
    div.appendChild(span);
    var isIgnored = (div.querySelector('#prototype_test_id .test') !== null);
    div = span = null;
    return isIgnored;
  })();
}

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

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

        var exclusion = [];
        while (e && le != e && (/\S/).test(e)) {
          le = e;
          for (var i = 0; i<len; i++) {
            name = p[i].name
            if (m = e.match(p[i].re)) {
              v = Object.isFunction(x[name]) ? x[name](m) : new Template(x[name]).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); c = false;',
    attr: function(m) {
      m[3] = (m[5] || m[6]);
      return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); 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: [
    { name: 'laterSibling', re: /^\s*~\s*/ },
    { name: 'child',        re: /^\s*>\s*/ },
    { name: 'adjacent',     re: /^\s*\+\s*/ },
    { name: 'descendant',   re: /^\s/ },

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

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

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

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

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

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

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

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

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

    index: function(parentNode, reverse, ofType) {
      parentNode._countedByPrototype = Prototype.emptyFunction;
      if (reverse) {
        for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
          var node = nodes[i];
          if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
        }
      } else {
        for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
          if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
      }
    },

    unique: function(nodes) {
      if (nodes.length == 0) return nodes;
      var results = [], n;
      for (var i = 0, l = nodes.length; i < l; i++)
        if (typeof (n = nodes[i])._countedByPrototype == 'undefined') {
          n._countedByPrototype = Prototype.emptyFunction;
          results.push(Element.extend(n));
        }
      return Selector.handlers.unmark(results);
    },

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

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

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

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

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

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

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

    id: function(nodes, root, id, combinator) {
      var targetNode = $(id), h = Selector.handlers;

      if (root == document) {
        if (!targetNode) return [];
        if (!nodes) return [targetNode];
      } else {
        if (!root.sourceIndex || root.sourceIndex < 1) {
          var nodes = root.getElementsByTagName('*');
          for (var j = 0, node; node = nodes[j]; j++) {
            if (node.id === id) return [node];
          }
        }
      }

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

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

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

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

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

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

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

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

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

    'empty': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (node.tagName == '!' || node.firstChild) continue;
        results.push(node);
      }
      return results;
    },

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

    'enabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node.disabled && (!node.type || node.type !== 'hidden'))
          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 == v || nv && nv.startsWith(v); },
    '$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); },
    '*=': function(nv, v) { return nv == v || nv && nv.include(v); },
    '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
    '|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() +
     '-').include('-' + (v || "").toUpperCase() + '-'); }
  },

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

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

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

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

if (Prototype.Browser.IE) {
  Object.extend(Selector.handlers, {
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        if (node.tagName !== "!") a.push(node);
      return a;
    },

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

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}

var Form = {
  reset: function(form) {
    form = $(form);
    form.reset();
    return form;
  },

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

    var data = elements.inject({ }, function(result, element) {
      if (!element.disabled && element.name) {
        key = element.name; value = $(element).getValue();
        if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted &&
            submit !== false && (!submit || key == submit) && (submitted = true)))) {
          if (key in result) {
            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) {
    var elements = $(form).getElementsByTagName('*'),
        element,
        arr = [ ],
        serializers = Form.Element.Serializers;
    for (var i = 0; element = elements[i]; i++) {
      arr.push(element);
    }
    return arr.inject([], function(elements, child) {
      if (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.disabled = true;
    return element;
  },

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

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

var Field = Form.Element;

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

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

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

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

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

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

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

  var 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: {}
  };

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

  function isLeftClick(event)   { return _isButton(event, 0) }

  function isMiddleClick(event) { return _isButton(event, 1) }

  function isRightClick(event)  { return _isButton(event, 2) }

  function element(event) {
    event = Event.extend(event);

    var node = event.target, type = event.type,
     currentTarget = event.currentTarget;

    if (currentTarget && currentTarget.tagName) {
      if (type === 'load' || type === 'error' ||
        (type === 'click' && currentTarget.tagName.toLowerCase() === 'input'
          && currentTarget.type === 'radio'))
            node = currentTarget;
    }

    if (node.nodeType == Node.TEXT_NODE)
      node = node.parentNode;

    return Element.extend(node);
  }

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

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

  function pointerX(event) {
    var docElement = document.documentElement,
     body = document.body || { scrollLeft: 0 };

    return event.pageX || (event.clientX +
      (docElement.scrollLeft || body.scrollLeft) -
      (docElement.clientLeft || 0));
  }

  function pointerY(event) {
    var docElement = document.documentElement,
     body = document.body || { scrollTop: 0 };

    return  event.pageY || (event.clientY +
       (docElement.scrollTop || body.scrollTop) -
       (docElement.clientTop || 0));
  }


  function stop(event) {
    Event.extend(event);
    event.preventDefault();
    event.stopPropagation();

    event.stopped = true;
  }

  Event.Methods = {
    isLeftClick: isLeftClick,
    isMiddleClick: isMiddleClick,
    isRightClick: isRightClick,

    element: element,
    findElement: findElement,

    pointer: pointer,
    pointerX: pointerX,
    pointerY: pointerY,

    stop: stop
  };


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

  if (Prototype.Browser.IE) {
    function _relatedTarget(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);
    }

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

    Event.extend = function(event, element) {
      if (!event) return false;
      if (event._extendedByPrototype) return event;

      event._extendedByPrototype = Prototype.emptyFunction;
      var pointer = Event.pointer(event);

      Object.extend(event, {
        target: event.srcElement || element,
        relatedTarget: _relatedTarget(event),
        pageX:  pointer.x,
        pageY:  pointer.y
      });

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

  function _createResponder(element, eventName, handler) {
    var registry = Element.retrieve(element, 'prototype_event_registry');

    if (Object.isUndefined(registry)) {
      CACHE.push(element);
      registry = Element.retrieve(element, 'prototype_event_registry', $H());
    }

    var respondersForEvent = registry.get(eventName);
    if (Object.isUndefined()) {
      respondersForEvent = [];
      registry.set(eventName, respondersForEvent);
    }

    if (respondersForEvent.pluck('handler').include(handler)) return false;

    var responder;
    if (eventName.include(":")) {
      responder = function(event) {
        if (Object.isUndefined(event.eventName))
          return false;

        if (event.eventName !== eventName)
          return false;

        Event.extend(event, element);
        handler.call(element, event);
      };
    } else {
      if (!Prototype.Browser.IE &&
       (eventName === "mouseenter" || eventName === "mouseleave")) {
        if (eventName === "mouseenter" || eventName === "mouseleave") {
          responder = function(event) {
            Event.extend(event, element);

            var parent = event.relatedTarget;
            while (parent && parent !== element) {
              try { parent = parent.parentNode; }
              catch(e) { parent = element; }
            }

            if (parent === element) return;

            handler.call(element, event);
          };
        }
      } else {
        responder = function(event) {
          Event.extend(event, element);
          handler.call(element, event);
        };
      }
    }

    responder.handler = handler;
    respondersForEvent.push(responder);
    return responder;
  }

  function _destroyCache() {
    for (var i = 0, length = CACHE.length; i < length; i++) {
      Event.stopObserving(CACHE[i]);
      CACHE[i] = null;
    }
  }

  var CACHE = [];

  if (Prototype.Browser.IE)
    window.attachEvent('onunload', _destroyCache);

  if (Prototype.Browser.WebKit)
    window.addEventListener('unload', Prototype.emptyFunction, false);


  var _getDOMEventName = Prototype.K;

  if (!Prototype.Browser.IE) {
    _getDOMEventName = function(eventName) {
      var translations = { mouseenter: "mouseover", mouseleave: "mouseout" };
      return eventName in translations ? translations[eventName] : eventName;
    };
  }

  function observe(element, eventName, handler) {
    element = $(element);

    var responder = _createResponder(element, eventName, handler);

    if (!responder) return element;

    if (eventName.include(':')) {
      if (element.addEventListener)
        element.addEventListener("dataavailable", responder, false);
      else {
        element.attachEvent("ondataavailable", responder);
        element.attachEvent("onfilterchange", responder);
      }
    } else {
      var actualEventName = _getDOMEventName(eventName);

      if (element.addEventListener)
        element.addEventListener(actualEventName, responder, false);
      else
        element.attachEvent("on" + actualEventName, responder);
    }

    return element;
  }

  function stopObserving(element, eventName, handler) {
    element = $(element);

    var registry = Element.retrieve(element, 'prototype_event_registry');

    if (Object.isUndefined(registry)) return element;

    if (eventName && !handler) {
      var responders = registry.get(eventName);

      if (Object.isUndefined(responders)) return element;

      responders.each( function(r) {
        Element.stopObserving(element, eventName, r.handler);
      });
      return element;
    } else if (!eventName) {
      registry.each( function(pair) {
        var eventName = pair.key, responders = pair.value;

        responders.each( function(r) {
          Element.stopObserving(element, eventName, r.handler);
        });
      });
      return element;
    }

    var responders = registry.get(eventName);

    if (!responders) return;

    var responder = responders.find( function(r) { return r.handler === handler; });
    if (!responder) return element;

    var actualEventName = _getDOMEventName(eventName);

    if (eventName.include(':')) {
      if (element.removeEventListener)
        element.removeEventListener("dataavailable", responder, false);
      else {
        element.detachEvent("ondataavailable", responder);
        element.detachEvent("onfilterchange",  responder);
      }
    } else {
      if (element.removeEventListener)
        element.removeEventListener(actualEventName, responder, false);
      else
        element.detachEvent('on' + actualEventName, responder);
    }

    registry.set(eventName, responders.without(responder));

    return element;
  }

  function fire(element, eventName, memo, bubble) {
    element = $(element);

    if (Object.isUndefined(bubble))
      bubble = true;

    if (element == document && document.createEvent && !element.dispatchEvent)
      element = document.documentElement;

    var event;
    if (document.createEvent) {
      event = document.createEvent('HTMLEvents');
      event.initEvent('dataavailable', true, true);
    } else {
      event = document.createEventObject();
      event.eventType = bubble ? 'ondataavailable' : 'onfilterchange';
    }

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

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

    return Event.extend(event);
  }


  Object.extend(Event, Event.Methods);

  Object.extend(Event, {
    fire:          fire,
    observe:       observe,
    stopObserving: stopObserving
  });

  Element.addMethods({
    fire:          fire,

    observe:       observe,

    stopObserving: stopObserving
  });

  Object.extend(document, {
    fire:          fire.methodize(),

    observe:       observe.methodize(),

    stopObserving: stopObserving.methodize(),

    loaded:        false
  });

  if (window.Event) Object.extend(window.Event, Event);
  else window.Event = Event;
})();

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

  var timer;

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

  function checkReadyState() {
    if (document.readyState === 'complete') {
      document.stopObserving('readystatechange', checkReadyState);
      fireContentLoadedEvent();
    }
  }

  function pollDoScroll() {
    try { document.documentElement.doScroll('left'); }
    catch(e) {
      timer = pollDoScroll.defer();
      return;
    }
    fireContentLoadedEvent();
  }

  if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false);
  } else {
    document.observe('readystatechange', checkReadyState);
    if (window == top)
      timer = pollDoScroll.defer();
  }

  Event.observe(window, 'load', fireContentLoadedEvent);
})();

Element.addMethods();

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

var Position = {
  includeScrollOffsets: false,

  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

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

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


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

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

/****************************************************************/
/*  original filename prototype_csfr_fix.js                        */
/****************************************************************/


// zsombor: add authenticity_token to *all* ajax requests, along with Prototype request headers
Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
  function(original, options){
    if(window._token){
      if(Object.isString(options.parameters)){
        options.parameters = options.parameters.toQueryParams();
      } else {
        options.parameters = options.parameters || {};
      }
      Object.extend(options.parameters, {
		      authenticity_token: window._token,
		      x_requested_with: 'XMLHttpRequest'
		    });
    }
    return original(options);
  });
/****************************************************************/
/*  original filename prototype_ajax_failure_fix.js                        */
/****************************************************************/


// AJAX failure notification (e.g. when internet connection is lost).
//
function start_ajax_timeout_sleeper(ajax_object, retry_function){
  ajax_object.retry_function = retry_function;
  (function(){
    if ( (0 == this.getStatus() || 12029 == this.getStatus()) && (null == this.getHeader('Server')) ) {
      new ModalDialog("Sorry, but we're having trouble connecting to Harvest. This problem is usually the result of a broken Internet connection. You can <a id=\"retry_request\" href=\"#\">retry the last request</a> or try <a id=\"refresh_page\" href=\"#\">refreshing this page</a>.");
      $('retry_request').observe('click', (function(){
        this.retry_function();
        ModalDialog.stop();
        return false;
      }).bind(this));
      $('refresh_page').observe('click', (function(){
        window.location.reload(true);
        return false;
      }).bind(this));
    }
  }).bind(ajax_object).delay(window._ajaxTimeOut || 10);
}

// These two classes come from Ajax.Base
//

Ajax.Request.prototype.initialize = Ajax.Request.prototype.initialize.wrap( function(original, url, options){
  start_ajax_timeout_sleeper( this, (function(){
      new Ajax.Request( this.url, this.options );
    }).bind(this)
  );
  original(url, options);
});

Ajax.PeriodicalUpdater.prototype.initialize = Ajax.PeriodicalUpdater.prototype.initialize.wrap( function(original, container, url, options){
  start_ajax_timeout_sleeper( this, (function(){
      new Ajax.PeriodicalUpdater( this.container, this.url, this.options );
    }).bind(this)
  );
  original(container, url, options);
});

/****************************************************************/
/*  original filename effects.js                        */
/****************************************************************/


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

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

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

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

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

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

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

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

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

var Effect = {
  _elementDoesNotExistError: {
    name: 'ElementDoesNotExistError',
    message: 'The specified DOM element does not exist, but is required for this effect to operate'
  },
  Transitions: {
    linear: Prototype.K,
    sinoidal: function(pos) {
      return (-Math.cos(pos*Math.PI)/2) + .5;
    },
    reverse: function(pos) {
      return 1-pos;
    },
    flicker: function(pos) {
      var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
      return pos > 1 ? 1 : pos;
    },
    wobble: function(pos) {
      return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
    },
    pulse: function(pos, pulses) {
      return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
    },
    spring: function(pos) {
      return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
    },
    none: function(pos) {
      return 0;
    },
    full: function(pos) {
      return 1;
    }
  },
  DefaultOptions: {
    duration:   1.0,   // seconds
    fps:        100,   // 100= assume 66fps max.
    sync:       false, // true for combining
    from:       0.0,
    to:         1.0,
    delay:      0.0,
    queue:      'parallel'
  },
  tagifyText: function(element) {
    var tagifyStyle = 'position:relative';
    if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';

    element = $(element);
    $A(element.childNodes).each( function(child) {
      if (child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            new Element('span', {style: tagifyStyle}).update(
              character == ' ' ? String.fromCharCode(160) : character),
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if (((typeof element == 'object') ||
        Object.isFunction(element)) &&
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;

    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || { });
    var masterDelay = options.delay;

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

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

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

Effect.ScopedQueue = Class.create(Enumerable, {
  initialize: function() {
    this.effects  = [];
    this.interval = null;
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();

    var position = Object.isString(effect.options.queue) ?
      effect.options.queue : effect.options.queue.position;

    switch(position) {
      case 'front':
        // move unstarted effects after this effect
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'with-last':
        timestamp = this.effects.pluck('startOn').max() || timestamp;
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }

    effect.startOn  += timestamp;
    effect.finishOn += timestamp;

    if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);

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

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if (!Object.isString(queueName)) return queueName;

    return this.instances.get(queueName) ||
      this.instances.set(queueName, new Effect.ScopedQueue());
  }
};
Effect.Queue = Effect.Queues.get('global');

Effect.Base = Class.create({
  position: null,
  start: function(options) {
    function codeForEvent(options,eventName){
      return (
        (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
        (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
      );
    }
    if (options && options.transition === false) options.transition = Effect.Transitions.linear;
    this.options      = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn+(this.options.duration*1000);
    this.fromToDelta  = this.options.to-this.options.from;
    this.totalTime    = this.finishOn-this.startOn;
    this.totalFrames  = this.options.fps*this.options.duration;

    this.render = (function() {
      function dispatch(effect, eventName) {
        if (effect.options[eventName + 'Internal'])
          effect.options[eventName + 'Internal'](effect);
        if (effect.options[eventName])
          effect.options[eventName](effect);
      }

      return function(pos) {
        if (this.state === "idle") {
          this.state = "running";
          dispatch(this, 'beforeSetup');
          if (this.setup) this.setup();
          dispatch(this, 'afterSetup');
        }
        if (this.state === "running") {
          pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
          this.position = pos;
          dispatch(this, 'beforeUpdate');
          if (this.update) this.update(pos);
          dispatch(this, 'afterUpdate');
        }
      };
    })();

    this.event('beforeStart');
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ?
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if (timePos >= this.startOn) {
      if (timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if (this.finish) this.finish();
        this.event('afterFinish');
        return;
      }
      var pos   = (timePos - this.startOn) / this.totalTime,
          frame = (pos * this.totalFrames).round();
      if (frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  cancel: function() {
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ?
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if (this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    var data = $H();
    for(property in this)
      if (!Object.isFunction(this[property])) data.set(property, this[property]);
    return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
});

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

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

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

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

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

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

Effect.Scale = Class.create(Effect.Base, {
  initialize: function(element, percent) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or { } with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || { });
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = this.element.getStyle('position');

    this.originalStyle = { };
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));

    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;

    var fontSize = this.element.getStyle('font-size') || '100%';
    ['em','px','%','pt'].each( function(fontSizeType) {
      if (fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));

    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;

    this.dims = null;
    if (this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if (/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if (!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if (this.options.scaleContent && this.fontSize)
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = { };
    if (this.options.scaleX) d.width = width.round() + 'px';
    if (this.options.scaleY) d.height = height.round() + 'px';
    if (this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if (this.elementPositioning == 'absolute') {
        if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if (this.options.scaleY) d.top = -topd + 'px';
        if (this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    this.element.setStyle(d);
  }
});

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

Effect.ScrollTo = function(element) {
  var options = arguments[1] || { },
  scrollOffsets = document.viewport.getScrollOffsets(),
  elementOffsets = $(element).cumulativeOffset();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  var dims = element.getDimensions();
  var initialMoveX, initialMoveY;
  var moveX, moveY;

  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0;
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }

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

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

  var dims = element.getDimensions();
  var moveX, moveY;

  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }

  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned().makeClipping();
         },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
       }, options)
  );
};

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || { },
    oldOpacity = element.getInlineOpacity(),
    transition = options.transition || Effect.Transitions.linear,
    reverser   = function(pos){
      return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
    };

  return new Effect.Opacity(element,
    Object.extend(Object.extend({  duration: 2.0, from: 0,
      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
    }, options), {transition: reverser}));
};

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

Effect.Morph = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      style: { }
    }, arguments[1] || { });

    if (!Object.isString(options.style)) this.style = $H(options.style);
    else {
      if (options.style.include(':'))
        this.style = options.style.parseStyle();
      else {
        this.element.addClassName(options.style);
        this.style = $H(this.element.getStyles());
        this.element.removeClassName(options.style);
        var css = this.element.getStyles();
        this.style = this.style.reject(function(style) {
          return style.value == css[style.key];
        });
        options.afterFinishInternal = function(effect) {
          effect.element.addClassName(effect.options.style);
          effect.transforms.each(function(transform) {
            effect.element.style[transform.style] = '';
          });
        };
      }
    }
    this.start(options);
  },

  setup: function(){
    function parseColor(color){
      if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
      color = color.parseColor();
      return $R(0,2).map(function(i){
        return parseInt( color.slice(i*2+1,i*2+3), 16 );
      });
    }
    this.transforms = this.style.map(function(pair){
      var property = pair[0], value = pair[1], unit = null;

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

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

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

Element.CSS_PROPERTIES = $w(
  'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
  'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
  'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
  'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
  'fontSize fontWeight height left letterSpacing lineHeight ' +
  'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
  'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
  'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
  'right textIndent top width wordSpacing zIndex');

Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;

String.__parseStyleElement = document.createElement('div');
String.prototype.parseStyle = function(){
  var style, styleRules = $H();
  if (Prototype.Browser.WebKit)
    style = new Element('div',{style:this}).style;
  else {
    String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
    style = String.__parseStyleElement.childNodes[0].style;
  }

  Element.CSS_PROPERTIES.each(function(property){
    if (style[property]) styleRules.set(property, style[property]);
  });

  if (Prototype.Browser.IE && this.include('opacity'))
    styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);

  return styleRules;
};

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

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

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

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

Element.addMethods(Effect.Methods);
/****************************************************************/
/*  original filename controls.js                        */
/****************************************************************/


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

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

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

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

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

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

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

    this.observer = null;

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

    Element.hide(this.update);

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

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

  fixIEOverlapping: function() {
    Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
    this.iefix.style.zIndex = 1;
    this.update.style.zIndex = 2;
    Element.show(this.iefix);
  },

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

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

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

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

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

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

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

  onHover: function(event) {
    var element = Event.findElement(event, 'LI');
    if(this.index != element.autocompleteIndex)
    {
        this.index = element.autocompleteIndex;
        this.render();
    }
    Event.stop(event);
  },

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

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

  render: function() {
    if(this.entryCount > 0) {
      for (var i = 0; i < this.entryCount; i++)
        this.index==i ?
          Element.addClassName(this.getEntry(i),"selected") :
          Element.removeClassName(this.getEntry(i),"selected");
      if(this.hasFocus) {
        this.show();
        this.active = true;
      }
    } else {
      this.active = false;
      this.hide();
    }
  },

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

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

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

  getCurrentEntry: function() {
    return this.getEntry(this.index);
  },

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

  updateElement: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');

    var bounds = this.getTokenBounds();
    if (bounds[0] != -1) {
      var newValue = this.element.value.substr(0, bounds[0]);
      var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value + this.element.value.substr(bounds[1]);
    } else {
      this.element.value = value;
    }
    this.oldElementValue = this.element.value;
    this.element.focus();

    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

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

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

      this.stopIndicator();
      this.index = 0;

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

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

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

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

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

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

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

  getUpdatedChoices: function() {
    this.startIndicator();

    var entry = encodeURIComponent(this.options.paramName) + '=' +
      encodeURIComponent(this.getToken());

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

    if(this.options.defaultParams)
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Request(this.url, this.options);
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

var Droppables = {
  drops: [],

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

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

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

    if(options.accept) options.accept = [options.accept].flatten();

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

    this.drops.push(options);
  },

  findDeepestChild: function(drops) {
    deepest = drops[0];

    for (i = 1; i < drops.length; ++i)
      if (Element.isParent(drops[i].element, deepest.element))
        deepest = drops[i];

    return deepest;
  },

  isContained: function(element, drop) {
    var containmentNode;
    if(drop.tree) {
      containmentNode = element.treeNode;
    } else {
      containmentNode = element.parentNode;
    }
    return drop._containers.detect(function(c) { return containmentNode == c });
  },

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

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

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

  show: function(point, element) {
    if(!this.drops.length) return;
    var drop, affected = [];

    this.drops.each( function(drop) {
      if(Droppables.isAffected(point, element, drop))
        affected.push(drop);
    });

    if(affected.length>0)
      drop = Droppables.findDeepestChild(affected);

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

      if (drop != this.last_active) Droppables.activate(drop);
    }
  },

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

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

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

var Draggables = {
  drags: [],
  observers: [],

  register: function(draggable) {
    if(this.drags.length == 0) {
      this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
      this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
      this.eventKeypress  = this.keyPress.bindAsEventListener(this);

      Event.observe(document, "mouseup", this.eventMouseUp);
      Event.observe(document, "mousemove", this.eventMouseMove);
      Event.observe(document, "keypress", this.eventKeypress);
    }
    this.drags.push(draggable);
  },

  unregister: function(draggable) {
    this.drags = this.drags.reject(function(d) { return d==draggable });
    if(this.drags.length == 0) {
      Event.stopObserving(document, "mouseup", this.eventMouseUp);
      Event.stopObserving(document, "mousemove", this.eventMouseMove);
      Event.stopObserving(document, "keypress", this.eventKeypress);
    }
  },

  activate: function(draggable) {
    if(draggable.options.delay) {
      this._timeout = setTimeout(function() {
        Draggables._timeout = null;
        window.focus();
        Draggables.activeDraggable = draggable;
      }.bind(this), draggable.options.delay);
    } else {
      window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
      this.activeDraggable = draggable;
    }
  },

  deactivate: function() {
    this.activeDraggable = null;
  },

  updateDrag: function(event) {
    if(!this.activeDraggable) return;
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    // Mozilla-based browsers fire successive mousemove events with
    // the same coordinates, prevent needless redrawing (moz bug?)
    if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
    this._lastPointer = pointer;

    this.activeDraggable.updateDrag(event, pointer);
  },

  endDrag: function(event) {
    if(this._timeout) {
      clearTimeout(this._timeout);
      this._timeout = null;
    }
    if(!this.activeDraggable) return;
    this._lastPointer = null;
    this.activeDraggable.endDrag(event);
    this.activeDraggable = null;
  },

  keyPress: function(event) {
    if(this.activeDraggable)
      this.activeDraggable.keyPress(event);
  },

  addObserver: function(observer) {
    this.observers.push(observer);
    this._cacheObserverCallbacks();
  },

  removeObserver: function(element) {  // element instead of observer fixes mem leaks
    this.observers = this.observers.reject( function(o) { return o.element==element });
    this._cacheObserverCallbacks();
  },

  notify: function(eventName, draggable, event) {  // 'onStart', 'onEnd', 'onDrag'
    if(this[eventName+'Count'] > 0)
      this.observers.each( function(o) {
        if(o[eventName]) o[eventName](eventName, draggable, event);
      });
    if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
  },

  _cacheObserverCallbacks: function() {
    ['onStart','onEnd','onDrag'].each( function(eventName) {
      Draggables[eventName+'Count'] = Draggables.observers.select(
        function(o) { return o[eventName]; }
      ).length;
    });
  }
};

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

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

    if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
      Object.extend(defaults, {
        starteffect: function(element) {
          element._opacity = Element.getOpacity(element);
          Draggable._dragging[element] = true;
          new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
        }
      });

    var options = Object.extend(defaults, arguments[1] || { });

    this.element = $(element);

    if(options.handle && Object.isString(options.handle))
      this.handle = this.element.down('.'+options.handle, 0);

    if(!this.handle) this.handle = $(options.handle);
    if(!this.handle) this.handle = this.element;

    if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
      options.scroll = $(options.scroll);
      this._isScrollChild = Element.childOf(this.element, options.scroll);
    }

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

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

    this.eventMouseDown = this.initDrag.bindAsEventListener(this);
    Event.observe(this.handle, "mousedown", this.eventMouseDown);

    Draggables.register(this);
  },

  destroy: function() {
    Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
    Draggables.unregister(this);
  },

  currentDelta: function() {
    return([
      parseInt(Element.getStyle(this.element,'left') || '0'),
      parseInt(Element.getStyle(this.element,'top') || '0')]);
  },

  initDrag: function(event) {
    if(!Object.isUndefined(Draggable._dragging[this.element]) &&
      Draggable._dragging[this.element]) return;
    if(Event.isLeftClick(event)) {
      // abort on form elements, fixes a Firefox issue
      var src = Event.element(event);
      if((tag_name = src.tagName.toUpperCase()) && (
        tag_name=='INPUT' ||
        tag_name=='SELECT' ||
        tag_name=='OPTION' ||
        tag_name=='BUTTON' ||
        tag_name=='TEXTAREA')) return;

      var pointer = [Event.pointerX(event), Event.pointerY(event)];
      var pos     = Position.cumulativeOffset(this.element);
      this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });

      Draggables.activate(this);
      Event.stop(event);
    }
  },

  startDrag: function(event) {
    this.dragging = true;
    if(!this.delta)
      this.delta = this.currentDelta();

    if(this.options.zindex) {
      this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
      this.element.style.zIndex = this.options.zindex;
    }

    if(this.options.ghosting) {
      this._clone = this.element.cloneNode(true);
      this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
      if (!this._originallyAbsolute)
        Position.absolutize(this.element);
      this.element.parentNode.insertBefore(this._clone, this.element);
    }

    if(this.options.scroll) {
      if (this.options.scroll == window) {
        var where = this._getWindowScroll(this.options.scroll);
        this.originalScrollLeft = where.left;
        this.originalScrollTop = where.top;
      } else {
        this.originalScrollLeft = this.options.scroll.scrollLeft;
        this.originalScrollTop = this.options.scroll.scrollTop;
      }
    }

    Draggables.notify('onStart', this, event);

    if(this.options.starteffect) this.options.starteffect(this.element);
  },

  updateDrag: function(event, pointer) {
    if(!this.dragging) this.startDrag(event);

    if(!this.options.quiet){
      Position.prepare();
      Droppables.show(pointer, this.element);
    }

    Draggables.notify('onDrag', this, event);

    this.draw(pointer);
    if(this.options.change) this.options.change(this);

    if(this.options.scroll) {
      this.stopScrolling();

      var p;
      if (this.options.scroll == window) {
        with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
      } else {
        p = Position.page(this.options.scroll);
        p[0] += this.options.scroll.scrollLeft + Position.deltaX;
        p[1] += this.options.scroll.scrollTop + Position.deltaY;
        p.push(p[0]+this.options.scroll.offsetWidth);
        p.push(p[1]+this.options.scroll.offsetHeight);
      }
      var speed = [0,0];
      if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
      if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
      if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
      if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
      this.startScrolling(speed);
    }

    // fix AppleWebKit rendering
    if(Prototype.Browser.WebKit) window.scrollBy(0,0);

    Event.stop(event);
  },

  finishDrag: function(event, success) {
    this.dragging = false;

    if(this.options.quiet){
      Position.prepare();
      var pointer = [Event.pointerX(event), Event.pointerY(event)];
      Droppables.show(pointer, this.element);
    }

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

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

    var revert = this.options.revert;
    if(revert && Object.isFunction(revert)) revert = revert(this.element);

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

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

    if(this.options.endeffect)
      this.options.endeffect(this.element);

    Draggables.deactivate(this);
    Droppables.reset();
  },

  keyPress: function(event) {
    if(event.keyCode!=Event.KEY_ESC) return;
    this.finishDrag(event, false);
    Event.stop(event);
  },

  endDrag: function(event) {
    if(!this.dragging) return;
    this.stopScrolling();
    this.finishDrag(event, true);
    Event.stop(event);
  },

  draw: function(point) {
    var pos = Position.cumulativeOffset(this.element);
    if(this.options.ghosting) {
      var r   = Position.realOffset(this.element);
      pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
    }

    var d = this.currentDelta();
    pos[0] -= d[0]; pos[1] -= d[1];

    if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
      pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
      pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
    }

    var p = [0,1].map(function(i){
      return (point[i]-pos[i]-this.offset[i])
    }.bind(this));

    if(this.options.snap) {
      if(Object.isFunction(this.options.snap)) {
        p = this.options.snap(p[0],p[1],this);
      } else {
      if(Object.isArray(this.options.snap)) {
        p = p.map( function(v, i) {
          return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
      } else {
        p = p.map( function(v) {
          return (v/this.options.snap).round()*this.options.snap }.bind(this));
      }
    }}

    var style = this.element.style;
    if((!this.options.constraint) || (this.options.constraint=='horizontal'))
      style.left = p[0] + "px";
    if((!this.options.constraint) || (this.options.constraint=='vertical'))
      style.top  = p[1] + "px";

    if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
  },

  stopScrolling: function() {
    if(this.scrollInterval) {
      clearInterval(this.scrollInterval);
      this.scrollInterval = null;
      Draggables._lastScrollPointer = null;
    }
  },

  startScrolling: function(speed) {
    if(!(speed[0] || speed[1])) return;
    this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
    this.lastScrolled = new Date();
    this.scrollInterval = setInterval(this.scroll.bind(this), 10);
  },

  scroll: function() {
    var current = new Date();
    var delta = current - this.lastScrolled;
    this.lastScrolled = current;
    if(this.options.scroll == window) {
      with (this._getWindowScroll(this.options.scroll)) {
        if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
          var d = delta / 1000;
          this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
        }
      }
    } else {
      this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
      this.options.scroll.scrollTop  += this.scrollSpeed[1] * delta / 1000;
    }

    Position.prepare();
    Droppables.show(Draggables._lastPointer, this.element);
    Draggables.notify('onDrag', this);
    if (this._isScrollChild) {
      Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
      Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
      Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
      if (Draggables._lastScrollPointer[0] < 0)
        Draggables._lastScrollPointer[0] = 0;
      if (Draggables._lastScrollPointer[1] < 0)
        Draggables._lastScrollPointer[1] = 0;
      this.draw(Draggables._lastScrollPointer);
    }

    if(this.options.change) this.options.change(this);
  },

  _getWindowScroll: function(w) {
    var T, L, W, H;
    with (w.document) {
      if (w.document.documentElement && documentElement.scrollTop) {
        T = documentElement.scrollTop;
        L = documentElement.scrollLeft;
      } else if (w.document.body) {
        T = body.scrollTop;
        L = body.scrollLeft;
      }
      if (w.innerWidth) {
        W = w.innerWidth;
        H = w.innerHeight;
      } else if (w.document.documentElement && documentElement.clientWidth) {
        W = documentElement.clientWidth;
        H = documentElement.clientHeight;
      } else {
        W = body.offsetWidth;
        H = body.offsetHeight;
      }
    }
    return { top: T, left: L, width: W, height: H };
  }
});

Draggable._dragging = { };

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

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

  onStart: function() {
    this.lastValue = Sortable.serialize(this.element);
  },

  onEnd: function() {
    Sortable.unmark();
    if(this.lastValue != Sortable.serialize(this.element))
      this.observer(this.element)
  }
});

var Sortable = {
  SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,

  sortables: { },

  _findRootElement: function(element) {
    while (element.tagName.toUpperCase() != "BODY") {
      if(element.id && Sortable.sortables[element.id]) return element;
      element = element.parentNode;
    }
  },

  options: function(element) {
    element = Sortable._findRootElement($(element));
    if(!element) return;
    return Sortable.sortables[element.id];
  },

  destroy: function(element){
    element = $(element);
    var s = Sortable.sortables[element.id];

    if(s) {
      Draggables.removeObserver(s.element);
      s.droppables.each(function(d){ Droppables.remove(d) });
      s.draggables.invoke('destroy');

      delete Sortable.sortables[s.element.id];
    }
  },

  create: function(element) {
    element = $(element);
    var options = Object.extend({
      element:     element,
      tag:         'li',       // assumes li children, override with tag: 'tagname'
      dropOnEmpty: false,
      tree:        false,
      treeTag:     'ul',
      overlap:     'vertical', // one of 'vertical', 'horizontal'
      constraint:  'vertical', // one of 'vertical', 'horizontal', false
      containment: element,    // also takes array of elements (or id's); or false
      handle:      false,      // or a CSS class
      only:        false,
      delay:       0,
      hoverclass:  null,
      ghosting:    false,
      quiet:       false,
      scroll:      false,
      scrollSensitivity: 20,
      scrollSpeed: 15,
      format:      this.SERIALIZE_RULE,

      // these take arrays of elements or ids and can be
      // used for better initialization performance
      elements:    false,
      handles:     false,

      onChange:    Prototype.emptyFunction,
      onUpdate:    Prototype.emptyFunction
    }, arguments[1] || { });

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

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

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

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

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

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

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

    var options_for_tree = {
      onHover:      Sortable.onEmptyHover,
      overlap:      options.overlap,
      containment:  options.containment,
      hoverclass:   options.hoverclass
    };

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

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

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

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

    if(options.tree) {
      (Sortable.findTreeElements(element, options) || []).each( function(e) {
        Droppables.add(e, options_for_tree);
        e.treeNode = element;
        options.droppables.push(e);
      });
    }

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

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

  },

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

  findTreeElements: function(element, options) {
    return Element.findChildren(
      element, options.only, options.tree ? true : false, options.treeTag);
  },

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

    if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
      return;
    } else if(overlap>0.5) {
      Sortable.mark(dropon, 'before');
      if(dropon.previousSibling != element) {
        var oldParentNode = element.parentNode;
        element.style.visibility = "hidden"; // fix gecko rendering
        dropon.parentNode.insertBefore(element, dropon);
        if(dropon.parentNode!=oldParentNode)
          Sortable.options(oldParentNode).onChange(element);
        Sortable.options(dropon.parentNode).onChange(element);
      }
    } else {
      Sortable.mark(dropon, 'after');
      var nextElement = dropon.nextSibling || null;
      if(nextElement != element) {
        var oldParentNode = element.parentNode;
        element.style.visibility = "hidden"; // fix gecko rendering
        dropon.parentNode.insertBefore(element, nextElement);
        if(dropon.parentNode!=oldParentNode)
          Sortable.options(oldParentNode).onChange(element);
        Sortable.options(dropon.parentNode).onChange(element);
      }
    }
  },

  onEmptyHover: function(element, dropon, overlap) {
    var oldParentNode = element.parentNode;
    var droponOptions = Sortable.options(dropon);

    if(!Element.isParent(dropon, element)) {
      var index;

      var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
      var child = null;

      if(children) {
        var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);

        for (index = 0; index < children.length; index += 1) {
          if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
            offset -= Element.offsetSize (children[index], droponOptions.overlap);
          } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
            child = index + 1 < children.length ? children[index + 1] : null;
            break;
          } else {
            child = children[index];
            break;
          }
        }
      }

      dropon.insertBefore(element, child);

      Sortable.options(oldParentNode).onChange(element);
      droponOptions.onChange(element);
    }
  },

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

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

    if(!Sortable._marker) {
      Sortable._marker =
        ($('dropmarker') || Element.extend(document.createElement('DIV'))).
          hide().addClassName('dropmarker').setStyle({position:'absolute'});
      document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
    }
    var offsets = Position.cumulativeOffset(dropon);
    Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});

    if(position=='after')
      if(sortable.overlap == 'horizontal')
        Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
      else
        Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});

    Sortable._marker.show();
  },

  _tree: function(element, options, parent) {
    var children = Sortable.findElements(element, options) || [];

    for (var i = 0; i < children.length; ++i) {
      var match = children[i].id.match(options.format);

      if (!match) continue;

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

      /* Get the element containing the children and recurse over it */
      if (child.container)
        this._tree(child.container, options, child);

      parent.children.push (child);
    }

    return parent;
  },

  tree: function(element) {
    element = $(element);
    var sortableOptions = this.options(element);
    var options = Object.extend({
      tag: sortableOptions.tag,
      treeTag: sortableOptions.treeTag,
      only: sortableOptions.only,
      name: element.id,
      format: sortableOptions.format
    }, arguments[1] || { });

    var root = {
      id: null,
      parent: null,
      children: [],
      container: element,
      position: 0
    };

    return Sortable._tree(element, options, root);
  },

  /* Construct a [i] index for a particular node */
  _constructIndex: function(node) {
    var index = '';
    do {
      if (node.id) index = '[' + node.position + ']' + index;
    } while ((node = node.parent) != null);
    return index;
  },

  sequence: function(element) {
    element = $(element);
    var options = Object.extend(this.options(element), arguments[1] || { });

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

  setSequence: function(element, new_sequence) {
    element = $(element);
    var options = Object.extend(this.options(element), arguments[2] || { });

    var nodeMap = { };
    this.findElements(element, options).each( function(n) {
        if (n.id.match(options.format))
            nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
        n.parentNode.removeChild(n);
    });

    new_sequence.each(function(ident) {
      var n = nodeMap[ident];
      if (n) {
        n[1].appendChild(n[0]);
        delete nodeMap[ident];
      }
    });
  },

  serialize: function(element) {
    element = $(element);
    var options = Object.extend(Sortable.options(element), arguments[1] || { });
    var name = encodeURIComponent(
      (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);

    if (options.tree) {
      return Sortable.tree(element, arguments[1]).children.map( function (item) {
        return [name + Sortable._constructIndex(item) + "[id]=" +
                encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
      }).flatten().join('&');
    } else {
      return Sortable.sequence(element, arguments[1]).map( function(item) {
        return name + "[]=" + encodeURIComponent(item);
      }).join('&');
    }
  }
};

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

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

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

Element.offsetSize = function (element, type) {
  return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
};
/****************************************************************/
/*  original filename tooltips-v02.js                        */
/****************************************************************/


/*
 * Copyright (c) 2006 Jonathan Weiss <jw@innerewut.de>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */


/* tooltip-0.2.js - Small tooltip library on top of Prototype
 * by Jonathan Weiss <jw@innerewut.de> distributed under the BSD license.
 *
 * This tooltip library works in two modes. If it gets a valid DOM element
 * or DOM id as an argument it uses this element as the tooltip. This
 * element will be placed (and shown) near the mouse pointer when a trigger-
 * element is moused-over.
 * If it gets only a text as an argument instead of a DOM id or DOM element
 * it will create a div with the classname 'tooltip' that holds the given text.
 * This newly created div will be used as the tooltip. This is usefull if you
 * want to use tooltip.js to create popups out of title attributes.
 *
 *
 * Usage:
 *   <script src="/javascripts/prototype.js" type="text/javascript"></script>
 *   <script src="/javascripts/tooltip.js" type="text/javascript"></script>
 *   <script type="text/javascript">
 *     // with valid DOM id
 *     var my_tooltip = new Tooltip('id_of_trigger_element', 'id_of_tooltip_to_show_element')
 *
 *     // with text
 *     var my_other_tooltip = new Tooltip('id_of_trigger_element', 'a nice description')
 *
 *     // create popups for each element with a title attribute
 *    Event.observe(window,"load",function() {
 *      $$("*").findAll(function(node){
 *        return node.getAttribute('title');
 *      }).each(function(node){
 *        new Tooltip(node,node.title);
 *        node.removeAttribute("title");
 *      });
 *    });
 *
 *   </script>
 *
 * Now whenever you trigger a mouseOver on the `trigger` element, the tooltip element will
 * be shown. On o mouseOut the tooltip disappears.
 *
 * Example:
 *
 *   <script src="/javascripts/prototype.js" type="text/javascript"></script>
 *   <script src="/javascripts/scriptaculous.js" type="text/javascript"></script>
 *   <script src="/javascripts/tooltip.js" type="text/javascript"></script>
 *
 *   <div id='tooltip' style="display:none; margin: 5px; background-color: red;">
 *     Detail infos on product 1....<br />
 *   </div>
 *
 *   <div id='product_1'>
 *     This is product 1
 *   </div>
 *
 *   <script type="text/javascript">
 *     var my_tooltip = new Tooltip('product_1', 'tooltip')
 *   </script>
 *
 * You can use my_tooltip.destroy() to remove the event observers and thereby the tooltip.
 */

var Tooltip = Class.create();
Tooltip.prototype = {
  initialize: function(element, tool_tip) {
    var options = Object.extend({
      default_css: false,
      margin: "0px",
        padding: "5px",
        backgroundColor: "#d6d6fc",
        min_distance_x: 5,
      min_distance_y: 5,
      delta_x: 0,
      delta_y: 0
    }, arguments[2] || {});

    this.element      = $(element);

    this.options      = options;

    // use the supplied tooltip element or create our own div
    if($(tool_tip)) {
      this.tool_tip = $(tool_tip);
    } else {
      this.tool_tip = $(document.createElement("div"));
      document.body.appendChild(this.tool_tip);
      this.tool_tip.addClassName("tooltip");
      this.tool_tip.appendChild(document.createTextNode(tool_tip));
    }

    this.tool_tip.hide();
    this.positionTooltip();

      var arrow = new Element('div');
    arrow.update('<img src="/images/tooltip-arrow.png" />').setStyle({bottom:"-6px",height:"6px",left:"15px",position:"absolute",width:"11px"});
    this.tool_tip.insert(arrow);

    if(Prototype.Browser.IE) var ieVersion = parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5));
    if(!Prototype.Browser.IE || (ieVersion!=6 && ieVersion!=7)) this.tool_tip.addClassName('tooltip_opacity');

    this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
    this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);
    //this.eventMouseMove  = this.moveTooltip.bindAsEventListener(this);

    this.registerEvents();
  },

  destroy: function() {
    Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
    Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
    //Event.stopObserving(this.element, "mousemove", this.eventMouseMove);
  },

  registerEvents: function() {
    Event.observe(this.element, "mouseover", this.eventMouseOver);
    Event.observe(this.element, "mouseout", this.eventMouseOut);
    //Event.observe(this.element, "mousemove", this.eventMouseMove);
  },

  moveTooltip: function(event){
      Event.stop(event);
      // get Mouse position
    var mouse_x = Event.pointerX(event);
      var mouse_y = Event.pointerY(event);

      // decide if wee need to switch sides for the tooltip
      var dimensions = Element.getDimensions( this.tool_tip );
      var element_width = dimensions.width;
      var element_height = dimensions.height;

      if ( (element_width + mouse_x) >= ( this.getWindowWidth() - this.options.min_distance_x) ){ // too big for X
          mouse_x = mouse_x - element_width;
          // apply min_distance to make sure that the mouse is not on the tool-tip
          mouse_x = mouse_x - this.options.min_distance_x;
      } else {
          mouse_x = mouse_x + this.options.min_distance_x;
      }

      if ( (element_height + mouse_y) >= ( this.getWindowHeight() - this.options.min_distance_y) ){ // too big for Y
          mouse_y = mouse_y - element_height;
        // apply min_distance to make sure that the mouse is not on the tool-tip
          mouse_y = mouse_y - this.options.min_distance_y;
      } else {
          mouse_y = mouse_y + this.options.min_distance_y;
      }

      // now set the right styles
      this.setStyles(mouse_x, mouse_y);
  },

  positionTooltip: function() {
    var spot = this.element.cumulativeOffset();
    var dimensions = Element.getDimensions( this.tool_tip );

      var newy = spot.top - dimensions.height - 7;
      var newx = Number(spot.left) + Math.round(this.element.getDimensions().width / 2) - 20;
      this.tool_tip.setStyle({left:newx+"px",top:newy + "px"});
  },

  showTooltip: function(event) {
    Event.stop(event);
//    this.moveTooltip(event);
    this.positionTooltip();
      new Element.show(this.tool_tip);
  },

  setStyles: function(x, y){
    // set the right styles to position the tool tip
      Element.setStyle(this.tool_tip, { position:'absolute',
                                         top:y + this.options.delta_y + "px",
                                         left:x + this.options.delta_x + "px"
                                       });

      // apply default theme if wanted
      if (this.options.default_css){
            Element.setStyle(this.tool_tip, { margin:this.options.margin,
                                                               padding:this.options.padding,
                                              backgroundColor:this.options.backgroundColor
                                             });
      }
  },

  hideTooltip: function(event){
      new Element.hide(this.tool_tip);
  },

  getWindowHeight: function(){
    var innerHeight;
      if (navigator.appVersion.indexOf('MSIE')>0) {
          innerHeight = document.body.clientHeight;
    } else {
          innerHeight = window.innerHeight;
    }
    return innerHeight;
  },

  getWindowWidth: function(){
    var innerWidth;
      if (navigator.appVersion.indexOf('MSIE')>0) {
          innerWidth = document.body.clientWidth;
    } else {
          innerWidth = window.innerWidth;
    }
    return innerWidth;
  }

}





/****************************************************************/
/*  original filename iridesco_tooltips.js                        */
/****************************************************************/


var g_FloatingIFrame;

var tip = {
  // Given a container_element, define an iFrame for appropriate display in IE6. size_basis_element
  // may be passed if a child element of the container element better defines the size of the floating
  // element.
  show: function(container_element, size_basis_element) {
    size_basis_element = size_basis_element || container_element;

    container_element.style.opacity = '';
    container_element.show();

    if(Prototype.Browser.IE) {
      container_element.style.zIndex = 201;

      var iFrame = new Element("IFRAME");
      iFrame.setAttribute("src", "/blank.html");
      iFrame.style.position = "absolute";
      iFrame.style.filter   = "alpha(Opacity=0)";
      iFrame.style.left     = size_basis_element.offsetLeft + 'px';
      iFrame.style.top      = size_basis_element.offsetTop + 'px';
      iFrame.style.width    = size_basis_element.offsetWidth + 'px';
      iFrame.style.height   = size_basis_element.offsetHeight + 'px';
      g_FloatingIFrame      = iFrame;

      container_element.insert(iFrame);
    }
  },

  fade: function(container_element) {
    if(!container_element.visible()) return;

    container_element.fade({duration: 0.2});

    if(Prototype.Browser.IE) {
      g_FloatingIFrame = null;
    }
  }

};




/****************************************************************/
/*  original filename dropdown.js                        */
/****************************************************************/


var Dropdown = Class.create();
Dropdown.prototype = {
  initialize: function(container){
    this.container = $(container);
    this.animation_in_progress = false;
    this.state = 'closed';
    this.container.observe('mouseover',
                      this.trigger_close_to_open_via_mouse_over.bindAsEventListener(this));
    this.container.observe('mouseout',
                      this.open_to_trigger_close_via_mouse_out.bindAsEventListener(this));

    this.container.down('a.arrow').observe('click',
                                           this.on_click.bindAsEventListener(this));
    this.menu = this.container.down('div.hover_menu');
    this.menu.select('li a').each(function(e) {
      e.observe('click', this.on_click.bindAsEventListener(this));
    }.bind(this));
  },

  closed_to_open_via_click: function(){
    this.toggle(function(){
      this.state = 'open';
    }.bind(this));
  },
  open_to_closed_via_click: function(){
    this.toggle(function(){
      this.state = 'closed';
    }.bind(this));
  },
  open_to_trigger_close_via_mouse_out: function(){
    if(this.state == 'open'){
      this.state = 'trigger_close';
      this.trigger_close_to_closed_via_timeout.bind(this).delay(1);
    }
  },
  trigger_close_to_open_via_mouse_over: function(){
    if(this.state == 'trigger_close'){
      this.state = 'open';
    }
  },
  trigger_close_to_closed_via_timeout: function(){
    if(this.state == 'trigger_close'){
      this.toggle(function(){
        this.state = 'closed';
      }.bind(this));
    }
  },

  on_click: function(){
    switch (this.state) {
      case 'trigger_close':
        this.state = 'open';
        // fall trough
      case 'open':
        this.open_to_closed_via_click();
        break;
      case 'closed':
        this.closed_to_open_via_click();
    };
  },

  toggle: function(on_complete){
    on_complete = on_complete || Prototype.K;
    if(this.animation_in_progress)
      return;
    this.animation_in_progress = true;
    this.container.
      toggleClassName('btn-medium-white-pressed').
      toggleClassName('btn-medium-white');
    var after_finish = function(){
      this.animation_in_progress = false;
      on_complete();
    }.bind(this);
    if(this.menu.visible()){
      new Effect.toggle( this.menu, 'appear', {
                           duration: 0.35,
                           afterFinish: after_finish});
    } else {
      this.menu.show();
      after_finish();
    }
  }
};

document.observe('dom:loaded',
  function(){
    $$('.dropdown-container').each(
      function(container){
        new Dropdown(container);
      });
  }
);

/****************************************************************/
/*  original filename currency.js                        */
/****************************************************************/


/* -*- Mode:JavaScript; c-basic-offset:2; indent-tabs-mode:nil; c-indentation-style:"k&r" -*- */
var Currency = {
  currency_symbol: '$',
  thousands_separator: ',',
  decimal_separator: '.',
  currency_format_string: '%u%n',

  // Borrowed from Rails helper library.  -BH
  number_to_currency: function (number, hash) {
    try {
      var options   = hash || {};
      var _precision = options["precision"] || 2;
      var _symbol = options["symbol"] || Currency.currency_symbol;
      _symbol = _symbol.length == 1 ? _symbol : _symbol + " ";
      var amount = Currency.number_with_delimiter(number, { precision : _precision });
      return Currency.currency_format_string.gsub(/%n/, amount).gsub(/%u/, _symbol.strip());
    } catch(e) {
      return number;
    }
  },

  // Borrowed from Rails helper library.  -BH
  number_with_delimiter: function (number, hash) {
    try {
      var options   = hash || {};
      var precision = options["precision"] || 2;
      number = Object.isNumber(number) ? number : Currency.parse_float(number.toString());
      var parts = number.toFixed(precision).split('.');
      parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + Currency.thousands_separator);
      return parts.join(Currency.decimal_separator);
    } catch(e) {
      return number;
    }
  },

  format_field: function(element) {
    var value = Currency.parse_float_with_currencies($F(element));
    if(isNaN(value))  value = 0;
    var parts = value.toString().split('.');
    var fractions = [((parts[1] != undefined && !parts[1].blank()) ? parts[1].length : 0), 2].max();
    $(element).value = Currency.number_with_delimiter(value, { precision : fractions });
  },

  parse_float: function(string) {
    var parts = string.toString().split(Currency.decimal_separator);
    var normalized_string = [parts[0].gsub(Currency.thousands_separator, '')];
    if(parts[1] != undefined && !parts[1].blank()){
      normalized_string.push(parts[1]);
    }
    return parseFloat(normalized_string.join('.'));
  },

  parse_float_with_currencies: function(string) {
    var arg = string.toString().gsub( Currency.currency_symbol.strip(), '').gsub(/\.\s+/, '');

      // Fail to parse if anything besides digits, '.' and ',', '\'' are found
    if(/[^\-0-9\.,\']/.test(arg.strip()))  return NaN;

    return Currency.parse_float( arg);
  },

  parse_float_with_multiple_currencies: function(string) {
    var arg = string.toString().gsub( /[^\-0-9\.,\']/, '');
    return Currency.parse_float( arg);
  },

  validate_format: function(value_string) {
    var naked_string = value_string.toString().gsub(Currency.currency_symbol, '').gsub(Currency.thousands_separator, '').gsub(' ', '');
    var only_allowed_characters = new RegExp("^[0-9]*(|\\" + Currency.decimal_separator + "[0-9]?[0-9]?)$");
    var valid = naked_string.match(only_allowed_characters);
    valid = valid && (naked_string.split(Currency.decimal_separator).size() <= 2);
    return (valid == true);
  }

};





/****************************************************************/
/*  original filename cents.js                        */
/****************************************************************/


var Cents = {

 mul: function(num1, num2) {
  return ((num1 * 100) * (num2*100)) / 10000.0;
 },

 add: function(num1, num2) {
  return ((num1 *100) + (num2*100)) / 100.0;
 },

 div: function(divisor, dividend) {
  return ((divisor *100) / (dividend*100));
 },

 sub: function(num1, num2) {
  return ((num1 *100) - (num2*100)) / 100.0;
 },

 round: function(amt) {
   return Math.round(amt * 100) / 100;
 }

};

/****************************************************************/
/*  original filename reports.js                        */
/****************************************************************/


var reports = {

  change_timeframe_pressed : false,

  check_for_valid_dates: function(){
    if(date.form_validation({start_date: 'start date', end_date: 'end date'})){
      reports.slow.submit();
    }
  },

  submit: function(start_year, start_month, start_day, end_year, end_month, end_day) {
    $('start_date').value = date.to_api_format(new Date(start_year, start_month - 1, start_day));
    $('end_date').value   = date.to_api_format(new Date(end_year, end_month - 1, end_day));
    reports.slow.submit();
  },

  slow: {
    submit: function(){
      var diff = date.from_api_format($F('end_date')) - date.from_api_format($F('start_date'));
      if(diff / ( 1000 * 60 * 60 * 24) > 14 && !Prototype.Browser.IE6){ //timeframe is larger than two weeks
	reports.slow.show();
      }
      $('selector_form').submit();
    },
    show: function(){
      $('overlay').addClassName('doing-work');
      $('overlay').style.display = 'block';

      // #doing-work is added at the bottom of this javascript - images weren't loading if we didn't automatically add that chunk
      $('doing-work').show();
    }
  },

  submit_to_url: function(url) {
    var id_fields = ['project_id', 'task_id', 'client_id', 'person_id'];
    //clear old ids
    id_fields.each(
        function(id) {
          $(id).value='';
        }
      );
    var store_id_in_hidden_field_if_present_in_url = function(id) {
      var rgxp = RegExp( id + '=(\\d+)');
      var m = rgxp.exec(url);
      if(m != null) {
        $(id).value = m[1];
      }
    };
    //store new ids
    id_fields.each(
        function(id) {
          store_id_in_hidden_field_if_present_in_url(id);
        }
    );
    if(url.match(/full_view\=true/)){
      $('full_view').disabled = false;
      $('full_view').value = 'true';
    } else {
      $('full_view').disabled = true;
    }
    //submit
    $('selector_form').action = url;
    // reports.format_dates_for_pretty_urls();
    reports.slow.submit();
  },

  // Format date for pretty URL's in preperation for submission.
  // format_dates_for_pretty_urls: function() {
  //   $('start_date').value = $F('start_date').gsub(date.date_seperator_regexp, '-');
  //   $('end_date').value = $F('end_date').gsub(date.date_seperator_regexp, '-');
  // },

  first_layer_switch: true,

  show_layer: function(toggler_link, label){
    var css_label = reports.cssize_label(label);
    var div_id = 'layer_' + css_label;
    var selected_layer = $(div_id);
    $$('#reporting_wide_col .report_layer').each(
        function(e) {
          if (Element.visible(e)) {
            e.style.display = 'none';
            selected_layer.style.display = '';
          }
        }
      );
    $$('#overlay_tabs .overlay_selected').each(
        function(e) {
          e.removeClassName('overlay_selected');
        }
      );
    $(toggler_link).addClassName('overlay_selected');
    $('visible_layer').value = label;
    // ignore first layer switch as it is always triggered by code.
    if(!reports.first_layer_switch){
      tracker.register_hit(label);
    }
    reports.first_layer_switch = false;
  },

  re_base_bar_graph_widths: function(){
    var rebase = function(css_selector){
      var items = $$(css_selector);
      var max_width = items.map(function(t) { return Currency.parse_float_with_currencies(t.style.width) || 0;}).max();
      if(max_width <= 0 || max_width >= 100)
        return;
      var rebased_max_width = 100.0 / max_width;
      items.each(function(t) {
          t.style.width = ((Currency.parse_float_with_currencies(t.style.width) || 0) * rebased_max_width) + '%';
        });
    };
    rebase('.report_layer .fill_hours, .report_layer .bg_hours');
    rebase('.report_layer .fill_budget, .report_layer .bg_budget, .report_layer .bg_over_budget');
  },

  add_nobdr_class_to_last_cells_in_reporting_tables: function(){
    $$('tbody.reporting_tbody > tr:last-child td').invoke('addClassName', 'nobdr');
  },

  cssize_label: function(label) {
    return label.toLowerCase().replace(/\-/, '_');
  },

  change_time_frame: function() {
    move_div_down('time_selector');
  },

  cancel_change_time_frame: function() {
    hide_big_div('time_selector');
  },

  sum_values_from: function(selector, to_value_functor){
    return $$(selector).pluck('firstChild').pluck('nodeValue').inject(0, function(sum, e)  {
        return sum + (to_value_functor(e) || 0);
      });
  },

  compute_detailed_sum: function () {
    return reports.number_with_delimiter(reports.sum_values_from('.number', reports.parse_float_with_parenthesized_negatives));
  },

  display_detailed_expense_sum: function () {
    var sum = reports.sum_values_from('.number', reports.parse_float_with_parenthesized_negatives);
    document.writeln(reports.number_to_currency(sum));
  },

  compute_sum_for: function(selector){
    var value = reports.sum_values_from(selector, reports.parse_float_with_parenthesized_negatives);
    return reports._return_value_with_parenthesized_negatives(value);
  },

  compute_difference_between: function(selector1, selector2) {
    var value1 = reports.parse_float_with_parenthesized_negatives(reports.compute_sum_for(selector1));
    var value2 = reports.parse_float_with_parenthesized_negatives(reports.compute_sum_for(selector2));
    return reports._return_value_with_parenthesized_negatives(value1 - value2);
  },

  _return_value_with_parenthesized_negatives: function(value) {
    if(value >= 0){
      return Currency.number_with_delimiter(value);
    }
    return "<span class='over_budget'>(" + Currency.number_with_delimiter(-value) + ")</span>";
  },

  compute_sum_costs_for: function(selector){
    return reports.number_to_currency(reports.sum_values_from(selector, Currency.parse_float_with_currencies));
  },

  compute_sum_costs_on_multiple_currencies_for: function(selector, symbol){
    return reports.number_to_currency(reports.sum_values_from(selector,
							      Currency.parse_float_with_multiple_currencies),
				      {'symbol' : symbol});
  },

  parse_float_with_parenthesized_negatives: function(string) {
    if (string.include('(')){
      return -(Currency.parse_float_with_currencies(hours.abs_time(string)));
    }
    return Currency.parse_float_with_currencies(string);
  },

  toggle_change_timeframe_btn: function() {
     Element.toggle('timeframe_selection');
     if (this.change_timeframe_pressed == false) {
       $('change_timeframe_btn').addClassName('pressed');
       this.change_timeframe_pressed = true;
       $('start_date').activate();
    } else {
       $('change_timeframe_btn').removeClassName('pressed');
       this.change_timeframe_pressed = false;
     }
  },

  toggle_detailed_time_toolbar: function() {
   $('detail_report_filter').toggle();
   $('toolbar').toggle();
  }

};

Object.extend(reports, Currency);

document.observe('dom:loaded',function() {
  var body = $$('body')[0];
  var dw = document.createElement('div');
  dw.id = 'doing-work';
  $(dw).hide();

  dwhtml = '<div class="doing-work-container"><div class="doing-work-logo"><img src="/images/slow_overlay/harvest_logo.gif" width="165" height="30" /></div><div class="doing-work-overlay-container">';
  if(Prototype.Browser.IE) dwhtml = dwhtml + '<div class="ie_shadow"></div>';
  dwhtml = dwhtml + '<div class="doing-work-overlay"><img src="/images/slow_overlay/spinny.gif" width="47" height="47" /><div class="work-content"><h4>Working on your request&hellip;</h4><p>We&rsquo;ll have the information you need in just a moment.</p></div><div style="clear:both;"></div></div></div></div>';

  dw.innerHTML = dwhtml;

  body.appendChild(dw);
});
/****************************************************************/
/*  original filename filter.js                        */
/****************************************************************/


var filter = {

  on_timeframe_change: function(options){
    options        = options || {};
    var prefix     = options['prefix'] || '';
    var grab_focus = typeof(options['grab_focus']) == 'undefined' ? true : options['grab_focus'];

    if($F(prefix + 'timeframe')=='Custom') {
      
      if(prefix=="expense_") filter.setExpenseCustom();
      
      $(prefix + 'custom_timeframe').show();
      if(grab_focus)  $(prefix + 'start_date').activate();
    } else {
      var get_date = function(str){
        str = str.toString();
        var a = [0, 0, 0];
        a[window._dateFormat[0].indexOf("yyyy")]  = str.substring(0, 4);
        a[window._dateFormat[0].indexOf("mm")]  = str.substring(4, 6);
        a[window._dateFormat[0].indexOf("dd")]  = str.substring(6, 8);
        return a.join(window._dateFormat[1]);
      };
      var timeframe = $F(prefix + 'timeframe').split(',');
      $(prefix + 'start_date').value = get_date(timeframe[0]);
      $(prefix + 'end_date').value = get_date(timeframe[1]);
      $(prefix + 'custom_timeframe').hide();
    }
  },

  setExpenseCustom: function(){
    $('expense_start_date').value = $F('start_date');
    $('expense_end_date').value = $F('end_date');
  },

  client_id_to_projects: $H({}),
  selected_project_id: null,
  show_archived_projects: false,

  heuristically_configure_archived_projects: function(projects){
    if(filter.show_archived_projects)
      return;
    var all_are_inactive = false;
    if($A(projects).all( function(project){ return !project.active; })){
      filter.show_archived_projects = true;
    }
  },

  on_client_change: function(){
    filter.combine_active_dropdown_with_archived('client_id');
    var selected_client_id = parseInt($F('client_id'));
    var projects = isNaN(selected_client_id) ?
                     filter.client_id_to_projects.values().flatten().sortBy(function(s) {return (s.name + s.code).toUpperCase(); }) :
               (filter.client_id_to_projects.get(selected_client_id) || []);
    filter.heuristically_configure_archived_projects(projects);
    var project_html = ["<select id='project_id' name='project_id'>"];
    if(filter.selected_project_id == null || filter.selected_project_id == '' ){
      project_html.push("<option value='any' selected='selected'>All</option>");
    } else {
      project_html.push("<option value='any'>All</option>");
    }
    for (var project_i = 0, projects_length = projects.length; project_i < projects_length; project_i++){
      var project = projects[project_i];
      if(!filter.show_archived_projects && !project.active)
    continue;
      if(project.id == filter.selected_project_id){
        project_html.push("<option value='", project.id, "' selected='selected'>", project.name, "</option>");
      } else {
        project_html.push("<option value='", project.id, "'>", project.name, "</option>");
      }
    }
    if(!filter.show_archived_projects){
      project_html.push("<option value='archived'>-- Show archived projects --</option>");
    }
    project_html.push("</select>");
    $('project_id_cont').update(project_html.join(''));
    $('project_id').observe('change', filter.on_project_change);
  },

  on_project_change: function(){
    if($F('project_id') == 'archived'){
      $$('#project_id option[value=\'archived\']').first().innerHTML = 'loading ...';
      filter.show_archived_projects = true;
      (function(){filter.on_client_change();}).delay(0.5);//.defer();
    }
  },

  on_person_change: function(){
    filter.combine_active_dropdown_with_archived('person_id');
  },

  combine_active_dropdown_with_archived: function(active){
    if($F(active) == 'archived') {
      $(active).select('option[value=\'archived\']').first().innerHTML = 'loading ...';
      (function(){
        var new_options = ["&nbsp;<option value='any'>All</option>"];
        $$('#' + active + ' option, #'+ active + '_archived option').select(function(option){
          return (option.value.match(/^\d+$/));
        }).sortBy(function(option){
          return option.innerHTML.toLowerCase();
        }).each(function(option){
          new_options.push("<option value='" + option.value + "'>" + option.innerHTML + "</option>");
        });

        // IE Bug (http://support.microsoft.com/default.aspx?scid=kb;en-us;276228) requires that
        // we don't set a select tag's innerHTML. So we must work with the parent's innerHTML.
        // We replace existing options with placeholder, replace the first placeholder with the new
        // options and replace all other placeholders with an empty string ("").
        var active_parent = $(active).up();
        var parent_inner  = active_parent.innerHTML.replace(/<option.+<\/option>/ig, "#$%#").replace("#$%#", new_options.join("")).replace(/#\$%#\s*/g, "");
        active_parent.innerHTML = parent_inner;

       }).delay(0.5);
    }
  },

  validate_filter: function() {
    if(!$('custom_timeframe').visible())
      return true;

    return date.form_validation({start_date: 'start date', end_date: 'end date'});
  }

};



/****************************************************************/
/*  original filename expense_reports.js                        */
/****************************************************************/


/* -*- Mode:JavaScript; c-basic-offset:2; indent-tabs-mode:nil; c-indentation-style:"k&r" -*- */
var expense_reports = {

  all_reportable_user_options: '',
  all_reportable_project_options: '',
  all_reportable_client_options: '',

  submit: function() {
    // Halt submission if custom timeframe has invalid dates entered.
    if(!filter.validate_filter()) {
      return false;
    }
    $('expense_report_filter_form').action = this.build_url();
    $('expense_report_filter_form').submit();
    return true;
  },

  build_url: function() {
    var timeframe_dates = this._get_timeframe_dates();
    var url = '/reports/expenses/' + timeframe_dates[0] + '/' + timeframe_dates[1];

    var select_fields = ['client_id', 'project_id', 'expense_category_id', 'person_id'];
    return select_fields.inject(url, function(url, select_field) {
      return url + '/' + encodeURIComponent($F(select_field));
    });
  },

  // Returns [start_date, end_date]
  _get_timeframe_dates: function() {
    if(this._custom_timeframe_selected()) {
      // reports.format_dates_for_pretty_urls();
      return [date.to_api_format(date.is_valid_date($F('start_date'))),
              date.to_api_format(date.is_valid_date($F('end_date')))];
    } else {
      return $F('timeframe').split(',');  // 'timeframe' select value is "start_date,end_date"
    }
  },

  // _mmddyyyy_to_yyyymmdd: function(date, separator) {
  //   separator  = separator || '-';
  //   date_parts = date.split(separator);
  //   return date_parts[2] + '-' + date_parts[0] + '-' + date_parts[1];
  // },

  register_on_change_handlers: function() {
    $$('select').each(function(e) {
      Event.observe(e, 'change', expense_reports.check_show_inactive);
    });
    $('timeframe').observe('change', expense_reports.toggle_custom_timeframe);
    expense_reports.toggle_custom_timeframe();
  },

  toggle_custom_timeframe: function() {
    if(expense_reports._custom_timeframe_selected()) {
      $('custom_timeframe').show();
      $('start_date').activate();
    } else {
      $('custom_timeframe').hide();
    }
  },

  _custom_timeframe_selected: function() {
    return 'Custom' == $F('timeframe');
  },

  // Force "Loading..." text within select box for a delayed amount of time.  This method
  // reduces the size of the option list to 1 option - it works in conjuction with
  // update_select_with_all.
  remove_options_and_load: function(select_id) {
    $(select_id).update("<option>loading...</option>");
    // $$("#" + select_id + " option[value='show_inactive']").first().innerHTML = 'loading ...';
    setTimeout("expense_reports.update_select_with_all('" + select_id + "')", 750);
  },

  // Updates select list specified by select_id with all reportable items, which should include
  // inactive items filtered out on initial page load.  The "all reportable items" variable
  // must be popluated by Rails upon page load.
  update_select_with_all: function(select_id) {
    // Remove the '_id'
    var all_options = expense_reports['all_reportable_' + select_id.gsub('_id', '') + '_options'];
    'project_id' == select_id ?
      expense_reports._update_select_with_grouped_results(select_id, all_options) :
      expense_reports._update_select_with_ungrouped_results(select_id, all_options);
  },

  _update_select_with_ungrouped_results: function(select_id, _options) {
    var markup = "";
    _options.each(function(option_array) {
      markup += "<option value='" + option_array[1] + "'>" + option_array[0] + "</option>";
    });
    $(select_id).update(markup);
  },

  _update_select_with_grouped_results: function(select_id, _options) {
    var markup = "";
    var previous_client_name = "";
    _options.each(function(option_array) {
      if(previous_client_name != option_array[0]) {
        if(previous_client_name != "")  markup += "</optgroup>";
        markup += "<optgroup label= '" + option_array[0] + "'>";
        previous_client_name = option_array[0];
      }
      markup += "<option value='" + option_array[2] + "'>" + option_array[1] + "</option>";
    });
    markup += "</optgroup>";
    $(select_id).update(markup);
  },

  // On an observed select box, this method replaces an "active-only" list with all items using
  // update_select_with_all.  Once inactive are shown, adds a hidden field to the form so this
  // state can be passed through to subsequent expense report filters.
  check_show_inactive: function(event) {
    var element = Event.element(event);
    if(expense_reports.show_inactive_id == element.getValue()) {
      expense_reports.remove_options_and_load(element.id);

      // Create hidden field associated with element.
      var model_name = element.id.sub(/_id$/, '');
      var h = document.createElement('input');
      h.setAttribute('type', 'hidden');
      h.setAttribute('id', 'show_inactive_' + model_name);
      h.setAttribute('name', 'show_inactive_' + model_name);
      h.setAttribute('value', 'true');

      // Append hidden field to the form
      element.up('form').appendChild(h);
    }
  }

};



/****************************************************************/
/*  original filename project.js                        */
/****************************************************************/


var project_mgr = {
  id: '',
  scheduled_search: null,

  request: function(url, parameters_, method_, onComplete_){
    method_ = typeof(method_) != 'undefined' ? method_ : 'post';
    parameters_ = typeof(parameters_) != 'undefined' ? parameters_ : '';
    onComplete_ = onComplete_ || function() {;};
    new Ajax.Request(url, {asynchronous:true, evalScripts:true, method: method_, parameters: parameters_, onComplete: onComplete_});
  },

  toggle_input_field: function(field, condition){
    if(condition){
      field.show();
    } else {
      field.blur();
      field.hide();
    }
  },

  rates_value: function() {
    return $('project_billable_false').checked ? 'none' : $F("project_rates_setting");
  },

  handle_change_of__bill_project_by_or_budget_by: function() {
    var new_rates_value   = project_mgr.rates_value();
    var new_budget_value  = $F("project_budget_setting");


    if('Tasks' == new_rates_value && 'task' == new_budget_value){
      $('total_task_budget_cost').show();
      project_mgr.update_sum_task_budgets();
    } else {
      $('total_task_budget_cost').hide();
    }

    if('People' == new_rates_value && 'person' == new_budget_value){
      $('total_people_budget_cost').show();
      project_mgr.update_sum_person_budgets();
    } else {
      $('total_people_budget_cost').hide();
    }

    if('none' == new_budget_value) {
      $('show_budget_to_all_check_box').hide();
      $('over_budget_notification_check_box').hide();
      $('project_show_budget_to_all').checked = false;
    } else {
      $('show_budget_to_all_check_box').show();
      $('over_budget_notification_check_box').show();
    }
  },

  handle_change_of__bill_project_by: function(page_load) {
    // If a page_load param is passed and it isn't the Event object.
    page_load = (page_load && typeof(page_load) != "object") ? true : false;

    var new_value = project_mgr.rates_value();

    $$('#tasks_edit .task_rates_td').each(function(e) {
        project_mgr.toggle_input_field(e, new_value == 'Tasks');
      });
    $$('#people_edit .people_rates_td').each(function(e) {
        project_mgr.toggle_input_field(e, new_value == 'People');
      });

    new_value = $F("project_rates_setting");
    switch(new_value){
    case 'Project':
      $$('#project_hourly_rate, #project_rates_label').invoke('show');
      if(!page_load)  $('project_hourly_rate').activate();
      break;
    default:
      $$('#project_hourly_rate, #project_rates_label').invoke('hide');
    }

    if($('total_task_budgets_cont'))
      project_mgr.handle_change_of__bill_project_by_or_budget_by();
  },

  register_budget_by_handler: function() {
    $("project_budget_setting").observe('change', project_mgr.handle_change_of__budget_by);
    project_mgr.handle_change_of__budget_by("page_load");
  },

  handle_change_of__budget_by: function(page_load) {
    // If a page_load param is passed and it isn't the Event object.
    page_load = (page_load && typeof(page_load) != "object") ? true : false;

    var new_value = $F("project_budget_setting");
    switch(new_value){
    case 'none':
      $('project_budget').value = '';
      $('project_budget').disabled = '';
      $('project_cost_budget').value = '';
      $('project_cost_budget').disabled = '';
      $$("#project_budget, #project_budget_label, "
         + "#project_cost_budget, #project_cost_budget_label, "
         + "#project_cost_budget_include_expenses_check_box, "
         + "#project_cost_budget_warning, "
         + "#total_task_budgets_cont, #total_people_budgets_cont, "
         + "#people_edit .person_budget_td, "
         + "#tasks_edit .task_budget_td").invoke('hide');
      break;
    case 'project':
      $$('#project_budget, #project_budget_label').invoke('show');
      $$("#project_cost_budget, #project_cost_budget_label, "
         + "#project_cost_budget_include_expenses_check_box, "
         + "#project_cost_budget_warning, "
         + "#total_task_budgets_cont, #tasks_edit .task_budget_td, "
         + "#total_people_budgets_cont, "
         + "#people_edit .person_budget_td").invoke('hide');
      if(!page_load)  $('project_budget').activate();
      break;
    case 'project_cost':
      $$("#project_cost_budget, #project_cost_budget_label, "
         + "#project_cost_budget_include_expenses_check_box").invoke('show');
      if($F('project_billable_true') == null){
    $('project_cost_budget_warning').show();
      }
      $$("#project_budget_label, #project_budget, "
         + "#total_task_budgets_cont, #tasks_edit .task_budget_td, "
         + "#total_people_budgets_cont, "
         + "#people_edit .person_budget_td").invoke('hide');
      if(!page_load)  $('project_cost_budget').activate();
      break;
    case 'task':
      $$("#project_budget_label, #project_budget, "
         + "#project_cost_budget, #project_cost_budget_label, "
         + "#project_cost_budget_include_expenses_check_box, "
         + "#project_cost_budget_warning, "
         + "#total_people_budgets_cont, "
         + "#people_edit .person_budget_td").invoke('hide');
      $$("#total_task_budgets_cont, "
         + "#tasks_edit .task_budget_td").invoke('show');
      break;
    case 'person':
      $$('#project_budget, #project_budget_label, '
         + "#project_cost_budget, #project_cost_budget_label, "
         + "#project_cost_budget_include_expenses_check_box, "
         + "#project_cost_budget_warning, "
         + '#total_task_budgets_cont, '
         + '#tasks_edit .task_budget_td').invoke('hide');
      $$("#total_people_budgets_cont, "
         + "#people_edit .person_budget_td").invoke('show');
      break;
    }
    if($('total_task_budgets_cont'))
      project_mgr.handle_change_of__bill_project_by_or_budget_by();
  },

  toggle_loading: function(id_prefix) {
    $(id_prefix + '-action').hide();
    $(id_prefix + '-loading').show();
  },

  delete_user: function(project_id, user_assignment_id){
    if (confirm("Remove this user from the current project?")) {
      project_mgr.toggle_loading('user-assignment-' + user_assignment_id);
      project_mgr.request('/projects/'+ project_id + '/user_assignments/' + user_assignment_id, '', 'delete', project_mgr.update_sum_person_budgets);
    }
  },

  re_activate_user: function(project_id, user_assignment_id){
    project_mgr.toggle_loading('user-assignment-' + user_assignment_id);
    project_mgr.request('/projects/'+ project_id + '/user_assignments/' + user_assignment_id + '/re_activate');
  },

  delete_task: function(project_id, task_assignment_id){
    if (confirm("Remove this task from the current project?")) {
      project_mgr.toggle_loading('task-assignment-' + task_assignment_id);
      project_mgr.request('/projects/'+ project_id + '/task_assignments/' + task_assignment_id, '', 'delete', project_mgr.update_sum_task_budgets);
    }
  },

  re_activate_task: function(project_id, task_assignment_id){
    project_mgr.toggle_loading('task-assignment-' + task_assignment_id);
    project_mgr.request('/projects/'+ project_id + '/task_assignments/' + task_assignment_id + '/re_activate');
  },

  toggle_project_status: function(project_id){
    $('project_activate_deactivate_progress').show();
    project_mgr.request('/projects/'+ project_id + '/toggle', { from_edit: true }, 'put');
  },

  latest_projects_with_code_per_client: {},

  show_latest_project_code_for_client: function() {
    if(!$('last-project-code-for-client'))
      return;

    var client_id = $F('project_client_id');
    var code = project_mgr.latest_projects_with_code_per_client[client_id];
    if(code != null) {
      $('last-project-code-for-client').innerHTML = "Last project code for client: <span class='project_code'>" + code + "</span>.";
    } else {
      $('last-project-code-for-client').innerHTML = '&nbsp;';
    }
  },

  check_unique_project_code: function(){
    if($F('project_code').blank())
      return;
    var url = '/projects/check_code?';
    if(!project_mgr.id.blank()){
      url += 'project_id=' + project_mgr.id + '&';
    }
    url += $('project_code').serialize();
    $('project_code_spinner').show();
    $('project_code_message').hide();
    new Ajax.Request(url, {asynchronous:true, evalScripts:true, method:'get'});
  },

  show_import_projects_from_basecamp: function() {
    project_mgr.hide_manage_index();
    $('add_project_form', 'add_project_header').invoke('hide');
    $('add_project_from_basecamp_header').show();
    project_mgr.show_div('add_project_from_basecamp', 'basecamp_projects');
  },

  hide_import_projects_from_basecamp: function() {
    $('add_project_from_basecamp_header').hide();
    project_mgr.hide_div('add_project_from_basecamp');
    project_mgr.show_manage_index();
  },

  show_import_projects_from_highrise: function() {
    project_mgr.hide_manage_index();
    $('add_project_form', 'add_project_header').invoke('hide');
    $('add_project_from_highrise_header').show();
    project_mgr.show_div('add_projects_from_highrise', 'highrise_projects');
  },

  hide_import_projects_from_highrise: function() {
    $('add_project_from_highrise_header').hide();
    $('highrise_message').hide();
    project_mgr.hide_div('add_projects_from_highrise');
    project_mgr.show_manage_index();
  },

  show_add_project: function() {
    project_mgr.hide_manage_index();
    $$('#add_project_from_basecamp, #add_project_from_basecamp_header').invoke('hide');
    $('add_project_header').show();
    project_mgr.show_div('add_project_form', 'project_client_id');
    project_mgr.register_on_change_handlers_for_billable_true();
    if(project_mgr.continuous_scroller){
        project_mgr.continuous_scroller.stopObserving();
    }
  },

  hide_add_project: function() {
    $('add_project_header').hide();
    project_mgr.hide_div('add_project_form');
    project_mgr.show_manage_index();
  },

  add_project: function() {
    if (!$F('project_name').blank()) {
      $('new_project').submit();
    } else {
      alert("Project name cannot be blank.");
    }
  },

  hide_manage_index: function() {
    if($('flash-message'))  $('flash-message').hide();
    $$('.index_field').invoke('hide');
    if(project_mgr.continuous_scroller){
       project_mgr.continuous_scroller.stopObserving();
    }
    $$('#load_more_projects').invoke('hide');
  },

  show_manage_index: function() {
    $$('.index_field').invoke('show');
    if(project_mgr.continuous_scroller){
       project_mgr.continuous_scroller.resumeObserving();
    }
    $$('#load_more_projects').invoke('show');
  },

  update_sum_task_budgets: function(){
    var sum_task_budgets = $$("#tasks_edit .task_budget").pluck('value').inject(0,
      function(sum, e) {
        return sum + (Currency.parse_float(e) || 0);
      });

    $('total_task_budgets').innerHTML = Currency.number_with_delimiter(sum_task_budgets);
    if($F("project_budget_setting") == "task"){
      $('project_budget').value = Currency.number_with_delimiter(sum_task_budgets);
    }

    project_mgr._update_sum_task_budgets_cost();
  },

  update_sum_person_budgets: function(){
    var sum_person_budgets = $$("#people_edit .person_budget").pluck('value').inject(0,
      function(sum, e) {
        return sum + (Currency.parse_float(e) || 0);
      });

    $('total_people_budgets').innerHTML = Currency.number_with_delimiter(sum_person_budgets);
    if($F("project_budget_setting") == "person"){
      $('project_budget').value = Currency.number_with_delimiter(sum_person_budgets);
    }

    project_mgr._update_sum_person_budgets_cost();
  },


  _update_sum_task_budgets_cost: function() {
    if(('Tasks' != $F("project_rates_setting")) || ('task' != $F("project_budget_setting")))
      return;

    var sum_task_budgets_cost =
      $$("#project_task_rows tr").inject(0,
        function(sum, e) {
          return sum +
            ((Currency.parse_float_with_currencies(e.select('.task_rates')[0].value) || 0)
             * (Currency.parse_float(e.select('.task_budget')[0].value || 0)));
      });

    $('total_task_budget_cost').innerHTML = '(' + project_mgr.number_to_currency(sum_task_budgets_cost) + ')';
  },

  _update_sum_person_budgets_cost: function() {
    if(('People' != $F("project_rates_setting")) || ('person' != $F("project_budget_setting")))
      return;

    var sum_person_budgets_cost =
      $$("#project_people_rows tr").inject(0,
        function(sum, e) {
          return sum +
            ((Currency.parse_float_with_currencies(e.select('.person_rates')[0].value) || 0)
              * (Currency.parse_float(e.select('.person_budget')[0].value || 0)));
      });

    $('total_people_budget_cost').innerHTML = '('
      + project_mgr.number_to_currency(sum_person_budgets_cost) + ')';
  },


  all_marked_as_billable: false,
  toggle_all_as_billable: function(){
    $$('#tasks_edit tr.active input[id$=billable]').each(function(e){
      e.checked = (project_mgr.all_marked_as_billable ? '' : 'false');
    });
    project_mgr.all_marked_as_billable = !project_mgr.all_marked_as_billable;
  },


  register_on_change_for: function(element_selector, change_handler) {
    var inputs = $$(element_selector);
    var length = inputs.length;
    for( var i = 0; i < length; i++) {
      if ('text' == inputs[i].type.toLowerCase()) {
        $(inputs[i]).observe('change', change_handler);
        $(inputs[i]).observe('keydown', timesheet.disable_enter_key);
      }
    }
  },

  register_on_change_handlers: function() {
    project_mgr.update_sum_task_budgets();
    project_mgr.update_sum_person_budgets();


    project_mgr.register_on_change_for('#project_task_rows input',
                                       project_mgr.update_sum_task_budgets);
    project_mgr.register_on_change_for('#project_people_rows input',
                                       project_mgr.update_sum_person_budgets);

    project_mgr.register_task_select_handler();
    $("project_client_id").observe('change', project_mgr.handle_onchange__select_client);
    project_mgr.register_budget_by_handler();

    project_mgr.register_on_change_handlers_for_billable_true();
    project_mgr.register_on_change_handlers_for_notify_when_over_budget();
    project_mgr.register_on_change_handlers_for_bill_project_by();

    $('new_task_name').observe('keydown', project_mgr.handle_enter_key_for_new_task_name);
  },

  register_on_change_handlers_for_billable_true: function() {
    $$('#project_billable input').each(function(control) {
      control.observe('click', project_mgr.handle_change_of__billable_true);
    });
    project_mgr.handle_change_of__billable_true();
  },

  handle_change_of__billable_true: function() {
    project_mgr.handle_change_of__bill_project_by("page_load");

    if($('project_billable_true').checked) {
      $$('#project_rates_setting, #project_hourly_rate').invoke("enable");
      $$('.billable_td').invoke('show');
    } else {
      $$('#project_rates_setting, #project_hourly_rate').invoke("disable");
      $$('.billable_td').invoke('hide');
    }
  },

  register_on_change_handlers_for_bill_project_by: function() {
    $("project_rates_setting").observe('change', project_mgr.handle_change_of__bill_project_by);
    project_mgr.handle_change_of__bill_project_by("page_load");
  },

  register_on_change_handlers_for_notify_when_over_budget: function() {
    if($('project_notify_when_over_budget')) {
      $('project_notify_when_over_budget').observe('change', project_mgr.handle_change_of__notify_when_over_budget);
      project_mgr.handle_change_of__notify_when_over_budget("page_load");
    }
  },

  handle_change_of__notify_when_over_budget: function(page_load) {
    // If a page_load param is passed and it isn't the Event object.
    page_load = (page_load && typeof(page_load) != "object") ? true : false;

    var over_budget_percentage_field = $('project_over_budget_notification_percentage');
    if($('project_notify_when_over_budget').checked) {
      over_budget_percentage_field.enable();
      if(!page_load) {
        if(over_budget_percentage_field.value.blank())  over_budget_percentage_field.value = 80;
        over_budget_percentage_field.activate();
      }
    } else {
      over_budget_percentage_field.disable();
    }
  },

  register_task_select_handler: function() {
    Event.observe($("tasks-select"), 'change', project_mgr.handle_onchange__add_task);
  },

  handle_onchange__add_task: function(){
    var task_value = $F("tasks-select");
    if(task_value == 'new_task'){
      $('tasks-select').hide();
      $('tasks-select').value = '';
      $('new_task_name_container').show();
      $('new_task_name').value = '';
      $('new_task_name').activate();
      $('add_new_task_cancel_button').show();
      $('add_existing_task_cancel_button').hide();
    }
  },

  handle_onchange__select_client: function(){
    var client_id = $F('project_client_id');
    if(client_id == 'new_client') {
      $('new_client_control').show();
      $('new_client_name').value = "Enter new client name";
      $('new_client_name').select();
      $('new_client_name').focus();
    }
    else {
      $('new_client_name').value='';
      $('new_client_control').hide();
    }
  },

  handle_task_assigment_billable_change: function(ta_id){
    if($('task-assignment-' + ta_id + '-billable').checked){
      $('task-assignment-' + ta_id + '-hourly-rate').enable();
    } else {
      $('task-assignment-' + ta_id + '-hourly-rate').disable();
    }
  },

  new_task_name_has_focus: false,

  handle_focus_new_task_name: function(event) {
    project_mgr.new_task_name_has_focus = true;
  },

  handle_blur_new_task_name: function(event) {
    project_mgr.new_task_name_has_focus = false;
  },

  enter_in_new_task_name: false,

  handle_enter_key_for_new_task_name: function(event) {
    if (event.keyCode == Event.KEY_RETURN) {
      project_mgr.enter_in_new_task_name = true;
    }
  },

  handle_enter_key_form_submit_when_new_task_name: function() {
    if (project_mgr.enter_in_new_task_name) {
      project_mgr.add_task();
      project_mgr.enter_in_new_task_name = false;
      return false;
    } else {
      return project_mgr.validate();
    }
  },

  add_task: function(project_id) {
    project_id = project_id || project_mgr.id;
    var task_id = $F('tasks-select');
    if(task_id.blank()) {
      var new_task_name = $F('new_task_name');
      if(!new_task_name.blank()) {
        $('add_task_buttons').hide();
        $('add_task_in_progress').show();
        project_mgr.request('/projects/'+ project_id + '/task_assignments/add_with_create_new_task', {"task[name]": new_task_name});
      }
    } else {
      $('add_task_buttons').hide();
      $('add_task_in_progress').show();
      project_mgr.request('/projects/'+ project_id + '/task_assignments',  {"task[id]": task_id});
    }
  },

  cancel_add_existing_task: function() {
    $('new_tasks_control', 'add_task_link').invoke('toggle');
  },

  cancel_add_new_task: function() {
    $('tasks-select', 'new_task_name_container').invoke('toggle');
    $$('.task_cancel_button').invoke('toggle');
  },

  show_import_people_from_basecamp: function() {
    project_mgr.hide_manage_index();
    $('add_people_from_basecamp_header').show();
    project_mgr.show_div('add_person_from_basecamp');
  },

  hide_import_people_from_basecamp: function() {
    $('add_people_from_basecamp_header').hide();
    project_mgr.hide_div('add_person_from_basecamp');
    project_mgr.show_manage_index();
  },

  add_person: function(project_id) {
    var person_id = $F('people-select');
    if(person_id.blank())
      return;
    $('add_person_buttons').hide();
    $('add_person_in_progress').show();
    project_mgr.request('/projects/' + project_id + '/user_assignments/',  {"user[id]": person_id} );
  },

  toggle_project_delete: function(id, parentRow, url, name) {
    var confirmId = 'project-' + id + '_confirm';
    if($(confirmId)) {
      $(parentRow + '-show', confirmId).invoke('toggle');
    } else {
      new InlineConfirmation('project-' + id, parentRow, url, { 'promptText' : "Would you like to archive the project <strong>" + name + "</strong>?", 'method' : 'put', 'linkToAjax' : true });
    }
  },

  toggle_project_activate: function(id) {
    $('project-' + id + '-show', 'project-' + id + '-activate').invoke('toggle');
  },

  hide_new_highrise_client: function() {
    $('client_selector').show();
    $('new_client_from_highrise').hide();
    $('create_new_client_from_highrise').value = "false";
  },

  show_new_highrise_client: function() {
    $('new_client_from_highrise').show();
    $('client_selector').hide();
    $('create_new_client_from_highrise').value = "true";
  },

  show_div: function(name, field_name) {
    move_div_down(name);
    if(field_name) {
      Form.Element.activate.delay(0.5, $(field_name));
    }
    if($('toolbar'))  $('toolbar').hide();
  },

  hide_div: function(name) {
    $(name).hide();
    if($('toolbar'))  $('toolbar').show();
  },

  validate: function() {
    if($$('.task').size() <= 0) {
      alert('A project must have at least one task.');
      return false;
    }
    return true;
  },

  activate_search_box: function(active) {
         if(active) {
             $('search_terms').removeClassName('inactive');
             $('search_terms').addClassName('active');
         } else {
             $('search_terms').removeClassName('active');
             $('search_terms').addClassName('inactive');
         }
     },

    skip_search_complete: false,
    search: function(element, value) {
        if(project_mgr.scheduled_search) clearTimeout(project_mgr.scheduled_search);

        var search_active = !(value.blank() || value == DefaultFieldValues.getDefaultFor($('search_terms')));
        project_mgr.activate_search_box(search_active);
        if(!search_active){
          if($('project_search_results').visible() || $('project_search_loading').visible()) {
            project_mgr.exit_search(false);
          }
          return;
        }
        project_mgr.search_loading();
        var search_pause = 1.1;
        project_mgr.scheduled_search =
        setTimeout( function() {
            new Ajax.Updater('project_search_results', '/projects/sphinx_search',
            {  asynchronous:true,
                evalScripts:true,
                onLoading: project_mgr.search_loading,
                onComplete: project_mgr.search_completed,
                insertion: function(receiver, text) {
                        if($('search_terms').value == value) {
                            receiver.update(text);
                            project_mgr.skip_search_complete = false;
                        } else {
                            project_mgr.skip_search_complete = true;
                        }
                },
                parameters:"search_terms=" + encodeURIComponent(value) });
        }, search_pause*1000);
    },

    search_loading: function() {
        $('project_search_loading').show();
        $$('#project_search_description, #add_project_controls, #archived_project_link').invoke('hide');
        $('active_projects_rows').addClassName('inactive');
        $('project_search_results').addClassName('inactive')
    },

    search_completed: function() {
        if(!project_mgr.skip_search_complete) {
          $$('#active_projects_rows, #project_search_loading').invoke('hide');
          $$('#project_search_results, #project_search_description').invoke('show');
          if(project_mgr.continuous_scroller) { project_mgr.continuous_scroller.stopObserving(); }
          project_mgr.continuous_search_scroller.resumeObserving();
          $('project_search_results').removeClassName('inactive')
        }
    },

    exit_search: function(reset_value) {
        $('active_projects_rows').removeClassName('inactive');
        project_mgr.activate_search_box(false);
        $$('#active_projects_rows, #add_project_controls, #archived_project_link').invoke('show');
        $$('#project_search_results, #project_search_description, #project_search_loading').invoke('hide');
        if(reset_value) { $('search_terms').value = DefaultFieldValues.getDefaultFor($('search_terms')); }
        project_mgr.continuous_search_scroller.stopObserving();
        if(project_mgr.continuous_scroller && $('last_client')){ project_mgr.continuous_scroller.resumeObserving(); }
    },

    after_archive_from_search: function(row_id) {
      $(row_id).childElements().reject(function(c) {
        return c.hasClassName("confirmation");
      }).invoke('show');

      $(row_id).childElements().reject(function(c) {
        return (!c.hasClassName("confirmation"));
      }).invoke('hide');

    }

};

Object.extend(project_mgr, Currency);








/****************************************************************/
/*  original filename task.js                        */
/****************************************************************/


var task = {
  toggle_editor: function(id, is_billable_by_default, is_default_task) {
    if($('task-' + id + '-show').visible()) {
      $('task-' + id + '-show').hide();
      if($('task-' + id + '-edit')) {
	      $('task-' + id + '-edit').show();
      } else {
	      var root = $('task-' + id);
	      var name = root.down('.name').innerHTML;
	      var rate_obj = root.down('.rate');
	      var rate = rate_obj ? rate_obj.innerHTML : '';
	      var template = $('task_inline_editor_template').innerHTML;
	      root.insert({ bottom:
		      template.gsub(/---TASK ID---/, id).
		      gsub(/---TASK NAME---/, name).
		      gsub(/---TASK DEFAULT HOURLY RATE---/, rate)});
	      $('task-' + id + '-show').hide();
	      if(is_billable_by_default) {
	        $('task-'+ id + '-billable-by-default').checked = true;
	      }
	      if(is_default_task) {
	        $('task-'+ id + '-is-default').checked = true;
	      }
	      $('task-' + id + '-edit').show();
      }
      $('task-' + id + '-edit').down('.task_name').activate();
    } else {
      $('task-' + id + '-show').show();
      $('task-' + id + '-edit').hide();
    }
    return false;
  },

  delete_text_prompt: function(id){
    var name = $('task-' + id).down('.name').innerHTML;
    var prompt = "Would you like to remove the task <strong>";
    prompt += name;
    prompt += "</strong>?";
    prompt += "<br />";
    prompt += "(Once you remove it, the task will also be removed from all the projects it is associated with.)";
    return prompt;
  },

  delete_inline_confirmation: function(id){
    new InlineConfirmation('task-' + id,
			   'task-' + id,
			   '/tasks/' + id,
			   { promptText: task.delete_text_prompt(id),
			     method: 'delete',
			     linkToAjax: true,
			     confirmApproveLoadingText: 'Deleting ...' });
  },

  activate_inline_confirmation: function(id, name){
    var prompt = 'Would you like to reactivate <em>' + name + '</em>';
    new InlineConfirmation('task-' + id, 'task-' + id, '/tasks/' + id + '/activate',
			   { promptText: prompt, method: 'post', linkToAjax: true, confirmApproveLoadingText: 'Activating ...' });
  }

};
/****************************************************************/
/*  original filename continuous_scroller.js                        */
/****************************************************************/



var ContinuousScroller = Class.create({
    initialize: function(url, inputIds, updateId, method) {
        this.url = url;
        this.inputIds = inputIds;
        this.updateId = updateId;
        this.method = method;
        this.loading = false;
        this.stopped = false;
        Event.observe(window, 'scroll', this.onScroll.bindAsEventListener(this));
    },
    onScroll: function(){
        if(this.stopped){ return false; };
        var docView, pxToTop, docHeight;
        //Get viewport's scroll offsets
        docView = document.viewport.getScrollOffsets();
        //Sum top offset and viewport height
        pxToTop = docView.top + document.viewport.getHeight();
        if(Prototype.Browser.IE) {
          docHeight = document.body.clientHeight;
        } else {
          docHeight = this.getDocHeight();
        }
        if (pxToTop >= docHeight) {
            if (!this.loading) {
                this.loading = true;
                var paramString = '';
                $$(this.inputIds).each(function(inp){
                    if(!paramString.blank()) { paramString += '&'; };
                    paramString += inp.readAttribute('name') + '=';
                    paramString += encodeURIComponent(inp.value);
                });
                new Ajax.Updater(this.updateId, this.url,{
                    asynchronous:true,
                    insertion: 'bottom',
                    evalScripts:true,
                    method:this.method,
                    onComplete:  this.onComplete.bind(this),
                    onLoading:  this.onLoading.bind(this),
                    parameters: paramString
                });
                return false;
            }
        }
    },
    onLoading: function() { $('loading').show(); },
    onComplete: function() {
        $('loading').hide();
        setTimeout(function(){ this.loading = false; }.bind(this), 350);
    },
    stopObserving: function() { this.stopped = true; },
    resumeObserving: function() { this.stopped = false; },
    getDocHeight: function() {
      var D = document;
      return Math.max(
          Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
          Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
          Math.max(D.body.clientHeight, D.documentElement.clientHeight)
      );
    }
});

/****************************************************************/
/*  original filename salaryman.js                        */
/****************************************************************/


// general purpose function to check / uncheck all checkboxes on a page
function checkUncheckAll(theForm, value) {
  var z = 0;
  for(z=0; z<theForm.length;z++) {
    if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall'){
      theForm[z].checked = value;
    }
  }
}

// general purpose function to check / uncheck all checkboxes with the given class
function checkUncheckAllByClass(class_name, value) {
  $$('input[type=checkbox][class*=' + class_name + ']').each(function(e) {
    e.checked = value;
  });
}

// update URL in sign up screen
function updateUrl(subdomain) {
  $('url_name').innerHTML = subdomain + ".harvestapp.com";
}

// suggests a subdomain based on their company name
function suggestSubdomain() {
    if($F('company_subdomain').blank()) {
      var company_name = document.getElementById('company_name').value;
      var subdomain  = company_name.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
      $('company_subdomain').value = subdomain;
    }
    new Ajax.Updater('subdomain_warning',
                     '/account/check_subdomain',
    { asynchronous:true, evalScripts:true, parameters:'sub_domain=' + $('company_subdomain').value });
}

// basically the same funciton as "suggestSubdomain" ... but defaults to a companies current subdomain instead of guessing at one.
function changeSubdomainCheck() {
    $('url_check_status').removeClassName('bad-sub');
    $('url_check_status').removeClassName('good-sub');

    if($F('company_subdomain').blank()) {
      $('company_subdomain').value = $F('company_original_subdomain');
    }

    if($F('company_subdomain')==$F('company_original_subdomain')) $('submit_url').disabled = false;
    else $('submit_url').disabled = true;

    $('url_check_status').innerHTML = '<img src="/images/check_sub_loader.gif" />Checking Availability';
    $('url_check_status').show();
    new Ajax.Updater('subdomain_warning',
                     '/account/check_subdomain',
    { asynchronous:true, evalScripts:true, parameters:'sub_domain=' + $('company_subdomain').value, onComplete:cleanUpSuggestSubdomain });
}
function cleanUpSuggestSubdomain(){
  var error_box = $('url_check_status');
  if($('subdomain_warning').innerHTML==""){
    error_box.innerHTML = "Available";
    error_box.addClassName('good-sub');
    $('submit_url').disabled = false;
  }
  else{
    error_box.innerHTML = "Not Available";
    error_box.addClassName('bad-sub');
  }
}

function enableSubmit(checkbox) {
  $('submit_button').disabled = !checkbox.checked;
}

// no need for spam!
function send_email(name, subject) {
  domain = "getharvest.com";
  document.location = "mailto:" + name + "@" + domain + "?subject=" + subject;
}

// shows support getharvest
function print_support_email() {
  xor_decode(":g&ntc`;$kgojri<usvvitrFngtpcurgvv(eik$8usvvitrFngtpcurgvv(eik:)g8");
}

function send_privacy_email() {
  xor_decode(":g&ntc`;$kgojri<vtopgeFacrngtpcur(eik(eik9sdlcer;Vtopge#46Vijoe#46Wscuroihu$8vtopgeFacrngtpcur(eik:)g8");
}

function send_support_email() {
  xor_decode(":g&ntc`;$kgojri<usvvitrFngtpcurgvv(eik9Usdlcer;NGTPCUR#46Usvvitr$8Rgjm&ri&su:)g8");
}

function send_tos_email() {
  xor_decode(":g&ntc`;$kgojri<riuFacrngtpcur(eik9Usdlcer;RIU#46wscuroihu$8riuFacrngtpcur(eik:)g8");
}

function xor_decode(guymal_enc){
  for(var guymal_i=0;guymal_i<guymal_enc.length;++guymal_i) {
    document.write(String.fromCharCode(6^guymal_enc.charCodeAt(guymal_i)));
  }
}

/*** short cuts to BlindDown & BlindUp, same speed throughout site ***/

function move_div_down(name) {
  new Effect.BlindDown(name, {duration: 0.3});
//  new Element.show(name);
}

function move_div_up(name) {
  new Effect.BlindUp(name, {duration: 0.2});
//  new Element.hide(name);
}

/*** shortcut to the specific movements ***/

// all inline divs (small forms) should use the same way to show up
function show_inline_div(name) {
  move_div_down(name);
}

function hide_inline_div(name) {
  move_div_up(name);
}

// show main divs, such as adding a project
// optional field_name for setting focus
function show_big_div(name, field_name) {
  Element.show(name);
    if(field_name) {
      setTimeout(function() {
        $(field_name).activate();
      }, 100);
    }
}

function hide_big_div(name) {
  move_div_up(name);
}

function move_edit_div() {
  //Element.toggle('project_display_form');
  new Effect.BlindDown('project_info_form', {duration: 0.3});
}
function hide_edit_div() {
  //Element.toggle('project_display_form');
  new Effect.BlindUp('project_info_form', {duration: 0.3});
}

function toggle_inactive(user_type) {
  $(user_type + '_inactive_link', user_type + '_inactive_list').invoke('toggle');
}

function toggle_help_box() {
  $('help_box_tip_control').toggle();
  $('helpbox').toggle();
  toggle_page_tips();
}

function toggle_page_tips() {
  $('page_tips').toggle();
  if($('page_tips').visible()) {
    var link_element = $$('#page_tips a').first();
    new Effect.Highlight(link_element);
  }
}

// A port of our ApplicationHelper#button method, to spit out proper markup for a
// stylized button.
function button(size, color, markup) {
  var button_markup = [];
  button_markup.push("<span class='btn btn-" + size + "-" + color + "'>");
  button_markup.push(markup);
  button_markup.push("</span>");
  return button_markup.join("");
}

// This checks for enter key (for submitting a JS-only form, typically), but
// allows for shift-enter/alt-enter to input multiple lines on a textarea.
function check_enter_with_text_area_features(event) {
  var element_type = event.element().type;
  return  (element_type != "textarea" && event.keyCode == Event.KEY_RETURN) ||
          (event.keyCode == Event.KEY_RETURN && !(event.shiftKey || event.altKey));

}

// gsub pattern is taken from Rails' ApplicationHelper#html_textilize. Propagate any
// changes to there.
function html_textilize(str) {
  var textilized_string = str.stripTags();
  textilized_string     = textilized_string.gsub(/(^|[^0-9A-Za-z])\*(.+?)\*($|[^0-9A-Za-z])/, function(match) {
    return match[1] + '<b>' + match[2] + '</b>' + match[3];
  }).gsub(/(^|[^0-9A-Za-z])\_(.+?)\_($|[^0-9A-Za-z])/, function(match) {
    return match[1] + '<i>' + match[2] + '</i>' + match[3];
  });
  return "<p>" + textilized_string.split(/\n+/).join("</p><p>") + "</p>";
}

function warning_callout(error_element, text) {
  error_element = $(error_element);
  var warning_markup = '<div class="callout_warning_container"><div class="callout_warning_top"><div class="callout_warning">' + text + '</div></div></div>';
  error_element.insert({after: warning_markup});
  // error_element.observe('keyup', fade_warning_callout);
  Element.observe.delay(0.5, error_element.id, 'keyup', fade_warning_callout);
}

function fade_warning_callout(event) {
  var element = event.element();
  var callout_warning_container = element.next('.callout_warning_container');
  callout_warning_container.fade();
  element.stopObserving('keyup');
}

// For left-padding a string with a character. Usually for working with numbers
// and padding with zero.
String.prototype.pad = function(character, length) {
  length = parseInt(length);
  return String(character.repeat(length) + this).slice(-length);
};

String.prototype.repeat = function(times) {
  times = parseInt(times);
  return (new Array(times+1)).join(this);
};

Element.addMethods({
    getHtml: function(element) {
        if ("outerHTML" in document.body) {
            return element.outerHTML;
        }
        var tmp = new Element("div").update(element.cloneNode(true));
        var html = tmp.innerHTML;
        delete tmp;
        return html;
    }
});



/****************************************************************/
/*  original filename time.js                        */
/****************************************************************/


// See Date JS documentation: http://code.google.com/p/datejs/wiki/APIDocumentation
// This is pretty much a class with only class methods. There were originally
// bigger plans for it, but...

var Time = Class.create({
  initialize: function() {
    ;
  }
});


// Class methods

// Add new case to add new time formats.
Time.toString = function(date, format, related_time) {
  switch(format) {
    case "24hour":
      return Time.toFormattedString(date, "H:mm");
    case "24hourZeroFilled":
      return Time.toFormattedString(date, "HH:mm");
    default:  // normalized
      return Time.toFormattedString(date, "h:mmtt", related_time).toLowerCase();
  }
}

Time.toFormattedString = function(date, format, related_time) {
  if("string" == typeof(date)) {
    if(date.blank())  return "";
    var date_ = Time.naturalParse(date, related_time);
    if(null == date_)  date_ = new Date;
    var date_string = date_.toString(format);
    delete date_;
  } else {
    var date_string = date.toString(format);
  }
  return date_string;
}

Time.naturalParse = function(date_string, related_date_string) {
  date_string = date_string.gsub(/\.|,/, ':');

  var match = date_string.match(/(\d{3,4})/);
  if(match) {
    var original_time    = match[1];
    var original_minutes = original_time.substring(original_time.length-2, original_time.length);
    var normalized_time  = original_time.replace(new RegExp(original_minutes + '$'), ":" + original_minutes);
    date_string          = date_string.replace(original_time, normalized_time);
  }

  if(date_string.match(/a|p/)) {
    return Date.parse(date_string);
  } else {
    match = date_string.match(/^(\d{1,2})/);
    if(match) {
      var hour_part = parseInt(match[1]);
      if(hours.wants_24h_time) {
        var median = (hour_part <= 11) ? 'am' : 'pm';
      } else {
        if(undefined == related_date_string) {
          var median = (7 <= hour_part && hour_part <= 11) ? 'am' : 'pm';
        } else {
          var related_match = related_date_string.match(/^(\d{1,2}):\d{2}(.+)/);
          var related_hour_part = parseInt(related_match[1]);
          var related_median = related_match[2];
          var median = hour_part >= related_hour_part ? related_median : Time.inverseMedian(related_median);
        }
      }
      date_string   = date_string + median;
    }
  }

  return Date.parse(date_string);
}

Time.inverseMedian = function(median) {
  return median.match(/a/) ? 'pm' : 'am';
}





/****************************************************************/
/*  original filename timesheet.js                        */
/****************************************************************/


var timesheet = {
  cpts_prefix: 'cpts_',
  register_daily_timesheet_handlers: function() {
    $$('input.edit_time, textarea.edit_time').each(function(e){
      e.observe('keydown', timesheet.check_enter_submit_update);
      e.observe('focus', timesheet.remove_tentative_class);
    });
    $$('input.add_time, textarea.add_time').each(function(e){
      e.observe('keydown', timesheet.check_enter_submit_create);
      e.observe('keyup', timesheet.check_for_hours_entered);
    });
    timesheet.check_for_hours_entered();
  },

  register_background_save: function() {
    new PeriodicalExecuter(timesheet.save, 10);
  },

  register_on_change_handlers: function() {
    var children = $('project_task_rows').getElementsByTagName('input');
    for( var i = 0; i < children.length; i++) {
      if ('text' == children[i].type.toLowerCase()) {
        children[i].onchange = timesheet.recompute_sums;
        children[i].onkeypress = timesheet.disable_enter_key;
      }
    }
    timesheet.recompute_sums();
    timesheet.needs_saving = false;
    timesheet.save();
    timesheet.disable_save_progress_button();
  },

  disable_enter_key: function(e){
    e = e || window.event;
    if( (typeof e != 'undefined') && e.keyCode == 13){
      e.cancelBubble = true;
      e.returnValue = false;
      return false;
    }
    return true;
  },

  year: '',
  yday: '',
  first_day_in_time_period: '',
  year_of_first_day_in_time_period: '',
  needs_saving: false,
  clients: {},
  first_project_id: 0,
  first_task_id: 0,
  daily_stopwatch_timer_func: '',
  daily_stopwatch_timer_running_id: '',

  // stops currently running timer
  stop_timer: function() {
    clearInterval( timesheet.daily_stopwatch_timer_func );
    timesheet.daily_stopwatch_timer_func = '';
    timesheet.daily_stopwatch_timer_running_id = '';
  },

  timer_value: 0,

  start_timer: function(day_entry_id){
    if( day_entry_id != ''){
      //invoke every 36 seconds = 0.01 hour
      timesheet.daily_stopwatch_timer_func = setInterval(function() { timesheet.update_active_timer(day_entry_id);}, 36000);
      timesheet.daily_stopwatch_timer_running_id = day_entry_id.toString();
      timesheet._set_timer_value(day_entry_id);
    }
  },

  _set_timer_value: function(day_entry_id) {
    timesheet.timer_value = hours.convert_time_to_float($('timer_link_' + day_entry_id).innerHTML);
  },

  //called every 36 seconds
  update_active_timer: function(day_entry_id) {
    var active_hours_counter = $('timer_link_' + day_entry_id);
    if( undefined == active_hours_counter || null == active_hours_counter){
      // entry was deleted clean up timer as well
      timesheet.stop_timer();
      return;
    }
    timesheet.timer_value += 0.01;    // add 36 seconds
    var new_value = hours.display_time(timesheet.timer_value);
    timesheet._update_timer_displays(day_entry_id, new_value);
    if(active_hours_counter.visible() && $('day_entry_' + day_entry_id + '_hours')) {
      $('day_entry_' + day_entry_id + '_hours').value = new_value;
    }
    if($('total_duration')){
      timesheet.recompute_day_entry_sums();
    }
  },

  zero_filled_array: function(length){
    var array = new Array(length);
    for( var i = 0; i < length; i++) {
      array[i]=0;
    }
    return array;
  },

  compute_row_and_column_sums: function(){
    var children = $('project_task_rows').getElementsByTagName('input');
    // let's use y days a week as an assumption
    var DAYS_IN_TIME_PERIOD = 7;

    var rowSum = timesheet.zero_filled_array(children.length/DAYS_IN_TIME_PERIOD);
    var colSum = timesheet.zero_filled_array(DAYS_IN_TIME_PERIOD);
    var totalSum = 0;
    var rowPos = 0;
    var colPos = 0;

    // start after the first "prototype" row
    for( var i = DAYS_IN_TIME_PERIOD; i < children.length; i++) {
      if (!hours.zero(children[i].value)) {
        //avoid rounding errors ie: 3355.53 + 660.97 - 660.97 = 3355.5299999999997
        var child_value = hours.parse_as_float(children[i].value) * 100;
        rowSum[rowPos] = rowSum[rowPos] + child_value;
        colSum[colPos] = colSum[colPos] + child_value;
        totalSum = totalSum + child_value;
      }

      colPos++;
      // end of period, get id for output purposes and increase/reset counters
      if (colPos == DAYS_IN_TIME_PERIOD) {
        var match_res = children[i].id.match(/^day\d+_project(\d+)_task(\d+)$/);
        if (match_res.length == 3) {
          var project_id = match_res[1], task_id = match_res[2];
          $('sum_' + row_name(project_id, task_id)).innerHTML = hours.display_time(rowSum[rowPos] / 100);
        }
        colPos = 0;
        rowPos++;
      }
    }
    // update the total row
    $('sum_total').innerHTML = hours.display_time(totalSum / 100);

    for (i = 0; i <DAYS_IN_TIME_PERIOD; i++) {
      $('sum_day' + timesheet.day_of_year(i)).innerHTML = (colSum[i] != 0 ? hours.display_time(colSum[i] / 100) : "<span class=\"zero\">0</span>");
    }
  },

  recompute_sums: function() {
    if(this.id && this.id.match(/^day\d+_project\d+_task\d+/)){
      $('changed_fields').value += ',' + this.id;
      var temp_value = hours.convert_time_to_float(this.value);

      //let's make sure if there are too many decimal places, trim it down to 2
      var myFactor =  Math.pow(10, 2);
      temp_value =  Math.round(temp_value * myFactor) / myFactor;
      this.value = hours.display_time(temp_value);
    }

    timesheet.needs_saving = true;
    if (false == timesheet.save_in_progress){
      timesheet.enable_save_progress_button();
    }
    timesheet.compute_row_and_column_sums();
  },

  day_of_year: function(i){
    var year = timesheet.year_of_first_day_in_time_period;
    var days_in_this_year = 337 + (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
    var day_of_year = timesheet.first_day_in_time_period + i;
    if (day_of_year <= days_in_this_year){
      return day_of_year;
    } else{
      return day_of_year - days_in_this_year;
    }
  },

  // bh - We have a better template version of the code, but it performs horribly on IE7. It's stored
  // in git (git show bd765bf3d61281371716797dad89591f807a9b85:public/javascripts/timesheet.js)
  //
  // bh - trailing_tab_index param is so the selectors can construct themselves with the proper tab index.
  // It should contain the tab index for the form field directly following these selectors.
  // This is a bit wonky, but necessary.
  construct_project_task_selector: function(prefix, selected_project_id, selected_task_id, trailing_tab_index) {
    var project_html = ["<select class='tasks_select' id='" + prefix + "project_selector' name='project' onchange=\"timesheet.show_tasks_for_project(this.options[this.selectedIndex].value, '" + prefix + "');\" tabindex='" + (trailing_tab_index-2) + "'>"];
    var task_html = [];
    for (var client_i = 0, clients_length = timesheet.clients.length; client_i < clients_length; client_i++){
      var client = timesheet.clients[client_i];
      project_html.push("<optgroup label='", client.name.gsub(/'/, '&#39;'), "'>");
      for (var project_i = 0, projects_length = client.projects.length; project_i < projects_length; project_i++){
        var project = client.projects[project_i];
    project_html.push("<option value='", project.id, "'");
        task_html.push("<select class='tasks_select' id='", prefix, "project", project.id, "_task_selector' name='tasks_4_project", project.id, "' tabindex='" + (trailing_tab_index-1) + "'");
        if(project.id == selected_project_id){
          project_html.push(" selected='selected'");
        } else {
          task_html.push(" style='display:none' disabled='true'");
        }
        project_html.push(" >", project.name, "</option>");
        task_html.push(">");
        var task_group = [[project.billable_tasks, 'Billable'], [project.non_billable_tasks, 'Non-billable']];
        for(var i=0; i<2; i++){
          var tasks = task_group[i][0];
          var tasks_length = tasks.length;
          if(tasks_length > 0){
            var label = task_group[i][1];
            task_html.push("<optgroup label='", label, "'>");
            for (var task_i = 0; task_i < tasks_length; task_i++){
              var task = tasks[task_i];
              task_html.push("<option value='", task.id, "' ",
                             ((project.id == selected_project_id && task.id == selected_task_id) ? "selected='selected'" : ""),
                             ">", task.name, "</option>");
            };
            task_html.push("</optgroup>");
          }
        };
        task_html.push("</select>");
      };
    };
    project_html.push("</select>");
    if (prefix == '') {
      //no extra formatting for prefixless case (used by add_form)
      return project_html.concat(task_html).join("");
    }
    project_html.push("<br />");
    return project_html.concat(task_html).join("");
  },

  pre_select_project_task_selector: function(prefix, project_task){
    project_task = $A(project_task);
    if(project_task.size() != 2)
      return;
    var project_id = project_task.first();
    var task_id = project_task.last();
    var project_selector = $('' + prefix + "project_selector");
    var not_disabled = function(option){
      return option.disabled == false;
    };
    if(!project_selector.select('option[value="' + project_id + '"]').any(not_disabled))
      return;
    project_selector.value = project_id;
    timesheet.show_tasks_for_project(project_id, prefix);
    var task_selector = $('' + prefix + "project" + project_id + "_task_selector");
    if(!task_selector.select('option[value="' + task_id + '"]').any(not_disabled))
      return;
    task_selector.value = task_id;
  },

  show_add_tasks: function() {
    $('add_form').show();
    $('add_day_entry_link').addClassName('disabled');
    $('add_day_entry_link').disable();
    if($('project_selector'))
      $('project_selector').focus();
  },

  hide_add_tasks: function() {
    $('add_form').hide();
    $('add_day_entry_link').removeClassName('disabled');
    $('add_day_entry_link').enable();
  },

  add_row: function() {
    var result = timesheet.selected_project_id__project_name__client_name();
    var project_id = result[0];
    var project = result[1];
    var client = result[2];
    result = timesheet.selected_task_id__task_name(project_id);
    var task_id = result[0];
    var task = result[1];
    var the_row = row_name(project_id, task_id);
    timesheet.enable_submit_button();
    if ( null == $(the_row)) {
      // This is not optimal: in order to avoid errors in the generated JS, we need to replace two versions of the
      // client/project/task names: one with quotes replaced and one with quotes untouched. Even worse, the type of
      // quoting replacement we use is different--one is an html entity, and one is backslash-escaped!
      function dequote(raw_string) { return raw_string.replace("'", "\\'").replace('"', '&quot;'); }
      var row_code = "<tr id=\"projectPROJECTID_taskTASKID\">" + $('projectPROJECTID_taskTASKID').innerHTML + "</tr>";
      row_code = row_code.replace(/PROJECTID/g, project_id).replace(/TASKID/g, task_id);
      row_code = row_code.replace(/CLIENT_ESC/g, dequote(client)).replace(/PROJECT_ESC/g, dequote(project)).replace(/TASK_ESC/g, dequote(task));
      row_code = row_code.replace(/CLIENT/g, client).replace(/PROJECT/g, project).replace(/TASK/g, task);
      new Insertion.Before('add_form', row_code);
      var row_id = "project" + project_id + "_task" + task_id;
      new Effect.Highlight($(row_id));
      timesheet.register_on_change_handlers();
      timesheet.needs_saving = true;
      $('changed_fields').value += ',' + $A($(the_row).getElementsByTagName('input')).pluck('id').join(',');
    } else {
      alert(project + '\'s \"' + task + '\" task was already added!');
    }
  },

  save_in_progress: false,

  remove_row: function(user_id, project_id, task_id, name) {
    if (confirm("Delete all entries to '"+ name + "' from the current time period?")) {
      if (false == timesheet.save_in_progress) {
        timesheet.save_in_progress = true;
        var the_row = row_name(project_id, task_id);
        var url = '/entry/remove_row?yday_begin=' + timesheet.first_day_in_time_period;
        url += '&year_begin=' + timesheet.year_of_first_day_in_time_period;
        url += '&project=' + project_id + '&task=' + task_id + '&of_user=' + user_id;
        Effect.Fade(the_row, { afterFinish: function() {
              Element.remove(the_row);
              timesheet.recompute_sums();
              new Ajax.Request(url, {asynchronous:true, evalScripts:true, onComplete:function(request){ timesheet.save_in_progress = false; } });},
              duration: 0.40});
      } else {
        alert('Background save in progress, please wait a while and retry!');
      }
    }
  },

  disable_save_progress_button: function() {
    // var save_progress_button = $('save-progress-button');
    // save_progress_button.disabled = 'true';
  },

  enable_save_progress_button: function() {
    // var save_progress_button = $('save-progress-button');
    // save_progress_button.disabled = '';
  },

  save: function(custom_after_save) {
    if ( (true == timesheet.needs_saving) && (false == timesheet.save_in_progress)) {
      timesheet.save_in_progress = true;
      timesheet.disable_save_progress_button();
      $('save-indicator').innerHTML = 'saving ...';
      var changed_fields_length = $F('changed_fields').length;
      new Ajax.Request('/entry/save', { evalScripts:true, asynchronous:true, parameters:Form.serialize('timesheet-form'), onComplete: function (request){
            timesheet.save_in_progress = false;
            if(request.status == 200){
              var now = new Date();
              if(request.responseText.match(/^\s*$/)){
                $('save-indicator').innerHTML = 'Last saved at: ' + now.getHours() + ':' + checkTime(now.getMinutes());
                timesheet.enable_submit_button();
                if (typeof custom_after_save == 'function') {
                  custom_after_save();
                }
                $('changed_fields').value = $F('changed_fields').substring(changed_fields_length + 1);
              } else{
                $('save-indicator').innerHTML =  '';
              }
              timesheet.needs_saving = $F('changed_fields').length != 0;
            } else {
              $('save-indicator').innerHTML =  '';
            }
          }
        });
    } else {
      if((false == timesheet.save_in_progress ) && (false == timesheet.needs_saving) && (typeof custom_after_save == 'function')){
        custom_after_save();
      }
    }
    return false;
  },

  // Submits an entry form for a full review process through /daily/review.
  submit_for_full_review: function() {
    var params = {
      of_user: timesheet.current_user_id,
      submitted_date: (new Date().yday()),
      submitted_date_year: (new Date().year()),
      period_begin: timesheet.first_day_in_time_period,
      period_begin_year: timesheet.year_of_first_day_in_time_period,
      authenticity_token: window._token
    };
    return timesheet._submit_timesheet_form('/daily/review', params);
  },

  // Submits an entry form for an expenses review process through /daily/review.
  submit_for_approval: function() {
    var params = {
      of_user: timesheet.current_user_id,
      submitted_date: (new Date().yday()),
      submitted_date_year: (new Date().year()),
      period_begin: timesheet.first_day_in_time_period,
      period_begin_year: timesheet.year_of_first_day_in_time_period,
      expenses_only: 'true',
      authenticity_token: window._token
    };
    return timesheet._submit_timesheet_form('/daily/review', params);
  },

  // Submits an entry form with no review.
  submit_timesheet: function() {
    var params = {
      of_user: timesheet.current_user_id,
      submitted_date: ((new Date()).to_url_string()),
      period_begin: timesheet.first_day_in_time_period,
      period_begin_year: timesheet.year_of_first_day_in_time_period,
      authenticity_token: window._token
    };
    return timesheet._submit_timesheet_form('/daily/submit', params);
  },

  _submit_timesheet_form: function(form_action, submit_params) {
    /* First do a real save then submit a dummy review form on complete */
    timesheet.save(function(){
      var submit_form = document.createElement('form');
      submit_form.style.display = 'none';
      $('mainbody').appendChild(submit_form);
      submit_form.method = 'POST';
      submit_form.action = form_action;
      $H(submit_params).each(function(pair) {
          var m = document.createElement('input');
          m.setAttribute('type', 'hidden');
          m.setAttribute('name', pair.key); m.setAttribute('value', pair.value);
          submit_form.appendChild(m);
        });
      // defer submit till DOM updates are taken into account.
      (function(){submit_form.submit();}).defer();
    });
    return false;
  },

  unlock: function() {
    if (confirm('Are you sure you want to unlock this timesheet and allow editing?')) {
      var frm = $('timesheet-form');
      frm.action = '/entry/unlock/';
      frm.submit();
    }
  },

  unlock_daily: function() {
    if (confirm('Are you sure you want to unlock this timesheet and allow editing?  This will unlock the entire week this day is associated with.\n\nRe-approve this timesheet to lock the hours when you are done.')) {
      var frm = $('daily_form');
      frm.action = '/entry/unlock/';
      frm.submit();
    }
  },

  selected_task_id__task_name: function (project_id) {
    var results = [];
    var task_selector = $('project' + project_id + '_task_selector');
    var selected_option = task_selector.options[task_selector.selectedIndex];
    results.push(selected_option.value);
    results.push(selected_option.innerHTML);
    return results;
  },

  selected_project_id__project_name__client_name: function() {
    var results = [];
    var project_selector = $('project_selector');
    var selected_option = project_selector.options[project_selector.selectedIndex];
    results.push(selected_option.value);
    results.push(selected_option.innerHTML);
    results.push(selected_option.parentNode.label);
    return results;
  },

  show_tasks_for_project: function(project_id, prefix) {
    var new_tasks_selector = $('' + prefix + 'project' + project_id + '_task_selector');
    var filter = new RegExp('^' + prefix + 'project\\d+_task_selector$');
    $$('.tasks_select').each(
        function(e) {
          if (Element.visible(e) && e.id.match(filter)) {
            e.style.display = 'none';
            e.disabled = 'true';
            new_tasks_selector.style.display = '';
            new_tasks_selector.disabled = '';
          }
        }
      );
  },

  day_entry_delete: function(day_entry_id){
    var of_user_id = timesheet.current_user_id;
    if(timesheet.daily_stopwatch_timer_running_id == day_entry_id)
      timesheet.stop_timer();
    $("day_entry_row_" + day_entry_id).remove();
    var confirm_row_element_id = "delete_" + day_entry_id + "_confirm_row";
    var confirm_fade_duration  = 0.5;
    $(confirm_row_element_id).fade({duration: confirm_fade_duration});
    Element.remove.delay(confirm_fade_duration + 0.1, confirm_row_element_id);
    timesheet.recompute_day_entry_sums();
    new Ajax.Request( '/daily/delete/' + day_entry_id + '?of_user=' + of_user_id, {asynchronous:true, evalScripts:true });
  },

  recompute_day_entry_sums: function(){
    var sum = 0;
    $$('.day_entry_hours').each(function(element) {
      sum += hours.convert_time_to_float(element.innerHTML);
    });
    $('total_duration').innerHTML = hours.display_time(sum);
  },

  current_edited_id: '',

  // toggles the edit day entry fields
  toggle_day_entry_editor: function(id, locked_day_entry) {
    if (timesheet.current_edited_id == id || timesheet.current_edited_id == '') {
      timesheet.current_edited_id = id;
      timesheet.toggle_day_entry_editor_non_interactive(id, locked_day_entry);
      if(Element.visible('timer_link_' + id)){
        timesheet.current_edited_id = '';
      }
      var cpt_control_id = 'client_project_task_controls_' + id;
      if((Prototype.Browser.IE7 || Prototype.Browser.IE8) && $(cpt_control_id).visible()) {
        $$('#' + cpt_control_id + ' select.tasks_select').each(function(sel) {
          new IEDropdown(sel);
        });
      }
    } else {
      timesheet.toggle_day_entry_editor_non_interactive(timesheet.current_edited_id, locked_day_entry);
      $('day_entry_' + timesheet.current_edited_id + '_notes').value
        = $('notes_for_' + timesheet.current_edited_id).innerHTML.unescapeHTML();
      if(!timesheet._has_timestamp_timers()) {
        $('day_entry_' + timesheet.current_edited_id + '_hours').value
          = $('timer_link_' + timesheet.current_edited_id).innerHTML.unescapeHTML();
      }
      timesheet.current_edited_id = id;
      timesheet.toggle_day_entry_editor(id);
      timesheet.recompute_day_entry_sums();
    }
  },

  toggle_day_entry_editor_non_interactive: function(id, locked_day_entry){
    $w('timer_link edit_hours notes_for edit_notes day_entry_controls edit_day_entry_controls').invoke('concat', '_', id).map(function(t){return $(t);}).invoke('toggle');
    if(locked_day_entry) {
      timesheet._edit_row_readonly_off(id);
      timesheet._activate_day_entry_hours_if_present(id);
      return;
    }
    var cpt = $('client_project_task_' + id);
    var cpt_control = $('client_project_task_controls_' + id);
    //zsombor: IE is very picky about executing functions on hidden-by-ancestor
    //         elements
    if(cpt.visible() && Element.visible('edit_hours_' + id)) {
      AutoExpandTextArea.updateSize($('day_entry_' + id + '_notes'));
      timesheet._edit_row_readonly_off(id);
      var project_id_task_id = cpt_control.innerHTML.split('.');
      var trailing_tab_index = timesheet.find_trailing_tab_index_for_timesheet_row('day_entry_row_' + id);
      cpt_control.update(timesheet.construct_project_task_selector(timesheet.cpts_prefix + id, project_id_task_id[0], project_id_task_id[1], trailing_tab_index));

      
      // bh - make for really sure that in Chrome the correct task value is selected in dropdown. I suspect
      // this Chrome bug could be resolved with construct_project_task_selector working with OPTION objects
      // rather than just shoving in the HTML directly for the select boxes. TODO later.
      var task_selector = $('cpts_' + id + 'project' + project_id_task_id[0] + '_task_selector');
      if(task_selector)  task_selector.value = project_id_task_id[1];

      timesheet._activate_day_entry_hours_if_present(id);
    } else {
      timesheet._edit_row_readonly_on(id);
      if(id != '') { id = timesheet.cpts_prefix + id; }
      var project_id = $('' + id + 'project_selector').value;
      var task_id = $('' + id + 'project' + project_id +'_task_selector').value;
      cpt_control.update('' + project_id + '.' + task_id);
    }
    [cpt_control, cpt].invoke('toggle');
  },

  toggle_day_entry_failed_update_row: function(id) {
    $('day_entry_controls_' + id).down('.loading').remove();
    $('day_entry_controls_' + id).descendants().invoke('show');
    $('day_entry_failed_update_row_' + id).hide();
    $('day_entry_row_' + id).show();
  },

  toggle_day_entry_spent_at: function(id) {
    var spent_at_element = $('day_entry_' + id + '_spent_at');
    spent_at_element.toggle();
    $('day_entry_' + id + '_spent_at_link').toggle();
    if(spent_at_element.visible())
      spent_at_element.focus();
  },

  _edit_row_readonly_on: function(id) {
    $('day_entry_row_' + id).addClassName('readonly');
    $('day_entry_row_' + id).removeClassName('edit_row_fields');
  },

  _edit_row_readonly_off: function(id) {
    $('day_entry_row_' + id).addClassName('edit_row_fields');
    $('day_entry_row_' + id).removeClassName('readonly');
  },

  find_trailing_tab_index_for_timesheet_row: function(row_element_id) {
    return parseInt($(row_element_id).down('.edit_time, .add_time').readAttribute('tabindex'));
  },

  _activate_day_entry_hours_if_present: function(id) {
    if($('day_entry_' + id + '_hours'))  $('day_entry_' + id + '_hours').activate();
  },

  // update the entry that is being edited in the daily view
  update_day_entry: function(id, locked_day_entry) {
    timesheet.current_edited_id = '';

    // Stop submission if new spent_at date is invalid
    var new_spent_at_date_element = $('day_entry_' + id + '_spent_at');
    var new_spent_at_date         = new_spent_at_date_element.value;
    if(new_spent_at_date_element.visible() && !date.is_valid_date(new_spent_at_date)) {
      return false;
    }

    // Update time and notes fields
    var normalized_hours  = $('day_entry_' + id + '_started_at') ? timesheet._edited_timestamp_duration(id) : $F('day_entry_' + id + '_hours');
    normalized_hours = hours.parse_and_display_time(normalized_hours);
    timesheet._update_timer_displays(id, normalized_hours);
    if($('day_entry_' + id + '_hours'))
      $('day_entry_' + id + '_hours').value = normalized_hours;
    var notes_value   = timesheet._notes_for_update_entry(id);
    var notes_element = $('day_entry_notes_' + id);
    $('notes_for_' + id).update(html_textilize(notes_value));
    notes_value.blank() ? notes_element.hide() : notes_element.show();

    // Update client, project fields
    var id_for_selectors        = (id != '') ? (timesheet.cpts_prefix + id) : id;
    var project_select_id       = '' + id_for_selectors + 'project_selector';
    var project_select_element  = $(project_select_id);
    if(project_select_element) {
      var project_select_option   = $$('select#' + project_select_id + ' option')[project_select_element.selectedIndex];
      $$('#client_project_task_' + id + ' .client')[0].update(project_select_option.up('optgroup').label.escapeHTML());
      $$('#client_project_task_' + id + ' .project')[0].update(timesheet._reverse_project_full_name(project_select_option.text.escapeHTML()));

      // Update task field
      var project_id          = project_select_element.value;
      var task_select_id      = '' + id_for_selectors + 'project' + project_id +'_task_selector';
      var task_select_element = $(task_select_id);
      var task_id             = task_select_element.value;
      $$('#client_project_task_' + id + ' .task')[0].update($$('select#' + task_select_id + ' option')[task_select_element.selectedIndex].text.escapeHTML());
    }


    if(date.to_localized_format($('spent_at_for_' + id).innerHTML) == date.to_localized_format(new_spent_at_date)) {
      $('client_project_task_controls_' + id).update(project_id + '.' + task_id);
      timesheet._edit_row_readonly_on(id);
      $('day_entry_row_' + id).addClassName('tentative');
      $w('timer_link edit_hours notes_for edit_notes client_project_task_controls client_project_task day_entry_controls edit_day_entry_controls').invoke('concat', '_', id).map(function(t){return $(t);}).invoke('toggle');
    } else {
      var moving_element = "<span id='day_entry_moving_" + id + "' class='loading'>Moving time entry to " + new_spent_at_date + "</span>";
      $('day_entry_controls_' + id).descendants().invoke('hide');
      $('day_entry_controls_' + id).insert({bottom: moving_element});
    }

    if(timesheet._day_entry_has_running_timer(id)) {
      timesheet._set_timer_value(id);
      var started_at_element = $('day_entry_' + id + '_started_at');
      if(started_at_element) {
        timesheet._update_timer_started_at(id, started_at_element.value, normalized_hours);
      }
    }

    if(locked_day_entry) {
      timesheet._visually_stop_timer(id);
      $('client_project_task_controls_' + id).hide();
      $('client_project_task_' + id).show();
      $('timer_link_' + id).replace("<div class='hours_nolink day_entry_hours'>" + normalized_hours + "</div>");
      $('edit_day_entry_controls_' + id).update("&nbsp;");
    }

    $('add_day_entry_link').focus();  // bh - Avoid focusing on toggle timer button for new entry
    timesheet.recompute_day_entry_sums();
    timesheet._ajax_call_to_update(id, project_id, task_id, locked_day_entry);
    return false;
  },

  _reverse_project_full_name: function(project_full_name) {
    var match_res = project_full_name.match(/(\[.+\])$/);
    if(null == match_res)  return project_full_name;
    return match_res[1] + ' ' + project_full_name.gsub(match_res[1], '').strip();
  },

  _notes_for_update_entry: function(id) {
    var notes = $F('day_entry_' + id + '_notes');
    if(!$('day_entry_' + id + '_started_at'))
      return notes;

    var started_at = $F('day_entry_' + id + '_started_at');
    var ended_at   = $F('day_entry_' + id + '_ended_at');
    if(started_at.blank() || ended_at.blank())
      return notes;

    return timesheet._notes_with_timestamp(notes, started_at, ended_at);
  },

  _ajax_call_to_update: function(id, project_id, task_id, locked_day_entry) {
    var of_user_id = timesheet.current_user_id;

    var notes  = $F('day_entry_' + id + '_notes');
    var url    = '/daily/update/' + id;
    var params = $H({notes: notes, of_user: of_user_id});
    if($('day_entry_' + id + '_started_at')) {
      params.set('started_at', $F('day_entry_' + id + '_started_at'));
      params.set('ended_at', $F('day_entry_' + id + '_ended_at'));
    } else {
      params.set('hours', $F('day_entry_' + id + '_hours'));
    }

    var spent_at = date.is_valid_date($F('day_entry_' + id + '_spent_at'));
    if(spent_at) {
      params.set('spent_at', date.to_api_format(spent_at));
    }

    if(locked_day_entry) {
      params.set('locked', 'true');
    } else {
      params.update({project_id: project_id, task_id: task_id});
    }
    new Ajax.Request(url, {evalScripts:true, asynchronous:true, parameters:params.toQueryString()});
  },

  create_day_entry: function() {
    var project_id = $F('project_selector');
    var task_id    = $F('project' + project_id +'_task_selector');

    timesheet._before_add_entry();
    timesheet._visually_create_day_entry();
    timesheet._ajax_call_to_create(project_id, task_id);
    timesheet._reset_add_form();
  },

  _before_add_entry: function() {
    if(timesheet._has_timestamp_timers()) {
      timesheet._force_normalize_timestamp_timer('day_entry_started_at');
      timesheet._force_normalize_timestamp_timer('day_entry_ended_at');
    }
  },

  add_counter: 0,

  _visually_create_day_entry: function(project_id, task_id, notes) {
    timesheet.add_counter = (new Date()).getTime();
    var seeded_day_entry  = "undefined" != typeof(project_id);
    var id                = timesheet.add_counter;
    var id_placeholder    = 'DAY_ENTRY_ID';
    var prototype_row     = $('day_entry_row_' + id_placeholder);
    var new_row           = prototype_row.clone();
    var new_row_id        = prototype_row.id.gsub(id_placeholder, id);
    new_row.id            = new_row_id;
    new Insertion.Bottom('project_task_rows', new_row);
    // Firefox has problems setting innerHTML before Insertion to the page
    new_row.update(prototype_row.innerHTML.gsub(id_placeholder, id));

    // Update time and notes fields
    var timer_hours   = timesheet._has_timestamp_timers() ? timesheet._timestamp_duration($F('day_entry_started_at'), $F('day_entry_ended_at')) : $F('day_entry_hours');
    timer_hours       = hours.parse_and_display_time(timer_hours);
    timesheet._update_timer_displays(id, timer_hours);
    var notes_value   = notes || timesheet._notes_for_add_entry();
    var notes_element = $('day_entry_notes_' + id);
    $('notes_for_' + id).update(html_textilize(notes_value));
    notes_value.blank() ? notes_element.hide() : notes_element.show();

    // Update client, project fields
    var project_select_id      = 'project_selector';
    var project_select_element = $(project_select_id);
    if(project_id)  project_select_element.value = project_id;
    var project_select_option  = $$('select#' + project_select_id + ' option')[project_select_element.selectedIndex];
    $$('#client_project_task_' + id + ' .client')[0].update(project_select_option.up('optgroup').label.escapeHTML());
    $$('#client_project_task_' + id + ' .project')[0].update(timesheet._reverse_project_full_name(project_select_option.text.escapeHTML()));

    // Update task field
    project_id              = project_select_element.value;
    var task_select_id      = 'project' + project_id +'_task_selector';
    var task_select_element = $(task_select_id);
    if(task_id)  task_select_element.value = task_id;
    task_id                 = task_select_element.value;
    $$('#client_project_task_' + id + ' .task')[0].update($$('select#' + task_select_id + ' option')[task_select_element.selectedIndex].text.escapeHTML());

    // Check for new running timer
    if(hours.zero(timer_hours)) {
      var started_at = new Date();
      if(timesheet._has_timestamp_timers() && !seeded_day_entry)  started_at = $F('day_entry_started_at');
      timesheet._visually_start_timer(id, started_at);
    }

    $('add_day_entry_link').focus();  // bh - Avoid focusing on toggle timer button for new entry
    new_row.show();
    timesheet.recompute_day_entry_sums();
  },

  _notes_for_add_entry: function() {
    var notes = $F('day_entry_notes');
    if(!timesheet._has_timestamp_timers())
      return notes;

    var started_at = $F('day_entry_started_at');
    var ended_at   = $F('day_entry_ended_at');
    if(started_at.blank() || ended_at.blank())
      return notes;

    return timesheet._notes_with_timestamp(notes, started_at, ended_at);
  },

  _notes_with_timestamp: function(notes, started_at, ended_at) {
    return ("[" + started_at.strip() + " - " + ended_at.strip() + "] " + notes).strip();
  },

  _reset_add_form: function() {
    $('day_entry_notes').value = '';

    if(timesheet._has_timestamp_timers()) {
      $('day_entry_started_at').value = '';
      $('day_entry_ended_at').value = '';
    } else {
      $('day_entry_hours').value = '';
    }

    if(timesheet._day_entry_has_running_timer(timesheet.add_counter)) {
      timesheet.hide_add_day_entry_form();
    } else {
      timesheet.add_day_entry_form_focus();
    }

    timesheet.check_for_hours_entered();
    if($('duplicate_timesheet'))  $('duplicate_timesheet').hide();
  },

  _ajax_call_to_create: function(project_id, task_id) {
    var url =
      '/daily/add/' + timesheet.current_user_id +
      '/'           + timesheet.yday +
      '/'           + timesheet.year;
    var params   = $H({project: project_id, 'day_entry[notes]': $F('day_entry_notes')});
    params.set('tasks_4_project'+project_id, task_id);

    if(timesheet._has_timestamp_timers()) {
      params.set('day_entry[started_at]', $F('day_entry_started_at'));
      params.set('day_entry[ended_at]', $F('day_entry_ended_at'));
    } else {
      params.set('day_entry[hours]', $F('day_entry_hours'));
    }
    params.set('add_counter', timesheet.add_counter);
    new Ajax.Request(url, {evalScripts:true, asynchronous:true, parameters:params.toQueryString()});
  },

  _edited_timestamp_duration: function(id) {
    var started_at_ = $F('day_entry_' + id + '_started_at');
    var ended_at_   = timesheet._day_entry_has_running_timer(id) ?
                        hours.normalize_timestamp(new Date()) :
                        $F('day_entry_' + id + '_ended_at');
    return timesheet._timestamp_duration(started_at_, ended_at_);
  },

  _timestamp_duration: function(start_time, end_time) {
    start_time = hours.normalize_timestamp(start_time);
    end_time   = hours.normalize_timestamp(end_time);
    if(start_time.blank() || end_time.blank())
      return "0";

    start_time = Time.naturalParse(start_time);
    end_time   = Time.naturalParse(end_time);
    if(end_time < start_time)
      end_time = end_time.add({hours: 24});
    var time_span = new TimeSpan(end_time - start_time);
    return '' + time_span.getHours() + ':' + time_span.getMinutes().toString().pad('0', 2);
  },

  toggle_counter: 0,

  toggle_timer: function(id, locked_day_entry) {
    if(locked_day_entry) {
      timesheet.toggle_day_entry_editor(id, locked_day_entry);
      return false;
    }

    if(timesheet._has_timestamp_timers() && !timesheet._day_entry_has_running_timer(id) && !hours.zero($('timer_link_' + id).innerHTML))
      return timesheet._start_timestamp_timer_generates_new_entry(id);

    timesheet._visually_toggle_timer(id);
    new Ajax.Request('/daily/timer/' + id + '?of_user=' + timesheet.current_user_id + '&toggle_counter=' + timesheet.toggle_counter,
                     {evalScripts:true, asynchronous:true});
    return false;
  },

  // If timestamp timesheet and trying to turn on a timer, instead generate a new entry.
  _start_timestamp_timer_generates_new_entry: function(id) {
    var project_task  = $('client_project_task_controls_' + id).innerHTML.split('.');
    var project_id    = project_task[0];
    var task_id       = project_task[1];
    var notes         = $F('day_entry_' + id + '_notes');
    timesheet._visually_create_day_entry(project_id, task_id, notes);

    params = $H({ of_user:            timesheet.current_user_id,
                  project:            project_id,
                  'day_entry[notes]': notes,
                  year:               timesheet.year,
                  day:                timesheet.yday,
                  add_counter:        timesheet.add_counter });
    params.set('tasks_4_project' + project_id, task_id);
    new Ajax.Request('/daily/add',
                     {asynchronous:true, evalScripts:true, parameters:params.toQueryString()});
    return false;
  },

  _visually_toggle_timer: function(id) {
    timesheet.toggle_counter = (new Date()).getTime();
    timesheet._day_entry_has_running_timer(id) ? timesheet._visually_stop_timer(id) : timesheet._visually_start_timer(id);
  },

  _visually_stop_timer: function(id) {
    timesheet.stop_timer();
    $('day_entry_row_' + id).removeClassName('running_timer');
    $('timer_started_at_' + id).hide();
    if(timesheet._has_timestamp_timers()) {
      var started_at_element = $('day_entry_' + id + '_started_at');
      if(started_at_element && !started_at_element.value.blank()) {
        timesheet._update_timeframes(id);
      }
    }
    if($('day_entry_' + id + '_ended_at'))  $('day_entry_' + id + '_ended_at').enable();
  },

  _update_timeframes: function(id) {
    if(!$('day_entry_' + id + '_notes'))  return; // Protect from some failures when starting a timer via add

    var notes           = $F('day_entry_' + id + '_notes');
    var started_at      = $F('day_entry_' + id + '_started_at');
    var duration_hh_mm  = $('timer_link_' + id).innerHTML;
    var duration        = hours.convert_time_to_float(duration_hh_mm);
    var ended_at        = hours.normalize_timestamp(Time.naturalParse(started_at).addHours(duration));
    notes               = html_textilize(timesheet._notes_with_timestamp(notes, started_at, ended_at));

    $('day_entry_' + id + '_ended_at').value = ended_at;
    $('notes_for_' + id).update(notes);
    $('day_entry_notes_' + id).show();
    timesheet._update_timer_displays(id, duration_hh_mm);
  },

  _update_timer_displays: function(id, duration_hh_mm) {
    $('timer_link_' + id).update(duration_hh_mm);

    var edit_duration_element = $('day_entry_' + id + '_edit_duration');
    if(edit_duration_element) {
      edit_duration_element.update(duration_hh_mm);
    }
  },

  _visually_start_timer: function(id, started_at_) {
    started_at_ = started_at_ || new Date();
    timesheet.fix_up_previously_running_timer();
    timesheet.start_timer(id);
    $('day_entry_row_' + id).addClassName('running_timer');
    timesheet._update_timer_started_at(id, started_at_, $('timer_link_' + id).innerHTML);
    $('timer_started_at_' + id).show();
    if(timesheet._has_timestamp_timers()) {
      var duration = timesheet._timestamp_duration(started_at_, new Date());
      $('timer_link_' + id).update(duration);
      if($('day_entry_' + id + '_started_at')) {
        $('day_entry_' + id + '_started_at').value = hours.normalize_timestamp(started_at_);
        var ended_at_element    = $('day_entry_' + id + '_ended_at');
        ended_at_element.value  = "";
        ended_at_element.disable();
        $('notes_for_' + id).update(timesheet._notes_for_update_entry(id));
      }
    }
  },

  _update_timer_started_at: function(id, time_, duration_) {
    duration_ = duration_ || "0:00";
    var with_hours = "";
    if(!timesheet._has_timestamp_timers) {
      with_hours = ("0:00" != duration_ && "0.00" !== duration_) ? (' with ' + duration_ + ' hours') : '';
    }
    time_ = hours.normalize_timestamp(time_);
    $('timer_started_at_' + id).update('(Timer started at ' + time_ + with_hours + ')');
  },

  fix_up_previously_running_timer: function() {
    if(!timesheet.daily_stopwatch_timer_running_id.blank())
      timesheet._visually_stop_timer(timesheet.daily_stopwatch_timer_running_id);
  },

  _day_entry_has_running_timer: function(id) {
    return $('day_entry_row_' + id).hasClassName('running_timer');
  },

  daily_control_updating: function(id, updating) {
    $w('edit_link update_indicator').invoke('concat', '_', id).map(function(t){return $(t);}).invoke('hide');
    if (updating == true)
      $('update_indicator_'+ id).show();
    else
      $('edit_link_' +id).show();
  },


  toggle_user: function() {
    $('user_selector_link', 'user_selector').invoke('toggle');
  },

  week_selector_on_change: function(to_url, select, user_id){
    var selected = select.options[select.selectedIndex].value.split('.');
    to_url += '/' + selected[0] + '/' + selected[1];
    if( user_id != null ){
      to_url +=  '?of_user=' + user_id;
    }
    if(selected[2] == 'all') {
      if( user_id != null )
        to_url += '&all_weeks=1';
      else
        to_url += '?all_weeks=1';
    }
    window.location = to_url;
  },

  remove_tentative_class: function(event) {
    event.element().up('tr').removeClassName('tentative');
  },

  current_user_id: 0,

  check_enter_submit_update: function(event) {
    if (check_enter_with_text_area_features(event)) {
      Event.stop(event);
      var element = Event.element(event);
      var match_res = element.id.match(/(\d+)/);
      var locked = element.hasClassName('locked');
      if (match_res && match_res.length == 2){
        var day_entry_id = match_res[1];
        if($('day_entry_' + day_entry_id + '_started_at')) {
          timesheet._force_normalize_timestamp_timer('day_entry_' + day_entry_id + '_started_at');
          timesheet._force_normalize_timestamp_timer('day_entry_' + day_entry_id + '_ended_at');
        }
        timesheet.update_day_entry(day_entry_id, locked);
      }
     }
  },

  check_enter_submit_create: function(event) {
    if (check_enter_with_text_area_features(event)) {
      Event.stop(event);
      timesheet.create_day_entry.defer();
    }
  },

  toggle_add_task_controls: function(){
    $('task_selectors', 'new_task_form', 'create_new_task').invoke('toggle');
    if ($('new_task_form').visible()){
      $('has_new_task').value =  'true';
      var task_name = $('task_name');
      task_name.value = 'task name here';
      task_name.focus();
      task_name.select();
    } else {
      $('has_new_task').value = 'false';
    }
  },

  calendar_url_for_weekly: function(postfix, day){
    var prefix = '/entry/show'
    if(day != undefined || day != null){
      return prefix + timesheet.dated_url_part(day) +
             postfix +
             '?of_user=' + timesheet.current_user_id;
    } else {
      return prefix + postfix;
    }
  },

  calendar_url_for_daily: function(postfix, day){
    var prefix = '/daily';
    if(day != undefined || day != null){
      return prefix + '/' + timesheet.current_user_id + timesheet.dated_url_part(day) +
             postfix;
    } else {
      return prefix + postfix
    }
  },

  dated_url_part: function(day){
    return '/' + day.yday() + '/' + day.year();
  },

  navigate_from_entry: function(url) {
    /* First do a real save then submit a dummy review form on complete */
    timesheet.save(function(){
      window.location = url;
    });
    return false;
  },

  enable_submit_button: function() {
    if($('submit_button')) {
      $('submit_button').disabled = false;
      $('submit_button').removeClassName('inactive');
    }
  },

  register_clear_timesheet_flash_faders: function() {
    $$('.timer, .edit_cont, .tasks_select').each(function(control) {
      control.observe('click', timesheet.handle_clear_timesheet_flash_fader);
    });
    $$('.time, .notes').each(function(control) {
      control.observe('keydown', timesheet.handle_clear_timesheet_flash_fader);
    });
  },

  handle_clear_timesheet_flash_fader: function() {
    $$('.clear_timesheet').invoke("fade");
  },

  _has_timestamp_timers: function() {
    return ($('day_entry_started_at') && $('day_entry_ended_at'));
  },

  initialize_timestamp_timers: function() {
    if(!timesheet._has_timestamp_timers())  return;
    timesheet.register_on_change_handlers_for_timestamp_timers();
    timesheet.register_on_change_handlers_for_timestamp_duration();
  },

  _latest_ended_at_time: function() {
    // Results in a list like: [["13:11", "1:11pm"], ["02:11", "2:11AM"], ["18:11", "18:11"]]
    var end_times = $$('.ended_at').map(function(e){ return [Time.toString(e.value, '24hourZeroFilled'), e.value]; });
    end_times = end_times.sortBy(function(e){ return e.first(); });
    return end_times.last().last();
  },

  register_on_change_handlers_for_timestamp_timers: function() {
    $$('.timestamp').each(function(element) {
      element.observe('blur', timesheet.handle_change_of__timestamp_timer);
    });
  },

  handle_change_of__timestamp_timer: function() {
    if(['day_entry_started_at', 'day_entry_ended_at'].include(this.id) && this.value.blank())
      return;

    if(null != Time.naturalParse(this.value) || ['t', 'n', '.'].include(this.value.strip())) {
      this.value = 'day_entry_ended_at' == this.id ? 
        hours.normalize_timestamp(this.value, $F('day_entry_started_at')) :
        hours.normalize_timestamp(this.value);
      return;
    }
    
    warning_callout(this.id, 'Incorrect time format.');
  },

  register_on_change_handlers_for_timestamp_duration: function() {
    $$('.timestamp').each(function(element) {
      element.observe('blur', timesheet.handle_change_of__timestamp_duration);
    });
  },

  handle_change_of__timestamp_duration: function() {
    var started_at_element  = this.hasClassName('started_at') ? this : this.adjacent('.started_at')[0];
    var ended_at_element    = this.hasClassName('ended_at')   ? this : this.adjacent('.ended_at')[0];
    var started_at          = started_at_element.value;
    // disabled ended_at_element means a running timer
    var ended_at            = ended_at_element.disabled ? hours.normalize_timestamp(new Date()) : ended_at_element.value;
    var new_duration        = "";

    if(hours.valid_hhmm_time(started_at) && hours.valid_hhmm_time(ended_at)) {
      new_duration = timesheet._timestamp_duration(started_at, ended_at);
    } else {
      new_duration = "0:00";
    }
    new_duration = new_duration.blank() ? "&nbsp;" : hours.parse_and_display_time(new_duration);
    this.adjacent('.duration')[0].update(new_duration);
  },

  _force_normalize_timestamp_timer: function(id) {
    var on_change_fn = timesheet.handle_change_of__timestamp_timer.bind($(id));
    on_change_fn();
  },

  show_add_day_entry_form: function() {
    var add_day_entry_link = $$('#timesheet_footer .new_entry')[0];
    if(add_day_entry_link.hasClassName('disabled'))
      return false;

    $('add_day_entry_row').show();
    timesheet.initialize_add_form();
    timesheet.add_day_entry_form_focus();
    timesheet.disable_add_day_entry_link();
    return true;
  },

  add_day_entry_form_focus: function() {
    if($('project_tasks_selector_cont').visible()) {
      $('project_selector').focus();
    } else if($('day_entry_hours')) {
      $('day_entry_hours').focus();
    } else {
      $('day_entry_started_at').focus();
    }
  },

  hide_add_day_entry_form: function() {
    $('add_day_entry_row').hide();
    timesheet.enable_add_day_entry_link();
  },

  disable_add_day_entry_link: function() {
    var add_day_entry_link = $$('#timesheet_footer .new_entry')[0];
    add_day_entry_link.addClassName('disabled');
  },

  enable_add_day_entry_link: function() {
    var add_day_entry_link = $$('#timesheet_footer .new_entry')[0];
    add_day_entry_link.removeClassName('disabled');
  },

  initialize_add_form: function() {
    if ($$('.add_row_fields').size() > 0) {
      if(timesheet._has_timestamp_timers()) {
        $('day_entry_started_at').value = "";
        $('day_entry_ended_at').value = "";
      } else {
        $('day_entry_hours').value = "";
      }
      $('day_entry_notes').value = "";
      timesheet.check_for_hours_entered();
    }
  },

  check_for_hours_entered: function() {
    if ($$('.add_row_fields').size() > 0) {
      var start_timer_button = false;
      if(timesheet._has_timestamp_timers()) {
        start_timer_button = $F('day_entry_started_at').blank() || $F('day_entry_ended_at').blank() ? true : false;
      } else {
        start_timer_button = $F('day_entry_hours').blank() ? true : false;
      }

      $('add_time_link').value = start_timer_button ? "Start Timer" : "Save Entry";
    }
  },

  show_duplication_form: function() {
    $('duplicate_timesheet').hide();
    $('add_day_entry_row').hide();
    $('duplicate_timesheet_confirmation').show();
  },

  hide_duplication_form: function() {
    $('duplicate_timesheet_confirmation').hide();
    $('add_day_entry_row').show();
    $('duplicate_timesheet').show();
  },

  register_duplicate_timesheet_handlers: function() {
    $$('#duplicate_timesheet_controls a').each(function(e) {
      e.observe('click', timesheet.handle_duplicate_timesheet);
    });
  },

  handle_duplicate_timesheet: function() {
    $('duplicate_timesheet_controls').hide();
    $('duplicate_timesheet_indicator').show();
  }

};

function row_name(project_id, task_id) {
  return ('project' + project_id + '_task' + task_id);
}

function checkTime(i) {
  if (i<10) {
    i="0" + i;
  }
  return i;
}

// randomly show tips about the app
function displayTip() {
  var tips = Array(5);
  tips[0] = '<strong>TIP:</strong> Time entries can be in either decimal or HH:MM format.  Example: 2.5 or 2:30';
  tips[1] = '<strong>TIP:</strong> Bookmark this page for quick access in the future.';
  tips[2] = '<strong>TIP:</strong> You can use the Harvest Timer from the Daily timesheets to track your tasks in real-time.';
  tips[3] = '<strong>TIP:</strong> You can use <a href="http://www.getharvest.com/widget" target="_blank">Harvest widgets</a> to track time from your desktop.';
  tips[4] = '<strong>TIP:</strong> You can view time in HH:MM format by changing your settings in Manage &gt; Account settings.';

  var ran = Math.round(Math.random()*4);
  document.writeln(tips[ran]);
}

// randomly show tips about the app when user is in daily view
function displayDailyTip() {
  var tips = Array(5);
  tips[0] = '<strong>TIP:</strong> Click on a clock icon to start/stop the corresponding task timer.';
  tips[1] = '<strong>TIP:</strong> Bookmark this page for quick access in the future.';
  tips[2] = '<strong>TIP:</strong> Running timers do not require you to keep your browser open.  Our servers will reliably track your time.';
  tips[3] = '<strong>TIP:</strong> You can use <a href="http://www.getharvest.com/widget" target="_blank">Harvest widgets</a> to track time from your desktop.';
  tips[4] = '<strong>TIP:</strong> You can view time in HH:MM format by changing your settings in Manage &gt; Account settings.';

  var ran = Math.round(Math.random()*4);
  document.writeln(tips[ran]);
}
















/****************************************************************/
/*  original filename timesheet_unsubmitted.js                        */
/****************************************************************/


/* -*- Mode:JavaScript; c-basic-offset:2; indent-tabs-mode:nil; c-indentation-style:"k&r" -*- */
var timesheet_unsubmitted = {
  register_on_change_handlers_for_approval_reminder: function() {
    Event.observe($("company_reminder_submit_for_approval_day"), 'change', timesheet_unsubmitted.handle_onchange__reminder_submit_for_approval_day);
  },

  handle_onchange__reminder_submit_for_approval_day: function() {
    var day       = $F('company_reminder_submit_for_approval_day');
    var timeframe = ['Thursday', 'Friday'].include(day) ? "this week's" : "previous week's";
    $('approval_reminder_timeframe').innerHTML = timeframe;
  }
}


/****************************************************************/
/*  original filename datejs.js                        */
/****************************************************************/


/**
 * @version: 1.0 Alpha-1
 * @author: Coolite Inc. http://www.coolite.com/
 * @date: 2008-05-13
 * @copyright: Copyright (c) 2006-2008, Coolite Inc. (http://www.coolite.com/). All rights reserved.
 * @license: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/.
 * @website: http://www.datejs.com/
 */
Date.CultureInfo={name:"en-US",englishName:"English (United States)",nativeName:"English (United States)",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbreviatedDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shortestDayNames:["Su","Mo","Tu","We","Th","Fr","Sa"],firstLetterDayNames:["S","M","T","W","T","F","S"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],abbreviatedMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,dateElementOrder:"mdy",formatPatterns:{shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^jan(uary)?/i,feb:/^feb(ruary)?/i,mar:/^mar(ch)?/i,apr:/^apr(il)?/i,may:/^may/i,jun:/^jun(e)?/i,jul:/^jul(y)?/i,aug:/^aug(ust)?/i,sep:/^sep(t(ember)?)?/i,oct:/^oct(ober)?/i,nov:/^nov(ember)?/i,dec:/^dec(ember)?/i,sun:/^su(n(day)?)?/i,mon:/^mo(n(day)?)?/i,tue:/^tu(e(s(day)?)?)?/i,wed:/^we(d(nesday)?)?/i,thu:/^th(u(r(s(day)?)?)?)?/i,fri:/^fr(i(day)?)?/i,sat:/^sa(t(urday)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|aft(er)?|from|hence)/i,subtract:/^(\-|bef(ore)?|ago)/i,yesterday:/^yes(terday)?/i,today:/^t(od(ay)?)?/i,tomorrow:/^tom(orrow)?/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^mn|min(ute)?s?/i,hour:/^h(our)?s?/i,week:/^w(eek)?s?/i,month:/^m(onth)?s?/i,day:/^d(ay)?s?/i,year:/^y(ear)?s?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a(?!u|p)|p)/i},timezones:[{name:"UTC",offset:"-000"},{name:"GMT",offset:"-000"},{name:"EST",offset:"-0500"},{name:"EDT",offset:"-0400"},{name:"CST",offset:"-0600"},{name:"CDT",offset:"-0500"},{name:"MST",offset:"-0700"},{name:"MDT",offset:"-0600"},{name:"PST",offset:"-0800"},{name:"PDT",offset:"-0700"}]};
(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo,p=function(s,l){if(!l){l=2;}
return("000"+s).slice(l*-1);};$P.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this;};$P.setTimeToNow=function(){var n=new Date();this.setHours(n.getHours());this.setMinutes(n.getMinutes());this.setSeconds(n.getSeconds());this.setMilliseconds(n.getMilliseconds());return this;};$D.today=function(){return new Date().clearTime();};$D.compare=function(date1,date2){if(isNaN(date1)||isNaN(date2)){throw new Error(date1+" - "+date2);}else if(date1 instanceof Date&&date2 instanceof Date){return(date1<date2)?-1:(date1>date2)?1:0;}else{throw new TypeError(date1+" - "+date2);}};$D.equals=function(date1,date2){return(date1.compareTo(date2)===0);};$D.getDayNumberFromName=function(name){var n=$C.dayNames,m=$C.abbreviatedDayNames,o=$C.shortestDayNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s||o[i].toLowerCase()==s){return i;}}
return-1;};$D.getMonthNumberFromName=function(name){var n=$C.monthNames,m=$C.abbreviatedMonthNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};$D.isLeapYear=function(year){return((year%4===0&&year%100!==0)||year%400===0);};$D.getDaysInMonth=function(year,month){return[31,($D.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];};$D.getTimezoneAbbreviation=function(offset){var z=$C.timezones,p;for(var i=0;i<z.length;i++){if(z[i].offset===offset){return z[i].name;}}
return null;};$D.getTimezoneOffset=function(name){var z=$C.timezones,p;for(var i=0;i<z.length;i++){if(z[i].name===name.toUpperCase()){return z[i].offset;}}
return null;};$P.clone=function(){return new Date(this.getTime());};$P.compareTo=function(date){return Date.compare(this,date);};$P.equals=function(date){return Date.equals(this,date||new Date());};$P.between=function(start,end){return this.getTime()>=start.getTime()&&this.getTime()<=end.getTime();};$P.isAfter=function(date){return this.compareTo(date||new Date())===1;};$P.isBefore=function(date){return(this.compareTo(date||new Date())===-1);};$P.isToday=function(){return this.isSameDay(new Date());};$P.isSameDay=function(date){return this.clone().clearTime().equals(date.clone().clearTime());};$P.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this;};$P.addSeconds=function(value){return this.addMilliseconds(value*1000);};$P.addMinutes=function(value){return this.addMilliseconds(value*60000);};$P.addHours=function(value){return this.addMilliseconds(value*3600000);};$P.addDays=function(value){this.setDate(this.getDate()+value);return this;};$P.addWeeks=function(value){return this.addDays(value*7);};$P.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,$D.getDaysInMonth(this.getFullYear(),this.getMonth())));return this;};$P.addYears=function(value){return this.addMonths(value*12);};$P.add=function(config){if(typeof config=="number"){this._orient=config;return this;}
var x=config;if(x.milliseconds){this.addMilliseconds(x.milliseconds);}
if(x.seconds){this.addSeconds(x.seconds);}
if(x.minutes){this.addMinutes(x.minutes);}
if(x.hours){this.addHours(x.hours);}
if(x.weeks){this.addWeeks(x.weeks);}
if(x.months){this.addMonths(x.months);}
if(x.years){this.addYears(x.years);}
if(x.days){this.addDays(x.days);}
return this;};var $y,$m,$d;$P.getWeek=function(){var a,b,c,d,e,f,g,n,s,w;$y=(!$y)?this.getFullYear():$y;$m=(!$m)?this.getMonth()+1:$m;$d=(!$d)?this.getDate():$d;if($m<=2){a=$y-1;b=(a/4|0)-(a/100|0)+(a/400|0);c=((a-1)/4|0)-((a-1)/100|0)+((a-1)/400|0);s=b-c;e=0;f=$d-1+(31*($m-1));}else{a=$y;b=(a/4|0)-(a/100|0)+(a/400|0);c=((a-1)/4|0)-((a-1)/100|0)+((a-1)/400|0);s=b-c;e=s+1;f=$d+((153*($m-3)+2)/5)+58+s;}
g=(a+b)%7;d=(f+g-e)%7;n=(f+3-d)|0;if(n<0){w=53-((g-s)/5|0);}else if(n>364+s){w=1;}else{w=(n/7|0)+1;}
$y=$m=$d=null;return w;};$P.getISOWeek=function(){$y=this.getUTCFullYear();$m=this.getUTCMonth()+1;$d=this.getUTCDate();return p(this.getWeek());};$P.setWeek=function(n){return this.moveToDayOfWeek(1).addWeeks(n-this.getWeek());};$D._validate=function(n,min,max,name){if(typeof n=="undefined"){return false;}else if(typeof n!="number"){throw new TypeError(n+" is not a Number.");}else if(n<min||n>max){throw new RangeError(n+" is not a valid value for "+name+".");}
return true;};$D.validateMillisecond=function(value){return $D._validate(value,0,999,"millisecond");};$D.validateSecond=function(value){return $D._validate(value,0,59,"second");};$D.validateMinute=function(value){return $D._validate(value,0,59,"minute");};$D.validateHour=function(value){return $D._validate(value,0,23,"hour");};$D.validateDay=function(value,year,month){return $D._validate(value,1,$D.getDaysInMonth(year,month),"day");};$D.validateMonth=function(value){return $D._validate(value,0,11,"month");};$D.validateYear=function(value){return $D._validate(value,0,9999,"year");};$P.set=function(config){if($D.validateMillisecond(config.millisecond)){this.addMilliseconds(config.millisecond-this.getMilliseconds());}
if($D.validateSecond(config.second)){this.addSeconds(config.second-this.getSeconds());}
if($D.validateMinute(config.minute)){this.addMinutes(config.minute-this.getMinutes());}
if($D.validateHour(config.hour)){this.addHours(config.hour-this.getHours());}
if($D.validateMonth(config.month)){this.addMonths(config.month-this.getMonth());}
if($D.validateYear(config.year)){this.addYears(config.year-this.getFullYear());}
if($D.validateDay(config.day,this.getFullYear(),this.getMonth())){this.addDays(config.day-this.getDate());}
if(config.timezone){this.setTimezone(config.timezone);}
if(config.timezoneOffset){this.setTimezoneOffset(config.timezoneOffset);}
if(config.week&&$D._validate(config.week,0,53,"week")){this.setWeek(config.week);}
return this;};$P.moveToFirstDayOfMonth=function(){return this.set({day:1});};$P.moveToLastDayOfMonth=function(){return this.set({day:$D.getDaysInMonth(this.getFullYear(),this.getMonth())});};$P.moveToNthOccurrence=function(dayOfWeek,occurrence){var shift=0;if(occurrence>0){shift=occurrence-1;}
else if(occurrence===-1){this.moveToLastDayOfMonth();if(this.getDay()!==dayOfWeek){this.moveToDayOfWeek(dayOfWeek,-1);}
return this;}
return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(dayOfWeek,+1).addWeeks(shift);};$P.moveToDayOfWeek=function(dayOfWeek,orient){var diff=(dayOfWeek-this.getDay()+7*(orient||+1))%7;return this.addDays((diff===0)?diff+=7*(orient||+1):diff);};$P.moveToMonth=function(month,orient){var diff=(month-this.getMonth()+12*(orient||+1))%12;return this.addMonths((diff===0)?diff+=12*(orient||+1):diff);};$P.getOrdinalNumber=function(){return Math.ceil((this.clone().clearTime()-new Date(this.getFullYear(),0,1))/86400000)+1;};$P.getTimezone=function(){return $D.getTimezoneAbbreviation(this.getUTCOffset());};$P.setTimezoneOffset=function(offset){var here=this.getTimezoneOffset(),there=Number(offset)*-6/10;return this.addMinutes(there-here);};$P.setTimezone=function(offset){return this.setTimezoneOffset($D.getTimezoneOffset(offset));};$P.hasDaylightSavingTime=function(){return(Date.today().set({month:0,day:1}).getTimezoneOffset()!==Date.today().set({month:6,day:1}).getTimezoneOffset());};$P.isDaylightSavingTime=function(){return(this.hasDaylightSavingTime()&&new Date().getTimezoneOffset()===Date.today().set({month:6,day:1}).getTimezoneOffset());};$P.getUTCOffset=function(){var n=this.getTimezoneOffset()*-10/6,r;if(n<0){r=(n-10000).toString();return r.charAt(0)+r.substr(2);}else{r=(n+10000).toString();return"+"+r.substr(1);}};$P.getElapsed=function(date){return(date||new Date())-this;};if(!$P.toISOString){$P.toISOString=function(){function f(n){return n<10?'0'+n:n;}
return'"'+this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z"';};}
$P._toString=$P.toString;$P.toString=function(format){var x=this;if(format&&format.length==1){var c=$C.formatPatterns;x.t=x.toString;switch(format){case"d":return x.t(c.shortDate);case"D":return x.t(c.longDate);case"F":return x.t(c.fullDateTime);case"m":return x.t(c.monthDay);case"r":return x.t(c.rfc1123);case"s":return x.t(c.sortableDateTime);case"t":return x.t(c.shortTime);case"T":return x.t(c.longTime);case"u":return x.t(c.universalSortableDateTime);case"y":return x.t(c.yearMonth);}}
var ord=function(n){switch(n*1){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};return format?format.replace(/(\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S)/g,function(m){if(m.charAt(0)==="\\"){return m.replace("\\","");}
x.h=x.getHours;switch(m){case"hh":return p(x.h()<13?(x.h()===0?12:x.h()):(x.h()-12));case"h":return x.h()<13?(x.h()===0?12:x.h()):(x.h()-12);case"HH":return p(x.h());case"H":return x.h();case"mm":return p(x.getMinutes());case"m":return x.getMinutes();case"ss":return p(x.getSeconds());case"s":return x.getSeconds();case"yyyy":return p(x.getFullYear(),4);case"yy":return p(x.getFullYear());case"dddd":return $C.dayNames[x.getDay()];case"ddd":return $C.abbreviatedDayNames[x.getDay()];case"dd":return p(x.getDate());case"d":return x.getDate();case"MMMM":return $C.monthNames[x.getMonth()];case"MMM":return $C.abbreviatedMonthNames[x.getMonth()];case"MM":return p((x.getMonth()+1));case"M":return x.getMonth()+1;case"t":return x.h()<12?$C.amDesignator.substring(0,1):$C.pmDesignator.substring(0,1);case"tt":return x.h()<12?$C.amDesignator:$C.pmDesignator;case"S":return ord(x.getDate());default:return m;}}):this._toString();};}());
(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo,$N=Number.prototype;$P._orient=+1;$P._nth=null;$P._is=false;$P._same=false;$P._isSecond=false;$N._dateElement="day";$P.next=function(){this._orient=+1;return this;};$D.next=function(){return $D.today().next();};$P.last=$P.prev=$P.previous=function(){this._orient=-1;return this;};$D.last=$D.prev=$D.previous=function(){return $D.today().last();};$P.is=function(){this._is=true;return this;};$P.same=function(){this._same=true;this._isSecond=false;return this;};$P.today=function(){return this.same().day();};$P.weekday=function(){if(this._is){this._is=false;return(!this.is().sat()&&!this.is().sun());}
return false;};$P.at=function(time){return(typeof time==="string")?$D.parse(this.toString("d")+" "+time):this.set(time);};$N.fromNow=$N.after=function(date){var c={};c[this._dateElement]=this;return((!date)?new Date():date.clone()).add(c);};$N.ago=$N.before=function(date){var c={};c[this._dateElement]=this*-1;return((!date)?new Date():date.clone()).add(c);};var dx=("sunday monday tuesday wednesday thursday friday saturday").split(/\s/),mx=("january february march april may june july august september october november december").split(/\s/),px=("Millisecond Second Minute Hour Day Week Month Year").split(/\s/),pxf=("Milliseconds Seconds Minutes Hours Date Week Month FullYear").split(/\s/),nth=("final first second third fourth fifth").split(/\s/),de;$P.toObject=function(){var o={};for(var i=0;i<px.length;i++){o[px[i].toLowerCase()]=this["get"+pxf[i]]();}
return o;};$D.fromObject=function(config){config.week=null;return Date.today().set(config);};var df=function(n){return function(){if(this._is){this._is=false;return this.getDay()==n;}
if(this._nth!==null){if(this._isSecond){this.addSeconds(this._orient*-1);}
this._isSecond=false;var ntemp=this._nth;this._nth=null;var temp=this.clone().moveToLastDayOfMonth();this.moveToNthOccurrence(n,ntemp);if(this>temp){throw new RangeError($D.getDayName(n)+" does not occur "+ntemp+" times in the month of "+$D.getMonthName(temp.getMonth())+" "+temp.getFullYear()+".");}
return this;}
return this.moveToDayOfWeek(n,this._orient);};};var sdf=function(n){return function(){var t=$D.today(),shift=n-t.getDay();if(n===0&&$C.firstDayOfWeek===1&&t.getDay()!==0){shift=shift+7;}
return t.addDays(shift);};};for(var i=0;i<dx.length;i++){$D[dx[i].toUpperCase()]=$D[dx[i].toUpperCase().substring(0,3)]=i;$D[dx[i]]=$D[dx[i].substring(0,3)]=sdf(i);$P[dx[i]]=$P[dx[i].substring(0,3)]=df(i);}
var mf=function(n){return function(){if(this._is){this._is=false;return this.getMonth()===n;}
return this.moveToMonth(n,this._orient);};};var smf=function(n){return function(){return $D.today().set({month:n,day:1});};};for(var j=0;j<mx.length;j++){$D[mx[j].toUpperCase()]=$D[mx[j].toUpperCase().substring(0,3)]=j;$D[mx[j]]=$D[mx[j].substring(0,3)]=smf(j);$P[mx[j]]=$P[mx[j].substring(0,3)]=mf(j);}
var ef=function(j){return function(){if(this._isSecond){this._isSecond=false;return this;}
if(this._same){this._same=this._is=false;var o1=this.toObject(),o2=(arguments[0]||new Date()).toObject(),v="",k=j.toLowerCase();for(var m=(px.length-1);m>-1;m--){v=px[m].toLowerCase();if(o1[v]!=o2[v]){return false;}
if(k==v){break;}}
return true;}
if(j.substring(j.length-1)!="s"){j+="s";}
return this["add"+j](this._orient);};};var nf=function(n){return function(){this._dateElement=n;return this;};};for(var k=0;k<px.length;k++){de=px[k].toLowerCase();$P[de]=$P[de+"s"]=ef(px[k]);$N[de]=$N[de+"s"]=nf(de);}
$P._ss=ef("Second");var nthfn=function(n){return function(dayOfWeek){if(this._same){return this._ss(arguments[0]);}
if(dayOfWeek||dayOfWeek===0){return this.moveToNthOccurrence(dayOfWeek,n);}
this._nth=n;if(n===2&&(dayOfWeek===undefined||dayOfWeek===null)){this._isSecond=true;return this.addSeconds(this._orient);}
return this;};};for(var l=0;l<nth.length;l++){$P[nth[l]]=(l===0)?nthfn(-1):nthfn(l);}}());
(function(){Date.Parsing={Exception:function(s){this.message="Parse error at '"+s.substring(0,10)+" ...'";}};var $P=Date.Parsing;var _=$P.Operators={rtoken:function(r){return function(s){var mx=s.match(r);if(mx){return([mx[0],s.substring(mx[0].length)]);}else{throw new $P.Exception(s);}};},token:function(s){return function(s){return _.rtoken(new RegExp("^\s*"+s+"\s*"))(s);};},stoken:function(s){return _.rtoken(new RegExp("^"+s));},until:function(p){return function(s){var qx=[],rx=null;while(s.length){try{rx=p.call(this,s);}catch(e){qx.push(rx[0]);s=rx[1];continue;}
break;}
return[qx,s];};},many:function(p){return function(s){var rx=[],r=null;while(s.length){try{r=p.call(this,s);}catch(e){return[rx,s];}
rx.push(r[0]);s=r[1];}
return[rx,s];};},optional:function(p){return function(s){var r=null;try{r=p.call(this,s);}catch(e){return[null,s];}
return[r[0],r[1]];};},not:function(p){return function(s){try{p.call(this,s);}catch(e){return[null,s];}
throw new $P.Exception(s);};},ignore:function(p){return p?function(s){var r=null;r=p.call(this,s);return[null,r[1]];}:null;},product:function(){var px=arguments[0],qx=Array.prototype.slice.call(arguments,1),rx=[];for(var i=0;i<px.length;i++){rx.push(_.each(px[i],qx));}
return rx;},cache:function(rule){var cache={},r=null;return function(s){try{r=cache[s]=(cache[s]||rule.call(this,s));}catch(e){r=cache[s]=e;}
if(r instanceof $P.Exception){throw r;}else{return r;}};},any:function(){var px=arguments;return function(s){var r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){r=null;}
if(r){return r;}}
throw new $P.Exception(s);};},each:function(){var px=arguments;return function(s){var rx=[],r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){throw new $P.Exception(s);}
rx.push(r[0]);s=r[1];}
return[rx,s];};},all:function(){var px=arguments,_=_;return _.each(_.optional(px));},sequence:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;if(px.length==1){return px[0];}
return function(s){var r=null,q=null;var rx=[];for(var i=0;i<px.length;i++){try{r=px[i].call(this,s);}catch(e){break;}
rx.push(r[0]);try{q=d.call(this,r[1]);}catch(ex){q=null;break;}
s=q[1];}
if(!r){throw new $P.Exception(s);}
if(q){throw new $P.Exception(q[1]);}
if(c){try{r=c.call(this,r[1]);}catch(ey){throw new $P.Exception(r[1]);}}
return[rx,(r?r[1]:s)];};},between:function(d1,p,d2){d2=d2||d1;var _fn=_.each(_.ignore(d1),p,_.ignore(d2));return function(s){var rx=_fn.call(this,s);return[[rx[0][0],r[0][2]],rx[1]];};},list:function(p,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return(p instanceof Array?_.each(_.product(p.slice(0,-1),_.ignore(d)),p.slice(-1),_.ignore(c)):_.each(_.many(_.each(p,_.ignore(d))),px,_.ignore(c)));},set:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return function(s){var r=null,p=null,q=null,rx=null,best=[[],s],last=false;for(var i=0;i<px.length;i++){q=null;p=null;r=null;last=(px.length==1);try{r=px[i].call(this,s);}catch(e){continue;}
rx=[[r[0]],r[1]];if(r[1].length>0&&!last){try{q=d.call(this,r[1]);}catch(ex){last=true;}}else{last=true;}
if(!last&&q[1].length===0){last=true;}
if(!last){var qx=[];for(var j=0;j<px.length;j++){if(i!=j){qx.push(px[j]);}}
p=_.set(qx,d).call(this,q[1]);if(p[0].length>0){rx[0]=rx[0].concat(p[0]);rx[1]=p[1];}}
if(rx[1].length<best[1].length){best=rx;}
if(best[1].length===0){break;}}
if(best[0].length===0){return best;}
if(c){try{q=c.call(this,best[1]);}catch(ey){throw new $P.Exception(best[1]);}
best[1]=q[1];}
return best;};},forward:function(gr,fname){return function(s){return gr[fname].call(this,s);};},replace:function(rule,repl){return function(s){var r=rule.call(this,s);return[repl,r[1]];};},process:function(rule,fn){return function(s){var r=rule.call(this,s);return[fn.call(this,r[0]),r[1]];};},min:function(min,rule){return function(s){var rx=rule.call(this,s);if(rx[0].length<min){throw new $P.Exception(s);}
return rx;};}};var _generator=function(op){return function(){var args=null,rx=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments);}else if(arguments[0]instanceof Array){args=arguments[0];}
if(args){for(var i=0,px=args.shift();i<px.length;i++){args.unshift(px[i]);rx.push(op.apply(null,args));args.shift();return rx;}}else{return op.apply(null,arguments);}};};var gx="optional not ignore cache".split(/\s/);for(var i=0;i<gx.length;i++){_[gx[i]]=_generator(_[gx[i]]);}
var _vector=function(op){return function(){if(arguments[0]instanceof Array){return op.apply(null,arguments[0]);}else{return op.apply(null,arguments);}};};var vx="each any all".split(/\s/);for(var j=0;j<vx.length;j++){_[vx[j]]=_vector(_[vx[j]]);}}());(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo;var flattenAndCompact=function(ax){var rx=[];for(var i=0;i<ax.length;i++){if(ax[i]instanceof Array){rx=rx.concat(flattenAndCompact(ax[i]));}else{if(ax[i]){rx.push(ax[i]);}}}
return rx;};$D.Grammar={};$D.Translator={hour:function(s){return function(){this.hour=Number(s);};},minute:function(s){return function(){this.minute=Number(s);};},second:function(s){return function(){this.second=Number(s);};},meridian:function(s){return function(){this.meridian=s.slice(0,1).toLowerCase();};},timezone:function(s){return function(){var n=s.replace(/[^\d\+\-]/g,"");if(n.length){this.timezoneOffset=Number(n);}else{this.timezone=s.toLowerCase();}};},day:function(x){var s=x[0];return function(){this.day=Number(s.match(/\d+/)[0]);};},month:function(s){return function(){this.month=(s.length==3)?"jan feb mar apr may jun jul aug sep oct nov dec".indexOf(s)/4:Number(s)-1;};},year:function(s){return function(){var n=Number(s);this.year=((s.length>2)?n:(n+(((n+2000)<$C.twoDigitYearMax)?2000:1900)));};},rday:function(s){return function(){switch(s){case"yesterday":this.days=-1;break;case"tomorrow":this.days=1;break;case"today":this.days=0;break;case"now":this.days=0;this.now=true;break;}};},finishExact:function(x){x=(x instanceof Array)?x:[x];for(var i=0;i<x.length;i++){if(x[i]){x[i].call(this);}}
var now=new Date();if((this.hour||this.minute)&&(!this.month&&!this.year&&!this.day)){this.day=now.getDate();}
if(!this.year){this.year=now.getFullYear();}
if(!this.month&&this.month!==0){this.month=now.getMonth();}
if(!this.day){this.day=1;}
if(!this.hour){this.hour=0;}
if(!this.minute){this.minute=0;}
if(!this.second){this.second=0;}
if(this.meridian&&this.hour){if(this.meridian=="p"&&this.hour<12){this.hour=this.hour+12;}else if(this.meridian=="a"&&this.hour==12){this.hour=0;}}
if(this.day>$D.getDaysInMonth(this.year,this.month)){throw new RangeError(this.day+" is not a valid value for days.");}
var r=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second);if(this.timezone){r.set({timezone:this.timezone});}else if(this.timezoneOffset){r.set({timezoneOffset:this.timezoneOffset});}
return r;},finish:function(x){x=(x instanceof Array)?flattenAndCompact(x):[x];if(x.length===0){return null;}
for(var i=0;i<x.length;i++){if(typeof x[i]=="function"){x[i].call(this);}}
var today=$D.today();if(this.now&&!this.unit&&!this.operator){return new Date();}else if(this.now){today=new Date();}
var expression=!!(this.days&&this.days!==null||this.orient||this.operator);var gap,mod,orient;orient=((this.orient=="past"||this.operator=="subtract")?-1:1);if(!this.now&&"hour minute second".indexOf(this.unit)!=-1){today.setTimeToNow();}
if(this.month||this.month===0){if("year day hour minute second".indexOf(this.unit)!=-1){this.value=this.month+1;this.month=null;expression=true;}}
if(!expression&&this.weekday&&!this.day&&!this.days){var temp=Date[this.weekday]();this.day=temp.getDate();if(!this.month){this.month=temp.getMonth();}
this.year=temp.getFullYear();}
if(expression&&this.weekday&&this.unit!="month"){this.unit="day";gap=($D.getDayNumberFromName(this.weekday)-today.getDay());mod=7;this.days=gap?((gap+(orient*mod))%mod):(orient*mod);}
if(this.month&&this.unit=="day"&&this.operator){this.value=(this.month+1);this.month=null;}
if(this.value!=null&&this.month!=null&&this.year!=null){this.day=this.value*1;}
if(this.month&&!this.day&&this.value){today.set({day:this.value*1});if(!expression){this.day=this.value*1;}}
if(!this.month&&this.value&&this.unit=="month"&&!this.now){this.month=this.value;expression=true;}
if(expression&&(this.month||this.month===0)&&this.unit!="year"){this.unit="month";gap=(this.month-today.getMonth());mod=12;this.months=gap?((gap+(orient*mod))%mod):(orient*mod);this.month=null;}
if(!this.unit){this.unit="day";}
if(!this.value&&this.operator&&this.operator!==null&&this[this.unit+"s"]&&this[this.unit+"s"]!==null){this[this.unit+"s"]=this[this.unit+"s"]+((this.operator=="add")?1:-1)+(this.value||0)*orient;}else if(this[this.unit+"s"]==null||this.operator!=null){if(!this.value){this.value=1;}
this[this.unit+"s"]=this.value*orient;}
if(this.meridian&&this.hour){if(this.meridian=="p"&&this.hour<12){this.hour=this.hour+12;}else if(this.meridian=="a"&&this.hour==12){this.hour=0;}}
if(this.weekday&&!this.day&&!this.days){var temp=Date[this.weekday]();this.day=temp.getDate();if(temp.getMonth()!==today.getMonth()){this.month=temp.getMonth();}}
if((this.month||this.month===0)&&!this.day){this.day=1;}
if(!this.orient&&!this.operator&&this.unit=="week"&&this.value&&!this.day&&!this.month){return Date.today().setWeek(this.value);}
if(expression&&this.timezone&&this.day&&this.days){this.day=this.days;}
return(expression)?today.add(this):today.set(this);}};var _=$D.Parsing.Operators,g=$D.Grammar,t=$D.Translator,_fn;g.datePartDelimiter=_.rtoken(/^([\s\-\.\,\/\x27]+)/);g.timePartDelimiter=_.stoken(":");g.whiteSpace=_.rtoken(/^\s*/);g.generalDelimiter=_.rtoken(/^(([\s\,]|at|@|on)+)/);var _C={};g.ctoken=function(keys){var fn=_C[keys];if(!fn){var c=$C.regexPatterns;var kx=keys.split(/\s+/),px=[];for(var i=0;i<kx.length;i++){px.push(_.replace(_.rtoken(c[kx[i]]),kx[i]));}
fn=_C[keys]=_.any.apply(null,px);}
return fn;};g.ctoken2=function(key){return _.rtoken($C.regexPatterns[key]);};g.h=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),t.hour));g.hh=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/),t.hour));g.H=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),t.hour));g.HH=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/),t.hour));g.m=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.minute));g.mm=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.minute));g.s=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.second));g.ss=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.second));g.hms=_.cache(_.sequence([g.H,g.m,g.s],g.timePartDelimiter));g.t=_.cache(_.process(g.ctoken2("shortMeridian"),t.meridian));g.tt=_.cache(_.process(g.ctoken2("longMeridian"),t.meridian));g.z=_.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),t.timezone));g.zz=_.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),t.timezone));g.zzz=_.cache(_.process(g.ctoken2("timezone"),t.timezone));g.timeSuffix=_.each(_.ignore(g.whiteSpace),_.set([g.tt,g.zzz]));g.time=_.each(_.optional(_.ignore(_.stoken("T"))),g.hms,g.timeSuffix);g.d=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.dd=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.ddd=g.dddd=_.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),function(s){return function(){this.weekday=s;};}));g.M=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/),t.month));g.MM=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/),t.month));g.MMM=g.MMMM=_.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),t.month));g.y=_.cache(_.process(_.rtoken(/^(\d\d?)/),t.year));g.yy=_.cache(_.process(_.rtoken(/^(\d\d)/),t.year));g.yyy=_.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/),t.year));g.yyyy=_.cache(_.process(_.rtoken(/^(\d\d\d\d)/),t.year));_fn=function(){return _.each(_.any.apply(null,arguments),_.not(g.ctoken2("timeContext")));};g.day=_fn(g.d,g.dd);g.month=_fn(g.M,g.MMM);g.year=_fn(g.yyyy,g.yy);g.orientation=_.process(g.ctoken("past future"),function(s){return function(){this.orient=s;};});g.operator=_.process(g.ctoken("add subtract"),function(s){return function(){this.operator=s;};});g.rday=_.process(g.ctoken("yesterday tomorrow today now"),t.rday);g.unit=_.process(g.ctoken("second minute hour day week month year"),function(s){return function(){this.unit=s;};});g.value=_.process(_.rtoken(/^\d\d?(st|nd|rd|th)?/),function(s){return function(){this.value=s.replace(/\D/g,"");};});g.expression=_.set([g.rday,g.operator,g.value,g.unit,g.orientation,g.ddd,g.MMM]);_fn=function(){return _.set(arguments,g.datePartDelimiter);};g.mdy=_fn(g.ddd,g.month,g.day,g.year);g.ymd=_fn(g.ddd,g.year,g.month,g.day);g.dmy=_fn(g.ddd,g.day,g.month,g.year);g.date=function(s){return((g[$C.dateElementOrder]||g.mdy).call(this,s));};g.format=_.process(_.many(_.any(_.process(_.rtoken(/^(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(fmt){if(g[fmt]){return g[fmt];}else{throw $D.Parsing.Exception(fmt);}}),_.process(_.rtoken(/^[^dMyhHmstz]+/),function(s){return _.ignore(_.stoken(s));}))),function(rules){return _.process(_.each.apply(null,rules),t.finishExact);});var _F={};var _get=function(f){return _F[f]=(_F[f]||g.format(f)[0]);};g.formats=function(fx){if(fx instanceof Array){var rx=[];for(var i=0;i<fx.length;i++){rx.push(_get(fx[i]));}
return _.any.apply(null,rx);}else{return _get(fx);}};g._formats=g.formats(["\"yyyy-MM-ddTHH:mm:ssZ\"","yyyy-MM-ddTHH:mm:ssZ","yyyy-MM-ddTHH:mm:ssz","yyyy-MM-ddTHH:mm:ss","yyyy-MM-ddTHH:mmZ","yyyy-MM-ddTHH:mmz","yyyy-MM-ddTHH:mm","ddd, MMM dd, yyyy H:mm:ss tt","ddd MMM d yyyy HH:mm:ss zzz","MMddyyyy","ddMMyyyy","Mddyyyy","ddMyyyy","Mdyyyy","dMyyyy","yyyy","Mdyy","dMyy","d"]);g._start=_.process(_.set([g.date,g.time,g.expression],g.generalDelimiter,g.whiteSpace),t.finish);g.start=function(s){try{var r=g._formats.call({},s);if(r[1].length===0){return r;}}catch(e){}
return g._start.call({},s);};$D._parse=$D.parse;$D.parse=function(s){var r=null;if(!s){return null;}
if(s instanceof Date){return s;}
try{r=$D.Grammar.start.call({},s.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1"));}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};$D.getParseFunction=function(fx){var fn=$D.Grammar.formats(fx);return function(s){var r=null;try{r=fn.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};};$D.parseExact=function(s,fx){return $D.getParseFunction(fx)(s);};}());





/****************************************************************/
/*  original filename timejs.js                        */
/****************************************************************/


/**
 * @version: 1.0 Alpha-1
 * @author: Coolite Inc. http://www.coolite.com/
 * @date: 2008-04-13
 * @copyright: Copyright (c) 2006-2008, Coolite Inc. (http://www.coolite.com/). All rights reserved.
 * @license: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/.
 * @website: http://www.datejs.com/
 */

/*
 * TimeSpan(milliseconds);
 * TimeSpan(days, hours, minutes, seconds);
 * TimeSpan(days, hours, minutes, seconds, milliseconds);
 */
var TimeSpan = function (days, hours, minutes, seconds, milliseconds) {
    var attrs = "days hours minutes seconds milliseconds".split(/\s+/);

    var gFn = function (attr) {
        return function () {
            return this[attr];
        };
    };

    var sFn = function (attr) {
        return function (val) {
            this[attr] = val;
            return this;
        };
    };

    for (var i = 0; i < attrs.length ; i++) {
        var $a = attrs[i], $b = $a.slice(0, 1).toUpperCase() + $a.slice(1);
        TimeSpan.prototype[$a] = 0;
        TimeSpan.prototype["get" + $b] = gFn($a);
        TimeSpan.prototype["set" + $b] = sFn($a);
    }

    if (arguments.length == 4) {
        this.setDays(days);
        this.setHours(hours);
        this.setMinutes(minutes);
        this.setSeconds(seconds);
    } else if (arguments.length == 5) {
        this.setDays(days);
        this.setHours(hours);
        this.setMinutes(minutes);
        this.setSeconds(seconds);
        this.setMilliseconds(milliseconds);
    } else if (arguments.length == 1 && typeof days == "number") {
        var orient = (days < 0) ? -1 : +1;
        this.setMilliseconds(Math.abs(days));

        this.setDays(Math.floor(this.getMilliseconds() / 86400000) * orient);
        this.setMilliseconds(this.getMilliseconds() % 86400000);

        this.setHours(Math.floor(this.getMilliseconds() / 3600000) * orient);
        this.setMilliseconds(this.getMilliseconds() % 3600000);

        this.setMinutes(Math.floor(this.getMilliseconds() / 60000) * orient);
        this.setMilliseconds(this.getMilliseconds() % 60000);

        this.setSeconds(Math.floor(this.getMilliseconds() / 1000) * orient);
        this.setMilliseconds(this.getMilliseconds() % 1000);

        this.setMilliseconds(this.getMilliseconds() * orient);
    }

    this.getTotalMilliseconds = function () {
        return (this.getDays() * 86400000) + (this.getHours() * 3600000) + (this.getMinutes() * 60000) + (this.getSeconds() * 1000);
    };

    this.compareTo = function (time) {
        var t1 = new Date(1970, 1, 1, this.getHours(), this.getMinutes(), this.getSeconds()), t2;
        if (time === null) {
            t2 = new Date(1970, 1, 1, 0, 0, 0);
        }
        else {
            t2 = new Date(1970, 1, 1, time.getHours(), time.getMinutes(), time.getSeconds());
        }
        return (t1 < t2) ? -1 : (t1 > t2) ? 1 : 0;
    };

    this.equals = function (time) {
        return (this.compareTo(time) === 0);
    };

    this.add = function (time) {
        return (time === null) ? this : this.addSeconds(time.getTotalMilliseconds() / 1000);
    };

    this.subtract = function (time) {
        return (time === null) ? this : this.addSeconds(-time.getTotalMilliseconds() / 1000);
    };

    this.addDays = function (n) {
        return new TimeSpan(this.getTotalMilliseconds() + (n * 86400000));
    };

    this.addHours = function (n) {
        return new TimeSpan(this.getTotalMilliseconds() + (n * 3600000));
    };

    this.addMinutes = function (n) {
        return new TimeSpan(this.getTotalMilliseconds() + (n * 60000));
    };

    this.addSeconds = function (n) {
        return new TimeSpan(this.getTotalMilliseconds() + (n * 1000));
    };

    this.addMilliseconds = function (n) {
        return new TimeSpan(this.getTotalMilliseconds() + n);
    };

    this.get12HourHour = function () {
        return (this.getHours() > 12) ? this.getHours() - 12 : (this.getHours() === 0) ? 12 : this.getHours();
    };

    this.getDesignator = function () {
        return (this.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator;
    };

    this.toString = function (format) {
        this._toString = function () {
            if (this.getDays() !== null && this.getDays() > 0) {
                return this.getDays() + "." + this.getHours() + ":" + this.p(this.getMinutes()) + ":" + this.p(this.getSeconds());
            }
            else {
                return this.getHours() + ":" + this.p(this.getMinutes()) + ":" + this.p(this.getSeconds());
            }
        };

        this.p = function (s) {
            return (s.toString().length < 2) ? "0" + s : s;
        };

        var me = this;

        return format ? format.replace(/dd?|HH?|hh?|mm?|ss?|tt?/g,
        function (format) {
            switch (format) {
            case "d":
                return me.getDays();
            case "dd":
                return me.p(me.getDays());
            case "H":
                return me.getHours();
            case "HH":
                return me.p(me.getHours());
            case "h":
                return me.get12HourHour();
            case "hh":
                return me.p(me.get12HourHour());
            case "m":
                return me.getMinutes();
            case "mm":
                return me.p(me.getMinutes());
            case "s":
                return me.getSeconds();
            case "ss":
                return me.p(me.getSeconds());
            case "t":
                return ((me.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator).substring(0, 1);
            case "tt":
                return (me.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator;
            }
        }
        ) : this._toString();
    };
    return this;
};

/**
 * Gets the time of day for this date instances.
 * @return {TimeSpan} TimeSpan
 */
Date.prototype.getTimeOfDay = function () {
    return new TimeSpan(0, this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
};

/*
 * TimePeriod(startDate, endDate);
 * TimePeriod(years, months, days, hours, minutes, seconds, milliseconds);
 */
var TimePeriod = function (years, months, days, hours, minutes, seconds, milliseconds) {
    var attrs = "years months days hours minutes seconds milliseconds".split(/\s+/);

    var gFn = function (attr) {
        return function () {
            return this[attr];
        };
    };

    var sFn = function (attr) {
        return function (val) {
            this[attr] = val;
            return this;
        };
    };

    for (var i = 0; i < attrs.length ; i++) {
        var $a = attrs[i], $b = $a.slice(0, 1).toUpperCase() + $a.slice(1);
        TimePeriod.prototype[$a] = 0;
        TimePeriod.prototype["get" + $b] = gFn($a);
        TimePeriod.prototype["set" + $b] = sFn($a);
    }

    if (arguments.length == 7) {
        this.years = years;
        this.months = months;
        this.setDays(days);
        this.setHours(hours);
        this.setMinutes(minutes);
        this.setSeconds(seconds);
        this.setMilliseconds(milliseconds);
    } else if (arguments.length == 2 && arguments[0] instanceof Date && arguments[1] instanceof Date) {
        // startDate and endDate as arguments

        var d1 = years.clone();
        var d2 = months.clone();

        var temp = d1.clone();
        var orient = (d1 > d2) ? -1 : +1;

        this.years = d2.getFullYear() - d1.getFullYear();
        temp.addYears(this.years);

        if (orient == +1) {
            if (temp > d2) {
                if (this.years !== 0) {
                    this.years--;
                }
            }
        } else {
            if (temp < d2) {
                if (this.years !== 0) {
                    this.years++;
                }
            }
        }

        d1.addYears(this.years);

        if (orient == +1) {
            while (d1 < d2 && d1.clone().addDays(Date.getDaysInMonth(d1.getYear(), d1.getMonth()) ) < d2) {
                d1.addMonths(1);
                this.months++;
            }
        }
        else {
            while (d1 > d2 && d1.clone().addDays(-d1.getDaysInMonth()) > d2) {
                d1.addMonths(-1);
                this.months--;
            }
        }

        var diff = d2 - d1;

        if (diff !== 0) {
            var ts = new TimeSpan(diff);
            this.setDays(ts.getDays());
            this.setHours(ts.getHours());
            this.setMinutes(ts.getMinutes());
            this.setSeconds(ts.getSeconds());
            this.setMilliseconds(ts.getMilliseconds());
        }
    }
    return this;
};


/****************************************************************/
/*  original filename date_extensions.js                        */
/****************************************************************/


/* -*- Mode:JavaScript; c-basic-offset:2; indent-tabs-mode:nil; c-indentation-style:"k&r" -*- */
// Add some methods with Ruby feeling to Date object, curtesy of Dee Zsombor

var RubyLikeDateMethods = {
  //alias for getFullYear
  year: function(){
    return this.getFullYear();
  },

  //day of year
  yday: function() {
    var year = this.year(), month = this.getMonth(), day = this.getDate();
    return (Date.UTC(year, month, day) - Date.UTC(year, 0, 1)) / 86400000 + 1;
  },

  to_localized_string: function(){
    var formatter = new DatePickerFormatter(window._dateFormat[0], window._dateFormat[1]);
    return formatter.date_to_string(this.year(), this.getMonth() + 1, this.getDate());
  },

  to_url_string: function(){
    var year = this.year(), month = this.getMonth() + 1, day = this.getDate();
    if(month < 10)
      month = '0' + month;
    if(day < 10)
      day = '0' + day;
    return [year, month, day].join('');
  }

};
Object.extend(Date.prototype, RubyLikeDateMethods);


/****************************************************************/
/*  original filename builder.js                        */
/****************************************************************/


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

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

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

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

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

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

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

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

/****************************************************************/
/*  original filename datepicker.js                        */
/****************************************************************/


/**
 * DatePicker widget using Prototype and Scriptaculous.
 * (c) 2007 Mathieu Jondet <mathieu@eulerian.com>
 * Eulerian Technologies
 *
 * DatePicker is freely distributable under the same terms as Prototype.
 *
 */

/**
 * DatePickerFormatter class for matching and stringifying dates.
 *
 * By Arturas Slajus <x11@arturaz.net>.
 */
var DatePickerFormatter = Class.create();
DatePickerFormatter.prototype = {
    /**
     * Create a DatePickerFormatter.
     *
     * format: specify a format by passing 3 value array consisting of
     *   "yyyy", "mm", "dd". Default: ["yyyy", "mm", "dd"].
     *
     * separator: string for splitting the values. Default: "-".
     *
     * Use it like this:
     *   var df = new DatePickerFormatter(["dd", "mm", "yyyy"], "/");
     *   df.current_date();
     *   df.match("7/7/2007");
     */
    initialize: function(format, separator) {
      if (Object.isUndefined(format))
        format = ["yyyy", "mm", "dd"];
      if (Object.isUndefined(separator))
        separator = "-";

      this._format    = format;
      this.separator  = separator;

      this._format_year_index = format.indexOf("yyyy");
      this._format_month_index= format.indexOf("mm");
      this._format_day_index  = format.indexOf("dd");

      this._year_regexp   = /^\d{4}$/;
      this._month_regexp  = /^0\d$|^1[012]$|^\d$/;
      this._day_regexp    = /^0\d$|^[12]\d$|^3[01]$|^\d$/;
    },

    /**
     * Match a string against date format.
     * Returns: [year, month, day]
     */
    match: function(str) {
      var d = str.split(this.separator);

      if (d.length < 3)
        return false;

      var year = d[this._format_year_index].match(this._year_regexp);
      if (year) { year = year[0]; } else { return false; }
      var month = d[this._format_month_index].match(this._month_regexp);
      if (month) { month = month[0]; } else { return false; }
      var day = d[this._format_day_index].match(this._day_regexp);
      if (day) { day = day[0]; } else { return false; }

      return [year, month, day];
    },

    /**
     * Return current date according to format.
     */
    current_date: function() {
        var d = new Date();

        return this.date_to_string(
            d.getFullYear(),
            d.getMonth() + 1,
            d.getDate()
       );
    },

    /**
     * Return a stringified date accordint to format.
     */
    date_to_string: function(year, month, day, separator) {
        if (Object.isUndefined(separator))
     separator = this.separator;

        var a = [0, 0, 0];
        a[this._format_year_index]  = year;
        a[this._format_month_index]     = month.toPaddedString(2);
        a[this._format_day_index]   = day.toPaddedString(2);

        return a.join(separator);
    }
};


/**
 * DatePicker
 */

var DatePicker  = Class.create();

DatePicker.prototype    = {
 Version    : '0.9.4',
 _relative  : null,
 _div       : null,
 _zindex    : 100,
 _keepFieldEmpty: false,
 _daysInMonth   : [31,28,31,30,31,30,31,31,30,31,30,31],
 _dateFormat    : window._dateFormat,
 /* language */
 _language  : 'en',
 _language_month    : $H({
  'en'  : [ 'January', 'February', 'March', 'April', 'May',
   'June', 'July', 'August', 'September', 'October', 'November', 'December' ]
 }),
 _language_day  : $H({
  'en'  : [ 'M', 'T', 'W', 'T', 'F', 'S', 'S' ]
 }),
 _language_close    : $H({
  'en'  : 'CLOSE'
 }),
 /* date manipulation */
 _todayDate     : new Date(),
 _current_date      : null,
 _clickCallback     : Prototype.emptyFunction,
 _cellCallback      : Prototype.emptyFunction,
 _id_datepicker     : null,
 _disablePastDate   : false,
 _disableFutureDate : false,
 _enableYearBrowse  : false,
 _oneDayInMs        : 24 * 3600 * 1000,
 /* positionning */
 _topOffset     : 0,
 _leftOffset        : 0,
 _isPositionned     : false,
 _relativePosition  : true,
 _setPositionTop    : 0,
 _setPositionLeft   : 0,
 _bodyAppend        : false,
 _contentAppend     : '',
 _showEvent     : 'click',
 /* Effects Adjustment */
 _showEffect        : "appear",
 _showDuration      : 0.001,
 _enableShowEffect  : true,
 _closeEffect       : "fade",
 _closeEffectDuration   : 0.1,
 _enableCloseEffect     : true,
 _closeTimer        : null,
 _enableCloseOnBlur : false,
 /* afterClose : called when the close function is executed */
 _afterClose    : Prototype.emptyFunction,
 /* return the name of current month in appropriate language */
 getMonthLocale : function ( month ) {
  return    this._language_month.get(this._language)[month];
 },
 getLocaleClose : function () {
  return    this._language_close.get(this._language);
 },

 set_to_current: function(){
   this._current_date = this._df.current_date();
   /* set the field value ? */
   if (!this._keepFieldEmpty)
     $(this._relative).value = this._current_date;
 },

 _initCurrentDate : function () {
  /* Create the DateFormatter */
  if(!this._df)
    this._df = new DatePickerFormatter(this._dateFormat[0], this._dateFormat[1]);
  /* check if value in field is proper, if not set to today */
  this._current_date = $F(this._relative);
  if (! this._df.match(this._current_date)){ this.set_to_current(); }

  var a_date = this._df.match(this._current_date);
  this._current_year = this._selected_year = Number(a_date[0]);
  this._current_mon = this._selected_mon = Number(a_date[1]) - 1;
  this._current_day = this._selected_day = Number(a_date[2]);
 },
 /* init */
 initialize : function ( h_p ) {
  this._dateFormat = window._dateFormat;
  /* arguments */
  this._relative= h_p["relative"];
  this._controller= h_p["controller"];
  if (h_p["language"])
   this._language = h_p["language"];
  this._zindex  = ( h_p["zindex"] ) ? parseInt(Number(h_p["zindex"])) : this._zindex;
  if (!Object.isUndefined(h_p["keepFieldEmpty"]))
   this._keepFieldEmpty = h_p["keepFieldEmpty"];
  if (Object.isFunction(h_p["clickCallback"]))
   this._clickCallback  = h_p["clickCallback"];
  if (!Object.isUndefined(h_p["leftOffset"]))
   this._leftOffset = parseInt(h_p["leftOffset"]);
  if (!Object.isUndefined(h_p["topOffset"]))
   this._topOffset  = parseInt(h_p["topOffset"]);
  if (!Object.isUndefined(h_p["relativePosition"]))
   this._relativePosition = h_p["relativePosition"];
  if (!Object.isUndefined(h_p["showEvent"]))
   this._showEvent  = h_p["showEvent"];
  if (!Object.isUndefined(h_p["showEffect"]))
   this._showEffect     = h_p["showEffect"];
  if (!Object.isUndefined(h_p["contentAppend"]))
   this._contentAppend  = h_p["contentAppend"];
  if (!Object.isUndefined(h_p["enableShowEffect"]))
   this._enableShowEffect   = h_p["enableShowEffect"];
  if (!Object.isUndefined(h_p["showDuration"]))
   this._showDuration   = h_p["showDuration"];
  if (!Object.isUndefined(h_p["closeEffect"]))
   this._closeEffect    = h_p["closeEffect"];
  if (!Object.isUndefined(h_p["enableCloseEffect"]))
   this._enableCloseEffect  = h_p["enableCloseEffect"];
  if (!Object.isUndefined(h_p["closeEffectDuration"]))
   this._closeEffectDuration = h_p["closeEffectDuration"];
  if (Object.isFunction(h_p["afterClose"]))
   this._afterClose = h_p["afterClose"];
  if (!Object.isUndefined(h_p["externalControl"]))
   this._externalControl= h_p["externalControl"];
  if (!Object.isUndefined(h_p["dateFormat"]))
   this._dateFormat = h_p["dateFormat"];
  if (Object.isFunction(h_p["cellCallback"]))
   this._cellCallback   = h_p["cellCallback"];
  this._setPositionTop  = ( h_p["setPositionTop"] ) ?
   parseInt(Number(h_p["setPositionTop"])) : 0;
  this._setPositionLeft = ( h_p["setPositionLeft"] ) ?
   parseInt(Number(h_p["setPositionLeft"])) : 0;
  if (!Object.isUndefined(h_p["enableCloseOnBlur"]) && h_p["enableCloseOnBlur"])
   this._enableCloseOnBlur  = true;
  if (!Object.isUndefined(h_p["disablePastDate"]) && h_p["disablePastDate"])
   this._disablePastDate    = true;
  if (!Object.isUndefined(h_p["disableFutureDate"]) &&
   !h_p["disableFutureDate"])
   this._disableFutureDate  = false;
  if (!Object.isUndefined(h_p["enableYearBrowse"]))
   this._enableYearBrowse   = true;
  this._id_datepicker       = 'datepicker-'+this._relative;
  this._id_datepicker_prev  = this._id_datepicker+'-prev';
  this._id_datepicker_next  = this._id_datepicker+'-next';
  this._id_datepicker_prev_year = this._id_datepicker_prev+'-year';
  this._id_datepicker_next_year = this._id_datepicker_next+'-year';
  this._id_datepicker_hdr   = this._id_datepicker+'-header';
/* this._id_datepicker_ftr   = this._id_datepicker+'-footer'; */

  /* build up calendar skel */
  this._div = new Element('div', {
   id : this._id_datepicker,
   className : 'datepicker',
   style : 'display: none; z-index:'+this._zindex });

  this._div.innerHTML = '<div class="datepicker-container"><div class="datepicker-navigation"><div id="'+this._id_datepicker_hdr+'">&nbsp;</div><a href="javascript:void(0);" id="'+this._id_datepicker_next+'" class="datepicker-next-month">&laquo;</a><a href="javascript:void(0);" id="'+this._id_datepicker_prev+'" class="datepicker-prev-month">&raquo;</a></div>'+
                        '<table><thead><tr><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th><th>S</th></tr><tr><td colspan="7">&nbsp;</td></tr></thead>' +
                        '<tbody id="'+this._id_datepicker+'-tbody"></tbody></table></div>';
  /* finally declare the event listener on input field */
  Event.observe(this._relative,
    this._showEvent, this.click.bindAsEventListener(this), false);
  /* need to append on body when doc is loaded for IE */
  document.observe('dom:loaded', this.load.bindAsEventListener(this), false);
  var close_with_delay = function (e) {
    this._closeTimer = this.close.bind(this).delay(0.1);
  };
  document.observe('keypress', close_with_delay.bindAsEventListener(this));
  /* automatically close when blur event is triggered */
  if ( this._enableCloseOnBlur ) {
   Event.observe(this._relative, 'blur', close_with_delay.bindAsEventListener(this));
   Event.observe(this._div, 'click', function (e) {
    if (this._closeTimer) {
     window.clearTimeout(this._closeTimer);
     this._closeTimer = null;
    }
   });
  }
 },
 /**
  * load    : called when document is fully-loaded to append datepicker
  *       to main object.
  */
 load       : function () {
  this._dateFormat = window._dateFormat;
  /* if externalControl defined set the observer on it */
  if (this._externalControl)
   Event.observe(this._externalControl, 'click',
    this.click.bindAsEventListener(this), false);
  /* append to page */
  if (this._relativeAppend) {
   /* append to parent node */
   if ($(this._relative).parentNode) {
    this._div.innerHTML = this._wrap_in_iframe(this._div.innerHTML);
    $(this._relative).parentNode.appendChild( this._div );
   }
  } else {
   /* append to body tag or to provided contentAppend id */
   var body = ( this._contentAppend ) ?
    $(this._contentAppend) : document.getElementsByTagName("body").item(0);
   if (body) {
    this._div.innerHTML = this._wrap_in_iframe(this._div.innerHTML);
    body.appendChild(this._div);
   }
   if ( this._relativePosition ) {
     var a_pos = (this._externalControl) ? Element.cumulativeOffset($(this._externalControl))  : Element.cumulativeOffset($(this._relative));
     this.setPosition((a_pos[1] + Element.getHeight($(this._relative) )), (a_pos[0] + Math.round( Element.getWidth($(this._relative) )/2)));
   } else {
    if (this._setPositionTop || this._setPositionLeft)
     this.setPosition(this._setPositionTop, this._setPositionLeft);
   }
  }
  /* init the date in field if needed */
  this._initCurrentDate();
  /* set the close locale content */
  /*$(this._id_datepicker_ftr).innerHTML = this.getLocaleClose();*/
  /* declare the observers for UI control */
  Event.observe($(this._id_datepicker_prev),
    'click', this.prevMonth.bindAsEventListener(this), false);
  Event.observe($(this._id_datepicker_next),
    'click', this.nextMonth.bindAsEventListener(this), false);
  if ( this._enableYearBrowse ) {
   Event.observe($(this._id_datepicker_prev_year),
     'click', this.prevYear.bindAsEventListener(this), false);
   Event.observe($(this._id_datepicker_next_year),
     'click', this.nextYear.bindAsEventListener(this), false);
  }
/*  Event.observe($(this._id_datepicker_ftr), 'click', this.close.bindAsEventListener(this), false); */
 },
 /* hack for buggy form elements layering in IE */
 _wrap_in_iframe    : function ( content ) {
  var _iframe_src   = '/blank.html';

  return ( Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6 ) ?
    "<div id=\"datepicker-ie6frame\"><iframe width='100%' height='100%' marginwidth='0' marginheight='0' frameborder='0' src='"+ _iframe_src +"' style='filter:alpha(Opacity=50);'></iframe>" + content + "</div>" : content;
 },
 /**
  * visible : return the visibility status of the datepicker.
  */
 visible    : function () {
  return    ( $(this._id_datepicker) ) ?
   $(this._id_datepicker).visible() : false;
 },
 /**
  * click   : called when input element is clicked
  */
 click      : function (event) {
  if ( $(this._id_datepicker) == null ) this.load();
  if (this._relativePosition) {
    var a_pos = (this._externalControl) ? Element.cumulativeOffset($(this._externalControl)) : Element.cumulativeOffset($(this._relative));
    this.setPosition((a_pos[1] + Element.getHeight($(this._relative) )),  (a_pos[0] + Math.round( Element.getWidth($(this._relative) )/2)));
    this._isPositionned  = true;
  }
  if (!this.visible()) {
   this._initCurrentDate();
   this._redrawCalendar();
  }
  eval(this._clickCallback());
  if ( this._enableShowEffect ) new Effect.toggle(this._id_datepicker, this._showEffect, { duration: this._showDuration });
  else $(this._id_datepicker).show();

  event.stop();
  var testClick = function(event){
    var elt = $(Event.element(event)).up('.datepicker');
    if (!elt && this.visible()) this.close();
  };
  Event.observe(document, 'click', testClick.bindAsEventListener(this));

  /* clean timer */
  if (this._closeTimer) {
   window.clearTimeout(this._closeTimer);
   this._closeTimer = null;
  }
 },
 /**
  * close   : called when the datepicker is closed
  */
  close      : function () {
    Event.stopObserving(document, 'click');


  if (!$(this._id_datepicker)) return;
  if ( this._enableCloseEffect ) {
   switch(this._closeEffect) {
    case 'puff':
     new Effect.Puff(this._id_datepicker, {
      duration : this._closeEffectDuration });
     break;
    case 'blindUp':
     new Effect.BlindUp(this._id_datepicker, {
      duration : this._closeEffectDuration });
     break;
    case 'dropOut':
     new Effect.DropOut(this._id_datepicker, {
      duration : this._closeEffectDuration });
     break;
    case 'switchOff':
     new Effect.SwitchOff(this._id_datepicker, {
      duration : this._closeEffectDuration });
     break;
    case 'squish':
     new Effect.Squish(this._id_datepicker, {
      duration : this._closeEffectDuration });
     break;
    case 'fold':
     new Effect.Fold(this._id_datepicker, {
      duration : this._closeEffectDuration });
     break;
    case 'shrink':
     new Effect.Shrink(this._id_datepicker, {
      duration : this._closeEffectDuration });
     break;
    default:
     new Effect.Fade(this._id_datepicker, {
      duration : this._closeEffectDuration });
     break;
   };
  } else {
   $(this._id_datepicker).hide();
  }
  eval(this._afterClose());
 },
 /**
  * setDateFormat
  */
 setDateFormat  : function ( format, separator ) {
  if (Object.isUndefined(format))
   format   = this._dateFormat[0];
  if (Object.isUndefined(separator))
   separator    = this._dateFormat[1];
  this._dateFormat  = [ format, separator ];
 },
 /**
  * setPosition : set the position of the datepicker.
  *  param : t=top | l=left
  */
 setPosition    : function ( t, l ) {
  var h_pos = { 'top' : '0px', 'left' : '0px' };
  if (!Object.isUndefined(t))
   h_pos['top'] = Number(t)+this._topOffset+'px';
  if (!Object.isUndefined(l))
   h_pos['left']= Number(l)+this._leftOffset+'px';
  $(this._id_datepicker).setStyle(h_pos);
  this._isPositionned   = true;
 },
 /**
  * _getMonthDays : given the year and month find the number of days.
  */
 _getMonthDays  : function ( year, month ) {
  if (((0 == (year%4)) &&
   ( (0 != (year%100)) || (0 == (year%400)))) && (month == 1))
   return 29;
  return this._daysInMonth[month];
 },
 /**
  * _buildCalendar  : draw the days array for current date
  */
 _buildCalendar     : function () {
  // PF
  var _self = this;
  var tbody = $(this._id_datepicker+'-tbody');
  try {
   while ( tbody.hasChildNodes() )
    tbody.removeChild(tbody.childNodes[0]);
  } catch ( e ) {};
  /* generate day headers
  var trDay = new Element('tr');
  this._language_day.get(this._language).each( function ( item ) {
   var td   = new Element('th');
   td.innerHTML = item;
   td.className = 'wday';
   trDay.appendChild( td );
  });
  tbody.appendChild( trDay );
  */
  /* generate the content of days */

  /* build-up days matrix */
  var a_d   = [ [ 0, 0, 0, 0, 0, 0, 0 ] ,[ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
  ];
  /* set date at beginning of month to display */
  var d     = new Date(this._current_year, this._current_mon, 1, 12);
  /* start the day list on monday */
  var startIndex    = ( !d.getDay() ) ? 6 : d.getDay() - 1;
  var nbDaysInMonth = this._getMonthDays(this._current_year, this._current_mon);
  var daysIndex     = 1;
  for ( var j = startIndex; j < 7; j++ ) {
    var classes = new Array();
    if((daysIndex == this._todayDate.getDate()) && (this._current_mon  == this._todayDate.getMonth()) && (this._current_year == this._todayDate.getFullYear())) classes.push('today');
    if(daysIndex==this._selected_day && this._current_mon == this._selected_mon && this._current_year == this._selected_year) classes.push('selected');
   a_d[0][j]    = {
     d : daysIndex
    ,m : this._current_mon
    ,y : this._current_year
    ,c : classes.join(' ')
   };
   daysIndex++;
  }
  var a_prevMY  = this._prevMonthYear();
  var nbDaysInMonthPrev = this._getMonthDays(a_prevMY[1], a_prevMY[0]);
  for ( var j = 0; j < startIndex; j++ ) {
    var classes = new Array('outbound');
    if((Number(nbDaysInMonthPrev - startIndex + j + 1) == this._todayDate.getDate()) && (Number(a_prevMY[0])  == this._todayDate.getMonth()) && (a_prevMY[1] == this._todayDate.getFullYear())) classes.push('today');
    if(Number(nbDaysInMonthPrev - startIndex + j + 1)==this._selected_day && Number(a_prevMY[0]) == this._selected_mon && a_prevMY[1] == this._selected_year) classes.push('selected');

   a_d[0][j]    = {
     d : Number(nbDaysInMonthPrev - startIndex + j + 1)
    ,m : Number(a_prevMY[0])
    ,y : a_prevMY[1]
    ,c : classes.join(' ')
   };
  }
  var switchNextMonth   = false;
  var currentMonth  = this._current_mon;
  var currentYear   = this._current_year;

  for ( var i = 1; i < 6; i++ ) {
   for ( var j = 0; j < 7; j++ ) {
     var classes = new Array();
     if(switchNextMonth) classes.push('outbound');
     if((daysIndex == this._todayDate.getDate()) && (currentMonth  == this._todayDate.getMonth()) && (currentYear == this._todayDate.getFullYear())) classes.push('today');
     if(daysIndex==this._selected_day && currentMonth == this._selected_mon && currentYear == this._selected_year) classes.push('selected');

     a_d[i][j]   = { d : daysIndex, m : currentMonth, y : currentYear, c : classes.join(' ')
    };
    daysIndex++;
    /* if at the end of the month : reset counter */
    if (daysIndex > nbDaysInMonth ) {
     daysIndex  = 1;
     switchNextMonth = true;
     if (this._current_mon + 1 > 11 ) {
      currentMonth = 0;
      currentYear += 1;
     } else {
      currentMonth += 1;
     }
    }
   }
  }
  /* generate days for current date */
  for ( var i = 0; i < 6; i++ ) {
   var tr   = new Element('tr');
   for ( var j = 0; j < 7; j++ ) {
    var h_ij    = a_d[i][j];
    var td  = new Element('td');
    /* id is : datepicker-day-mon-year or depending on language other way */
    /* don't forget to add 1 on month for proper formmatting */
    var id  = $A([
     this._relative,
     this._df.date_to_string(h_ij["y"], h_ij["m"]+1, h_ij["d"], '-')
    ]).join('-');
    /* set id and classname for cell if exists */
    td.setAttribute('id', id);
    if (h_ij["c"])
     td.className   = h_ij["c"];
    /* on onclick : rebuild date value from id of current cell */
    var _curDate    = new Date();
    _curDate.setFullYear(h_ij["y"], h_ij["m"], h_ij["d"]);
    if ( this._disablePastDate || this._disableFutureDate ) {
     if ( this._disablePastDate ) {
      var _res  = ( _curDate >= this._todayDate ) ? true : false;
      this._bindCellOnClick( td, true, _res, h_ij["c"] );
     }
     if ( this._disableFutureDate ) {
      var _res  = ( this._todayDate.getTime() + this._oneDayInMs > _curDate.getTime() ) ? true : false;
      this._bindCellOnClick( td, true, _res,  h_ij["c"] );
     }
    } else {
     this._bindCellOnClick( td, false );
    }
    td.innerHTML= h_ij["d"];
    tr.appendChild( td );
   }
   tbody.appendChild( tr );
  }
  return    tbody;
 },
 /**
  * _bindCellOnClick    : bind the cell onclick depending on status.
  */
 _bindCellOnClick   : function ( td, wcompare, compareresult, h_ij_c ) {
  var doBind    = false;
  if ( wcompare ) {
   if ( compareresult ) {
    doBind  = true;
   } else {
    td.className= ( h_ij_c ) ? 'nclick_outbound' : 'nclick';
   }
  } else {
   doBind   = true;
  }
  if ( doBind ) {
   var _self    = this;
   td.onclick   = function () {
    $(_self._relative).value = String($(this).readAttribute('id')
      ).replace(_self._relative+'-','').replace(/-/g, _self._df.separator);
    /* if we have a cellCallback defined call it and pass it the cell */
    if (_self._cellCallback)
     _self._cellCallback(this);
    _self.close();
     if(_self._controller) {
       var yymmdd = _self._df.match($F(_self._relative));
       DatePickerHelper.redirectToDate(new Date(yymmdd[0], Number(yymmdd[1])-1, yymmdd[2]), _self._controller);
     }

   };
  }
 },
 /**
  * nextMonth   : redraw the calendar content for next month.
  */
 _nextMonthYear : function () {
  var c_mon = this._current_mon;
  var c_year    = this._current_year;
  if (c_mon + 1 > 11) {
   c_mon    = 0;
   c_year   += 1;
  } else {
   c_mon    += 1;
  }
  return    [ c_mon, c_year ];
 },
 nextMonth  : function () {
  var a_next    = this._nextMonthYear();
  var _nextMon  = a_next[0];
  var _nextYear = a_next[1];
  var _curDate  = new Date(); _curDate.setFullYear(_nextYear, _nextMon, 1);
  var _res  = ( this._todayDate.getTime() + this._oneDayInMs > _curDate.getTime() ) ? true : false;
  if ( this._disableFutureDate && !_res )
   return;
  this._current_mon = _nextMon;
  this._current_year    = _nextYear;
  this._redrawCalendar();
 },
 /**
  * prevMonth   : redraw the calendar content for previous month.
  */
 _prevMonthYear : function () {
  var c_mon = this._current_mon;
  var c_year    = this._current_year;
  if (c_mon - 1 < 0) {
   c_mon    = 11;
   c_year   -= 1;
  } else {
   c_mon    -= 1;
  }
  return    [ c_mon, c_year ];
 },
 prevMonth  : function () {
  var a_prev    = this._prevMonthYear();
  var _prevMon  = a_prev[0];
  var _prevYear = a_prev[1];
  var _curDate  = new Date(); _curDate.setFullYear(_prevYear, _prevMon, 1);
  var _res  = ( _curDate >= this._todayDate ) ? true : false;
  if ( this._disablePastDate && !_res && (_prevMon!=this._todayDate.getMonth()))
   return;
  this._current_mon = _prevMon;
  this._current_year    = _prevYear;
  this._redrawCalendar();
 },
 /**
  * prevYear    : redraw the calendar content for prev year.
  */
 _prevYear  : function () {
  var c_mon = this._current_mon;
  var c_year    = (this._current_year - 1);

  return    [ c_mon, c_year ];
 },
 prevYear   : function () {
  var a_next    = this._prevYear();
  var _nextMon  = a_next[0];
  var _nextYear = a_next[1];
  var _curDate  = new Date(); _curDate.setFullYear(_nextYear, _nextMon, 1);
  var _res  = ( this._todayDate.getTime() + this._oneDayInMs > _curDate.getTime() ) ? true : false;
  if ( this._disableFutureDate && !_res )
   return;
  this._current_mon = _nextMon;
  this._current_year    = _nextYear;
  this._redrawCalendar();
 },

 /**
  * nextYear    : redraw the calendar content for next year.
  */
 _nextYear  : function () {
  var c_mon = this._current_mon;
  var c_year    = (this._current_year + 1);

  return    [ c_mon, c_year ];
 },
 nextYear   : function () {
  var a_next    = this._nextYear();
  var _nextMon  = a_next[0];
  var _nextYear = a_next[1];
  var _curDate  = new Date(); _curDate.setFullYear(_nextYear, _nextMon, 1);
  var _res  = ( this._todayDate.getTime() + this._oneDayInMs > _curDate.getTime() ) ? true : false;
  if ( this._disableFutureDate && !_res )
   return;
  this._current_mon = _nextMon;
  this._current_year    = _nextYear;
  this._redrawCalendar();
 },

 _redrawCalendar    : function () {
  this._setLocaleHdr(); this._buildCalendar();
 },
 _setLocaleHdr  : function () {
  /* next link */
  var a_next    = this._nextMonthYear();
  $(this._id_datepicker_next).setAttribute('title',
   this.getMonthLocale(a_next[0])+' '+a_next[1]);
  /* prev link */
  var a_prev    = this._prevMonthYear();
  $(this._id_datepicker_prev).setAttribute('title',
   this.getMonthLocale(a_prev[0])+' '+a_prev[1]);
  /* year browse */
  if ( this._enableYearBrowse ) {
   var a_next_y = this._nextYear();
   $(this._id_datepicker_next_year).setAttribute('title',
     this.getMonthLocale(a_next_y[0])+' '+a_next_y[1]);
   var a_prev_y = this._prevYear();
   $(this._id_datepicker_prev_year).setAttribute('title',
     this.getMonthLocale(a_prev_y[0])+' '+a_prev_y[1]);
  }
  /* header */
  $(this._id_datepicker_hdr).update(this.getMonthLocale(this._current_mon)+'&nbsp;'+this._current_year);
 }
};
var DatePickerHelper = {
  redirectToDate: function(day, controller) {
    window.location = controller(day);
  }

}





/****************************************************************/
/*  original filename expense_category.js                        */
/****************************************************************/


var expense_category = {

  toggle_expense_category_editor: function(id) {
    $('expense-category-' + id + '-show', 'expense-category-' + id + '-edit').invoke('toggle');
    if($('expense-category-' + id + '-edit').visible())  $('expense-category-' + id + '-edit').down('.expense_category_name').activate();
  },

  toggle_expense_category_delete: function(id) {
    $('expense-category-' + id + '-edit', 'expense-category-' + id + '-delete').invoke('toggle');
  },

  save_buttons_id: 'save_buttons',
  save_loading_id: 'save_loading',

  save_loading: function(id) {
    expense_category.load_ids(id);
    $(expense_category.save_buttons_id).hide();
    $(expense_category.save_loading_id).show();
  },

  save_loaded: function(id) {
    expense_category.load_ids(id);
    $(expense_category.save_loading_id).hide();
    $(expense_category.save_buttons_id).show();
  },

  load_ids: function(id) {
    if(id) {
      expense_category.save_buttons_id = 'expense-category-' + id + '-save-buttons';
      expense_category.save_loading_id = 'expense-category-' + id + '-save-loading';
    }
  }

};






/****************************************************************/
/*  original filename expense.js                        */
/****************************************************************/


var expense = {
  current_user_id: 0,
  active_edit_expense_id: '',
  active_edit_expense_values: {},
  unit_based_categories: {},
  specific_year: '',
  specific_day: '',
  clients: [],
  categories: [],
  project_currencies: [],

  clear_active_edit_expense_id: function() {
    expense.active_edit_expense_id = '';
  },

  recompute_expense_entry_costs: function() {
    var costs = $$('#user_expense_rows .cost').pluck('innerHTML');
    var currency_symbols = costs.map(function(cost) {return cost.gsub(/[0-9\.\,\'\ ]/, ''); }).uniq();
    var total = 0;
    if(currency_symbols.size() == 1){
      var backup_symbol = Currency.currency_symbol;
      try  {
        Currency.currency_symbol = currency_symbols.first();
        total = costs.inject(0, function(sum, e) { return sum + (Currency.parse_float_with_currencies(e) || 0); });
      } finally{
        Currency.currency_symbol = backup_symbol;
      }
      $('total_amount').innerHTML = Currency.number_to_currency(total, {symbol : currency_symbols.first()});
      $('total_amount').show();
    } else if(currency_symbols.size() == 0) {
      $('total_amount').innerHTML = Currency.number_to_currency(0, {symbol : Currency.currency_symbol});
      $('total_amount').show();
    } else {
      $('total_amount').hide();
    }
  },

  register_on_change_handlers: function() {
    $('add_expense_project_category_selects').innerHTML = expense.construct_selectors_for('');
    $('expense_project_id').observe('change',expense.show_appropriate_currency);
    $('expense_expense_category_id').observe('change', expense.toggle_amount_inputs);
    expense.toggle_amount_inputs();
  },
  
  show_appropriate_currency: function(i) {
    var spotid = (parseInt(i)) ? "expense-"+parseInt(i)+"-currency-symbol" : "currency_symbol_spot";
    var projectid = (parseInt(i)) ? "expense-"+parseInt(i)+"-project-id" : "expense_project_id";
    
    if($(projectid).value!="" && expense.project_currencies[$(projectid).value]) $(spotid).innerHTML = expense.project_currencies[$(projectid).value];
  },

  calendar_url_for_weekly: function(day){
    var variable_part = '';
    if(day != undefined || day != null){
      variable_part = '/' + expense.current_user_id + expense.dated_url_part(day);
    }
    return '/expenses' + variable_part;
  },

  dated_url_part: function(day) {
    return '/' + day.yday() + '/' + day.year();
  },

  show_add_expense_form: function() {
    if(!$('add_expense_form').visible()) {
      $('add_expense_form').show();
      expense.initialize_add_expense_form();
      // TODO: EXPENSES: Initialize selection of date.  Today if possible?
      $('expense_spent_at').focus();
      expense.disable_add_expense_link();
    }
  },

  disable_add_expense_link: function() {
    $$('#add_expense_link a')[0].addClassName('disabled');
  },

  enable_add_expense_link: function() {
    $$('#add_expense_link a')[0].removeClassName('disabled');
  },

  initialize_add_expense_form: function() {
    $('expense_total_cost').value = "";
    $('expense_units').value = "";
    $('expense_notes').value = "";
    CustomFileInput.getInputFor('add_expense_receipt').clearSelection();
    expense.update_add_form_validation_errors();
  },

  validate_expense_form: function(id) {
    var errors = [];

    var project_id = id ? $F('expense-' + id + '-project-id') : $F('expense_project_id');
    if("" == project_id) {
      errors.push('project');
    }

    var expense_category_id = id ? $F('expense-' + id + '-expense-category-id') : $F('expense_expense_category_id');
    if("" == expense_category_id) {
      errors.push('expense category');
    }

    var expense_total_amount_id = id ? 'expense-' + id + '-total-cost' : 'expense_total_cost';
    var expense_units_id = id ? 'expense-' + id + '-units' : 'expense_units';
    var expense_total_amount = $F(expense_total_amount_id);
    var expense_id = expense_total_amount ? expense_total_amount_id : expense_units_id;
    $(expense_id).value = expense_total_amount = (expense_total_amount || $F(expense_units_id)).gsub(/[^\-0-9\.,\']/, '').gsub(expense.currency_symbol, '');
    // If expense total cost is unparseable, there is in error in its value.
    expense_total_amount = expense.parse_float_with_currencies(expense_total_amount);
    if(isNaN(expense_total_amount) || (expense_total_amount < 0)) {
      errors.push('amount');
    }

    if($F(expense_total_amount_id) && !Currency.validate_format(expense_total_amount)) {
      errors.push('amount');
    }

    if(errors.size() > 0) {
      //alert("Please check: " + errors.join(', '));
      alert("Please make sure that you have selected a project and an expense category.  For expense amount, it must be in a valid format(e.g. '12.65').");
      return false;
    } else {
      return true;
    }
  },

  clone_inputs_to_remote_form: function(id) {
    if(!expense.validate_expense_form(id))  return false;
     var fields_to_copy = [ 'spent-at', 'project-id', 'expense-category-id', 'total-cost', 'units', 'notes']; 
     fields_to_copy.each(function(field_name) {
      var value = $F('expense-' + id + '-' + field_name);
      var hidden_field = $('expense-' + id + '-' + field_name + '-hidden');
      hidden_field.value = value;
    });

    $('expense-' + id + '-of-user-hidden').value = expense.current_user_id;
    // Add year/day parameters if dealing with an expense for a specific week.
    if(expense.specific_year && expense.specific_day) {
      $('expense-' + id + '-year-hidden').value = expense.specific_year;
      $('expense-' + id + '-day-hidden').value = expense.specific_day;
    } else {
      $('expense-' + id + '-year-hidden').value = '';
      $('expense-' + id + '-day-hidden').value = '';
    }
  },

  toggle_expense_row: function(id) {
    if(expense.active_edit_expense_id != id) {
      // Only attempt to toggle prior row and reset expense form values if a row was actually active
      if(expense.active_edit_expense_id != '') {
        if($('expense-' + expense.active_edit_expense_id + '-entry-form').visible()) {
          $('expense-' + expense.active_edit_expense_id + '-entry-form').hide();
          $('expense-' + expense.active_edit_expense_id + '-entry-row').show();
          $('expense-' + expense.active_edit_expense_id + '-project-category-cont').hide();
          $('expense-' + expense.active_edit_expense_id + '-project-category-cont').update(
            $F('expense-' + expense.active_edit_expense_id + '-project-id') +
            '.' +
            $F('expense-' + expense.active_edit_expense_id + '-expense-category-id'));
        }
      }

      // Only reset the id and initial expense values upon editing a new row
      expense.active_edit_expense_id = id;
      expense.save_active_edit_expense_values(id);
    }

    var control_id =  'expense-' + id + '-project-category-cont';
    if($('expense-' + id + '-entry-row').visible()){
      $(control_id).innerHTML = expense.construct_selectors_for(id);
      $(control_id).show();
      if(Prototype.Browser.IE7 || Prototype.Browser.IE8) {
        $$("#" + control_id + " select").each(function(el) {
          new IEDropdown(el);
        });
        new IEDropdown('expense-' + id + '-spent-at');
      }
      
      expense.show_appropriate_currency(id);
    } else {
      $(control_id).hide();
      $(control_id).innerHTML = expense.project_category_dotted_pair(id);
      CustomFileInput.getInputFor('expense-' + id + '-receipt').revertToInitial();
      $('receipt_' + id + '_validation_errors').hide();
    }
    
    $('expense-' + id + '-entry-row').toggle();
    $('expense-' + id + '-entry-form').toggle();
    $('expense-' + id + '-total-cost-amount').visible() ? $('expense-' + id + '-total-cost').activate() : $('expense-' + id + '-units').activate();
  },

  construct_selectors_for: function(id){
    var html = ["<select"];
    
    if(id.blank()){
      html.push(" id='expense_project_id' name='expense[project_id]' ");
    } else {
      html.push(" id='expense-" + id + "-project-id' name='expense[project_id]' ");
    }
    html.push(">");
    if(id.blank()){
      html.push("<option value=''>Choose a project</option>");
    }
    
    var build_project_currencies = (!expense.project_currencies.length) ? true : false;
    
    for(var client_i = 0, clients_length = expense.clients.length; client_i < clients_length; client_i++){
      var client = expense.clients[client_i];
      html.push("<optgroup label='", client.name.gsub(/'/, '&#39;'), "' >");
      for(var project_i = 0, projects_length = client.projects.length; project_i < projects_length; project_i++){
        var project = client.projects[project_i];
        html.push("<option value='", project.id, "' ");
        if(!id.blank() && project.id == expense.active_edit_expense_values.project_id){
          html.push(" selected='selected'");
        }
        html.push(" >", project.name, "</option>");
        if(build_project_currencies){
          expense.project_currencies[project.id] = client.currency_symbol;
        }
      }
    }
    html.push("</select> <br /> <select ");
    if(id.blank()){
      html.push(" id='expense_expense_category_id' ");
    }
    else {
      html.push(" id='expense-" + id + "-expense-category-id' ");
      html.push("onchange=\"expense.toggle_amount_inputs('" + id + "')\"");
    }
    html.push(" name='expense[expense_category_id]' >");
    if(id.blank()){
      html.push("<option value=''>Choose a category</option>");
    }
    for(var category_i = 0, category_length = expense.categories.length; category_i< category_length; category_i++){
      var category = expense.categories[category_i];
      html.push("<option value='", category.id, "'");
      if(!id.blank() && category.id == expense.active_edit_expense_values.expense_category_id){
        html.push(" selected='selected'");
      }
      html.push(" >", category.name, "</option>");
    }
    html.push('</select>');
    return html.join('');
  },


  toggle_amount_inputs: function(id) {
    var dom_id            = (id && ("string" == typeof id)) ? 'expense-' + id + '-expense-category-id' : 'expense_expense_category_id';
    var unit_dom_id       = (id && ("string" == typeof id)) ? 'expense-' + id + '-unit-amount'         : 'expense_unit_amount';
    var total_cost_dom_id = (id && ("string" == typeof id)) ? 'expense-' + id + '-total-cost-amount'   : 'expense_total_cost_amount';

    var expense_selected_id = $F(dom_id);
    if(expense.unit_based_categories[expense_selected_id]) {
      $(unit_dom_id).show();
      $(unit_dom_id).down(".unit_name").innerHTML = expense.unit_based_categories[expense_selected_id];
      $(total_cost_dom_id).down().value = '';
      $(total_cost_dom_id).hide();
    } else {
      $(total_cost_dom_id).show();
      $(unit_dom_id).down().value = '';
      $(unit_dom_id).hide();
    }
  },

  // Save off the original expense form values in case edit form is toggled off and
  // the values need reset to their original state.
  save_active_edit_expense_values: function(id) {
    var project_category = $('expense-' + id + '-project-category-cont').innerHTML.split('.');
    expense.active_edit_expense_values = {
      spent_at: $F('expense-' + id + '-spent-at'),
      project_id: project_category[0],
      expense_category_id: project_category[1],
      total_cost: $F('expense-' + id + '-total-cost'),
      units: $F('expense-' + id + '-units'),
      notes: $F('expense-' + id + '-notes')
    };
  },

  project_category_dotted_pair: function(id){
    return [$F('expense-' + id + '-project-id'), $F('expense-' + id + '-expense-category-id')].join('.');
  },

  check_enter_submit: function(event) {
    if (event.keyCode == Event.KEY_RETURN) {
      var element = Event.element(event);
      // element.id is like 'element-23-more-description'.  Remove prefix and parse out the id.
      var id = parseInt(element.id.split('expense-')[1]);
      expense.update(id);
    }
  },

  update_add_form_validation_errors: function(errors) {
    if(errors) {
      $('receipt_validation_errors').update('<p>' + errors + '</p>');
      $('receipt_validation_errors').show();
      CustomFileInput.getInputFor('add_expense_receipt').clearAfterValidation();
    } else {
      $('receipt_validation_errors').hide();
    }
    $('add_indicator').hide();
    $('add_expense_controls').show();
  },

  update_edit_form_validation_errors: function(expense_id, errors) {
    var validation_box = $('receipt_' + expense_id + '_validation_errors');
    if(errors) {
      validation_box.update('<p>' + errors + '</p>');
      validation_box.show();
      CustomFileInput.getInputFor('expense-' + expense_id + '-receipt').clearAfterValidation();
    } else {
      validation_box.hide();
    }
    $('expense-' + expense_id + '-loading').hide();
    $('expense-' + expense_id + '-controls').show();
  },

  add: function() {
    if(expense.validate_expense_form()) { 
      $('add_expense_controls').hide();
      $('add_indicator').show(); 
      return true; 
    } else { 
      return false; 
    }
  },

  update: function(id) {
    if(expense.validate_expense_form(id)) { 
      expense.save_active_edit_expense_values(id);
      expense.clone_inputs_to_remote_form(id); 
      $('expense-' + id + '-controls').hide(); 
      $('expense-' + id + '-loading').show();  
      return true; 
    } else { 
      return false;
    }
  },

  view_receipt: function(id){
     var lb = new Lightbox('<div class="small_box "><div style="text-align: center; width: 100%;"><div style="margin: auto; width: 140px;" class="loading"> Loading Receipt ... </div></div></div>');
     // Should really just make the lightbox capable of centering itself...
     var w = ((navigator.appName =="Netscape") ? window.innerWidth  : document.body.clientWidth);
     var h = ((navigator.appName =="Netscape") ? window.innerHeight : document.body.clientHeight);
     var left = parseInt(w/2 - 380); var top = parseInt(h/2 - 50);
     $('lightbox').setStyle({ 'margin': top + 'px 0 0 ' + left + 'px', 'top': '0px', 'left': '0px' });

     var i = new Image();
     i.src = '/expenses/' + id + '/receipt?' + (new Date()).getTime();
     i.onload = function() { expense.resize_lightbox(id, i); };
  },

  lightbox_style : { 'margin': '-200px 0 0 -374px', 'top': '40%', 'left':'50%', 'height':'185px', 'width' : '750px' },

  resize_lightbox : function (id, img) {
    Lightbox.prototype.deactivate();
    var w = img.width; 
    var h = img.height; 
    var max_w = document.viewport.getWidth() - 140;
    var max_h = document.viewport.getHeight() - 140;
    var scaled_down = false;

    if(h > max_h) {
        scale = max_h / h;
        h = h * scale;
        w = w * scale;
        scaled_down = true;
    } 

    if(w > max_w) {
        scale = max_w / w ;
        h = h * scale;
        w = w * scale;
        scaled_down = true;
    }

    h = parseInt(h);
    w = parseInt(w);
    var left = parseInt((max_w - w) / 2 + 50);
    var top = parseInt((max_h - h) / 2 + 50);

    var view_url = '/expenses/' + id + '/receipt_view?' + (new Date()).getTime(); 
    var html =  '<div class="small_box" style="height: ' + h + 'px; width: ' + w + 'px;" >' +
                 '<a href="#" class="graphic btn_close" onclick="expense.close_receipt();">Close</a>' +
                 '<a href="' + view_url + '" target="receipt_' + id + '" title="View in new window" alt="View in new window" ><img id="lightbox-receipt"  src="' + img.src + '" ></a>' +
                 '<div style="width: 100%; text-align: center; margin-top: 7px;">';
    if(scaled_down) {
      html += '<a href="' + view_url + '" target="receipt_' + id +'">view full size</a> | ';
    }
    html += '<a href="#" onclick="expense.print_receipt(' + id + ')">print</a></div></div>';
    var lb = new Lightbox(html);
    $('lightbox').setStyle({ 'margin': top + 'px 0 0 ' + left + 'px', 'top': '0px', 'left': '0px', 'height': h + 'px', 'width' : w + 'px' });
  },

  close_receipt: function() {
    $('lightbox').setStyle(expense.lightbox_style);
    Lightbox.prototype.deactivate(); return false
  },

  print_receipt: function(id) {
    var html = "<html><head><title>Print Rceipt</title>" +
               "<script> function schedulePrint() { setTimeout(doPrint, 10); }; " + 
               "  function doPrint() { window.print();   window.close(); }; " +
               "</scr" + "ipt> </head> " +
               "<body onload='schedulePrint();'> <img src='/expenses/" + id +"/receipt' /></body> </html> ";

    var print_window = window.open("about:blank", "_new");
    print_window.document.open();
    print_window.document.write(html);
    print_window.document.close();
  }

};

Object.extend(expense, Currency);



/****************************************************************/
/*  original filename client_document.js                        */
/****************************************************************/


var client_document = {
  document_type: "invoice",

  // Makes certain functions "variable" between invoices, recurring invoices, and estimates
  id_prefix: 'invoice',

  configure:  {
    active: function(){
      return $($$('#nav_for_configure_tab .selected').first().id.gsub(/^navigation_/, ''));
    },
    preselect: function(){
      var current = window.location.hash.gsub('#', '') + '_edit';
      if($(current)){
    client_document.configure.switch_to(current);
      }
    },

    switch_to: function(new_tab){
      window.location.hash = new_tab.gsub(/_edit$/, '');
      var current = client_document.configure.active();
      new_tab = $(new_tab);
      if(new_tab != current) {
        client_document.configure.navigation_for(current).removeClassName('selected');
        client_document.configure.navigation_for(new_tab).addClassName('selected');
        
        $('configure_container').setStyle({'min-height':( (Prototype.Browser.IE) ? new_tab.getHeight() + 18 : new_tab.getHeight() )+'px'});
        
        current.hide();
        new Effect.Appear(new_tab,{duration: .25});
//      new Effect.Parallel([ new Effect.Fade(current), new Effect.Appear(new_tab)],{duration: 0.25});//.show();
      }
    },

    navigation_for: function(tab) {
      return $('navigation_'+tab.id);
    },

    gateway_clicked: function(gw_type) {
      if($('gw_checkbox_for_' + gw_type).checked) {
        $$('.gw_checkbox').each(function(cb){
          var cb_type = cb.id.match(/gw_checkbox_for_(.*)/)[1];
          if(cb_type != gw_type) {
            cb.checked = false;
            $('form_for_' + cb_type).hide();
          }
        });
        $('form_for_' + gw_type).show();
      } else {
          $('form_for_' + gw_type).hide();
      }
    },

    open_checked_gateway: function() {
        $$('.gw_checkbox').each(function(cb){
          if(cb.checked) {
            var cb_type = cb.id.match(/gw_checkbox_for_(.*)/)[1];
            $('form_for_' + cb_type).show();
          } else {
            $('form_for_' + cb_type).hide();
          }
        });
    }

  },

  dashboard: {

    multiple_currencies_present: function(){
      return $('outstanding_sub_total') == null;
    },

    active: function(){
      return $$('#invoice_dash_filter li.selected').first().id.gsub(/^dash_filter_/, '');
    },

    on_mouse_over: function(row){
      $(row).addClassName('highlight').removeClassName('normal');
    },

    on_mouse_out: function(row){
      $(row).addClassName('normal').removeClassName('highlight');
    },

    filter: function(kind){
      var current = client_document.dashboard.active();
      if(current == kind)
        return;
      var new_sum = 0;

      $$('#outstanding_invoices tr').each(
        function(row){
          if(kind == 'all' || row.hasClassName(kind)){
            row.show();
            new_sum += Currency.parse_float_with_currencies(row.down('span.balance').innerHTML);
          } else {
            row.hide();
          }
        }
      );
      $('dash_filter_' + current).toggleClassName('selected');
      $('dash_filter_' + kind).toggleClassName('selected');
      if(!client_document.dashboard.multiple_currencies_present()){
        if(kind == 'all'){
          $('outstanding_sub_total_container').hide();
        } else {
          $('outstanding_sub_total').innerHTML = Currency.number_to_currency(new_sum);
          $('outstanding_sub_total_container').show();
        }
      }
      window.location.hash = kind;
    },

    preselect_filter: function(){
      var kind = window.location.hash.gsub(/#/, '');
      if(!kind.blank() && $('dash_filter_' + kind) != null){
        client_document.dashboard.filter(kind);
      }
    }
  },

  message: {
    valid: function () {
      if($$('.select_recipients').pluck('checked').any(Prototype.K) == false) {
        alert('You need to select at least one recipient.');
        return false;
      }
      if($('message_number_of_days_late') && !$F('message_number_of_days_late').strip().match(/^\d+$/)){
          alert('You need enter a valid number of days.');
        return false;
      }
      return true;
    },

    toggle_mark_as_sent: function() {
      $('mark_as_sent_form').toggle();
    }
  },

  toggle_item_category_controls: function() {
    var args = $A(arguments);
    var id = args.shift();

    args.each(function(control) {
        $('category-' + id + '-' + control).toggle();
      });
  },

  toggle_item_category_editor: function(id) {
    client_document.toggle_item_category_controls(id, 'show', 'edit');
    if($('category-' + id + '-edit').visible()) {
      $('category-' + id + '-edit-name').activate();
    }
  },

  check_for_valid_line_items: function(){
    var quantities = $$("#invoice_item_rows .quantity input").pluck('value').map(
      function(value){
        return Currency.parse_float(value);
      });
    var unit_prices = $$("#invoice_item_rows .price input").pluck('value').map(
      function(value){
        return Currency.parse_float_with_currencies(value);
      });
    var any_is_NaN = function(list){
      return $A(list).any(
        function(value){
          return isNaN(value);
        });
      };
    if(any_is_NaN(quantities)){
      alert('Please enter valid quantities!');
      return false;
    }
    if(any_is_NaN(unit_prices)){
      alert('Please enter valid unit prices!');
      return false;
    }
    return true;
  },

  toggle_dashboard_filter: function() {
    $('filter_options').toggle();
    $('toolbar').toggle();
  },

  on_change_timeframe_filter: function() {
    if($F('timeframe') == 'custom') {
      $('custom_timeframe').show();
      $$('#custom_timeframe input').each(function(control) { control.disabled = false;});
      $('from').activate();
    } else{
      $('custom_timeframe').hide();
      $$('#custom_timeframe input').each(function(control) { control.disabled = true;});
    }
  },

  validate_archive_report_filter: function() {
    if(!$('custom_timeframe').visible())
      return true;

    return date.form_validation({from: 'start date', to: 'end date'});
  },

  register_on_change_handlers_for_archive_report_check_boxes: function(document_type) {
    if($(document_type + '_status_all')){
      $(document_type + '_status_all').observe('click',
        function(){
          if($(document_type + '_status_all').checked)
            $$('.other_status').each( function(other){ other.checked = true;});
      });
      $$('.other_status').each(
        function(other){
          other.observe('click',
            function(e){
              if(Event.element(e).checked != true || $$('.other_status').pluck('checked').all(Prototype.K)==false){
                $(document_type + '_status_all').checked = false;
              }
            });
      });
    }
  },

  check_for_valid_message_form: function() {
    return date.form_validation({'message_created_at_human_format': 'date'});
  },

  show_new_client_form: function() {
    $('new_client_control').show();
    if ($('select_invoice_type')) $('select_invoice_type').hide();
    $('new_client_name').value = "Enter new client name";
    $('new_client_name').select();
    $('new_client_name').focus();
  },

  clear_new_client_form: function() {
     $('new_client_name').value='';
     $('new_client_control').hide();
     if ($('select_invoice_type')) $('select_invoice_type').show();
  },

  client_was_selected: function() {
    if(($F('clients_list') == "") || ($F('clients_list') == "new_client" && $('new_client_name').value =="")) {
      alert('You must select a client');
      return false;
    }
    return true;
  }

};

function document_id(id_string) {
  return client_document.id_prefix + '_' + id_string;
}










/****************************************************************/
/*  original filename invoice.js                        */
/****************************************************************/


var invoice = {

  register_on_change_handlers_for_dashboard: function() {
    $$('.hover_item').each(function(control) {
      control.observe('mouseover', invoice.on_mouseover_invoice);
      control.observe('mouseout', invoice.on_mouseout_invoice);
    });
  },

  on_mouseover_invoice: function() {
    $$('.hover_nugget').invoke('hide');
    this.down('.hover_nugget').show();
  },

  on_mouseout_invoice: function() {
    this.down('.hover_nugget').hide();
  },

  register_on_change_handlers_for_step1: function() {
    $w('project task people detailed').each(function(type) {
      var invoice_type_cnt = $('invoice_type_summary_' + type);
      if(invoice_type_cnt){
        invoice_type_cnt.observe('click', invoice.on_change_type);
      }
    });
    $w('project category people detailed').each(function(type) {
      var invoice_expense_type_radio = $('invoice_expense_summary_' + type);
      if(invoice_expense_type_radio) {
        invoice_expense_type_radio.observe('click', invoice.on_change_expense_summary_type);
      }
    });
    $$('.select_detailed_info').each(function(control) {
        control.observe('click', invoice.on_change_detailed_info_part);
      });
    $$('.select_detailed_expense_info').each(function(control) {
        control.observe('click', invoice.on_change_expense_detailed_info_part);
      });
    $$('.select_project_checkbox').each(function(c) {
      c.observe('click', invoice.on_change_project_to_invoice);
      });
    if($('select-all-projects-link'))  $('select-all-projects-link').observe('click', invoice.set_custom_timeframe_defaults_for_all);
    if($('select-none-projects-link'))  $('select-none-projects-link').observe('click', invoice.set_custom_timeframe_defaults_for_none);
    $('start_date').observe('focus', function(e){ invoice.disable_time_frame_calculation = true; });
    $('end_date').observe('focus', function(e){ invoice.disable_time_frame_calculation = true; });
    $('timeframe').observe('focus', invoice.on_focus_timeframe);
    $('expense_timeframe').observe('focus', invoice.on_focus_expense_timeframe);
    $('do_not_import_expenses').observe('click', invoice.on_import_expenses_changed);
    $('import_expenses').observe('click', invoice.on_import_expenses_changed);
    invoice.on_change_project_to_invoice();
    invoice.on_change_type();
    invoice.on_import_expenses_changed();
  },

  on_change_type: function() {
    if($('invoice_type_summary_detailed').checked) {
      $('detailed_config').show();
    } else {
      $('detailed_config').hide();
    }
  },

  on_change_expense_summary_type: function() {
    $('detailed_expense_config')[($('invoice_expense_summary_detailed').checked ? 'show' : 'hide')]();
  },

  on_change_due_date_default_value: function(dropdown) {
    if($F(dropdown) == 'custom') {
      $('profile_custom_due_date_span').show();
    } else {
      $('profile_due_date_custom').value = '';
      $('profile_custom_due_date_span').hide();
    }
  },

  on_change_project_to_invoice: function() {
    var checked_projects = invoice.select_checked('.select_project_checkbox').map(function(c) {
      return c.id.gsub(/^project-/, '').gsub(/-include$/, '');
    });
    if($('projects_to_invoice'))  $('projects_to_invoice').value = checked_projects.join(',');
    invoice.set_custom_timeframe_defaults(checked_projects);
  },

  set_custom_timeframe_defaults_for_all: function() {
    invoice.set_custom_timeframe_defaults(
      $$('.select_detailed_info').map(function(c) {
        return c.name.gsub(/^include-/, '');
      })
    );
  },

  set_custom_timeframe_defaults_for_none: function() {
    invoice.set_custom_timeframe_defaults(new Array());
  },

  set_custom_timeframe_defaults : function(selected_projects) {
    if(!$('custom_timeframe').visible()) {
      return;
    }

    // If the user has already changed the custom time frame, let's leave it alone.
    if(invoice.disable_time_frame_calculation || (invoice.projects_and_last_efforts.keys().length == 0)) {
      return;
    }

    // If there are no selected projects, then let's set it back to the default.
    if(selected_projects == null || selected_projects.length == 0) {
      invoice.set_custom_timeframe_to_last_month();
      return;
    }

    // Otherwise, let's find some sane start/end dates.
    var new_start_date = new Date();
    var found_selected_project = false;
    invoice.projects_and_last_efforts.each(function(project) {
      if(selected_projects.include(project.key)) {
        var end_date = date.is_valid_date(project.value.end_date);
        if(end_date && (end_date < new_start_date)) {
          new_start_date = end_date;
        }
        found_selected_project = true;
      }
    });

    // There is the case that none of the selected projects have a last effort (they are "N/A")
    if(!found_selected_project) {
      if($F('timeframe') == 'Custom') {
        invoice.set_custom_timeframe_to_last_month();
      }
      return;
    }

    // Start the following day
    new_start_date = new_start_date.add(1).days();

    var new_end_date = null;
    if(new_start_date.getMonth() < Date.today().getMonth()) {
      new_end_date = Date.parse('last month').moveToLastDayOfMonth();
    } else if(new_start_date <= Date.parse('yesterday')){
      new_end_date = Date.parse('yesterday');
    } else {
      new_end_date = new Date(new_start_date);
      new_end_date.add(1).month();
    }

    $('start_date').value = date.to_localized_format(new_start_date);
    $('end_date').value = date.to_localized_format(new_end_date);
  },

  set_custom_timeframe_to_last_month: function() {
    var new_end_date = Date.parse('last month').moveToLastDayOfMonth();
    var new_start_date = Date.parse('last month').moveToFirstDayOfMonth();
    $('start_date').value = date.to_localized_format(new_start_date);
    $('end_date').value = date.to_localized_format(new_end_date);
  },

  on_focus_timeframe: function() {
    $('import_hours').checked = true;
  },

  on_focus_expense_timeframe: function() {
    $('import_expenses').checked = true;
    invoice.on_import_expenses_changed();
  },

  on_import_expenses_changed: function() {
    // By default, don't import expenses
    if($('import_expenses').checked == false && $('do_not_import_expenses').checked == false) {
      $('do_not_import_expenses').checked = true;
    }
    if($('import_expenses').checked == true) {
      $('select_expense_summary_type').show();
    } else {
      $('select_expense_summary_type').hide();
    }
  },

  on_change_detailed_info: function() {
    if($('detailed_config').visible()==false) {
      $('detailed_info_to_include').value = '';
      return;
    }
    invoice.on_change_detailed_info_part();
  },

  on_change_detailed_info_part: function() {
    $('detailed_info_to_include').value = invoice.select_checked('.select_detailed_info').map(function(c) {
        return c.name.gsub(/^include-/, '');
      }).join(',');
  },

  on_change_expense_detailed_info_part: function() {
    $('detailed_expense_info_to_include').value = invoice.select_checked('.select_detailed_expense_info').map(function(c) {
        return c.name.gsub(/^include-/, '');
      }).join(',');
  },

  on_change_clients_list_for_recurring: function() {
    if($F('clients_list') == "new_client") {
      client_document.show_new_client_form();
    } else {
      client_document.clear_new_client_form();
    }
  },

  on_change_clients_list: function() {
    var selected_client = $F('clients_list');
    // First, is it new?
    if(selected_client == "new_client") {
      client_document.show_new_client_form();
      return;
    }
    client_document.clear_new_client_form();
    if(selected_client == "") {
      $('select_invoice_type').hide();
      return;
    }
    // Next, see if we can optimize the form based on this client?
    if(projectless_clients[selected_client] == 'no-projects') {
      $('invoice_free_form_id').checked = true;
      $('select_invoice_type').hide();
    } else {
      $('select_invoice_type').show();
      if(free_form_clients[selected_client] == 'free_form') {
        $('invoice_free_form_id').checked = true;
      } else {
        $('invoice_project_hours_id').checked = true;
      }
    }
  },

  create_invoice_validations: function() {
    if($('invoice_type_summary_detailed') &&
       $('invoice_type_summary_detailed').checked &&
       !$$('.select_detailed_info').pluck('checked').any(Prototype.K)) {
      alert('You need to select at least one field for detailed line items');
      return false;
    }
    var select_project_checkboxes = $$('.select_project_checkbox');
    if(select_project_checkboxes.length > 0 && !select_project_checkboxes.pluck('checked').any(Prototype.K)) {
      alert('You need to select at least one project');
      return false;
    }
    if($('import_hours').checked && !invoice.timeframe_valid('start_date', 'end_date')) {
      alert('You need to select a valid timeframe');
      return false;
    }
    if($('import_expenses').checked && !invoice.timeframe_valid('expense_start_date', 'expense_end_date')) {
      alert('You need to select a valid timeframe for expenses');
      return false;
    }
    if($('import_expenses').checked && $('invoice_expense_summary_detailed') &&
       $('invoice_expense_summary_detailed').checked &&
       !$$('.select_detailed_expense_info').pluck('checked').any(Prototype.K)) {
      alert('You need to select at least one field for detailed expense line items');
      return false;
    }
    if($('invoice_type_ledes') && $('invoice_number') && $('invoice_subject') &&
       ($F('invoice_number').blank() || $F('invoice_subject').blank())){
      alert('Invoice number and invoice description are mandatory fields for a LEDES invoice');
      return false;
    }
    if(invoice.should_check_for_duplicate_number()) {
      invoice.duplicate_number_check();
      return false; // The callback will submit the form, if it's valid.
    }
    return true;
  },

  timeframe_valid: function(from_field, to_field) {
    return (date.is_valid_date($F(from_field)) && date.is_valid_date($F(to_field)));
  },

  check_for_valid_form: function() {
    var options = new Object();
    options["invoice_issued_at_human_format"] = 'issue_date';
    
    
   if($('invoice_due_at_human_format') && "custom" == $F('invoice_due_at_human_format'))
      options["invoice_due_at"] = 'due date';

    if(!date.form_validation(options)) {
      return false;
    }

    if(!client_document.check_for_valid_line_items()){
      return false;
    }

    if(invoice.should_check_for_duplicate_number()) {
      invoice.duplicate_number_check();
      return false; // The callback will submit the form, if it's valid.
    }
    
    return true;
  },

  should_check_for_duplicate_number: function() {
    return ($('allow_duplicate_invoice_numbers') &&
            $F('allow_duplicate_invoice_numbers') == 'false' &&
            $('invoice_number'));
  },

  duplicate_number_check: function() {
    var params = new Object();
    params.invoice_number = $F('invoice_number');
    if($('editing_invoice_id')) { params.invoice_id = $F('editing_invoice_id'); }
    new Ajax.Request('/invoices/check_for_duplicate_number', { evalScripts:true, asynchronous:true, method:'post', parameters : params });
  },

  duplicate_number_found : function(duplicate_number) {
    alert('An invoice with number ' + duplicate_number + ' already exists.  Please select a unique invoice number and try again.');
  },

  submit_form : function() {
    if($('new_invoice_form')) {
      $('new_invoice_form').submit();
    } else if ($('edit_invoice_form')) {
      $('edit_invoice_form').submit();
    }
  },

  // Validates each time/expense form field if the field is found.
  validate_recurring_invoice: function(form) {
    var errors = [];
    
    //Check start date field
    var start_date = $F('recurring_start_date_human_format');
    if(false == date.is_valid_date(start_date))
      errors.push('Invalid start date');
    else if ( !$('initial_start_date') || ( start_date != $F('initial_start_date') ) ){
      if( ! date.is_future_date(start_date, $F('today_date')) ) errors.push('You must choose a start date in the future.');
    }

    //Check recipient list
    if($('email_recipients').visible()) {
      checkboxes = $('email_recipients').select("input[type=checkbox][name*=send-to-]");
      recipient_checked = checkboxes.any(function(e) { return e.checked; });
      if(!recipient_checked)  errors.push('No client recipient selected');
    }

    //Check frequency field if custom frequency chosen
    if('custom' == $F(document_id('frequency_human_format')) &&
       (!$F('recurring_frequency').strip().match(/^\d+$/) ||
        (parseInt($F('recurring_frequency').strip()) <= 0))) {

      errors.push('A days field greater than 0 is required for custom frequency');
    }

    //Check due at field if custom due at chosen
    if('custom' == $F(document_id('due_at_human_format')) &&
       (!$F('recurring_due_at').strip().match(/^\d+$/) ||
        (parseInt($F('recurring_due_at').strip()) <= 0))) {

      errors.push('A days field greater than 0 is required for custom due date');
    }

    if(errors.length > 0) {
      alert("There are errors in this recurring invoice:\n\n\t" + errors.join('\n\t'));
      return false;
    }
    return client_document.check_for_valid_line_items();
  },

  toggle_contact_info_edit: function() {
    if($('company-contact').visible()) {
      $('company-contact').toggle();
      show_big_div('company-contact-edit');
      $('company_name').activate();
    } else {
      $('company-contact-edit').toggle();
      show_big_div('company-contact');
    }
  },

  select_checked: function(css_selector) {
    return $$(css_selector).select(function(c) {return c.checked;});
  },

  register_on_change_handlers_for_recurring_invoice: function() {
    invoice.register_on_change_handlers_for_frequency();
    invoice.register_on_change_handlers_for_send_automatically_true();
    invoice.register_on_change_handlers_for_send_reminder();
    invoice.register_on_change_handlers_for_step2();
  },

  register_on_change_handlers_for_step2: function() {
    invoice.recompute_amounts_and_totals();
    $$("#invoice_item_rows .quantity input, "
       + "#invoice_item_rows .price input, "
       + "#invoice_item_rows .tax2 input, "
       + "#invoice_item_rows .tax input, "
       + "#" + document_id('discount') + ", "
       + "#" + document_id('tax') + ", "
       + "#" + document_id('tax2')).each(function(control) {
        control.observe('change', invoice.recompute_amounts_and_totals);
      });
    invoice.register_on_change_handlers_for_payment_due();
    invoice.show_or_hide_payment_gateways();
  },

  register_on_change_handlers_for_payment_due: function() {
    if($(document_id('due_at_human_format'))) {
      $(document_id('due_at_human_format')).observe('change', invoice.on_change_payment_due);
      invoice.on_change_payment_due();
    }
  },

  on_change_payment_due: function() {
    var task_value = $F(document_id('due_at_human_format'));
    if(task_value == 'custom') {
      $('due_at_timeframe').show();
      $(document_id('due_at')).activate();
    } else{
      $('due_at_timeframe').hide();
    }
  },

  register_on_change_handlers_for_frequency: function() {
    $(document_id('frequency_human_format')).observe('change', invoice.on_change_frequency);
    invoice.on_change_frequency();
  },

  on_change_frequency: function() {
    var frequency_value = $F(document_id('frequency_human_format'));
    if(frequency_value == 'custom') {
      $('frequency_days').show();
      $(document_id('frequency')).activate();
    } else {
      $('recurring_frequency').value = "";
      $('frequency_days').hide();
    }
  },

  register_on_change_handlers_for_send_automatically_true: function() {
    $$('#' + document_id('send_automatically') + ' input').each(function(control) {
      control.observe('click', invoice.on_change_send_automatically_true);
    });
    invoice.on_change_send_automatically_true();
  },

  on_change_send_automatically_true: function() {
    var send_automatically_true_checked = $(document_id('send_automatically_true')).checked;
    if(send_automatically_true_checked) {
      $$('.email_fields').invoke('show');
    } else {
      $$('.email_fields').invoke('hide');
    }
  },

  register_on_change_handlers_for_send_reminder: function() {
    $(document_id('has_payment_reminder')).observe('click', invoice.on_change_send_reminder_with_focus);
    invoice.on_change_send_reminder();
  },

  on_change_send_reminder_with_focus: function() {
    invoice.on_change_send_reminder("focus");
  },

  on_change_send_reminder: function(focus) {
    var check_box = $(document_id('has_payment_reminder'));
    var days_text_box = $(document_id('reminder_after_nr_days_due'));
    if(check_box.checked) {
      days_text_box.enable();
      if(focus)  days_text_box.activate();
    } else {
      days_text_box.disable();
      check_box.focus();
    }
  },

  remove_line_item: function(i) {
    $('item-row-' + i).remove();
    invoice.recompute_amounts_and_totals();
    invoice.test_reorder_enable();
  },

  add_line_item: function() {
    var html_prototype = "<tr id=\"item-row-NUMBER\">" + $('item-row-NUMBER').innerHTML + "</tr>";
    html_prototype = html_prototype.replace(/NUMBER/g, invoice.next_free_row_id());
    new Insertion.Bottom('invoice_item_rows', html_prototype);
    var new_row = $($('invoice_item_rows').lastChild);
    var mark_as_taxed =  function(e){
      e.value = '1'; e.checked = true;
    };
    if(invoice.parse_float($F(document_id('tax')) || 0) > 0){
      // default new row to taxed
      new_row.select('.tax input').each(mark_as_taxed);
    }
    if(invoice.parse_float($F(document_id('tax2')) || 0) > 0){
      // default new row to taxed
      new_row.select('.tax2 input').each(mark_as_taxed);
    }
    new_row.getElementsBySelector('.quantity input, .price input, .tax input, .tax2 input').each(function(control) {
        control.observe('change', invoice.recompute_amounts_and_totals);
      });
    new Effect.Highlight(new_row);
    autoExpandTextArea.refreshObservers();
    invoice.test_reorder_enable();
  },

  next_free_row_id: function() {
    var max = $$("#invoice_item_rows tr").pluck('id').map(function(e) {
        return parseInt(e.gsub(/^item-row-/, '')) || -1;
      }).max();
    //zs 0 || -1 => -1 hence increasing by two
    return max + 2;
  },

  test_reorder_enable: function() {
    if($('sort_line_items_link')){
      if( $$('#invoice_item_rows tr').length - 1 <= 1) $('sort_line_items_link').hide();
      else  $('sort_line_items_link').show();
    }
  },

  on_line_items_reorder_done: function(){
    $('sort_order').value = $$('#invoice_item_rows tr').collect(function(e){return e.id.gsub('item-row-', '');}).join(',');
  },
  register_line_items_for_reorder_by_drag: function(){
    invoice.on_line_items_reorder_done();
  },

  last_known_tax_value : '',
  last_known_tax2_value : '',
  last_known_discount_value : '',

  show_tax_fields: function(tax_kind) {
    if(undefined == tax_kind) {
      tax_kind = '';
    } else {
      $('tax_2_columns').show();
      $('tax_controls').hide();
    }
    $('apply_tax'+ tax_kind + '_link').hide();
    $$('#tax'+ tax_kind + '_field_control, #invoice_item_rows .tax'+ tax_kind).invoke('show');
    if($$('#sort_invoice_item_list li').size() == 0){
      $('invoice_table_footer').addClassName('tax_pad');
      $$('#tax'+ tax_kind + '_table_head').invoke('show');
    }
    $$('#invoice_item_rows .tax'+ tax_kind + ' input').each(function(e) { e.value = '1'; e.checked = true;});
    $(document_id('tax' + tax_kind)).focus();
    if('2' == tax_kind) {
      $(document_id('tax' + tax_kind)).value = invoice.last_known_tax2_value.blank() ? invoice.last_known_tax_value : invoice.last_known_tax2_value;
    } else {
      $(document_id('tax' + tax_kind)).value = invoice.last_known_tax_value;
    }
    this.recompute_amounts_and_totals();
  },

  do_not_apply_tax: function(tax_kind) {
    if(undefined == tax_kind) {
      tax_kind = '';
    } else {
      $('tax_2_columns').hide();
      $('tax_controls').show();
    }
    $('apply_tax'+ tax_kind + '_link').show();
    $$('#tax'+ tax_kind + '_field_control, #tax'+ tax_kind + '_table_head, #invoice_item_rows .tax'+ tax_kind + '').invoke('hide');
    $$('#invoice_item_rows .tax'+ tax_kind + ' input').each(function(e) { e.value = '0'; e.checked = false;});
    $('invoice_table_footer').removeClassName('tax_pad');
    invoice.last_known_tax_value = $F(document_id('tax'+ tax_kind));
    $(document_id('tax'+ tax_kind)).value = '';
    this.recompute_amounts_and_totals();
  },

  has_discount: function(){
    return invoice.parse_float($F(document_id('discount')) || 0) > 0;
  },

  parse_out_currency_symbol: function() {
    var value = $F(document_id('currency_with_symbol')).match(/^.+\s\((.+)\)$/);
    Currency.currency_symbol = ((value && value.length == 2) ? value[1] : '$');
  },

  show_or_hide_payment_gateways: function() {
    var iso_shorthand = $F(document_id('currency_with_symbol')).match(/^.+\s-\s(.+)\s\(.+\)$/)[1];
    if($('payment_gateways')) {
      $$("#payment_gateways .gateway").invoke('hide');
      var some_visible = false;
      $$("#payment_gateways .currency_" + iso_shorthand).each(function(cb){
       some_visible = true;
       cb.show();
      });
      $('no_payment_gateways_supported')[(some_visible ? 'hide' : 'show')]();
      $('payment_gateways')[(some_visible ? 'show' : 'hide')]();
    }
  },

  taxes_for_amount: function(amount, tax_multiplier, tax2_multiplier, taxed, taxed2){
    var tax_amount = 0;
    var tax2_amount = 0;
    if(taxed) {
      tax_amount = amount * tax_multiplier;
    }
    if(taxed2) {
      tax2_amount = amount * tax2_multiplier;
    }
    return [tax_amount, tax2_amount];
  },

  compound_taxes_for_amount: function(amount, tax_multiplier, tax2_multiplier, taxed, taxed2){
    var tax_amount = 0;
    var tax2_amount = 0;
    if(taxed) {
      tax_amount = amount * tax_multiplier;
    }
    if(taxed2) {
      tax2_amount = (tax_amount + amount) * tax2_multiplier;
    }
    return [tax_amount, tax2_amount];
  },

  recompute_amounts_and_totals: function() {
    var quantities = $$("#invoice_item_rows .quantity input").pluck('value');
    var unit_prices = $$("#invoice_item_rows .price input").pluck('value');
    var taxed = $$("#invoice_item_rows .tax input").pluck('checked');
    var taxed2 = $$("#invoice_item_rows .tax2 input").pluck('checked');
    var discount_multiplier = invoice.parse_float($F(document_id('discount')) || 0) / 100;
    var tax_multiplier = invoice.parse_float($F(document_id('tax')) || 0) / 100;
    var tax2_multiplier = 0 ;
    if($(document_id('tax2'))){
      tax2_multiplier = invoice.parse_float($F(document_id('tax2')) || 0) / 100;
    }
    var amount_fields = $$("#invoice_item_rows .amount");
    var sub_total = 0;
    var tax_total = 0;
    var tax2_total = 0;
    var discount_total = 0;
    for (var i = 0, len = amount_fields.length; i < len; ++i) {
      var amount      = Cents.mul((invoice.parse_float(quantities[i]) || 0), (invoice.parse_float_with_currencies(unit_prices[i]) || 0));
      var amount_in_currency = invoice.number_to_currency(Cents.round(amount)); // Round amount before calculations
      amount = Currency.parse_float_with_currencies(amount_in_currency);
      var discount    = Cents.round(Cents.mul(amount, discount_multiplier));
      var taxes       = invoice.taxes_for_amount(amount-discount, tax_multiplier, tax2_multiplier, taxed[i], taxed2[i]);
      discount_total  = Cents.add(discount_total, discount);
      tax_total       = Cents.add(tax_total, taxes[0]);
      tax2_total      = Cents.add(tax2_total, taxes[1]);
      amount_fields[i].innerHTML = amount_in_currency;
      sub_total  = Cents.add(sub_total, amount);
    }
    tax_total = Cents.round(tax_total);  // Force proper rounding rather than truncating of tax_total
    tax2_total = Cents.round(tax2_total);
    var total_amount = sub_total - discount_total + tax_total + tax2_total;
    var retainer_payment_total = invoice.retainer.draw_retainer_balance_present() ? Math.min(total_amount, invoice.retainer.draw_retainer_balance) : 0;
    $('sub_total_amount').update(invoice.number_to_currency(sub_total));
    $('total_amount').update(invoice.number_to_currency(total_amount - retainer_payment_total));
    if(!invoice.has_discount()) {
      $('discount_total_row').hide();
    } else {
      $('discount_total_row').show();
      $('total_discount_amount').update(invoice.number_to_currency(discount_total));
      var parts = $F(document_id('discount')).split(Currency.decimal_symbol);
      var discount_fractions = [((parts[1] != undefined && !parts[1].blank()) ? parts[1].length : 0), 2].max();
      $('discount_percentage').update('(' + Currency.number_with_delimiter(Currency.parse_float($F(document_id('discount')) || 0), {precision: discount_fractions}) + '%)');
    }
    if($('apply_tax_link').visible()) {
      $('tax_total_row').hide();
    } else {
      $('tax_total_row').show();
      $('total_tax_amount').update(invoice.number_to_currency(tax_total));
      var parts = $F(document_id('tax')).split(Currency.decimal_symbol);
      var tax_fractions = [((parts[1] != undefined && !parts[1].blank()) ? parts[1].length : 0), 2].max();
      $('tax_percentage').update('(' + Currency.number_with_delimiter(Currency.parse_float($F(document_id('tax')) || 0), {precision: tax_fractions}) + '%)');
    }
    if($('apply_tax2_link')){
      if($('apply_tax2_link').visible()) {
        $('tax2_total_row').hide();
      } else {
        $('tax2_total_row').show();
        $('total_tax2_amount').update(invoice.number_to_currency(tax2_total));
        var parts = $F(document_id('tax2')).split(Currency.decimal_symbol);
        var tax_fractions = [((parts[1] != undefined && !parts[1].blank()) ? parts[1].length : 0), 2].max();
        $('tax2_percentage').update('(' + Currency.number_with_delimiter(Currency.parse_float($F(document_id('tax2')) || 0), {precision: tax_fractions}) + '%)');
      }
    }
    if($('retainer_payment_total_row')) {
      if(retainer_payment_total > 0) {
        $('total_retainer_payment_amount').update(invoice.number_to_currency(retainer_payment_total));
        $('retainer_payment_total_row').show();
      } else {
        $('retainer_payment_total_row').hide();
      }
    }
    if($$('#sort_invoice_item_list li').size() != 0){
      $$('#sort_invoice_item_list li').each(
    function(li){
      var amount = Cents.mul(invoice.parse_float(li.down('.sort-list-quantity').innerHTML),
                 invoice.parse_float_with_currencies(li.down('.sort-list-unit-price').innerHTML));
      var amount_in_currency = invoice.number_to_currency(Cents.round(amount));
      li.down('.sort-list-type').innerHTML = amount_in_currency;
    });
    }
  },

  payment: {

    apply_retainer_form : null,

    toggle: function(){
      $('payment_form').toggle();
      $('recieve_payment_links').toggle();
      if($('payment_form').visible()) {
        var amount_field = $('payment_amount');
        amount_field.focus();
        amount_field.select();
      }
      else
        $('payment_apply_retainer').innerHTML = '';
    },

    apply_retainer_toggle: function(){
      $('apply_retainer_form').toggle();
      $('recieve_payment_links').toggle();
      /*if(!invoice.payment.apply_retainer_form){
        invoice.payment.apply_retainer_form = $('retainer_payment_template').innerHTML;
        $('retainer_payment_template').innerHTML = "";
      }
      $('payment_apply_retainer').innerHTML = invoice.payment.apply_retainer_form;

      invoice.payment.toggle();*/
    },

    valid: function() {
      if(!date.is_valid_date($F('payment_paid_at_human_format'))) {
        alert('You need to select a valid payment date.');
        return false;
      }
      return true;
    }
  },

  message: {
    toggle: function(){
      var form_id = 'send_invoice_form';
      if($('payment-button') &&
         $('payment-button').hasClassName('btn-medium-green-on')) {
          invoice.payment.toggle();
      }
      $(form_id).toggle();
      $('send-invoice-button').
        toggleClassName('btn-medium-white-on').
        toggleClassName('btn-medium-white');
    }
  },

  reminder: {
    toggle: function(){
      $('late_payment_form').toggle();
      $$('tr.new_retainer').invoke('toggle');
    }
  },
  
  retainers_to_projects: $H({}),

  retainer: {
    currencies: $H({}),
    draw_retainer_id: null,
    draw_retainer_balance: null,
    
    draw_retainer_balance_present: function() {
      return invoice.retainer.draw_retainer_balance != null;
    },

    register_observers_for_withdraw_form: function() {
      $('invoice_currency_with_symbol').observe('change', invoice.retainer.currency_change);
      $('draw_from_retainer').observe('change', invoice.retainer.test_currency);
      $('draw_from_retainer_id').observe('change', invoice.retainer.retainer_switch);
    },

    currency_change: function(){
      // Note: This function probably shouldn't be necessary - but i put it here _just in case_
      if( $('draw_from_retainer').checked && !invoice.retainer.test_currency_match() ){
        alert("You've chosen a currency that doesn't match the selected retainer. Retainer deselected.");
        $('draw_from_retainer').checked = false;
      }
    },

    retainer_switch: function(){
      if($('draw_from_retainer').checked && !invoice.retainer.test_currency_match()){
        console.log(">> TODO: let's make a prettier confirm process.");
        if(confirm("Do you want to apply this retainer and change the currency of your invoice!?")) invoice.retainer.retainer_selected();
        else{
          $('draw_from_retainer_id').value = invoice.retainer.draw_retainer_id;
          if(invoice.retainer.draw_retainer_id == null) $('draw_from_retainer').checked = false;
        }
      }
      else invoice.retainer.retainer_selected();
    },

    test_currency: function(){
      if($('draw_from_retainer').checked && !invoice.retainer.test_currency_match()){
        console.log(">> TODO: let's make a prettier confirm process.");
        if(confirm("Do you want to apply this retainer and change the currency of your invoice!?")) invoice.retainer.retainer_selected();
        else $('draw_from_retainer').checked = false;
      }
      else invoice.retainer.retainer_selected();
    },

    retainer_selected: function(){
      if($('draw_from_retainer').checked){

        invoice.retainer.draw_retainer_id = $('draw_from_retainer_id').value;

        $('invoice_currency_with_symbol').disable();
        console.log(">> TODO: draw payments line!");
        $('invoice_currency_with_symbol').value = invoice.retainer.currencies.get($('draw_from_retainer_id').value);

        console.log(">> TODO: draw payments line!");
        // Update the invoice rows
        invoice.parse_out_currency_symbol(); invoice.recompute_amounts_and_totals();
      }
      else{
        invoice.retainer.draw_retainer_id = null;
        $('invoice_currency_with_symbol').enable();
      }
    },

    test_currency_match: function(){
      // At one point this was more complicated and required it's own function. Now it's pretty simple, but let's keep it separate _just in case_
      return ( $('invoice_currency_with_symbol').value == invoice.retainer.currencies.get($('draw_from_retainer_id').value) );
    },

    register_observers_for_apply_form: function() {
      $('activity_retainer_id').observe('click', invoice.retainer.handle_change_of_retainer);
      // invoice.retainer.handle_change_of_retainer();
    },

    handle_change_of_retainer: function() {
      var retainer_selection = $F('activity_retainer_id');
      'new_retainer' == retainer_selection ? invoice.retainer.show_new_retainer_form_elements() : invoice.retainer.hide_new_retainer_form_elements();
    },

    show_new_retainer_form_elements: function() {
      $$('tr.new_retainer').invoke('show');
    },

    hide_new_retainer_form_elements: function() {
      $$('tr.new_retainer').invoke('hide');
    }
  },


  register_on_change_handlers_for_invoice_report_selected: function() {
    $('invoice_report_selected', 'invoice_report_not_selected').each(function(control) {
      control.observe('click', invoice.on_change_invoice_report_selected);
    });
    invoice.on_change_invoice_report_selected();
    client_document.register_on_change_handlers_for_archive_report_check_boxes('invoice');
  },

  on_change_invoice_report_selected: function() {
    var on_change_invoice_report_selected = $('invoice_report_selected').checked;
    var form_ = $('filter_form');
    if(on_change_invoice_report_selected) {
      form_.action = form_.action.gsub('/payments_archive', '/archive');
      $('filter_status_row').show();
    } else {
      form_.action = form_.action.gsub('/archive', '/payments_archive');
      $('filter_status_row').hide();
    }
  },

  toggle_create_category_form: function() {
    $('add_category').toggle();
    $('add-category-button').toggleClassName('pressed');
    $('add_category_name').activate();
  },

  destroy: function(path) {
    if(confirm('Are you sure you want to delete this invoice?')) {
      new Ajax.Request(path, { evalScripts:true, asynchronous:true, method:'delete'});
    }
    return false;
  },

  toggle_payment_form: function() {
    if($('send-invoice-button').hasClassName('pressed')) {
      invoice.toggle_send_invoice_form();
    }
    $('payment_form').toggle();
    $('payment-button').toggleClassName('pressed');
    if($('payment_form').visible()) {
      var amount_field = $('payment_amount');
      amount_field.focus();
      amount_field.select();
    }
  },

  toggle_create_invoice_form: function() {
    $('create-invoice-form').toggle();
    $('create-invoice-button').toggleClassName('pressed');
  },

  toggle_send_invoice_form: function() {
    if($('payment-button') && $('payment-button').hasClassName('pressed')) {
      invoice.toggle_payment_form();
    }
    $('send_invoice_form').toggle();
    $('send-invoice-button').toggleClassName('pressed');
    if ($('send-invoice-button').hasClassName('pressed')) {
      $('message_body').activate();
    }
  },

  adjust_amount_before_submitting_to_pay_pal: function() {
    var amount = $F('localized_amount');
    amount = amount.strip().gsub(/[^\-0-9\.,]/, '');
    amount = amount.gsub(Currency.thousands_separator, '');
    amount = amount.gsub(Currency.decimal_separator, '.');
    $('amount').value = amount;
  },

  sort_line_items: function(){
    $('invoice_table_footer').removeClassName('tax_pad');
    $$('#tax_table_head, #tax2_table_head').invoke('hide');
    var theForm = document.forms[0];

    $$('ul#sort_invoice_item_list li').invoke('remove');

    $('sort_line_items_link').hide();
    $('close_sort_items_link').show();

    $('add_line_item_link').hide();

    var newlis = [""];

    $$('#invoice_item_rows tr').each(function(el){
      var iid = el.identify();
      if(iid.search("NUMBER")<1){
        var id = iid.substr(9);

        var description = theForm.elements["item"+id+"[description]"].value;
        if(description=="") description = "&nbsp;";

        newlis.push("<li id=\"sortlist_", id, "\">");
        newlis.push("<div class=\"sort-list-description\">", description, "&nbsp;</div>");
        newlis.push("<div class=\"sort-list-handle\"><img src=\"/images/icons/reorder_handle.png\" /></div>");
        newlis.push("<div class=\"sort-list-ab sort-list-kind\">", theForm.elements["item"+id+"[kind]"].value, "</div>");
        newlis.push("<div class=\"sort-list-ab sort-list-quantity\">", theForm.elements["item"+id+"[quantity]"].value, "</div>");
        newlis.push("<div class=\"sort-list-ab sort-list-unit-price\">", theForm.elements["item"+id+"[unit_price]"].value, "</div>");
        newlis.push("<div class=\"sort-list-ab sort-list-type\">", el.down('.amount').innerHTML, "</div>");
        newlis.push("</li>");
      }
    });

    $('sort_invoice_item_list').update(newlis.join(''));
    //$$('#invoice_item_rows tr').invoke('remove');

    $$('#sort_invoice_item_list li').each(function(el){
      el.observe('mousedown', function(event){ Event.element(event).up('li').addClassName('block-hover'); });
      el.observe('mouseup', function(event){ Event.element(event).up('li').removeClassName('block-hover'); });
    });
    Sortable.create('sort_invoice_item_list', {tag: 'li', onUpdate: invoice.update_sort_list });

    $('invoice_item_rows').hide();
    $('testing_sort').show();

  },

  update_sort_list: function(){
    $$('ul#sort_invoice_item_list li').each(function(el){
      var iid = el.identify().substr(9);

      var the_row = $('item-row-'+iid);
      the_row.remove();
      $('invoice_item_rows').appendChild(the_row);
    });
    invoice.on_line_items_reorder_done();
  },

  close_sort_items: function(){
    $('invoice_item_rows').show();
    $('testing_sort').hide();
    $('sort_line_items_link').show();
    $('close_sort_items_link').hide();
    $('add_line_item_link').show();

    $$('ul#sort_invoice_item_list li').invoke('remove');
    Sortable.destroy('sort_invoice_item_list');
    if($('tax_total_row').visible()){
      $('invoice_table_footer').addClassName('tax_pad');
      $('tax_table_head').show();
    }
    if($('tax2_total_row').visible()){
      $('invoice_table_footer').addClassName('tax_pad');
      $('tax2_table_head').show();
    }
  },
  
  configure_selected_retainer: 0,
  
  handle_configure_retainer_selection: function(){
    if(invoice.configure_selected_retainer!=0 && invoice.retainers_to_projects.get(invoice.configure_selected_retainer)){
      $$('.select_project_checkbox').each(function(e){
        if( e.identify() != "project-" + invoice.retainers_to_projects.get(invoice.configure_selected_retainer) + "-include" )
          e.checked = false;
        else{
         e.siblings(0).each(function(e){
           $('invoice_project_name').innerHTML = ' ' + e.innerHTML;
           $('thatdarns').hide();
         });
        }
      });
      $('configure_projects_invoice_table').hide();
    }
    
    $('retainer_apply_select').hide();
    $('invoice_configure_projects').show();
    return false;
  },

  projects_and_last_efforts: new Hash(),
  disable_time_frame_calculation: false,

  protect_against_silly_comma_problems: ''

};

Object.extend(invoice, Currency);

/****************************************************************/
/*  original filename import.js                        */
/****************************************************************/


var imports = {

  toggle_third_party_form: function(selected) {
    var selectedFormId = selected.toLowerCase() + "_form";
    $$(".third-party-import-form").each(function(formElement) {
      if(formElement.id == selectedFormId) {
        formElement.show();
      } else {
        formElement.hide();
      }
    }) ;

    var selectedHintsId = selected.toLowerCase() + "_hints";
    $$(".third-party-import-hints").each(function(formElement) {
      if(formElement.id == selectedHintsId) {
        formElement.show();
      } else {
        formElement.hide();
      }
    }) ;

    var selectedLogoId = selected.toLowerCase() + "_logo";
    $$(".third-party-import-logo").each(function(formElement) {
      if(formElement.id == selectedLogoId) {
        formElement.show();
      } else {
        formElement.hide();
      }
    }) ;
  }
}



/****************************************************************/
/*  original filename estimate.js                        */
/****************************************************************/


var estimate = {
  check_for_valid_form: function() {
    return (date.form_validation({estimate_issued_at_human_format: 'issue date'}) &&
      client_document.check_for_valid_line_items());
  },

  destroy: function(path) {
    if(confirm('Are you sure you want to delete this estimate?')) {
      new Ajax.Request(path, { evalScripts:true, asynchronous:true, method:'delete'});
    }
    return false;
  },

  toggle_send_estimate_form: function() {
    $('send_estimate_form').toggle();
    $('send-estimate-button').toggleClassName('pressed');
    if ($('send-estimate-button').hasClassName('pressed')) {
      $('message_body').activate();
    }
  },

  message: {
    toggle: function(){
      $('send_estimate_form').toggle();
      $('send-estimate-button').
        toggleClassName('btn-medium-white-on').
        toggleClassName('btn-medium-white');
    }
  }

};

Object.extend(estimate, Currency);










/****************************************************************/
/*  original filename retainer.js                        */
/****************************************************************/


var retainer = {
  //clients_and_currencies: $H({}),
  clients_and_projects: $H({}),
  display_clients_and_projects: $H({}),
  selected_project_id: null,

  register_handlers: function() {
    $('clients_list').observe('change', retainer.on_change_clients_list);
  },

  show_new_retainer_form: function() {
    show_big_div('create_retainer_form', 'clients_list');
    retainer.on_change_clients_list();
  },

  on_change_clients_list: function() {
    var selected_client = $F('clients_list');

    if("" == selected_client) $('project_list').hide();
    else {
      retainer.update_project_selection();
      $('project_list').show();
    }
  },
  
  retainer_create_form_submit: function(){
    if(client_document.client_was_selected()){
      if($F('project_list')!="") return true
      else alert("Please choose a retainer project.");
    }
  
    return false;
  },

  update_project_selection: function() {
    $('project_list_cont').update('');
    var selected_client_id = $F('clients_list');

    var project_html = ["<select id='project_list' name='retainer[project_id]' style='width: 400px'>"];

    var projects = isNaN(selected_client_id) ? [] : (retainer.clients_and_projects.get(selected_client_id) || []);
    var existing_retainer_project_ids = isNaN(selected_client_id) ? [] : (retainer.display_clients_and_projects.get(selected_client_id).project_ids || []);

    if(projects.length && existing_retainer_project_ids.length)
      projects = projects.reject(function(p) { return existing_retainer_project_ids.include(p.id)})
    if(projects.length){
        for (var project_i = 0, projects_length = projects.length; project_i < projects_length; project_i++){
          var project = projects[project_i];
          if(project.id == filter.selected_project_id){
            project_html.push("<option value='", project.id, "' selected='selected'>", project.name, "</option>");
          } else {
            project_html.push("<option value='", project.id, "'>", project.name, "</option>");
          }
        }
        
      if(!existing_retainer_project_ids.length)
        project_html.push("<option value=''>---------------</option>");

    }
    
    if(!existing_retainer_project_ids.length)
      project_html.push("<option value='all'>Apply to all projects</option>");
    
    project_html.push("</select>");
    $('project_list_cont').update(project_html.join(''));
  },

  hide_project_list: function() {
    $('project_list_section').hide();
    if($('project_list'))  $('project_list').remove();
  },

  show_new_activity_form: function() {
    show_big_div('create_activity_form', 'activity_summary');
  },

  show_new_invoice_form: function() {
    show_big_div('create_invoice_form');
  },

  toggle_activity_edit: function(id) {
    $('activity-' + id + '-edit', 'activity-' + id + '-show').invoke('toggle');
  },

  clear_add_activity_form: function() {
    $('activity_summary').value = '';
    $('activity_amount').value = '';
  },

  navigate_to_new_invoice: function(retainer_id, client_id, project_id) {
    if($('invoice_withdraw') && $('invoice_withdraw').checked) {
      var project_param = project_id.blank() ? '' : '&draw_project_id=' + project_id;
      location.href = '/invoices/new?invoice[client_id]=' + client_id +
                      '&invoice[kind]=project_hours' +
				              '&draw_retainer_id=' + retainer_id +
				              project_param;
    } else {
      location.href = '/invoices/new?invoice[retainer_id]=' + retainer_id +
                      '&invoice[client_id]=' + client_id +
                      '&invoice[kind]=retainer';
    }
  }

};

Object.extend(retainer, Currency);

/****************************************************************/
/*  original filename import.js                        */
/****************************************************************/


var imports = {

  toggle_third_party_form: function(selected) {
    var selectedFormId = selected.toLowerCase() + "_form";
    $$(".third-party-import-form").each(function(formElement) {
      if(formElement.id == selectedFormId) {
        formElement.show();
      } else {
        formElement.hide();
      }
    }) ;

    var selectedHintsId = selected.toLowerCase() + "_hints";
    $$(".third-party-import-hints").each(function(formElement) {
      if(formElement.id == selectedHintsId) {
        formElement.show();
      } else {
        formElement.hide();
      }
    }) ;

    var selectedLogoId = selected.toLowerCase() + "_logo";
    $$(".third-party-import-logo").each(function(formElement) {
      if(formElement.id == selectedLogoId) {
        formElement.show();
      } else {
        formElement.hide();
      }
    }) ;
  }
}



/****************************************************************/
/*  original filename budget.js                        */
/****************************************************************/


var budget = {
  projects_with_loaded_details: $A([]),

  toggle_details: function(remote_url, project_id) {
    if(budget.projects_with_loaded_details.include(project_id)) {
      budget.adjust_project_row_class(project_id);
      $$('tr.project-' + project_id + '-detail').invoke('toggle');
    } else {
      budget.load_budget_details(remote_url, project_id);
    }
  },

  load_budget_details: function(remote_url, project_id) {
    budget.projects_with_loaded_details.push(project_id);
    budget.open_row_class(project_id);
    $('project-' + project_id + '-loading').show();
    new Ajax.Request(remote_url, {
      'asynchronous': true,
      'evalScripts': true,
      'method': 'get',
      'onComplete': function(transport) {
        budget.open_row_class(project_id);
      }
    });
  },

  adjust_project_row_class: function(project_id) {
    if($('project-' + project_id).hasClassName('with_budget')) {
      budget.open_row_class(project_id);
    } else {
      budget.close_row_class(project_id);
    }
  },

  open_row_class: function(project_id) {
    var project_row = $('project-' + project_id);
    project_row.addClassName('with_budget_open');
    project_row.removeClassName('with_budget');
  },

  close_row_class: function(project_id) {
    var project_row = $('project-' + project_id);
    project_row.addClassName('with_budget');
    project_row.removeClassName('with_budget_open');
  }

};




/****************************************************************/
/*  original filename payment.js                        */
/****************************************************************/


var payment = {
  plans: { },

  attrs: { },

  box: { },

  submitted: false,

  current_active_users: 0,

  max_users_allowed_for_original_plan_name: null,

  select: function(plan_name){
    var html = $('form_prototype').innerHTML;
    payment.attrs = payment.plans[plan_name];
    if(payment.current_active_users > payment.attrs.max_users_allowed){
      return false;
    }
    payment.max_users_allowed_for_original_plan_name = payment.plans[plan_name].max_users_allowed;
    new Lightbox(html.gsub(/---PLAN NAME---/, plan_name)
                 .gsub(/---CAPITALIZED PLAN NAME---/, plan_name.capitalize())
                 .gsub(/---PLAN INCLUDED USERS USERS---/, payment.attrs.included_users_users)
                 .gsub(/---PLAN ACTIVE USERS---/, payment.attrs.active_users)
                 .gsub(/---PLAN BASE PRICE---/, payment.attrs.base_price.toFixed(2))
                 .gsub(/---PLAN ADDITIONAL USER COUNT---/, payment.attrs.additional_user_count)
                 .gsub(/---EXTRA PRICE PER USER---/, payment.attrs.per_user_price)
                 .gsub(/---TOTAL PRICE FOR EXTRA USERS---/, 0)
                 .gsub(/---PLAN TOTAL PRICE---/, payment.attrs.base_price)
                 .gsub(/---PLAN TOTAL YEARLY PRICE PER MONTH---/, (payment.attrs.base_price*(1-payment.attrs.yearly_deduction)).toFixed(2))
                 .gsub(/---PLAN TOTAL YEARLY PRICE---/, (payment.attrs.base_price*(1-payment.attrs.yearly_deduction)*12).toFixed(2))
                 .gsub(/---PLAN YEARLY SAVINGS---/, (payment.attrs.base_price*payment.attrs.yearly_deduction*12).toFixed(2)));

    payment.box = $('lightbox').down('.payment_box');
    payment.on_user_count_change();
    payment.box.appear( { duration: 0.3,
                          afterFinish: function(){
                            var field = $('lightbox').down('.nr-of-users');
                            field.observe('keyup', payment.on_user_count_change);
                            field.focus(); }});

    return false;
  },

  best_plan_for_user_count: function(user_count){
    var  best_plan = $A(['solo', 'basic', 'business']).find(
      function(pname){
        return payment.plans[pname].max_users_allowed >= user_count;
      });
    if(best_plan == 'basic' && user_count == 10){
      return 'business';
    }
    return best_plan;
  },

  on_user_count_change: function(){
    var lb = $('lightbox');
    payment.box = lb.down('.payment_box');
    var flash = lb.down('.please-archive-users-first');
    flash.removeClassName('payment-highlight');
    var user_count = payment.box.down('.nr-of-users').value;
    if(user_count == ''){
      return;
    }

    var next_plan = payment.best_plan_for_user_count(user_count);
    //http://lists.getharvest.com/space/1/todo_items/1089#comment_10178
    if(next_plan != payment.attrs.name &&
       (user_count >= payment.attrs.max_users_allowed ||
    payment.max_users_allowed_for_original_plan_name <= payment.plans[next_plan].max_users_allowed)) {
      payment.attrs = payment.plans[next_plan];
      payment.box = lb.down('.payment_box');
      lb.select('.capitalized_plan_name').each(
        function(e){ e.innerHTML = next_plan.capitalize(); });
      lb.select('.plan_included_users_users').each(
        function(e){ e.innerHTML = payment.attrs.included_users_users; });
      lb.select('.plan_base_price').each(
        function(e){ e.innerHTML = payment.attrs.base_price.toFixed(2); });
      lb.select('.extra_price_per_user').each(
        function(e){ e.innerHTML = payment.attrs.per_user_price; });
    }
    if(user_count < payment.current_active_users){
      lb.select('.payment-button').invoke('addClassName', 'disabled-button');
      payment.flash_user_payment_message.delay(.5);
      return;
    }
    lb.select('.payment-button').invoke('removeClassName', 'disabled-button');

    var extra_users = [user_count - payment.attrs.included_users, 0].max();
    payment.box.down('.additional-user-count').innerHTML = extra_users;
    payment.box.down('.additional-price').innerHTML = (payment.attrs.per_user_price * extra_users).toFixed(2);
    var monthly = (payment.attrs.base_price +
                   parseFloat((payment.attrs.per_user_price * extra_users).toFixed(2))).toFixed(2);
    payment.box.select('.monthly-total-price').each(
      function(span){
        span.innerHTML = monthly;
      });
    var yearly_per_month = (monthly*(1-payment.attrs.yearly_deduction)).toFixed(2);
    payment.box.select('.yearly-total-price-per-month').each(
      function(span){
        span.innerHTML =  yearly_per_month;
      });
    payment.box.select('.yearly-total-price').each(
      function(span){
        span.innerHTML = (yearly_per_month*12).toFixed(2);
      });
    payment.box.select('.yearly-total-price-savings').each(
      function(span){
        span.innerHTML = (monthly*12-yearly_per_month*12).toFixed(2);
      });
    payment.show_or_hide_rows_for_additional_users();
  },

  flash_user_payment_message: function() {
    /* PF: This uses a lot of repeat logic from above, but it was the fastest way to bang out fixing the issues delay() presented in UI */
    var user_count = payment.box.down('.nr-of-users').value;
    var lb = $('lightbox');
    var flash = lb.down('.please-archive-users-first');
    flash.removeClassName('payment-highlight');

    if(user_count < payment.current_active_users)
      flash.addClassName('payment-highlight');
  },

  show_or_hide_rows_for_additional_users: function() {
    payment.box.select('.additional-users-row').each(
      function(e){
        var user_count = parseInt(payment.box.down('.nr-of-users').value);
        if( user_count == payment.attrs.included_users){
          e.hide();
        } else {
          if(user_count > payment.attrs.included_users){
            Effect.BlindDown(e, { duration: 2 });
          }
        }
      });
  },

  submit: function(term){
    if(payment.submitted == false) {
      payment.submitted = true;

      var user_count = parseInt(payment.box.down('.nr-of-users').value);
      if(user_count < payment.current_active_users){
        payment.submitted = false;
        return false;
      }

      var f = document.createElement('form'); f.style.display = 'none';
      payment.box.appendChild(f);
      f.method = 'POST';
      f.action = '/company/edit_plan';

      $H({ user_count: user_count,
           plan_name: payment.attrs.name,
           authenticity_token : window._token,
           term: term }).each(
             function(pair) {
               var s = document.createElement('input');
               s.setAttribute('type', 'hidden');
               s.setAttribute('name', pair.first());
               s.setAttribute('value', pair.last());
               f.appendChild(s);
             });
      f.submit();
    }
    return false;
  },

  apply_coupon: function(on_plan, term, user_count) {
    var coupon_code = $F('subscription_coupon_code');
    if(!coupon_code.blank()){
      var params =$H({plan_name : on_plan, coupon_code : coupon_code, term : term, user_count : user_count});
      new Ajax.Request('/payment/apply/coupon',
                       {asynchronous:true, evalScripts:true, parameters:params.toQueryString()});
    }
    return false;
  },

  show_hide_label_hints: function(){
    $$('label').each(function(label){
        var input = $(label.readAttribute('for'));
        if(input){
          if($F(input).blank()){
              label.show();
          } else {
              label.hide();
          }
        }
    });
  },

  re_compute_plan_total: function(coupon_deduced_amount, number_of_months, is_monthly_deduction){
    var base_price = Currency.parse_float_with_currencies($('base_price').innerHTML);
    var additional_users_price = 0;
    if($('additional_price')){
      additional_users_price = Currency.parse_float_with_currencies($('additional_price').innerHTML);
    }
    var full_price = base_price + additional_users_price;
    if($('annual_payment_discount')){
      full_price -=  coupon_deduced_amount * (is_monthly_deduction ? number_of_months : 1 );
      $('annual_payment_discount').innerHTML = '-$' + (full_price * 0.1).toFixed(2);
      full_price += Currency.parse_float_with_currencies($('annual_payment_discount').innerHTML);
    } else {
      full_price -=  coupon_deduced_amount * (is_monthly_deduction ? number_of_months : 0 );
    }
    $('total_price').innerHTML = '$' + full_price.toFixed(2);
  },

  via: {
    credit_card: function(){
      $('credit_card_info').show();
    },

    invoice: function(){
      $('credit_card_info').hide();
    }
  }

};


/****************************************************************/
/*  original filename hours.js                        */
/****************************************************************/


/* -*- Mode:JavaScript; c-basic-offset:2; indent-tabs-mode:nil; c-indentation-style:"k&r" -*- */
var hours = {

  DECIMAL_TIME_FORMAT: 'decimal',
  HOURS_MINUTES_TIME_FORMAT: 'hours_minutes',
  time_format: 'decimal',
  wants_24h_time: false,
  negative_regexp: /(^-)|(^\()/,  // Begins with '-' or '('
  operator_regex: /\+|-/,

  parse_and_display_time: function(number) {
    var parsed_number = hours._math_in_number(number) ? hours._calculate_math_in_number(number) : number;
    return hours.display_time(hours.convert_time_to_float(parsed_number));
  },

  _math_in_number: function(number) {
    var stripped_number = number.strip();
    var operators       = [];
    stripped_number.scan(hours.operator_regex, function(match) {operators.push(match[0])});

    if(0 == operators.length)  return false;
    if((1 == operators.length) && stripped_number.match(/^[\+|-]/))  return false;
    return true;
  },

  _calculate_math_in_number: function(number_containing_math) {
    var numbers         = number_containing_math.toString().split(hours.operator_regex);
    var operators       = [];
    number_containing_math.scan(hours.operator_regex, function(match) {operators.push(match[0])});

    var first_number    = hours.convert_time_to_hhmm(numbers.shift());
    var starting_value  = Date.parse(first_number);
    var total_value     = starting_value;

    var hours_minutes   = [];
    var operator        = '';
    numbers.each(function(number, index) {
      hours_minutes = hours.convert_time_to_hhmm(number).split(':');
      operator      = operators[index];
      total_value   = total_value.add({hours: operator + hours_minutes[0], minutes: operator + hours_minutes[1]});
    });

    return Time.toString(total_value, '24hour');
  },

  display_time: function(number) {
    if(number < 0)  number = 0;
    return (hours.DECIMAL_TIME_FORMAT == hours.time_format ? Currency.number_with_delimiter(number) : hours.convert_decimal_to_hhmm(number));
  },

  convert_time_to_float: function(number){
    if(hours.zero(number)){
      return 0;
    }
    var converted_time = parseFloat(hours.convert_hhmm_to_decimal(number.toString().gsub(/\,/, '.')));
    return isNaN(converted_time) ? 0 : converted_time;
  },

  convert_time_to_hhmm: function(number) {
    return hours.convert_decimal_to_hhmm(hours.convert_time_to_float(number));
  },

  convert_hhmm_to_decimal: function(input_value) {
    if ((input_value != null) && (input_value.indexOf) && (input_value.indexOf(':') != -1)) {
      var time = input_value.split(':');
      var negative = false;
      if(time[0].match(/^-/)) {
        negative = true;
        time[0] = time[0].sub('-', '');
      }
      var hours = (time[0] == "") ? 0 : parseFloat(time[0]);
      var minutes = parseFloat(time[1] / 60);
      input_value = (minutes + 0 + hours).toFixed(2);
      if(negative) input_value = 0 - input_value;
    }
    return input_value;
  },

  convert_decimal_to_hhmm: function(input_value) {
    var hours_and_decimal_part = input_value.toFixed(2).split('.');
    var hours                  = hours_and_decimal_part[0] || '0';
    var decimal_part           = hours_and_decimal_part[1];
    var minutes                = Math.round(parseFloat(decimal_part) * 60 / 100);

    // Add '0' to the front of single digit minutes for use in building a full time string like "7:08".
    minutes                    = minutes >= 10 ? minutes : '0' + minutes;

    return hours + ':' + minutes;
  },

  // Get the absolute value of time, removing '-', '(', and ')'
  abs_time: function(time) {
    return time.gsub(/-|\(|\)/, '');
  },

  parse_as_float: function (input_value) {
    if(input_value.indexOf(':') != -1) {
      return hours.convert_hhmm_to_decimal(input_value);
    }
    if(hours.zero(input_value)){
      return 0.0;
    }
    return Currency.parse_float(input_value);
  },

  // Checks if given time is equivalent to "0:00"
  zero: function(time) {
    return time.blank() || '0' == time || '0:00' == time || 0 == time;
  },

  valid_hhmm_time: function(time) {
    time = time.strip();
    return time.match(/\d:\d{2}/) || time.match(/^\d{1,2}[a|p]?m?$/i) || time.match(/\d{3,4}/);
  },

  normalize_timestamp: function(time, related_time) {
    if (time && (typeof time == 'String'))
      time = time.toLowerCase();
    return hours.wants_24h_time ? Time.toString(time, '24hour') : Time.toString(time, '12hour', related_time);
  }
};

/****************************************************************/
/*  original filename date.js                        */
/****************************************************************/


var date = {
  handle_onblur_date_field: function(event) {
    var element = Event.element(event);
    date.reformat_date_string(element);
    date.warn_if_invalid(element);
  },

  reformat_date_string: function(date_id) {
    date._reformat_date_string_separators(date_id);
    date._reformat_unaccepted_characters(date_id);
    date._reformat_date_string_year(date_id);
  },

  _reformat_date_string_separators: function(date_id) {
    date._load_date_format();
    $(date_id).value = $F(date_id).gsub(/\.|\/|-/, date.format.separator).strip();
  },

  _reformat_unaccepted_characters: function(date_id) {
    date._load_date_format();
    if(!(date.format instanceof N8DatePickerFormatter)) {
      $(date_id).value = $F(date_id).gsub(/[^0-9./-]/, '');
    }
  },

  _reformat_date_string_year: function(date_id) {
    if(date.format instanceof N8DatePickerFormatter) {
      $(date_id).value = date.format.reformat($F(date_id));
      return;
    }
    var d = $F(date_id).split(date.format.separator);
    var year = d[date.format._format_year_index];
    if((typeof(year) != "undefined") && (2 == year.length)) {
      year = '20' + year;
      var month = d[date.format._format_month_index];
      var day = d[date.format._format_day_index];
      $(date_id).value = date.format.date_to_string(parseInt(year), parseInt(month), parseInt(day));
    }
  },

  warn_if_invalid: function(date_id) {
    if(date.is_valid_date($F(date_id))) {
      return true;
    }

    var container_element = $(date_id).next('.callout_warning_container');
    tip.show(container_element, container_element.down(".callout_warning_top"));
    // setTimeout("$('" + date_id + "').activate()", 10);  // This makes it hard to cancel a page since it hijacks focus
    // setTimeout("date.fade_warning('" + date_id + "')", 5000);
    return false;
  },

  fade_warning: function(event) {
    var element = Event.element(event);
    var warning_div = element.next('.callout_warning_container');
    if(warning_div)
      tip.fade(warning_div);
  },

  picker_cell_callback: function(element){
    Form.Element.focus(element);
  },

  picker_on_page_load: function(element_id, this_picker){
    document.observe('dom:loaded', function(){
      date.picker_observations(element_id, this_picker);
    }, false);
  },

  picker_observations: function(element_id, this_picker) {
    var element = $(element_id);
    element.observe('blur', date.handle_onblur_date_field);
    element.observe('keydown', date.fade_warning);
    element.observe('click', date.fade_warning);
    $$('input, textarea, select').without(element).each(function(e) {
      e.observe('focus', date.handle_focus_off_picker.curry(this_picker));
    });
  },

  handle_focus_off_picker: function(this_picker) {
    var date_picker_element = $(this_picker._id_datepicker);
    if(date_picker_element && date_picker_element.visible()) {
      this_picker.close();
    }
  },

  // date_hash includes the field id as key and field name (for error message) as value.
  //   {invoice_issued_at_human_format: 'issue date'}
  form_validation: function(date_hash) {
    date_hash = new Hash(date_hash);
    var issue_date = '';
    var errors = [];

    date_hash.each(function(pair) {
      date.reformat_date_string(pair.key);

      if (!date.is_valid_date($F(pair.key))) {
        errors.push('Please select a valid ' + pair.value + '.');
      }
    });

    if(errors.size() > 0) {
      alert(errors.join('\n'));
      return false;
    } else {
      return true;
    }
  },

  is_valid_date: function(input_date){
    date._load_date_format();
    var parts = date.format.match(input_date);
    if(!parts){
      return false;
    }
    var year = parts[0];
    var month = parts[1];
    var day = parts[2];
    var check_date = new Date(year, month - 1, day);
    if ((day==check_date.getDate()) && (month==check_date.getMonth() + 1) && (year==check_date.getFullYear())){
      return check_date;
    }
    return false;
  },

  is_future_date: function(input_date,today_date){
    date._load_date_format();

    var input_parts = date.format.match(input_date);
    var input_date = new Date(input_parts[0], input_parts[1] - 1, input_parts[2]);
    
    var today_parts = date.format.match(today_date);
    var today_date = new Date(today_parts[0], today_parts[1] - 1, today_parts[2]);
    
    if(today_date < input_date) return true;
    
    return false;
  },

  to_localized_format: function(v){
    date._load_date_format();

    if("string" == typeof(v)) {
      v = date.is_valid_date(v);  // Converts string to date object
    }

    if(v) {
      return date.format.date_to_string(v.getFullYear(), v.getMonth() + 1, v.getDate());
    } else {
      return NaN;
    }
  },

  to_api_format: function(v) {
    var adjust_to_2_digits = function(value){
      if(value < 10){
        return '0' + value;
      }
      return value;
    };
    return [v.getFullYear(), adjust_to_2_digits(v.getMonth() + 1), adjust_to_2_digits(v.getDate())].join('');
  },

  from_api_format: function(str){
    var parts = str.match(/^(\d\d\d\d)(\d\d)(\d\d)$/);
    if(parts){
      return new Date(parts[1], parts[2]-1, parts[3]);
    } else {
      return date.is_valid_date(str);
    }
  },

  time_ago_in_words: function(date_str){
    var hours_ago = ((new Date - new Date(date_str) ) / (3600*1000));
    if(hours_ago < 24) {
      if(hours_ago.toFixed(0) == 1) {
        return "one hour ago";
      }
      if(hours_ago.toFixed(0) == 0) {
        return "few minutes ago";
      }
      return hours_ago.toFixed(0) + " hours ago";
    }
    var days_ago = (hours_ago / 24).toFixed(0);
    if(days_ago == 1){
      return "one day ago";
    }
    return days_ago + " days ago";
  },

  _load_date_format: function() {
    if(date.format == undefined) {
      date.format = new DatePickerFormatter(window._dateFormat[0], window._dateFormat[1]);
    }
  },

  format: undefined
};














/****************************************************************/
/*  original filename form_protector.js                        */
/****************************************************************/


// Adapted from: http://www.phpriot.com/articles/reminding-users-to-submit-forms
var FormProtector = Class.create({

  form    : null,     // the form being protected
  alert   : false,    // whether or not to show the confirm box

  // the message to display in confirm box
  message : 'Please remember to submit your form',

  initialize : function(form) {
    this.form = $(form);
    this.form.observe('submit', this._onFormSubmit.bindAsEventListener(this));

    this.form.getElements().each(function(element) {
      element.observe('change', function() {
        this.alert = true;
      }.bindAsEventListener(this));
    }.bind(this));

    Event.observe(window, 'beforeunload', this._onBeforeUnload.bindAsEventListener(this));
  },

  setMessage : function(str) {
    this.message = str;
  },

  _onFormSubmit : function(e) {
    this.alert = false;
  },

  _onBeforeUnload : function(e) {
    if (this.alert) e.returnValue = this.message;
  }
});
/****************************************************************/
/*  original filename validate.js                        */
/****************************************************************/


var validate = {
  EMAIL_REGEX: /^([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,

  email: function(email_address, options_hash) {
    options_hash = options_hash || {};
    if(options_hash['accept_blank'] && email_address.blank())  return true;
    return validate.EMAIL_REGEX.test(email_address);
  }
};


// Simple class to enable/disabled submit buttons when required form inputs are non-empty/empty.
// Note that the form fields which are required should have a 'required' CSS class on them.
// Parameters:
//    formId : The ID of the form to observe for changes.
//    options hash:
//       submitButtons : Pass in a CSS selector if you want to control which buttons are enabled/disabled, otherwise
//                        any input of type "submit" will be enabled/disabled.
//
//       extraElements : Pass in a CSS selector if you want any other elements to be marked by a disabled class.
//
//       disabledClass : The class to apply to submit buttons that are disabled (defaults to "button_disabled").
//
//       extraDisabledClass : The class to apply to extra elements when the buttons are disabled (defaults to "btn-large-disabled").
//
var NonBlankFormValidator = Class.create({
  initialize: function(formId, options) {
    this.options = options || { };
    this.formId = formId;
    this.options.disabledClass    = this.options.disabledClass || "button_disabled";
    this.options.extraDisabledClass = this.options.extraDisabledClass || "btn-large-disabled";

    if(this.options.submitButtons == null) {
      this.buttons = $(this.formId).getInputs('submit');
    } else {
      this.buttons = $$(this.options.submitButtons);
    }

    if(this.options.extraElements == null) {
      this.exraElements = null;
    } else {
      this.extraElements = $$(this.options.extraElements);
    }
    new Form.Observer( this.formId, 0.5, this.toggleSubmitButton.bindAsEventListener(this));

    // Note: I have no idea why, but file fields are not accurately observed by Form.Observer.
    // What's up with that prototype?
    var fileFields = $(this.formId).getInputs("file");
    fileFields.each(function(formField){
      if(formField.hasClassName('required')) {
        formField.observe("change", this.toggleSubmitButton.bindAsEventListener(this));
      }
    }, this);

  },

  toggleSubmitButton: function(el, value){
    var allFields = $(this.formId).getInputs();
    var allRequiredPresent = true;
    allFields.each(function(formField){
      if(formField.hasClassName('required')) {
         if($F(formField) == '' || $F(formField) == null) {
               allRequiredPresent = false;
         }
      }
    });

    if(allRequiredPresent){
      this.formValid();
    } else {
      this.formNotValid();
    }
  },

  formValid: function() {
    this.buttons.each(function(button) {
      button.removeClassName(this.options.disabledClass);
      button.disabled = false;
    }, this);
    this.extraElements.each(function(extra) {
      extra.removeClassName(this.options.extraDisabledClass);
    }, this);
  },

  formNotValid: function() {
    this.buttons.each(function(button) {
      button.addClassName(this.options.disabledClass);
      button.disabled = true;
    }, this);
    this.extraElements.each(function(extra) {
      extra.addClassName(this.options.extraDisabledClass);
    }, this);

  }

});



/****************************************************************/
/*  original filename inline_confirmation.js                        */
/****************************************************************/


// This is built to be executed in the onclick event of a link/button. For instance,
// by using Rails' link_to_function helper. Note that there would be less memory usage
// if it were built to observe clicks on specified buttons as multiple clicks would
// not instantiate multiple objects. But we're not unobtrusive now and the code would
// be less readable if we went "observe click" instead of "onclick" on this one.

// NOTE: Default instance options are listed at the button of this file.

var InlineConfirmation = Class.create({
  initialize: function(elementId, confirmContainerElementId, targetUrl, options) {
    this.elementId                = elementId;
    this.confirmContainerElement  = $(confirmContainerElementId);
    this.confirmId                = elementId + "_confirm";
    this.confirmButtonsId         = elementId + "_confirm_buttons";
    this.loadingId                = elementId + "_confirm_loading";
    this.cancelLinkId             = elementId + "_confirm_cancel";
    this.targetUrl                = targetUrl;
    this.options                  = Object.extend(Object.clone(InlineConfirmation.Options), options || {});
    this.start();
  },

  start: function() {
    if(!$(this.confirmId)) {
      this.buildConfirmationMarkup();
      this.insertConfirmationMarkup();
      this.registerCancelOnClickObserver();
    }
    this.showConfirmationMarkup();
  },

  buildConfirmationMarkup: function() {
    this.confirmationMarkup =
      "<div id='" + this.confirmId + "' class='confirmation' style='display:none;'>" +
        this.options.promptText + " " +
        "<div id='" + this.confirmButtonsId + "' class='btn_container'>" +
          button("small", "white", this.confirmationApproveLink()) +
          button("small", "white", "<a href='#' class=\"no\" id='" + this.cancelLinkId + "' onclick='return false;'>" + this.options.confirmCancelText + "</a>") +
        "</div>" +
        (this.options.confirmLoadingSpinner ? "<div id='" + this.loadingId + "' class='loading' style='display:none;'>" + this.options.confirmApproveLoadingText + "</div>" : "") +
      "</div>";
  },

  confirmationApproveLink: function() {
    if(this.options.linkToAjax) {
      return this.confirmationApproveLinkToAjax();
    } else if(this.options.linkToFunction) {
      return this.confirmationApproveLinkToFunction();
    } else {
      return this.confirmationApproveLinkToNonAjax();
    }
  },

  // Essentially a port of Rails' UrlHelper#method_javascript_function. If this
  // needs reused elsewhere, pull out into it's own class/object.
  confirmationApproveLinkToNonAjax: function() {
    var onclickFunction   = this.loadingFunction();
    var specialMethodCode = "";

    // Pass PUT or DELETE attribute, as we mock that functionality using POST
    if(['put', 'delete'].include(this.options.method)) {
      specialMethodCode =
        "var m = document.createElement('input'); m.setAttribute('type', 'hidden'); " +
        "m.setAttribute('name', '_method'); m.setAttribute('value', '" + this.options.method + "'); f.appendChild(m);";
    }

    // Construct a form to pass POSTS via a link. Set authenticity token on form.
    if(this.options.method != "get") {
      onclickFunction +=
        "var f = document.createElement('form'); f.style.display = 'none'; " +
        "this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href; " +
        specialMethodCode +
        "var s = document.createElement('input'); s.setAttribute('type', 'hidden'); " +
        "s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', '" + window._token + "'); f.appendChild(s);" +
        "f.submit(); return false;";
    }
    onclickFunction = "onclick=\"" + onclickFunction + "\"";

    return "<a href=\"" + this.targetUrl + "\" " + onclickFunction + ">" + this.options.confirmApproveText + "</a> ";
  },

  confirmationApproveLinkToFunction: function() {
    return "<a href=\"#\" class=\"yes\" onclick=\"" + this.loadingFunction() + this.targetUrl + "; return false;\">" + this.options.confirmApproveText + "</a> ";
  },

  confirmationApproveLinkToAjax: function() {
    var onclickFunction = "new Ajax.Request('" + this.targetUrl + "', {" +
                            "asynchronous: true, " +
                            "evalScripts:  true, " +
                            "method:       '" + this.options.method + "' })";

    return "<a href=\"#\" class=\"yes\" onclick=\""+ this.loadingFunction() + onclickFunction + "; return false;\">" + this.options.confirmApproveText + "</a> ";
  },

  loadingFunction: function() {
    if(this.options.confirmLoadingSpinner)
      return "$('" + this.confirmButtonsId + "').hide();$('" + this.loadingId + "').show();";

    return "";
  },

  insertConfirmationMarkup: function() {
    if(this.shouldToggleWithTableRow()) {
      if(!$(this.confirmRowId())) {
        var tdCount = this.confirmContainerElement.childElements().size();
        this.confirmContainerElement.insert({after: "<tr id='" + this.confirmRowId() + "'><td class='confirmation' colspan='" + tdCount + "'>" + this.confirmationMarkup + "</td></tr>"});
      }
    } else {
      this.confirmContainerElement.insert({bottom: this.confirmationMarkup});
    }
  },

  registerCancelOnClickObserver: function() {
    $(this.cancelLinkId).observe('click', this.handleCancelOnClick.bind(this));
  },

  handleCancelOnClick: function() {
    if(this.shouldToggleWithTableRow()) {
      $(this.confirmRowId()).hide();
      $(this.confirmContainerElement.show());
    }
    $(this.confirmId).hide();
    this.toggleConfirmContainerChildren();
  },

  showConfirmationMarkup: function() {
    if(this.shouldToggleWithTableRow()) {
      $(this.confirmRowId()).show();
      $(this.confirmContainerElement.hide());
    }
    $(this.confirmId).show();
    this.toggleConfirmContainerChildren();
  },

  toggleConfirmContainerChildren: function() {
    this.confirmContainerElement.childElements().reject(function(c) {
      return c.hasClassName("confirmation");
    }.bind(this)).invoke('toggle');
  },

  shouldToggleWithTableRow: function() {
    return "TR" == this.confirmContainerElement.tagName;
  },

  confirmRowId: function() {
    return this.elementId + "_confirm_row";
  }

});

Object.extend(InlineConfirmation, {
  Options: {
    promptText:                "Are you sure?",
    method:                    "post",
    confirmApproveText:        "Yes",
    confirmCancelText:         "No",
    confirmLoadingSpinner:     true,
    confirmApproveLoadingText: "Updating...",
    linkToAjax:                false,
    linkToFunction:            false
  }
});





/****************************************************************/
/*  original filename modal_dialog.js                        */
/****************************************************************/


// Pops up a nice modal dialog box.
// bh - this clas seems pretty punchless now, but I imagine we will add to it over time.

var ModalDialog = Class.create({
  initialize: function(text) {
    this.text = text;
    this.start();
  },

  start: function() {
    ModalDialog.stop();
    ModalDialog.activeDialog = new Lightbox(this.buildDialogMarkup(), {allowEsc: false});
  },

  buildDialogMarkup: function() {
    return  "<div class='small_box'>" +
              "<p>" + this.text + "</p>" +
            "</div>";
  }

});

Object.extend(ModalDialog, {

  activeDialog: false,

  stop: function() {
    if(ModalDialog.activeDialog != false) {
      ModalDialog.activeDialog.deactivate();
      ModalDialog.activeDialog = false;
    }
  }

});






/****************************************************************/
/*  original filename hover_observer.js                        */
/****************************************************************/


// Our HoverObserver is designed to show controls, typically on a UL or table row,
// when the user hovers over the entry. Naturally, there is a required markup format
// to work with this observer:
//
//   Give the hover target, which will trigger the display of controls, the class
//   name of the targetClass for the observer.
//
// The markup for the "nugget", or displayed control, should be something like:
//
//   <div class="hover_nugget" style="display:none;">
//     <div class="nugget_container">
//       <%= link_to("PDF", "link") -%>
//     </div>
//   </div>

// NOTE: Default instance options are listed at the button of this file.

var HoverObserver = Class.create({
  initialize: function(options) {
    this.options = Object.extend(Object.clone(HoverObserver.Options), options || {});
    this.start();
  },

  start: function() {
    $$('.' + this.options.targetClass).each(function(control) {
      this.observeControl(control);
    }.bind(this));
  },

  onMouseover: function(event) {
    var element = event.element();
    $$('.' + this.options.nuggetClass).invoke('hide');
    this.getRootElement(element).down('.' + this.options.nuggetClass).show();
  },

  onMouseout: function(event) {
    var element = event.element();
    this.getRootElement(element).down('.' + this.options.nuggetClass).hide();
  },

  getRootElement: function(element) {
    if(element.hasClassName(this.options.targetClass))
      return element;

    return element.up('.' + this.options.targetClass);
  },

  observeControl: function(control) {
    control.observe('mouseover', this.onMouseover.bind(this));
    control.observe('mouseout', this.onMouseout.bind(this));
  }

});

Object.extend(HoverObserver, {
  Options: {
    targetClass: "hover_item",
    nuggetClass: "hover_nugget"
  }
});


/****************************************************************/
/*  original filename auto_expand_text_area.js                        */
/****************************************************************/


// AutoExpandTextArea will create observers to expand textareas on any text area with
// the class "expand". This happens automatically as the text reaches the bottom of
// the textarea.
//
// To use on a given page, provide the proper class to the textarea, then declare the
// following on page load:
//
//   new AutoExpandTextArea();
//

// NOTE: Default instance options and class methods are listed at the button of this file.

var AutoExpandTextArea = Class.create({
  initialize: function(options) {
    this.options = Object.extend(Object.clone(AutoExpandTextArea.Options), options || {});
    this.original_style_height = {};
    this.observedControls = this.observedControls || $H({});
    this.start();
  },

  start: function() {
    var class_selector = this.options.allTextAreas ? '' : '.' + this.options.targetClass;
    $$('textarea' + class_selector).each(function(control) {
      if(!control.id.blank() && !control.style.height.blank())
        this.original_style_height[control.id] = control.style.height;
      this.observeControl(control);
    }.bind(this));
  },
  
  // Stopping requires the target controls have DOM ID's.
  stop: function() {
    $$('textarea' + this.classSelector()).each(function(control) {
      control.stopObserving('keyup', this.observedControls.get(control.id));
    }.bind(this));
  },
  
  classSelector: function() {
    return class_selector = this.options.allTextAreas ? '' : '.' + this.options.targetClass;
  },

  observeControl: function(control) {
    control.setStyle({overflow: 'hidden'});  // Hides scrollbars from view.
    this.observedControls.set(control.id, this.handleTextAreaKeyup.bind(this));
    control.observe('keyup', this.observedControls.get(control.id));
    AutoExpandTextArea.updateSize(control);
  },

  handleTextAreaKeyup: function(event) {
    AutoExpandTextArea.updateSize(event.element());
  },

  revertSize: function(id) {
    if($(id)){
      var new_height = this.original_style_height[id] ? this.original_style_height[id] : "";
      $(id).setStyle({height: new_height});
    }
  },
  
  refreshObservers: function() {
    this.stop();
    this.start();
  }

});

Object.extend(AutoExpandTextArea, {
  Options: {
    targetClass: "expand",
    allTextAreas: false
  }
});

Object.extend(AutoExpandTextArea, {
  // If scrollbars "appear," make the text area bigger. Don't increase size if bigger than the user's
  // browser area.
  updateSize: function(element) {
    if((element.getHeight() < element.scrollHeight) && (element.getHeight() < document.viewport.getHeight())) {
      element.style.height = element.getHeight() + 25 + 'px';
      AutoExpandTextArea.updateSize(element); // Recurse until size is big enough to handle any pastes
    }
  }
});


/****************************************************************/
/*  original filename character_limit_observer.js                        */
/****************************************************************/


var CharacterLimitObserver = Class.create({
  initialize: function(targetClass, characterLimit) {
    this.targetClass    = targetClass;
    this.characterLimit = characterLimit;
    this.start();
  },

  start: function() {
    $$('.' + this.targetClass).each(function(control) {
      this.observeControl(control);
    }.bind(this));
  },

  onKeyup: function(event) {
    var element = event.element();

    // bh - undefined check is for IE. Not sure why it is happening.
    if("undefined" == typeof(element.value) || element.value.length <= this.characterLimit)  return;

    element.value = element.value.substring(0, this.characterLimit);
    this.warn(element);
    this.boundWarningFadeHandler = this.warningFadeHandler.bind(this);
    element.observe('blur', this.boundWarningFadeHandler);
  },

  warn: function(element) {
    var warningElement = element.adjacent('.message_inline')[0];
    if("undefined" == typeof(warningElement)) {
      this._insertWarning(element);
      this.warn(element);
      return;
    }
    warningElement.show();
    Effect.ScrollTo(warningElement.id, {duration: 1.5, offset: -150});
  },

  _insertWarning: function(element) {
    var id      = (new Date()).getTime();
    var warning = "<div id='" + id + "' class='message_inline png-alpha'>Sorry, but you may only enter " + this.characterLimit + " characters.</div>"
    element.insert({after: warning});
  },

  warningFadeHandler: function(event) {
    var element = event.element();
    var warningElement = element.adjacent('.message_inline')[0];

    warningElement.fade({duration: 2.0});
    element.stopObserving('blur', this.boundWarningFadeHandler);
  },

  observeControl: function(control) {
    control.observe('keyup', this.onKeyup.bind(this));
  }

});




/****************************************************************/
/*  original filename tracker.js                        */
/****************************************************************/


var tracker = {
  register_hit: function(click){
    // new Ajax.Request('/hits/', {
    // 		       asynchronous:true,
    // 		       parameters: {
    // 			 name: window._source_name,
    // 			 click: click
    // 		       }});
  }
};
/****************************************************************/
/*  original filename default_field_values.js                        */
/****************************************************************/


// DefaultFieldValues can be loaded on any page with input elements that make use of
// the harvest default value attribute name in their attribute list. This class will
// handle adding and removing "blank" classes on the element, as well as setting the
// element's value to the default value as appropriate.

var DefaultFieldValues = Class.create({
  initialize: function(options) {
    this.attributeName = DefaultFieldValues.attributeName;
    this.options       = Object.extend(Object.clone(DefaultFieldValues.Options), options || {});
    this.start();
  },

  start: function() {
    $$('input[type="text"][' + this.attributeName + ']', 'textarea[' + this.attributeName + ']').each(function(element) {
      if(element.readAttribute(this.attributeName)) {
        this.observeControl(element);
      }
    }.bind(this));
  },

  observeControl: function(control) {
    control = $(control);
    control.observe('blur', this.handleBlur.bind(this));
    if(this.options.hideDefaultOnKeypress) {
      this.addInlineLabelFor(control);
      control = $(control.id);  // Need to reload control after updating the DOM
      control.observe('keyup', this.handleKeyup.bind(this));
    } else {
      control.observe('focus', this.handleFocus.bind(this));
    }
    this.blurred(control);
  },

  handleBlur: function(event) {
    this.blurred(event.element());
  },

  blurred: function(element) {
    if('' == element.value) {
      this.options.hideDefaultOnKeypress ? this.blurredWhenKeypressHiding(element) : this.blurredWhenFocusHiding(element);
    }
  },

  // Hmm...I think this path forking should be handled by a pattern construct. Oh, well! (BH)
  blurredWhenKeypressHiding: function(element) {
    this.labelElementFor(element).show();
  },

  blurredWhenFocusHiding: function(element) {
    element.value = element.readAttribute(this.attributeName);
    element.addClassName('blank');
  },

  handleFocus: function(event) {
    var element = event.element();
    if(element.readAttribute(this.attributeName) == element.value) {
      element.value = '';
    }
    element.removeClassName('blank');
  },

  handleKeyup: function(event) {
    var element = event.element();
    var label_element = this.labelElementFor(element);
    if('' == element.value) {
      label_element.show();
    } else {
      label_element.hide();
    }
  },

  labelElementFor: function(element) {
    return element.previous('label[for=' + element.id + ']');
  },

  addInlineLabelFor: function(element) {
    element.replace("<span class='overlay_wrapper'>" +
                      "<label for='" + element.id + "' id='" + element.id + "_label' class='inlabel' style='display:none;'>" + element.readAttribute(this.attributeName) + "</label>" +
                      element.getHtml() +
                    "</span");
  }

});

Object.extend(DefaultFieldValues, {
  attributeName: "harvestDefaultValue",

  getDefaultFor: function(el) {
    return $(el).readAttribute(DefaultFieldValues.attributeName);
  },

  Options: {
    hideDefaultOnKeypress: false  // Otherwise hides on focus
  }
});





/****************************************************************/
/*  original filename ie_fix.js                        */
/****************************************************************/


Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;

var IEDropdown = Class.create({
    initialize: function(element) {
        this.element = $(element);
        this.originalWidth = this.element.style.width;
        this.dontWiden = false;
        Event.observe(this.element, 'mousedown', this.widen.bindAsEventListener(this));
        Event.observe(this.element, 'blur', this.shrink.bindAsEventListener(this));
        Event.observe(this.element, 'change', this.shrink.bindAsEventListener(this));
    },


    widen: function(e) {
        if(this.dontWiden) return;
        var styledWidth = this.element.offsetWidth;
        this.element.style.width = 'auto';
        var desiredWidth = this.element.offsetWidth;
        // If this control needs less than it was styled for, then we don't need to bother with widening it.
        if(desiredWidth < styledWidth) {
           this.dontWiden = true;
           this.element.style.width = this.originalWidth;
           this.element.click(); // Simulate another click, since setting styles has already caused the box to close at this point.
        }
    },

    shrink: function(e) {
        this.element.style.width = this.originalWidth;
    }
});


/****************************************************************/
/*  original filename lightbox.js                        */
/****************************************************************/


/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
*/

/*
 *  Modified by Biro Eszter (eszter@primalgrasp.com): allow programatic loading
 *  of lightbox with a specific content, sparring an extra request. Useful
 *  when triggering from an already ajaxed action.
 *
 *  Consult repo history for differences before merging an upstream version.
 */
// updated by Dee Zsombor to conform to latest prototype conventions, removed dead code etc.

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

var Lightbox = Class.create({

  yPos : 0,
  xPos : 0,

  initialize: function(with_text, options) {
    this.options = Object.extend(Object.clone(Lightbox.Options), options || {});
    this.activate(with_text);
  },

  // Turn everything on - mainly the IE fixes
  activate: function(with_text){
    if (Prototype.Browser.IE){
      this.getScroll();
      this.prepareIE('100%', 'hidden');
      this.setScroll(0,0);
      this.hideSelects('hidden');
    }
    this.registerObservers();
    this.displayLightbox("block", with_text);
  },

  // Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
  prepareIE: function(height, overflow){
    var body = $$('body')[0];
    body.style.height = height;
    body.style.overflow = overflow;

    var html = $$('html')[0];
    html.style.height = height;
    html.style.overflow = overflow;
  },

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

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

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

  registerObservers: function() {
    if(this.options.allowEsc) {
      document.observe('keydown', this.handleKeydown.bindAsEventListener(this));
    }
  },

  handleKeydown: function(event) {
    var event = event || window.event;
    if('27' == event.keyCode) {
      // Do not override ESC behavior for SELECT boxes
            var element;
      if(event.target)  element = event.target;
      else if(event.srcElement)  element = event.srcElement;
            if(element.nodeType==3)  element=element.parentNode;
            if(element.tagName == 'SELECT')  return;

      this.deactivate();
    }
  },

  stopObservers: function() {
    document.stopObserving('keydown');
  },

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

  // Begin Ajax request based off of the href of the clicked linked
  loadInfo: function(with_text) {
    if(with_text.type == "click"){
      var myAjax = new Ajax.Request(
          this.content,
          {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
        );
    } else {
      this.displayText(with_text);
    }
  },

  // Display a text
  displayText: function(text){
    var info = "<div id='lbContent'>" + text + "</div>";
    new Insertion.Before($('lbLoadMessage'), info);
    $('lightbox').className = "done";
    this.actions();
  },

  processInfo: function(response){
    this.displayText(response.responseText);
  },

  // Search through new links within the lightbox, and attach click event
  actions: function(){
    var lbActions = $$('.lbAction');
    for(var i = 0; i < lbActions.length; i++) {
      $(lbActions[i]).observe('click', this[lbActions[i].rel].bindAsEventListener(this));
      lbActions[i].onclick = function(){return false;};
    }
  },

  // Example of creating your own functionality once lightbox is initiated
  insert: function(e){
    var link = Event.element(e).parentNode;
    $('lbContent').remove();
    var myAjax = new Ajax.Request(
       link.href,
       {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
    );
  },

  // Example of creating your own functionality once lightbox is initiated
  deactivate: function(){
    $('lbContent').remove();
    if (Prototype.Browser.IE){
      this.setScroll(0,this.yPos);
      this.prepareIE("auto", "auto");
      this.hideSelects("visible");
    }
    this.stopObservers();
    this.displayLightbox("none", true);
  }
});

Object.extend(Lightbox, {
  Options: {
    allowEsc: true
  }
});

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


document.observe('dom:loaded',function() {
  // Add in markup necessary to make this work. Basically two divs:
  // Overlay holds the shadow
  // Lightbox is the centered square that the content is put into.
  var body = $$('body')[0];
  var overlay = document.createElement('div');
  overlay.id = 'overlay';
  var lb = document.createElement('div');
  lb.id = 'lightbox';
  lb.className  = 'loading';
  lb.innerHTML  = '<div id="lbLoadMessage" style="display:none;text-align:center;padding-top:60px;">' +
//              '<img src="/images/lightbox-loading.gif" />' +
             '</div>';
  body.appendChild(overlay);
  body.appendChild(lb);
  //zs: removed all hooks for lbon class on purpuse
}, false);





/****************************************************************/
/*  original filename link_to.js                        */
/****************************************************************/


// To emulate a put/delete request from a link, a la rails link_to.  
// Nice to have this somewhere central so we don't have to repeat it for every row of projects, tasks, etc.
// See application_helper's link_to_compact method.  -DRF
function link_to_js(element, method) {
 var f = document.createElement('form'); 
 f.style.display = 'none'; 
 element.parentNode.appendChild(f); 
 f.method = 'POST'; 
 f.action = element.href;
 var m = document.createElement('input'); 
 m.setAttribute('type', 'hidden'); 
 m.setAttribute('name', '_method'); 
 m.setAttribute('value', method); 
 f.appendChild(m);
 var s = document.createElement('input'); 
 s.setAttribute('type', 'hidden'); 
 s.setAttribute('name', 'authenticity_token'); 
 s.setAttribute('value', window._token); 
 f.appendChild(s);
 f.submit();
 return false;
}

/****************************************************************/
/*  original filename custom_file_input.js                        */
/****************************************************************/


var CustomFileInput = Class.create( {

  // This input control uses two different approaches to achieve the same
  // effect in both IE and non-IE browsers:

  //   non-IE: The file input is displayed transparently, above an anchor tag.
  //           Users clicking the anchor automatically trigger the file input selction
  //           dialog because they are actually clicking on the invisible file input
  //           box.  This technique is described in detail here:
  //           http://www.quirksmode.org/dom/inputfile.html

  //   IE:     The same technique does not quite work in IE.  Plus, there is a
  //           security limitation in IE where using the "click()" function on file
  //           inputs will prevent the file from being uploaded. So we have to show the
  //           real file selector in that case.

  initialize: function(id, opts) {
    this.options = { link : "Choose file", displayLength : 17, inputWidth : '140' };
    Object.extend(this.options, opts || { });
        this.container = $(id);
        this.fileInput = this.container.down('input.file');
        // Important!  If it is too wide, then the overlay technique won't
        // catch clicks and they will be sent to the anchor underneath.
        if(!Prototype.Browser.IE) {
          this.fileInput.setStyle({ width: this.options.inputWidth + 'px' }); 
        }

        // 1. Build the extra HTML
        this.display   = new Element('span', { 'id' : id + '_file-name' });
        this.link      = new Element('a', { 'href' : '#', 'style' : 'text-decoration: underline' }).update(this.options.link);
        this.clearLink = new Element('a', { 'href' : '#', 'class' : 'delete-link' }).update('<img src="/images/icon-remove.gif">');
        this.overlayContainer = new Element('div', {'class' : 'overlay-container' });
        this.wrapper = new Element('div', {'class' : 'custom-file-input-wrapper', 'id' : id + '_wrapper' });
        
        Element.insert(this.container, { bottom : this.overlayContainer });
        if( Prototype.Browser.IE ) {
          this.IECancelLink = new Element('a', { 'href' : '#', 'class' : 'delete-link' }).update('<img src="/images/icon-remove.gif">');
          Element.insert(this.overlayContainer, { before : this.link });
          Element.insert(this.fileInput,        { after : this.IECancelLink });
        } else {
          Element.insert(this.overlayContainer, { bottom : this.link });
        }

        Element.wrap(this.container, this.wrapper);
        Element.insert(this.wrapper, { top : this.display });
        Element.insert(this.display, { after : this.clearLink });
    
        // 2. Update the display with the current selection
        if(this.options.initialValue != null && this.options.initialValue.length > 0) {
          this.updateDisplay( this.options.initialValue );
          this.link.update(this.options.changeLink);
        } else {
          this.clearLink.hide();
        }

        // 3. Set up observers
        if( Prototype.Browser.IE ) {
          this.fileInput.hide();
          this.IECancelLink.hide();
          Event.observe(this.link, "click", this.selectFileIE.bindAsEventListener(this));
          Event.observe(this.IECancelLink, "click", this.revertToInitial.bindAsEventListener(this));
        } else {
          Event.observe(this.fileInput, "change", this.onSelect.bindAsEventListener(this));
        }
        Event.observe(this.clearLink, "click", this.clearSelection.bindAsEventListener(this));

        // 4. Add this to our hash of custom inputs for easy access by ID
        CustomFileInput.setInputFor(id, this);
  },

  onSelect: function() {
   if(Prototype.Browser.IE) { return; } // IE just uses a regular file input
   if(this.fileInput.value != null) {
     this.updateDisplay( this.fileInput.value );
     if(this.fileInput.value.length > 0) {
       this.link.update(this.options.changeLink);
       this.clearLink.show();
       if(this.options.showChangeLink == false) {
         this.link.hide();
         this.fileInput.hide();
       }
       if(this.options.selectCallback) {
          this.options.selectCallback();
       }
     }
   }
  },

  selectFileIE: function(e) {
    [ this.display, this.clearLink, this.link ].invoke('hide');
    [ this.IECancelLink, this.fileInput ].invoke('show');
  },

  updateDisplay: function(txt) {
    if(txt == null) {
     this.display.innerHTML = "";
    } else {
     this.display.innerHTML = txt.truncate(this.options.displayLength); 
    }
  },

  revertToInitial: function() {
     this.clearSelection(); // If they had already selection something, we want to get rid of that now.
     this.updateDisplay( this.options.initialValue );
     if(this.options.initialValue != null && this.options.initialValue.length > 0) {
       this.link.update(this.options.changeLink);
       this.clearLink.show();
     }

     if(Prototype.Browser.IE) {
       [this.fileInput, this.IECancelLink].invoke('hide');
       [this.link, this.display].invoke('show');
     }

     if(this.options.revertCallback) {
        this.options.revertCallback();
     }
  },

  clearSelection: function() {
      var name = this.fileInput.getAttribute('name');
      // Replace the old fileInput since there's no way to "unset" file inputs via JS.
      var newInput = new Element('input', { 'name' : name, 'class' : 'file', 'type' : 'file' });
      if(!Prototype.Browser.IE) {
        newInput.setStyle({ width: this.options.inputWidth + 'px' }); 
      }
      Element.replace(this.fileInput, newInput);
      this.fileInput = newInput;

      this.display.update('');
      this.link.update(this.options.link);

      this.clearLink.hide();

      if(this.options.showChangeLink == false) {
         this.link.show();
         this.fileInput.show();
      }

      if( Prototype.Browser.IE) { 
          [this.fileInput, this.IECancelLink].invoke('hide');
          [this.link].invoke('show');
      } else {
        Event.observe(this.fileInput, "change", this.onSelect.bindAsEventListener(this));
      }

      if(this.options.clearCallback) {
        this.options.clearCallback();
      }

  },

  clearAfterValidation: function() {
    this.clearSelection();
    if(Prototype.Browser.IE) {
      [this.fileInput, this.IECancelLink].invoke('show');
      [this.link].invoke('hide');
    }
  }

});

Object.extend(CustomFileInput , {
  inputsHash: { },

  getInputFor: function(id) {
    return CustomFileInput.inputsHash[id]; 
  },

  setInputFor:function(id, inputObject) {
    CustomFileInput.inputsHash[id] = inputObject;
  }

});


/****************************************************************/
/*  original filename n8/n8_date_picker_formatter.js                        */
/****************************************************************/


// This is a custom date formatter that attempts to delegate most parsing and
// formatting to the datejs lib.  This is intended to be a safe way to relax
// the accepted formats in N8 transactions without impacting the rest of the
// date code in Harvest
var N8DatePickerFormatter = Class.create();

N8DatePickerFormatter.prototype = {

    initialize: function(acceptedFormats, displayFormat, yearOptional) {

      // This picker is separator-agnostic, but our date class in date.js
      // expects it to define a separator anyway.

      this.separator = "/";
      this.acceptedFormats = acceptedFormats;
      this.displayFormat   = displayFormat;
      this.yearOptional    = yearOptional;
      if(this.yearOptional) {
       this.displayFormatWithoutYear = this.displayFormat.gsub(/[\.\-\/\ ]?yyyy[\.\-\/\ ]?/, '');
      }
    },

    /**
     * Match a string against date format.
     * Returns: [year, month, day] or false if there's no match
     */
    match: function(str) {
      str = str.strip();
      var d = Date.parseExact(str, this.acceptedFormats);
      if(d){
        return [d.getFullYear() + "", d.getMonth() + 1 + "", d.getDate() + ""];
      } else {
        return false;
      }
    },

    allows_month_names: function() {
      return true;
    },

    to_string: function(d) {
      if(this.yearOptional && d.getFullYear() == Date.today().getFullYear()) {
        return d.toString(this.displayFormatWithoutYear);
      } else {
        return d.toString(this.displayFormat);
      }
    },

    reformat: function(str) {
      var d = Date.parseExact(str, this.acceptedFormats);
      if(d) {
        return this.to_string(d);
      } else {
        return str;
      }
    },
    /**
     * Return current date according to format.
     */
    current_date: function() {
      return this.to_string(Date.today());
    },

    /**
     * Return a stringified date accordint to format.
     */
    date_to_string: function(year, month, day, separator) {
        var d = new Date(year, month - 1, day);
        return this.to_string(d);
    }
};


