
    /**
     * Ha a jobb felsõ sarokba kattintunk, lenyílik a teteje az oldalnak, hírdetést jelenítve meg.
     * 
     * @param event
     * @param element
     */
    function BannerTopDropDownToggle(event,element)
    {
        jQuery(".banner_top_dropdown").slideToggle('slow');
    }
/*  Prototype JavaScript framework, version 1.6.0.3
 *  (c) 2005-2008 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://www.prototypejs.org/
 *
 *--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.6.0.3',

  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: !!window.HTMLElement,
    SpecificElementExtensions:
      document.createElement('div')['__proto__'] &&
      document.createElement('div')['__proto__'] !==
        document.createElement('form')['__proto__']
  },

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

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

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


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

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

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

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

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

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

    klass.prototype.constructor = klass;

    return klass;
  }
};

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

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

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && Object.isFunction(value) &&
          value.argumentNames().first() == "$super") {
        var method = value;
        value = (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;
  }
};

var Abstract = { };

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

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

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

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

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

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

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

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

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

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

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

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

  isArray: function(object) {
    return object != null && typeof object == "object" &&
      'splice' in object && 'join' in object;
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return returnValue;
  }
};

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

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

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

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

    this.registerCallback();
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return camelized;
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

var $break = { };

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

  eachSlice: function(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);
  },

  all: function(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;
  },

  any: function(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;
  },

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

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

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

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

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

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

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

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

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

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

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

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

  min: function(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;
  },

  partition: function(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];
  },

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

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

  sortBy: function(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');
  },

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

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

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

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

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

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

if (Prototype.Browser.WebKit) {
  $A = function(iterable) {
    if (!iterable) return [];
    // In Safari, only use the `toArray` method if it's not a NodeList.
    // A NodeList is a function, has an function `item` property, and a numeric
    // `length` property. Adapted from Google Doctype.
    if (!(typeof iterable === 'function' && typeof iterable.length ===
        'number' && typeof iterable.item === 'function') && iterable.toArray)
      return iterable.toArray();
    var length = iterable.length || 0, results = new Array(length);
    while (length--) results[length] = iterable[length];
    return results;
  };
}

Array.from = $A;

Object.extend(Array.prototype, Enumerable);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    get: function(key) {
      // simulating poorly supported hasOwnProperty
      if (this._object[key] !== Object.prototype[key])
        return this._object[key];
    },

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

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

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

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

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

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

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

    toQueryString: function() {
      return this.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('&');
    },

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

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

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

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

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

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

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

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

  activeRequestCount: 0
};

Ajax.Responders = {
  responders: [],

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

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

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

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

Object.extend(Ajax.Responders, Enumerable);

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

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

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

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

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

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

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

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

    this.parameters = params;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      var contentType = response.getHeader('Content-type');
      if (this.options.evalJS == 'force'
          || (this.options.evalJS && 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') {
      // avoid memory leak in MSIE: clean up
      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) {
  // DOM level 2 ECMAScript Language Binding
  Object.extend(Node, {
    ELEMENT_NODE: 1,
    ATTRIBUTE_NODE: 2,
    TEXT_NODE: 3,
    CDATA_SECTION_NODE: 4,
    ENTITY_REFERENCE_NODE: 5,
    ENTITY_NODE: 6,
    PROCESSING_INSTRUCTION_NODE: 7,
    COMMENT_NODE: 8,
    DOCUMENT_NODE: 9,
    DOCUMENT_TYPE_NODE: 10,
    DOCUMENT_FRAGMENT_NODE: 11,
    NOTATION_NODE: 12
  });
}

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

Element.cache = { };

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

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

  hide: function(element) {
    element = $(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(element, content) {
    element = $(element);
    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) return element.update().insert(content);
    content = Object.toHTML(content);
    element.innerHTML = content.stripScripts();
    content.evalScripts.bind(content).defer();
    return element;
  },

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

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

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

    var content, insert, tagName, childNodes;

    for (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("*");
  },

  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'), self = arguments.callee;
    if (id) return id;
    do { id = 'anonymous_element_' + self.counter++ } while ($(id));
    element.writeAttribute('id', id);
    return id;
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (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;
    // Position.prepare(); // To be done manually by Scripty when it needs it.

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

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

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

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

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

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

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

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

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

    return $(document.body);
  },

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

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

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

    } while (element = element.offsetParent);

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

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

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

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

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

Element.Methods.identify.counter = 1;

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

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

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

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

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

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

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

else if (Prototype.Browser.IE) {
  // IE doesn't report offsets correctly for static elements, so we change them
  // to "relative" to get the values, then change them back.
  Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
    function(proceed, element) {
      element = $(element);
      // IE throws an error if element is not in document
      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);
        // Trigger hasLayout on the offset parent so that IE6 reports
        // accurate offsetTop and offsetLeft values for position: fixed.
        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 = {
    read: {
      names: {
        'class': 'className',
        'for':   'htmlFor'
      },
      values: {
        _getAttr: function(element, attribute) {
          return element.getAttribute(attribute, 2);
        },
        _getAttrNode: function(element, attribute) {
          var node = element.getAttributeNode(attribute);
          return node ? node.value : "";
        },
        _getEv: function(element, attribute) {
          attribute = element.getAttribute(attribute);
          return attribute ? attribute.toString().slice(23, -2) : null;
        },
        _flag: function(element, attribute) {
          return $(element).hasAttribute(attribute) ? attribute : null;
        },
        style: function(element) {
          return element.style.cssText.toLowerCase();
        },
        title: function(element) {
          return element.title;
        }
      }
    }
  };

  Element._attributeTranslations.write = {
    names: Object.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);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Element.Methods.ByTag = { };

Object.extend(Element, Element.Methods);

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

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

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

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

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

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

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

    element._extendedByPrototype = Prototype.emptyFunction;
    return element;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

document.viewport = {
  getDimensions: function() {
    var dimensions = { }, B = Prototype.Browser;
    $w('width height').each(function(d) {
      var D = d.capitalize();
      if (B.WebKit && !document.evaluate) {
        // Safari <3.0 needs self.innerWidth/Height
        dimensions[d] = self['inner' + D];
      } else if (B.Opera && parseFloat(window.opera.version()) < 9.5) {
        // Opera <9.5 needs document.body.clientWidth/Height
        dimensions[d] = document.body['client' + D]
      } else {
        dimensions[d] = document.documentElement['client' + D];
      }
    });
    return dimensions;
  },

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

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

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

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

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

  },

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

    var e = this.expression;

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

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

    return true;
  },

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

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

    // Make sure the browser treats the selector as valid. Test on an
    // isolated element to minimize cost of this check.
    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;

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

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

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

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

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

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

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

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

  findElements: function(root) {
    root = root || document;
    var e = this.expression, results;

    switch (this.mode) {
      case 'selectorsAPI':
        // querySelectorAll queries document-wide, then filters to descendants
        // of the context element. That's not what we want.
        // Add an explicit context to the selector if necessary.
        if (root !== document) {
          var oldId = root.id, id = $(root).identify();
          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;

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

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

    return match;
  },

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

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

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

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

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

  criteria: {
    tagName:      'n = h.tagName(n, r, "#{1}", c);      c = false;',
    className:    'n = h.className(n, r, "#{1}", c);    c = false;',
    id:           'n = h.id(n, r, "#{1}", c);           c = false;',
    attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); 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: {
    // combinators must be listed first
    // (and descendant needs to be last combinator)
    laterSibling: /^\s*~\s*/,
    child:        /^\s*>\s*/,
    adjacent:     /^\s*\+\s*/,
    descendant:   /^\s/,

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

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

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

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

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

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

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

    // marks an array of nodes for counting
    mark: function(nodes) {
      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;
    },

    // mark each child node with its position (for nth calls)
    // "ofType" flag indicates whether we're indexing for nth-of-type
    // rather than nth-child
    index: function(parentNode, reverse, ofType) {
      parentNode._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++;
      }
    },

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

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

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

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

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

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

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

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

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

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

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

    attrPresence: function(nodes, root, attr, 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);
    },

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

    // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
    nth: function(nodes, formula, root, reverse, ofType) {
      if (nodes.length == 0) return [];
      if (formula == 'even') formula = '2n+0';
      if (formula == 'odd')  formula = '2n+1';
      var h = Selector.handlers, results = [], indexed = [], m;
      h.mark(nodes);
      for (var i = 0, node; node = nodes[i]; i++) {
        if (!node.parentNode._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++) {
        // IE treats comments as element nodes
        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.endsWith(v); },
    '*=': function(nv, v) { return nv.include(v); },
    '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
    '|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() +
     '-').include('-' + (v || "").toUpperCase() + '-'); }
  },

  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, {
    // IE returns comment nodes on getElementsByTagName("*").
    // Filter them out.
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        if (node.tagName !== "!") a.push(node);
      return a;
    },

    // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
    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).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) {
            // a key is already present; construct an array of values
            if (!Object.isArray(result[key])) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

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

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

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

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

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

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

    return matchingInputs;
  },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  disable: function(element) {
    element = $(element);
    element.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) {
    // extend element because hasAttribute may not be native
    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  cache: { },

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

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

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

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

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

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

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

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

      if (currentTarget && currentTarget.tagName) {
        // Firefox screws up the "click" event when moving between radio buttons
        // via arrow keys. It also screws up the "load" and "error" events on images,
        // reporting the document as the target instead of the original image.
        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);
    },

    findElement: function(event, expression) {
      var element = Event.element(event);
      if (!expression) return element;
      var elements = [element].concat(element.ancestors());
      return Selector.findElement(elements, expression, 0);
    },
    
    pointer: function(event) {
      var docElement = document.documentElement,
      body = document.body || { scrollLeft: 0, scrollTop: 0 };
      return {
        x: event.pageX || (event.clientX +
          (docElement.scrollLeft || body.scrollLeft) -
          (docElement.clientLeft || 0)),
        y: event.pageY || (event.clientY +
          (docElement.scrollTop || body.scrollTop) -
          (docElement.clientTop || 0)) 
      };
    },

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

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

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

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

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

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

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

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

  function getEventID(element) {
    if (element._prototypeEventID) return element._prototypeEventID[0];
    arguments.callee.id = arguments.callee.id || 1;
    return element._prototypeEventID = [++arguments.callee.id];
  }

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

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

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

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

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

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

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

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

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

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


  // Internet Explorer needs to remove event handlers on page unload
  // in order to avoid memory leaks.
  if (window.attachEvent) {
    window.attachEvent("onunload", destroyCache);
  }

  // Safari has a dummy event handler on page unload so that it won't
  // use its bfcache. Safari <= 3.1 has an issue with restoring the "document"
  // object when page is returned to via the back button using its bfcache.
  if (Prototype.Browser.WebKit) {
    window.addEventListener('unload', Prototype.emptyFunction, false);
  }

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

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

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

      return element;
    },

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

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

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

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

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

      destroyWrapper(id, eventName, handler);

      return element;
    },

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

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

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

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

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

Object.extend(Event, Event.Methods);

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

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

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

  var timer;

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

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

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

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

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

Hash.toQueryString = Object.toQueryString;

var Toggle = { display: Element.toggle };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  cumulativeOffset: Element.Methods.cumulativeOffset,

  positionedOffset: Element.Methods.positionedOffset,

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

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

  realOffset: Element.Methods.cumulativeScrollOffset,

  offsetParent: Element.Methods.getOffsetParent,

  page: Element.Methods.viewportOffset,

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Element.addMethods();/*!
 * jQuery JavaScript Library v1.3.1
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-01-21 20:42:16 -0500 (Wed, 21 Jan 2009)
 * Revision: 6158
 */
(function(){

var 
    // Will speed up references to window, and allows munging its name.
    window = this,
    // Will speed up references to undefined, and allows munging its name.
    undefined,
    // Map over jQuery in case of overwrite
    _jQuery = window.jQuery,
    // Map over the $ in case of overwrite
    _$ = window.$,

    jQuery = window.jQuery = window.$ = function( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context );
    },

    // A simple way to check for HTML strings or ID strings
    // (both of which we optimize for)
    quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
    // Is it a simple selector
    isSimple = /^.[^:#\[\.,]*$/;

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {
        // Make sure that a selection was provided
        selector = selector || document;

        // Handle $(DOMElement)
        if ( selector.nodeType ) {
            this[0] = selector;
            this.length = 1;
            this.context = selector;
            return this;
        }
        // Handle HTML strings
        if ( typeof selector === "string" ) {
            // Are we dealing with HTML string or an ID?
            var match = quickExpr.exec( selector );

            // Verify a match, and that no context was specified for #id
            if ( match && (match[1] || !context) ) {

                // HANDLE: $(html) -> $(array)
                if ( match[1] )
                    selector = jQuery.clean( [ match[1] ], context );

                // HANDLE: $("#id")
                else {
                    var elem = document.getElementById( match[3] );

                    // Handle the case where IE and Opera return items
                    // by name instead of ID
                    if ( elem && elem.id != match[3] )
                        return jQuery().find( selector );

                    // Otherwise, we inject the element directly into the jQuery object
                    var ret = jQuery( elem || [] );
                    ret.context = document;
                    ret.selector = selector;
                    return ret;
                }

            // HANDLE: $(expr, [context])
            // (which is just equivalent to: $(content).find(expr)
            } else
                return jQuery( context ).find( selector );

        // HANDLE: $(function)
        // Shortcut for document ready
        } else if ( jQuery.isFunction( selector ) )
            return jQuery( document ).ready( selector );

        // Make sure that old selector state is passed along
        if ( selector.selector && selector.context ) {
            this.selector = selector.selector;
            this.context = selector.context;
        }

        return this.setArray(jQuery.makeArray(selector));
    },

    // Start with an empty selector
    selector: "",

    // The current version of jQuery being used
    jquery: "1.3.1",

    // The number of elements contained in the matched element set
    size: function() {
        return this.length;
    },

    // Get the Nth element in the matched element set OR
    // Get the whole matched element set as a clean array
    get: function( num ) {
        return num === undefined ?

            // Return a 'clean' array
            jQuery.makeArray( this ) :

            // Return just the object
            this[ num ];
    },

    // Take an array of elements and push it onto the stack
    // (returning the new matched element set)
    pushStack: function( elems, name, selector ) {
        // Build a new jQuery matched element set
        var ret = jQuery( elems );

        // Add the old object onto the stack (as a reference)
        ret.prevObject = this;

        ret.context = this.context;

        if ( name === "find" )
            ret.selector = this.selector + (this.selector ? " " : "") + selector;
        else if ( name )
            ret.selector = this.selector + "." + name + "(" + selector + ")";

        // Return the newly-formed element set
        return ret;
    },

    // Force the current matched set of elements to become
    // the specified array of elements (destroying the stack in the process)
    // You should use pushStack() in order to do this, but maintain the stack
    setArray: function( elems ) {
        // Resetting the length to 0, then using the native Array push
        // is a super-fast way to populate an object with array-like properties
        this.length = 0;
        Array.prototype.push.apply( this, elems );

        return this;
    },

    // Execute a callback for every element in the matched set.
    // (You can seed the arguments with an array of args, but this is
    // only used internally.)
    each: function( callback, args ) {
        return jQuery.each( this, callback, args );
    },

    // Determine the position of an element within
    // the matched set of elements
    index: function( elem ) {
        // Locate the position of the desired element
        return jQuery.inArray(
            // If it receives a jQuery object, the first element is used
            elem && elem.jquery ? elem[0] : elem
        , this );
    },

    attr: function( name, value, type ) {
        var options = name;

        // Look for the case where we're accessing a style value
        if ( typeof name === "string" )
            if ( value === undefined )
                return this[0] && jQuery[ type || "attr" ]( this[0], name );

            else {
                options = {};
                options[ name ] = value;
            }

        // Check to see if we're setting style values
        return this.each(function(i){
            // Set all the styles
            for ( name in options )
                jQuery.attr(
                    type ?
                        this.style :
                        this,
                    name, jQuery.prop( this, options[ name ], type, i, name )
                );
        });
    },

    css: function( key, value ) {
        // ignore negative width and height values
        if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
            value = undefined;
        return this.attr( key, value, "curCSS" );
    },

    text: function( text ) {
        if ( typeof text !== "object" && text != null )
            return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );

        var ret = "";

        jQuery.each( text || this, function(){
            jQuery.each( this.childNodes, function(){
                if ( this.nodeType != 8 )
                    ret += this.nodeType != 1 ?
                        this.nodeValue :
                        jQuery.fn.text( [ this ] );
            });
        });

        return ret;
    },

    wrapAll: function( html ) {
        if ( this[0] ) {
            // The elements to wrap the target around
            var wrap = jQuery( html, this[0].ownerDocument ).clone();

            if ( this[0].parentNode )
                wrap.insertBefore( this[0] );

            wrap.map(function(){
                var elem = this;

                while ( elem.firstChild )
                    elem = elem.firstChild;

                return elem;
            }).append(this);
        }

        return this;
    },

    wrapInner: function( html ) {
        return this.each(function(){
            jQuery( this ).contents().wrapAll( html );
        });
    },

    wrap: function( html ) {
        return this.each(function(){
            jQuery( this ).wrapAll( html );
        });
    },

    append: function() {
        return this.domManip(arguments, true, function(elem){
            if (this.nodeType == 1)
                this.appendChild( elem );
        });
    },

    prepend: function() {
        return this.domManip(arguments, true, function(elem){
            if (this.nodeType == 1)
                this.insertBefore( elem, this.firstChild );
        });
    },

    before: function() {
        return this.domManip(arguments, false, function(elem){
            this.parentNode.insertBefore( elem, this );
        });
    },

    after: function() {
        return this.domManip(arguments, false, function(elem){
            this.parentNode.insertBefore( elem, this.nextSibling );
        });
    },

    end: function() {
        return this.prevObject || jQuery( [] );
    },

    // For internal use only.
    // Behaves like an Array's .push method, not like a jQuery method.
    push: [].push,

    find: function( selector ) {
        if ( this.length === 1 && !/,/.test(selector) ) {
            var ret = this.pushStack( [], "find", selector );
            ret.length = 0;
            jQuery.find( selector, this[0], ret );
            return ret;
        } else {
            var elems = jQuery.map(this, function(elem){
                return jQuery.find( selector, elem );
            });

            return this.pushStack( /[^+>] [^+>]/.test( selector ) ?
                jQuery.unique( elems ) :
                elems, "find", selector );
        }
    },

    clone: function( events ) {
        // Do the clone
        var ret = this.map(function(){
            if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
                // IE copies events bound via attachEvent when
                // using cloneNode. Calling detachEvent on the
                // clone will also remove the events from the orignal
                // In order to get around this, we use innerHTML.
                // Unfortunately, this means some modifications to
                // attributes in IE that are actually only stored
                // as properties will not be copied (such as the
                // the name attribute on an input).
                var clone = this.cloneNode(true),
                    container = document.createElement("div");
                container.appendChild(clone);
                return jQuery.clean([container.innerHTML])[0];
            } else
                return this.cloneNode(true);
        });

        // Need to set the expando to null on the cloned set if it exists
        // removeData doesn't work here, IE removes it from the original as well
        // this is primarily for IE but the data expando shouldn't be copied over in any browser
        var clone = ret.find("*").andSelf().each(function(){
            if ( this[ expando ] !== undefined )
                this[ expando ] = null;
        });

        // Copy the events from the original to the clone
        if ( events === true )
            this.find("*").andSelf().each(function(i){
                if (this.nodeType == 3)
                    return;
                var events = jQuery.data( this, "events" );

                for ( var type in events )
                    for ( var handler in events[ type ] )
                        jQuery.event.add( clone[ i ], type, events[ type ][ handler ], events[ type ][ handler ].data );
            });

        // Return the cloned set
        return ret;
    },

    filter: function( selector ) {
        return this.pushStack(
            jQuery.isFunction( selector ) &&
            jQuery.grep(this, function(elem, i){
                return selector.call( elem, i );
            }) ||

            jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
                return elem.nodeType === 1;
            }) ), "filter", selector );
    },

    closest: function( selector ) {
        var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null;

        return this.map(function(){
            var cur = this;
            while ( cur && cur.ownerDocument ) {
                if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) )
                    return cur;
                cur = cur.parentNode;
            }
        });
    },

    not: function( selector ) {
        if ( typeof selector === "string" )
            // test special case where just one selector is passed in
            if ( isSimple.test( selector ) )
                return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
            else
                selector = jQuery.multiFilter( selector, this );

        var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
        return this.filter(function() {
            return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
        });
    },

    add: function( selector ) {
        return this.pushStack( jQuery.unique( jQuery.merge(
            this.get(),
            typeof selector === "string" ?
                jQuery( selector ) :
                jQuery.makeArray( selector )
        )));
    },

    is: function( selector ) {
        return !!selector && jQuery.multiFilter( selector, this ).length > 0;
    },

    hasClass: function( selector ) {
        return !!selector && this.is( "." + selector );
    },

    val: function( value ) {
        if ( value === undefined ) {            
            var elem = this[0];

            if ( elem ) {
                if( jQuery.nodeName( elem, 'option' ) )
                    return (elem.attributes.value || {}).specified ? elem.value : elem.text;
                
                // We need to handle select boxes special
                if ( jQuery.nodeName( elem, "select" ) ) {
                    var index = elem.selectedIndex,
                        values = [],
                        options = elem.options,
                        one = elem.type == "select-one";

                    // Nothing was selected
                    if ( index < 0 )
                        return null;

                    // Loop through all the selected options
                    for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
                        var option = options[ i ];

                        if ( option.selected ) {
                            // Get the specifc value for the option
                            value = jQuery(option).val();

                            // We don't need an array for one selects
                            if ( one )
                                return value;

                            // Multi-Selects return an array
                            values.push( value );
                        }
                    }

                    return values;              
                }

                // Everything else, we just grab the value
                return (elem.value || "").replace(/\r/g, "");

            }

            return undefined;
        }

        if ( typeof value === "number" )
            value += '';

        return this.each(function(){
            if ( this.nodeType != 1 )
                return;

            if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
                this.checked = (jQuery.inArray(this.value, value) >= 0 ||
                    jQuery.inArray(this.name, value) >= 0);

            else if ( jQuery.nodeName( this, "select" ) ) {
                var values = jQuery.makeArray(value);

                jQuery( "option", this ).each(function(){
                    this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
                        jQuery.inArray( this.text, values ) >= 0);
                });

                if ( !values.length )
                    this.selectedIndex = -1;

            } else
                this.value = value;
        });
    },

    html: function( value ) {
        return value === undefined ?
            (this[0] ?
                this[0].innerHTML :
                null) :
            this.empty().append( value );
    },

    replaceWith: function( value ) {
        return this.after( value ).remove();
    },

    eq: function( i ) {
        return this.slice( i, +i + 1 );
    },

    slice: function() {
        return this.pushStack( Array.prototype.slice.apply( this, arguments ),
            "slice", Array.prototype.slice.call(arguments).join(",") );
    },

    map: function( callback ) {
        return this.pushStack( jQuery.map(this, function(elem, i){
            return callback.call( elem, i, elem );
        }));
    },

    andSelf: function() {
        return this.add( this.prevObject );
    },

    domManip: function( args, table, callback ) {
        if ( this[0] ) {
            var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
                scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
                first = fragment.firstChild,
                extra = this.length > 1 ? fragment.cloneNode(true) : fragment;

            if ( first )
                for ( var i = 0, l = this.length; i < l; i++ )
                    callback.call( root(this[i], first), i > 0 ? extra.cloneNode(true) : fragment );
            
            if ( scripts )
                jQuery.each( scripts, evalScript );
        }

        return this;
        
        function root( elem, cur ) {
            return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
                (elem.getElementsByTagName("tbody")[0] ||
                elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
                elem;
        }
    }
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

function evalScript( i, elem ) {
    if ( elem.src )
        jQuery.ajax({
            url: elem.src,
            async: false,
            dataType: "script"
        });

    else
        jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );

    if ( elem.parentNode )
        elem.parentNode.removeChild( elem );
}

function now(){
    return +new Date;
}

jQuery.extend = jQuery.fn.extend = function() {
    // copy reference to target object
    var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;
        target = arguments[1] || {};
        // skip the boolean and the target
        i = 2;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction(target) )
        target = {};

    // extend jQuery itself if only one argument is passed
    if ( length == i ) {
        target = this;
        --i;
    }

    for ( ; i < length; i++ )
        // Only deal with non-null/undefined values
        if ( (options = arguments[ i ]) != null )
            // Extend the base object
            for ( var name in options ) {
                var src = target[ name ], copy = options[ name ];

                // Prevent never-ending loop
                if ( target === copy )
                    continue;

                // Recurse if we're merging object values
                if ( deep && copy && typeof copy === "object" && !copy.nodeType )
                    target[ name ] = jQuery.extend( deep, 
                        // Never move original objects, clone them
                        src || ( copy.length != null ? [ ] : { } )
                    , copy );

                // Don't bring in undefined values
                else if ( copy !== undefined )
                    target[ name ] = copy;

            }

    // Return the modified object
    return target;
};

// exclude the following css properties to add px
var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
    // cache defaultView
    defaultView = document.defaultView || {},
    toString = Object.prototype.toString;

jQuery.extend({
    noConflict: function( deep ) {
        window.$ = _$;

        if ( deep )
            window.jQuery = _jQuery;

        return jQuery;
    },

    // See test/unit/core.js for details concerning isFunction.
    // Since version 1.3, DOM methods and functions like alert
    // aren't supported. They return false on IE (#2968).
    isFunction: function( obj ) {
        return toString.call(obj) === "[object Function]";
    },

    isArray: function( obj ) {
        return toString.call(obj) === "[object Array]";
    },

    // check if an element is in a (or is an) XML document
    isXMLDoc: function( elem ) {
        return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
            !!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
    },

    // Evalulates a script in a global context
    globalEval: function( data ) {
        data = jQuery.trim( data );

        if ( data ) {
            // Inspired by code by Andrea Giammarchi
            // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
            var head = document.getElementsByTagName("head")[0] || document.documentElement,
                script = document.createElement("script");

            script.type = "text/javascript";
            if ( jQuery.support.scriptEval )
                script.appendChild( document.createTextNode( data ) );
            else
                script.text = data;

            // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
            // This arises when a base node is used (#2709).
            head.insertBefore( script, head.firstChild );
            head.removeChild( script );
        }
    },

    nodeName: function( elem, name ) {
        return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
    },

    // args is for internal usage only
    each: function( object, callback, args ) {
        var name, i = 0, length = object.length;

        if ( args ) {
            if ( length === undefined ) {
                for ( name in object )
                    if ( callback.apply( object[ name ], args ) === false )
                        break;
            } else
                for ( ; i < length; )
                    if ( callback.apply( object[ i++ ], args ) === false )
                        break;

        // A special, fast, case for the most common use of each
        } else {
            if ( length === undefined ) {
                for ( name in object )
                    if ( callback.call( object[ name ], name, object[ name ] ) === false )
                        break;
            } else
                for ( var value = object[0];
                    i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
        }

        return object;
    },

    prop: function( elem, value, type, i, name ) {
        // Handle executable functions
        if ( jQuery.isFunction( value ) )
            value = value.call( elem, i );

        // Handle passing in a number to a CSS property
        return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
            value + "px" :
            value;
    },

    className: {
        // internal only, use addClass("class")
        add: function( elem, classNames ) {
            jQuery.each((classNames || "").split(/\s+/), function(i, className){
                if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
                    elem.className += (elem.className ? " " : "") + className;
            });
        },

        // internal only, use removeClass("class")
        remove: function( elem, classNames ) {
            if (elem.nodeType == 1)
                elem.className = classNames !== undefined ?
                    jQuery.grep(elem.className.split(/\s+/), function(className){
                        return !jQuery.className.has( classNames, className );
                    }).join(" ") :
                    "";
        },

        // internal only, use hasClass("class")
        has: function( elem, className ) {
            return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
        }
    },

    // A method for quickly swapping in/out CSS properties to get correct calculations
    swap: function( elem, options, callback ) {
        var old = {};
        // Remember the old values, and insert the new ones
        for ( var name in options ) {
            old[ name ] = elem.style[ name ];
            elem.style[ name ] = options[ name ];
        }

        callback.call( elem );

        // Revert the old values
        for ( var name in options )
            elem.style[ name ] = old[ name ];
    },

    css: function( elem, name, force ) {
        if ( name == "width" || name == "height" ) {
            var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];

            function getWH() {
                val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
                var padding = 0, border = 0;
                jQuery.each( which, function() {
                    padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
                    border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
                });
                val -= Math.round(padding + border);
            }

            if ( jQuery(elem).is(":visible") )
                getWH();
            else
                jQuery.swap( elem, props, getWH );

            return Math.max(0, val);
        }

        return jQuery.curCSS( elem, name, force );
    },

    curCSS: function( elem, name, force ) {
        var ret, style = elem.style;

        // We need to handle opacity special in IE
        if ( name == "opacity" && !jQuery.support.opacity ) {
            ret = jQuery.attr( style, "opacity" );

            return ret == "" ?
                "1" :
                ret;
        }

        // Make sure we're using the right name for getting the float value
        if ( name.match( /float/i ) )
            name = styleFloat;

        if ( !force && style && style[ name ] )
            ret = style[ name ];

        else if ( defaultView.getComputedStyle ) {

            // Only "float" is needed here
            if ( name.match( /float/i ) )
                name = "float";

            name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();

            var computedStyle = defaultView.getComputedStyle( elem, null );

            if ( computedStyle )
                ret = computedStyle.getPropertyValue( name );

            // We should always get a number back from opacity
            if ( name == "opacity" && ret == "" )
                ret = "1";

        } else if ( elem.currentStyle ) {
            var camelCase = name.replace(/\-(\w)/g, function(all, letter){
                return letter.toUpperCase();
            });

            ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];

            // From the awesome hack by Dean Edwards
            // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

            // If we're not dealing with a regular pixel number
            // but a number that has a weird ending, we need to convert it to pixels
            if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
                // Remember the original values
                var left = style.left, rsLeft = elem.runtimeStyle.left;

                // Put in the new values to get a computed value out
                elem.runtimeStyle.left = elem.currentStyle.left;
                style.left = ret || 0;
                ret = style.pixelLeft + "px";

                // Revert the changed values
                style.left = left;
                elem.runtimeStyle.left = rsLeft;
            }
        }

        return ret;
    },

    clean: function( elems, context, fragment ) {
        context = context || document;

        // !context.createElement fails in IE with an error but returns typeof 'object'
        if ( typeof context.createElement === "undefined" )
            context = context.ownerDocument || context[0] && context[0].ownerDocument || document;

        // If a single string is passed in and it's a single tag
        // just do a createElement and skip the rest
        if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
            var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
            if ( match )
                return [ context.createElement( match[1] ) ];
        }

        var ret = [], scripts = [], div = context.createElement("div");

        jQuery.each(elems, function(i, elem){
            if ( typeof elem === "number" )
                elem += '';

            if ( !elem )
                return;

            // Convert html string into DOM nodes
            if ( typeof elem === "string" ) {
                // Fix "XHTML"-style tags in all browsers
                elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
                    return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
                        all :
                        front + "></" + tag + ">";
                });

                // Trim whitespace, otherwise indexOf won't work as expected
                var tags = jQuery.trim( elem ).toLowerCase();

                var wrap =
                    // option or optgroup
                    !tags.indexOf("<opt") &&
                    [ 1, "<select multiple='multiple'>", "</select>" ] ||

                    !tags.indexOf("<leg") &&
                    [ 1, "<fieldset>", "</fieldset>" ] ||

                    tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
                    [ 1, "<table>", "</table>" ] ||

                    !tags.indexOf("<tr") &&
                    [ 2, "<table><tbody>", "</tbody></table>" ] ||

                    // <thead> matched above
                    (!tags.indexOf("<td") || !tags.indexOf("<th")) &&
                    [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||

                    !tags.indexOf("<col") &&
                    [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||

                    // IE can't serialize <link> and <script> tags normally
                    !jQuery.support.htmlSerialize &&
                    [ 1, "div<div>", "</div>" ] ||

                    [ 0, "", "" ];

                // Go to html and back, then peel off extra wrappers
                div.innerHTML = wrap[1] + elem + wrap[2];

                // Move to the right depth
                while ( wrap[0]-- )
                    div = div.lastChild;

                // Remove IE's autoinserted <tbody> from table fragments
                if ( !jQuery.support.tbody ) {

                    // String was a <table>, *may* have spurious <tbody>
                    var tbody = !tags.indexOf("<table") && tags.indexOf("<tbody") < 0 ?
                        div.firstChild && div.firstChild.childNodes :

                        // String was a bare <thead> or <tfoot>
                        wrap[1] == "<table>" && tags.indexOf("<tbody") < 0 ?
                            div.childNodes :
                            [];

                    for ( var j = tbody.length - 1; j >= 0 ; --j )
                        if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
                            tbody[ j ].parentNode.removeChild( tbody[ j ] );

                    }

                // IE completely kills leading whitespace when innerHTML is used
                if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
                    div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
                
                elem = jQuery.makeArray( div.childNodes );
            }

            if ( elem.nodeType )
                ret.push( elem );
            else
                ret = jQuery.merge( ret, elem );

        });

        if ( fragment ) {
            for ( var i = 0; ret[i]; i++ ) {
                if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
                    scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
                } else {
                    if ( ret[i].nodeType === 1 )
                        ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
                    fragment.appendChild( ret[i] );
                }
            }
            
            return scripts;
        }

        return ret;
    },

    attr: function( elem, name, value ) {
        // don't set attributes on text and comment nodes
        if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
            return undefined;

        var notxml = !jQuery.isXMLDoc( elem ),
            // Whether we are setting (or getting)
            set = value !== undefined;

        // Try to normalize/fix the name
        name = notxml && jQuery.props[ name ] || name;

        // Only do all the following if this is a node (faster for style)
        // IE elem.getAttribute passes even for style
        if ( elem.tagName ) {

            // These attributes require special treatment
            var special = /href|src|style/.test( name );

            // Safari mis-reports the default selected property of a hidden option
            // Accessing the parent's selectedIndex property fixes it
            if ( name == "selected" && elem.parentNode )
                elem.parentNode.selectedIndex;

            // If applicable, access the attribute via the DOM 0 way
            if ( name in elem && notxml && !special ) {
                if ( set ){
                    // We can't allow the type property to be changed (since it causes problems in IE)
                    if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
                        throw "type property can't be changed";

                    elem[ name ] = value;
                }

                // browsers index elements by id/name on forms, give priority to attributes.
                if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
                    return elem.getAttributeNode( name ).nodeValue;

                // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
                // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
                if ( name == "tabIndex" ) {
                    var attributeNode = elem.getAttributeNode( "tabIndex" );
                    return attributeNode && attributeNode.specified
                        ? attributeNode.value
                        : elem.nodeName.match(/(button|input|object|select|textarea)/i)
                            ? 0
                            : elem.nodeName.match(/^(a|area)$/i) && elem.href
                                ? 0
                                : undefined;
                }

                return elem[ name ];
            }

            if ( !jQuery.support.style && notxml &&  name == "style" )
                return jQuery.attr( elem.style, "cssText", value );

            if ( set )
                // convert the value to a string (all browsers do this but IE) see #1070
                elem.setAttribute( name, "" + value );

            var attr = !jQuery.support.hrefNormalized && notxml && special
                    // Some attributes require a special call on IE
                    ? elem.getAttribute( name, 2 )
                    : elem.getAttribute( name );

            // Non-existent attributes return null, we normalize to undefined
            return attr === null ? undefined : attr;
        }

        // elem is actually elem.style ... set the style

        // IE uses filters for opacity
        if ( !jQuery.support.opacity && name == "opacity" ) {
            if ( set ) {
                // IE has trouble with opacity if it does not have layout
                // Force it by setting the zoom level
                elem.zoom = 1;

                // Set the alpha filter to set the opacity
                elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
                    (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
            }

            return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
                (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
                "";
        }

        name = name.replace(/-([a-z])/ig, function(all, letter){
            return letter.toUpperCase();
        });

        if ( set )
            elem[ name ] = value;

        return elem[ name ];
    },

    trim: function( text ) {
        return (text || "").replace( /^\s+|\s+$/g, "" );
    },

    makeArray: function( array ) {
        var ret = [];

        if( array != null ){
            var i = array.length;
            // The window, strings (and functions) also have 'length'
            if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
                ret[0] = array;
            else
                while( i )
                    ret[--i] = array[i];
        }

        return ret;
    },

    inArray: function( elem, array ) {
        for ( var i = 0, length = array.length; i < length; i++ )
        // Use === because on IE, window == document
            if ( array[ i ] === elem )
                return i;

        return -1;
    },

    merge: function( first, second ) {
        // We have to loop this way because IE & Opera overwrite the length
        // expando of getElementsByTagName
        var i = 0, elem, pos = first.length;
        // Also, we need to make sure that the correct elements are being returned
        // (IE returns comment nodes in a '*' query)
        if ( !jQuery.support.getAll ) {
            while ( (elem = second[ i++ ]) != null )
                if ( elem.nodeType != 8 )
                    first[ pos++ ] = elem;

        } else
            while ( (elem = second[ i++ ]) != null )
                first[ pos++ ] = elem;

        return first;
    },

    unique: function( array ) {
        var ret = [], done = {};

        try {

            for ( var i = 0, length = array.length; i < length; i++ ) {
                var id = jQuery.data( array[ i ] );

                if ( !done[ id ] ) {
                    done[ id ] = true;
                    ret.push( array[ i ] );
                }
            }

        } catch( e ) {
            ret = array;
        }

        return ret;
    },

    grep: function( elems, callback, inv ) {
        var ret = [];

        // Go through the array, only saving the items
        // that pass the validator function
        for ( var i = 0, length = elems.length; i < length; i++ )
            if ( !inv != !callback( elems[ i ], i ) )
                ret.push( elems[ i ] );

        return ret;
    },

    map: function( elems, callback ) {
        var ret = [];

        // Go through the array, translating each of the items to their
        // new value (or values).
        for ( var i = 0, length = elems.length; i < length; i++ ) {
            var value = callback( elems[ i ], i );

            if ( value != null )
                ret[ ret.length ] = value;
        }

        return ret.concat.apply( [], ret );
    }
});

// Use of jQuery.browser is deprecated.
// It's included for backwards compatibility and plugins,
// although they should work to migrate away.

var userAgent = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
jQuery.browser = {
    version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
    safari: /webkit/.test( userAgent ),
    opera: /opera/.test( userAgent ),
    msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
    mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

jQuery.each({
    parent: function(elem){return elem.parentNode;},
    parents: function(elem){return jQuery.dir(elem,"parentNode");},
    next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
    prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
    nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
    prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
    siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
    children: function(elem){return jQuery.sibling(elem.firstChild);},
    contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
}, function(name, fn){
    jQuery.fn[ name ] = function( selector ) {
        var ret = jQuery.map( this, fn );

        if ( selector && typeof selector == "string" )
            ret = jQuery.multiFilter( selector, ret );

        return this.pushStack( jQuery.unique( ret ), name, selector );
    };
});

jQuery.each({
    appendTo: "append",
    prependTo: "prepend",
    insertBefore: "before",
    insertAfter: "after",
    replaceAll: "replaceWith"
}, function(name, original){
    jQuery.fn[ name ] = function() {
        var args = arguments;

        return this.each(function(){
            for ( var i = 0, length = args.length; i < length; i++ )
                jQuery( args[ i ] )[ original ]( this );
        });
    };
});

jQuery.each({
    removeAttr: function( name ) {
        jQuery.attr( this, name, "" );
        if (this.nodeType == 1)
            this.removeAttribute( name );
    },

    addClass: function( classNames ) {
        jQuery.className.add( this, classNames );
    },

    removeClass: function( classNames ) {
        jQuery.className.remove( this, classNames );
    },

    toggleClass: function( classNames, state ) {
        if( typeof state !== "boolean" )
            state = !jQuery.className.has( this, classNames );
        jQuery.className[ state ? "add" : "remove" ]( this, classNames );
    },

    remove: function( selector ) {
        if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
            // Prevent memory leaks
            jQuery( "*", this ).add([this]).each(function(){
                jQuery.event.remove(this);
                jQuery.removeData(this);
            });
            if (this.parentNode)
                this.parentNode.removeChild( this );
        }
    },

    empty: function() {
        // Remove element nodes and prevent memory leaks
        jQuery( ">*", this ).remove();

        // Remove any remaining nodes
        while ( this.firstChild )
            this.removeChild( this.firstChild );
    }
}, function(name, fn){
    jQuery.fn[ name ] = function(){
        return this.each( fn, arguments );
    };
});

// Helper function used by the dimensions and offset modules
function num(elem, prop) {
    return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
}
var expando = "jQuery" + now(), uuid = 0, windowData = {};

jQuery.extend({
    cache: {},

    data: function( elem, name, data ) {
        elem = elem == window ?
            windowData :
            elem;

        var id = elem[ expando ];

        // Compute a unique ID for the element
        if ( !id )
            id = elem[ expando ] = ++uuid;

        // Only generate the data cache if we're
        // trying to access or manipulate it
        if ( name && !jQuery.cache[ id ] )
            jQuery.cache[ id ] = {};

        // Prevent overriding the named cache with undefined values
        if ( data !== undefined )
            jQuery.cache[ id ][ name ] = data;

        // Return the named cache data, or the ID for the element
        return name ?
            jQuery.cache[ id ][ name ] :
            id;
    },

    removeData: function( elem, name ) {
        elem = elem == window ?
            windowData :
            elem;

        var id = elem[ expando ];

        // If we want to remove a specific section of the element's data
        if ( name ) {
            if ( jQuery.cache[ id ] ) {
                // Remove the section of cache data
                delete jQuery.cache[ id ][ name ];

                // If we've removed all the data, remove the element's cache
                name = "";

                for ( name in jQuery.cache[ id ] )
                    break;

                if ( !name )
                    jQuery.removeData( elem );
            }

        // Otherwise, we want to remove all of the element's data
        } else {
            // Clean up the element expando
            try {
                delete elem[ expando ];
            } catch(e){
                // IE has trouble directly removing the expando
                // but it's ok with using removeAttribute
                if ( elem.removeAttribute )
                    elem.removeAttribute( expando );
            }

            // Completely remove the data cache
            delete jQuery.cache[ id ];
        }
    },
    queue: function( elem, type, data ) {
        if ( elem ){
    
            type = (type || "fx") + "queue";
    
            var q = jQuery.data( elem, type );
    
            if ( !q || jQuery.isArray(data) )
                q = jQuery.data( elem, type, jQuery.makeArray(data) );
            else if( data )
                q.push( data );
    
        }
        return q;
    },

    dequeue: function( elem, type ){
        var queue = jQuery.queue( elem, type ),
            fn = queue.shift();
        
        if( !type || type === "fx" )
            fn = queue[0];
            
        if( fn !== undefined )
            fn.call(elem);
    }
});

jQuery.fn.extend({
    data: function( key, value ){
        var parts = key.split(".");
        parts[1] = parts[1] ? "." + parts[1] : "";

        if ( value === undefined ) {
            var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);

            if ( data === undefined && this.length )
                data = jQuery.data( this[0], key );

            return data === undefined && parts[1] ?
                this.data( parts[0] ) :
                data;
        } else
            return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
                jQuery.data( this, key, value );
            });
    },

    removeData: function( key ){
        return this.each(function(){
            jQuery.removeData( this, key );
        });
    },
    queue: function(type, data){
        if ( typeof type !== "string" ) {
            data = type;
            type = "fx";
        }

        if ( data === undefined )
            return jQuery.queue( this[0], type );

        return this.each(function(){
            var queue = jQuery.queue( this, type, data );
            
             if( type == "fx" && queue.length == 1 )
                queue[0].call(this);
        });
    },
    dequeue: function(type){
        return this.each(function(){
            jQuery.dequeue( this, type );
        });
    }
});/*!
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){

var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]+['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[]+)+|[>+~])(\s*,\s*)?/g,
    done = 0,
    toString = Object.prototype.toString;

var Sizzle = function(selector, context, results, seed) {
    results = results || [];
    context = context || document;

    if ( context.nodeType !== 1 && context.nodeType !== 9 )
        return [];
    
    if ( !selector || typeof selector !== "string" ) {
        return results;
    }

    var parts = [], m, set, checkSet, check, mode, extra, prune = true;
    
    // Reset the position of the chunker regexp (start from head)
    chunker.lastIndex = 0;
    
    while ( (m = chunker.exec(selector)) !== null ) {
        parts.push( m[1] );
        
        if ( m[2] ) {
            extra = RegExp.rightContext;
            break;
        }
    }

    if ( parts.length > 1 && origPOS.exec( selector ) ) {
        if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
            set = posProcess( parts[0] + parts[1], context );
        } else {
            set = Expr.relative[ parts[0] ] ?
                [ context ] :
                Sizzle( parts.shift(), context );

            while ( parts.length ) {
                selector = parts.shift();

                if ( Expr.relative[ selector ] )
                    selector += parts.shift();

                set = posProcess( selector, set );
            }
        }
    } else {
        var ret = seed ?
            { expr: parts.pop(), set: makeArray(seed) } :
            Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) );
        set = Sizzle.filter( ret.expr, ret.set );

        if ( parts.length > 0 ) {
            checkSet = makeArray(set);
        } else {
            prune = false;
        }

        while ( parts.length ) {
            var cur = parts.pop(), pop = cur;

            if ( !Expr.relative[ cur ] ) {
                cur = "";
            } else {
                pop = parts.pop();
            }

            if ( pop == null ) {
                pop = context;
            }

            Expr.relative[ cur ]( checkSet, pop, isXML(context) );
        }
    }

    if ( !checkSet ) {
        checkSet = set;
    }

    if ( !checkSet ) {
        throw "Syntax error, unrecognized expression: " + (cur || selector);
    }

    if ( toString.call(checkSet) === "[object Array]" ) {
        if ( !prune ) {
            results.push.apply( results, checkSet );
        } else if ( context.nodeType === 1 ) {
            for ( var i = 0; checkSet[i] != null; i++ ) {
                if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
                    results.push( set[i] );
                }
            }
        } else {
            for ( var i = 0; checkSet[i] != null; i++ ) {
                if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
                    results.push( set[i] );
                }
            }
        }
    } else {
        makeArray( checkSet, results );
    }

    if ( extra ) {
        Sizzle( extra, context, results, seed );
    }

    return results;
};

Sizzle.matches = function(expr, set){
    return Sizzle(expr, null, null, set);
};

Sizzle.find = function(expr, context, isXML){
    var set, match;

    if ( !expr ) {
        return [];
    }

    for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
        var type = Expr.order[i], match;
        
        if ( (match = Expr.match[ type ].exec( expr )) ) {
            var left = RegExp.leftContext;

            if ( left.substr( left.length - 1 ) !== "\\" ) {
                match[1] = (match[1] || "").replace(/\\/g, "");
                set = Expr.find[ type ]( match, context, isXML );
                if ( set != null ) {
                    expr = expr.replace( Expr.match[ type ], "" );
                    break;
                }
            }
        }
    }

    if ( !set ) {
        set = context.getElementsByTagName("*");
    }

    return {set: set, expr: expr};
};

Sizzle.filter = function(expr, set, inplace, not){
    var old = expr, result = [], curLoop = set, match, anyFound;

    while ( expr && set.length ) {
        for ( var type in Expr.filter ) {
            if ( (match = Expr.match[ type ].exec( expr )) != null ) {
                var filter = Expr.filter[ type ], found, item;
                anyFound = false;

                if ( curLoop == result ) {
                    result = [];
                }

                if ( Expr.preFilter[ type ] ) {
                    match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not );

                    if ( !match ) {
                        anyFound = found = true;
                    } else if ( match === true ) {
                        continue;
                    }
                }

                if ( match ) {
                    for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
                        if ( item ) {
                            found = filter( item, match, i, curLoop );
                            var pass = not ^ !!found;

                            if ( inplace && found != null ) {
                                if ( pass ) {
                                    anyFound = true;
                                } else {
                                    curLoop[i] = false;
                                }
                            } else if ( pass ) {
                                result.push( item );
                                anyFound = true;
                            }
                        }
                    }
                }

                if ( found !== undefined ) {
                    if ( !inplace ) {
                        curLoop = result;
                    }

                    expr = expr.replace( Expr.match[ type ], "" );

                    if ( !anyFound ) {
                        return [];
                    }

                    break;
                }
            }
        }

        expr = expr.replace(/\s*,\s*/, "");

        // Improper expression
        if ( expr == old ) {
            if ( anyFound == null ) {
                throw "Syntax error, unrecognized expression: " + expr;
            } else {
                break;
            }
        }

        old = expr;
    }

    return curLoop;
};

var Expr = Sizzle.selectors = {
    order: [ "ID", "NAME", "TAG" ],
    match: {
        ID: /#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
        CLASS: /\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
        NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,
        ATTR: /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
        TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,
        CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
        POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
        PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
    },
    attrMap: {
        "class": "className",
        "for": "htmlFor"
    },
    attrHandle: {
        href: function(elem){
            return elem.getAttribute("href");
        }
    },
    relative: {
        "+": function(checkSet, part){
            for ( var i = 0, l = checkSet.length; i < l; i++ ) {
                var elem = checkSet[i];
                if ( elem ) {
                    var cur = elem.previousSibling;
                    while ( cur && cur.nodeType !== 1 ) {
                        cur = cur.previousSibling;
                    }
                    checkSet[i] = typeof part === "string" ?
                        cur || false :
                        cur === part;
                }
            }

            if ( typeof part === "string" ) {
                Sizzle.filter( part, checkSet, true );
            }
        },
        ">": function(checkSet, part, isXML){
            if ( typeof part === "string" && !/\W/.test(part) ) {
                part = isXML ? part : part.toUpperCase();

                for ( var i = 0, l = checkSet.length; i < l; i++ ) {
                    var elem = checkSet[i];
                    if ( elem ) {
                        var parent = elem.parentNode;
                        checkSet[i] = parent.nodeName === part ? parent : false;
                    }
                }
            } else {
                for ( var i = 0, l = checkSet.length; i < l; i++ ) {
                    var elem = checkSet[i];
                    if ( elem ) {
                        checkSet[i] = typeof part === "string" ?
                            elem.parentNode :
                            elem.parentNode === part;
                    }
                }

                if ( typeof part === "string" ) {
                    Sizzle.filter( part, checkSet, true );
                }
            }
        },
        "": function(checkSet, part, isXML){
            var doneName = "done" + (done++), checkFn = dirCheck;

            if ( !part.match(/\W/) ) {
                var nodeCheck = part = isXML ? part : part.toUpperCase();
                checkFn = dirNodeCheck;
            }

            checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
        },
        "~": function(checkSet, part, isXML){
            var doneName = "done" + (done++), checkFn = dirCheck;

            if ( typeof part === "string" && !part.match(/\W/) ) {
                var nodeCheck = part = isXML ? part : part.toUpperCase();
                checkFn = dirNodeCheck;
            }

            checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
        }
    },
    find: {
        ID: function(match, context, isXML){
            if ( typeof context.getElementById !== "undefined" && !isXML ) {
                var m = context.getElementById(match[1]);
                return m ? [m] : [];
            }
        },
        NAME: function(match, context, isXML){
            if ( typeof context.getElementsByName !== "undefined" && !isXML ) {
                return context.getElementsByName(match[1]);
            }
        },
        TAG: function(match, context){
            return context.getElementsByTagName(match[1]);
        }
    },
    preFilter: {
        CLASS: function(match, curLoop, inplace, result, not){
            match = " " + match[1].replace(/\\/g, "") + " ";

            var elem;
            for ( var i = 0; (elem = curLoop[i]) != null; i++ ) {
                if ( elem ) {
                    if ( not ^ (" " + elem.className + " ").indexOf(match) >= 0 ) {
                        if ( !inplace )
                            result.push( elem );
                    } else if ( inplace ) {
                        curLoop[i] = false;
                    }
                }
            }

            return false;
        },
        ID: function(match){
            return match[1].replace(/\\/g, "");
        },
        TAG: function(match, curLoop){
            for ( var i = 0; curLoop[i] === false; i++ ){}
            return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
        },
        CHILD: function(match){
            if ( match[1] == "nth" ) {
                // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
                var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
                    match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
                    !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);

                // calculate the numbers (first)n+(last) including if they are negative
                match[2] = (test[1] + (test[2] || 1)) - 0;
                match[3] = test[3] - 0;
            }

            // TODO: Move to normal caching system
            match[0] = "done" + (done++);

            return match;
        },
        ATTR: function(match){
            var name = match[1].replace(/\\/g, "");
            
            if ( Expr.attrMap[name] ) {
                match[1] = Expr.attrMap[name];
            }

            if ( match[2] === "~=" ) {
                match[4] = " " + match[4] + " ";
            }

            return match;
        },
        PSEUDO: function(match, curLoop, inplace, result, not){
            if ( match[1] === "not" ) {
                // If we're dealing with a complex expression, or a simple one
                if ( match[3].match(chunker).length > 1 ) {
                    match[3] = Sizzle(match[3], null, null, curLoop);
                } else {
                    var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
                    if ( !inplace ) {
                        result.push.apply( result, ret );
                    }
                    return false;
                }
            } else if ( Expr.match.POS.test( match[0] ) ) {
                return true;
            }
            
            return match;
        },
        POS: function(match){
            match.unshift( true );
            return match;
        }
    },
    filters: {
        enabled: function(elem){
            return elem.disabled === false && elem.type !== "hidden";
        },
        disabled: function(elem){
            return elem.disabled === true;
        },
        checked: function(elem){
            return elem.checked === true;
        },
        selected: function(elem){
            // Accessing this property makes selected-by-default
            // options in Safari work properly
            elem.parentNode.selectedIndex;
            return elem.selected === true;
        },
        parent: function(elem){
            return !!elem.firstChild;
        },
        empty: function(elem){
            return !elem.firstChild;
        },
        has: function(elem, i, match){
            return !!Sizzle( match[3], elem ).length;
        },
        header: function(elem){
            return /h\d/i.test( elem.nodeName );
        },
        text: function(elem){
            return "text" === elem.type;
        },
        radio: function(elem){
            return "radio" === elem.type;
        },
        checkbox: function(elem){
            return "checkbox" === elem.type;
        },
        file: function(elem){
            return "file" === elem.type;
        },
        password: function(elem){
            return "password" === elem.type;
        },
        submit: function(elem){
            return "submit" === elem.type;
        },
        image: function(elem){
            return "image" === elem.type;
        },
        reset: function(elem){
            return "reset" === elem.type;
        },
        button: function(elem){
            return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
        },
        input: function(elem){
            return /input|select|textarea|button/i.test(elem.nodeName);
        }
    },
    setFilters: {
        first: function(elem, i){
            return i === 0;
        },
        last: function(elem, i, match, array){
            return i === array.length - 1;
        },
        even: function(elem, i){
            return i % 2 === 0;
        },
        odd: function(elem, i){
            return i % 2 === 1;
        },
        lt: function(elem, i, match){
            return i < match[3] - 0;
        },
        gt: function(elem, i, match){
            return i > match[3] - 0;
        },
        nth: function(elem, i, match){
            return match[3] - 0 == i;
        },
        eq: function(elem, i, match){
            return match[3] - 0 == i;
        }
    },
    filter: {
        CHILD: function(elem, match){
            var type = match[1], parent = elem.parentNode;

            var doneName = match[0];
            
            if ( parent && (!parent[ doneName ] || !elem.nodeIndex) ) {
                var count = 1;

                for ( var node = parent.firstChild; node; node = node.nextSibling ) {
                    if ( node.nodeType == 1 ) {
                        node.nodeIndex = count++;
                    }
                }

                parent[ doneName ] = count - 1;
            }

            if ( type == "first" ) {
                return elem.nodeIndex == 1;
            } else if ( type == "last" ) {
                return elem.nodeIndex == parent[ doneName ];
            } else if ( type == "only" ) {
                return parent[ doneName ] == 1;
            } else if ( type == "nth" ) {
                var add = false, first = match[2], last = match[3];

                if ( first == 1 && last == 0 ) {
                    return true;
                }

                if ( first == 0 ) {
                    if ( elem.nodeIndex == last ) {
                        add = true;
                    }
                } else if ( (elem.nodeIndex - last) % first == 0 && (elem.nodeIndex - last) / first >= 0 ) {
                    add = true;
                }

                return add;
            }
        },
        PSEUDO: function(elem, match, i, array){
            var name = match[1], filter = Expr.filters[ name ];

            if ( filter ) {
                return filter( elem, i, match, array );
            } else if ( name === "contains" ) {
                return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
            } else if ( name === "not" ) {
                var not = match[3];

                for ( var i = 0, l = not.length; i < l; i++ ) {
                    if ( not[i] === elem ) {
                        return false;
                    }
                }

                return true;
            }
        },
        ID: function(elem, match){
            return elem.nodeType === 1 && elem.getAttribute("id") === match;
        },
        TAG: function(elem, match){
            return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
        },
        CLASS: function(elem, match){
            return match.test( elem.className );
        },
        ATTR: function(elem, match){
            var result = Expr.attrHandle[ match[1] ] ? Expr.attrHandle[ match[1] ]( elem ) : elem[ match[1] ] || elem.getAttribute( match[1] ), value = result + "", type = match[2], check = match[4];
            return result == null ?
                type === "!=" :
                type === "=" ?
                value === check :
                type === "*=" ?
                value.indexOf(check) >= 0 :
                type === "~=" ?
                (" " + value + " ").indexOf(check) >= 0 :
                !match[4] ?
                result :
                type === "!=" ?
                value != check :
                type === "^=" ?
                value.indexOf(check) === 0 :
                type === "$=" ?
                value.substr(value.length - check.length) === check :
                type === "|=" ?
                value === check || value.substr(0, check.length + 1) === check + "-" :
                false;
        },
        POS: function(elem, match, i, array){
            var name = match[2], filter = Expr.setFilters[ name ];

            if ( filter ) {
                return filter( elem, i, match, array );
            }
        }
    }
};

var origPOS = Expr.match.POS;

for ( var type in Expr.match ) {
    Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
}

var makeArray = function(array, results) {
    array = Array.prototype.slice.call( array );

    if ( results ) {
        results.push.apply( results, array );
        return results;
    }
    
    return array;
};

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
try {
    Array.prototype.slice.call( document.documentElement.childNodes );

// Provide a fallback method if it does not work
} catch(e){
    makeArray = function(array, results) {
        var ret = results || [];

        if ( toString.call(array) === "[object Array]" ) {
            Array.prototype.push.apply( ret, array );
        } else {
            if ( typeof array.length === "number" ) {
                for ( var i = 0, l = array.length; i < l; i++ ) {
                    ret.push( array[i] );
                }
            } else {
                for ( var i = 0; array[i]; i++ ) {
                    ret.push( array[i] );
                }
            }
        }

        return ret;
    };
}

// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
    // We're going to inject a fake input element with a specified name
    var form = document.createElement("form"),
        id = "script" + (new Date).getTime();
    form.innerHTML = "<input name='" + id + "'/>";

    // Inject it into the root element, check its status, and remove it quickly
    var root = document.documentElement;
    root.insertBefore( form, root.firstChild );

    // The workaround has to do additional checks after a getElementById
    // Which slows things down for other browsers (hence the branching)
    if ( !!document.getElementById( id ) ) {
        Expr.find.ID = function(match, context, isXML){
            if ( typeof context.getElementById !== "undefined" && !isXML ) {
                var m = context.getElementById(match[1]);
                return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
            }
        };

        Expr.filter.ID = function(elem, match){
            var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
            return elem.nodeType === 1 && node && node.nodeValue === match;
        };
    }

    root.removeChild( form );
})();

(function(){
    // Check to see if the browser returns only elements
    // when doing getElementsByTagName("*")

    // Create a fake element
    var div = document.createElement("div");
    div.appendChild( document.createComment("") );

    // Make sure no comments are found
    if ( div.getElementsByTagName("*").length > 0 ) {
        Expr.find.TAG = function(match, context){
            var results = context.getElementsByTagName(match[1]);

            // Filter out possible comments
            if ( match[1] === "*" ) {
                var tmp = [];

                for ( var i = 0; results[i]; i++ ) {
                    if ( results[i].nodeType === 1 ) {
                        tmp.push( results[i] );
                    }
                }

                results = tmp;
            }

            return results;
        };
    }

    // Check to see if an attribute returns normalized href attributes
    div.innerHTML = "<a href='#'></a>";
    if ( div.firstChild && div.firstChild.getAttribute("href") !== "#" ) {
        Expr.attrHandle.href = function(elem){
            return elem.getAttribute("href", 2);
        };
    }
})();

if ( document.querySelectorAll ) (function(){
    var oldSizzle = Sizzle, div = document.createElement("div");
    div.innerHTML = "<p class='TEST'></p>";

    // Safari can't handle uppercase or unicode characters when
    // in quirks mode.
    if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
        return;
    }
    
    Sizzle = function(query, context, extra, seed){
        context = context || document;

        // Only use querySelectorAll on non-XML documents
        // (ID selectors don't work in non-HTML documents)
        if ( !seed && context.nodeType === 9 && !isXML(context) ) {
            try {
                return makeArray( context.querySelectorAll(query), extra );
            } catch(e){}
        }
        
        return oldSizzle(query, context, extra, seed);
    };

    Sizzle.find = oldSizzle.find;
    Sizzle.filter = oldSizzle.filter;
    Sizzle.selectors = oldSizzle.selectors;
    Sizzle.matches = oldSizzle.matches;
})();

if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) {
    Expr.order.splice(1, 0, "CLASS");
    Expr.find.CLASS = function(match, context) {
        return context.getElementsByClassName(match[1]);
    };
}

function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
    for ( var i = 0, l = checkSet.length; i < l; i++ ) {
        var elem = checkSet[i];
        if ( elem ) {
            elem = elem[dir];
            var match = false;

            while ( elem && elem.nodeType ) {
                var done = elem[doneName];
                if ( done ) {
                    match = checkSet[ done ];
                    break;
                }

                if ( elem.nodeType === 1 && !isXML )
                    elem[doneName] = i;

                if ( elem.nodeName === cur ) {
                    match = elem;
                    break;
                }

                elem = elem[dir];
            }

            checkSet[i] = match;
        }
    }
}

function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
    for ( var i = 0, l = checkSet.length; i < l; i++ ) {
        var elem = checkSet[i];
        if ( elem ) {
            elem = elem[dir];
            var match = false;

            while ( elem && elem.nodeType ) {
                if ( elem[doneName] ) {
                    match = checkSet[ elem[doneName] ];
                    break;
                }

                if ( elem.nodeType === 1 ) {
                    if ( !isXML )
                        elem[doneName] = i;

                    if ( typeof cur !== "string" ) {
                        if ( elem === cur ) {
                            match = true;
                            break;
                        }

                    } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
                        match = elem;
                        break;
                    }
                }

                elem = elem[dir];
            }

            checkSet[i] = match;
        }
    }
}

var contains = document.compareDocumentPosition ?  function(a, b){
    return a.compareDocumentPosition(b) & 16;
} : function(a, b){
    return a !== b && (a.contains ? a.contains(b) : true);
};

var isXML = function(elem){
    return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
        !!elem.ownerDocument && isXML( elem.ownerDocument );
};

var posProcess = function(selector, context){
    var tmpSet = [], later = "", match,
        root = context.nodeType ? [context] : context;

    // Position selectors must be done after the filter
    // And so must :not(positional) so we move all PSEUDOs to the end
    while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
        later += match[0];
        selector = selector.replace( Expr.match.PSEUDO, "" );
    }

    selector = Expr.relative[selector] ? selector + "*" : selector;

    for ( var i = 0, l = root.length; i < l; i++ ) {
        Sizzle( selector, root[i], tmpSet );
    }

    return Sizzle.filter( later, tmpSet );
};

// EXPOSE
jQuery.find = Sizzle;
jQuery.filter = Sizzle.filter;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;

Sizzle.selectors.filters.hidden = function(elem){
    return "hidden" === elem.type ||
        jQuery.css(elem, "display") === "none" ||
        jQuery.css(elem, "visibility") === "hidden";
};

Sizzle.selectors.filters.visible = function(elem){
    return "hidden" !== elem.type &&
        jQuery.css(elem, "display") !== "none" &&
        jQuery.css(elem, "visibility") !== "hidden";
};

Sizzle.selectors.filters.animated = function(elem){
    return jQuery.grep(jQuery.timers, function(fn){
        return elem === fn.elem;
    }).length;
};

jQuery.multiFilter = function( expr, elems, not ) {
    if ( not ) {
        expr = ":not(" + expr + ")";
    }

    return Sizzle.matches(expr, elems);
};

jQuery.dir = function( elem, dir ){
    var matched = [], cur = elem[dir];
    while ( cur && cur != document ) {
        if ( cur.nodeType == 1 )
            matched.push( cur );
        cur = cur[dir];
    }
    return matched;
};

jQuery.nth = function(cur, result, dir, elem){
    result = result || 1;
    var num = 0;

    for ( ; cur; cur = cur[dir] )
        if ( cur.nodeType == 1 && ++num == result )
            break;

    return cur;
};

jQuery.sibling = function(n, elem){
    var r = [];

    for ( ; n; n = n.nextSibling ) {
        if ( n.nodeType == 1 && n != elem )
            r.push( n );
    }

    return r;
};

return;

window.Sizzle = Sizzle;

})();
/*
 * A number of helper functions used for managing events.
 * Many of the ideas behind this code originated from
 * Dean Edwards' addEvent library.
 */
jQuery.event = {

    // Bind an event to an element
    // Original by Dean Edwards
    add: function(elem, types, handler, data) {
        if ( elem.nodeType == 3 || elem.nodeType == 8 )
            return;

        // For whatever reason, IE has trouble passing the window object
        // around, causing it to be cloned in the process
        if ( elem.setInterval && elem != window )
            elem = window;

        // Make sure that the function being executed has a unique ID
        if ( !handler.guid )
            handler.guid = this.guid++;

        // if data is passed, bind to handler
        if ( data !== undefined ) {
            // Create temporary function pointer to original handler
            var fn = handler;

            // Create unique handler function, wrapped around original handler
            handler = this.proxy( fn );

            // Store data in unique handler
            handler.data = data;
        }

        // Init the element's event structure
        var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
            handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
                // Handle the second event of a trigger and when
                // an event is called after a page has unloaded
                return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
                    jQuery.event.handle.apply(arguments.callee.elem, arguments) :
                    undefined;
            });
        // Add elem as a property of the handle function
        // This is to prevent a memory leak with non-native
        // event in IE.
        handle.elem = elem;

        // Handle multiple events separated by a space
        // jQuery(...).bind("mouseover mouseout", fn);
        jQuery.each(types.split(/\s+/), function(index, type) {
            // Namespaced event handlers
            var namespaces = type.split(".");
            type = namespaces.shift();
            handler.type = namespaces.slice().sort().join(".");

            // Get the current list of functions bound to this event
            var handlers = events[type];
            
            if ( jQuery.event.specialAll[type] )
                jQuery.event.specialAll[type].setup.call(elem, data, namespaces);

            // Init the event handler queue
            if (!handlers) {
                handlers = events[type] = {};

                // Check for a special event handler
                // Only use addEventListener/attachEvent if the special
                // events handler returns false
                if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
                    // Bind the global event handler to the element
                    if (elem.addEventListener)
                        elem.addEventListener(type, handle, false);
                    else if (elem.attachEvent)
                        elem.attachEvent("on" + type, handle);
                }
            }

            // Add the function to the element's handler list
            handlers[handler.guid] = handler;

            // Keep track of which events have been used, for global triggering
            jQuery.event.global[type] = true;
        });

        // Nullify elem to prevent memory leaks in IE
        elem = null;
    },

    guid: 1,
    global: {},

    // Detach an event or set of events from an element
    remove: function(elem, types, handler) {
        // don't do events on text and comment nodes
        if ( elem.nodeType == 3 || elem.nodeType == 8 )
            return;

        var events = jQuery.data(elem, "events"), ret, index;

        if ( events ) {
            // Unbind all events for the element
            if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
                for ( var type in events )
                    this.remove( elem, type + (types || "") );
            else {
                // types is actually an event object here
                if ( types.type ) {
                    handler = types.handler;
                    types = types.type;
                }

                // Handle multiple events seperated by a space
                // jQuery(...).unbind("mouseover mouseout", fn);
                jQuery.each(types.split(/\s+/), function(index, type){
                    // Namespaced event handlers
                    var namespaces = type.split(".");
                    type = namespaces.shift();
                    var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

                    if ( events[type] ) {
                        // remove the given handler for the given type
                        if ( handler )
                            delete events[type][handler.guid];

                        // remove all handlers for the given type
                        else
                            for ( var handle in events[type] )
                                // Handle the removal of namespaced events
                                if ( namespace.test(events[type][handle].type) )
                                    delete events[type][handle];
                                    
                        if ( jQuery.event.specialAll[type] )
                            jQuery.event.specialAll[type].teardown.call(elem, namespaces);

                        // remove generic event handler if no more handlers exist
                        for ( ret in events[type] ) break;
                        if ( !ret ) {
                            if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
                                if (elem.removeEventListener)
                                    elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
                                else if (elem.detachEvent)
                                    elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
                            }
                            ret = null;
                            delete events[type];
                        }
                    }
                });
            }

            // Remove the expando if it's no longer used
            for ( ret in events ) break;
            if ( !ret ) {
                var handle = jQuery.data( elem, "handle" );
                if ( handle ) handle.elem = null;
                jQuery.removeData( elem, "events" );
                jQuery.removeData( elem, "handle" );
            }
        }
    },

    // bubbling is internal
    trigger: function( event, data, elem, bubbling ) {
        // Event object or event type
        var type = event.type || event;

        if( !bubbling ){
            event = typeof event === "object" ?
                // jQuery.Event object
                event[expando] ? event :
                // Object literal
                jQuery.extend( jQuery.Event(type), event ) :
                // Just the event type (string)
                jQuery.Event(type);

            if ( type.indexOf("!") >= 0 ) {
                event.type = type = type.slice(0, -1);
                event.exclusive = true;
            }

            // Handle a global trigger
            if ( !elem ) {
                // Don't bubble custom events when global (to avoid too much overhead)
                event.stopPropagation();
                // Only trigger if we've ever bound an event for it
                if ( this.global[type] )
                    jQuery.each( jQuery.cache, function(){
                        if ( this.events && this.events[type] )
                            jQuery.event.trigger( event, data, this.handle.elem );
                    });
            }

            // Handle triggering a single element

            // don't do events on text and comment nodes
            if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
                return undefined;
            
            // Clean up in case it is reused
            event.result = undefined;
            event.target = elem;
            
            // Clone the incoming data, if any
            data = jQuery.makeArray(data);
            data.unshift( event );
        }

        event.currentTarget = elem;

        // Trigger the event, it is assumed that "handle" is a function
        var handle = jQuery.data(elem, "handle");
        if ( handle )
            handle.apply( elem, data );

        // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
        if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
            event.result = false;

        // Trigger the native events (except for clicks on links)
        if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
            this.triggered = true;
            try {
                elem[ type ]();
            // prevent IE from throwing an error for some hidden elements
            } catch (e) {}
        }

        this.triggered = false;

        if ( !event.isPropagationStopped() ) {
            var parent = elem.parentNode || elem.ownerDocument;
            if ( parent )
                jQuery.event.trigger(event, data, parent, true);
        }
    },

    handle: function(event) {
        // returned undefined or false
        var all, handlers;

        event = arguments[0] = jQuery.event.fix( event || window.event );

        // Namespaced event handlers
        var namespaces = event.type.split(".");
        event.type = namespaces.shift();

        // Cache this now, all = true means, any handler
        all = !namespaces.length && !event.exclusive;
        
        var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

        handlers = ( jQuery.data(this, "events") || {} )[event.type];

        for ( var j in handlers ) {
            var handler = handlers[j];

            // Filter the functions by class
            if ( all || namespace.test(handler.type) ) {
                // Pass in a reference to the handler function itself
                // So that we can later remove it
                event.handler = handler;
                event.data = handler.data;

                var ret = handler.apply(this, arguments);

                if( ret !== undefined ){
                    event.result = ret;
                    if ( ret === false ) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                }

                if( event.isImmediatePropagationStopped() )
                    break;

            }
        }
    },

    props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),

    fix: function(event) {
        if ( event[expando] )
            return event;

        // store a copy of the original event object
        // and "clone" to set read-only properties
        var originalEvent = event;
        event = jQuery.Event( originalEvent );

        for ( var i = this.props.length, prop; i; ){
            prop = this.props[ --i ];
            event[ prop ] = originalEvent[ prop ];
        }

        // Fix target property, if necessary
        if ( !event.target )
            event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either

        // check if target is a textnode (safari)
        if ( event.target.nodeType == 3 )
            event.target = event.target.parentNode;

        // Add relatedTarget, if necessary
        if ( !event.relatedTarget && event.fromElement )
            event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;

        // Calculate pageX/Y if missing and clientX/Y available
        if ( event.pageX == null && event.clientX != null ) {
            var doc = document.documentElement, body = document.body;
            event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
            event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
        }

        // Add which for key events
        if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
            event.which = event.charCode || event.keyCode;

        // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
        if ( !event.metaKey && event.ctrlKey )
            event.metaKey = event.ctrlKey;

        // Add which for click: 1 == left; 2 == middle; 3 == right
        // Note: button is not normalized, so don't use it
        if ( !event.which && event.button )
            event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));

        return event;
    },

    proxy: function( fn, proxy ){
        proxy = proxy || function(){ return fn.apply(this, arguments); };
        // Set the guid of unique handler to the same of original handler, so it can be removed
        proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
        // So proxy can be declared as an argument
        return proxy;
    },

    special: {
        ready: {
            // Make sure the ready event is setup
            setup: bindReady,
            teardown: function() {}
        }
    },
    
    specialAll: {
        live: {
            setup: function( selector, namespaces ){
                jQuery.event.add( this, namespaces[0], liveHandler );
            },
            teardown:  function( namespaces ){
                if ( namespaces.length ) {
                    var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
                    
                    jQuery.each( (jQuery.data(this, "events").live || {}), function(){
                        if ( name.test(this.type) )
                            remove++;
                    });
                    
                    if ( remove < 1 )
                        jQuery.event.remove( this, namespaces[0], liveHandler );
                }
            }
        }
    }
};

jQuery.Event = function( src ){
    // Allow instantiation without the 'new' keyword
    if( !this.preventDefault )
        return new jQuery.Event(src);
    
    // Event object
    if( src && src.type ){
        this.originalEvent = src;
        this.type = src.type;
    // Event type
    }else
        this.type = src;

    // timeStamp is buggy for some events on Firefox(#3843)
    // So we won't rely on the native value
    this.timeStamp = now();
    
    // Mark it as fixed
    this[expando] = true;
};

function returnFalse(){
    return false;
}
function returnTrue(){
    return true;
}

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
    preventDefault: function() {
        this.isDefaultPrevented = returnTrue;

        var e = this.originalEvent;
        if( !e )
            return;
        // if preventDefault exists run it on the original event
        if (e.preventDefault)
            e.preventDefault();
        // otherwise set the returnValue property of the original event to false (IE)
        e.returnValue = false;
    },
    stopPropagation: function() {
        this.isPropagationStopped = returnTrue;

        var e = this.originalEvent;
        if( !e )
            return;
        // if stopPropagation exists run it on the original event
        if (e.stopPropagation)
            e.stopPropagation();
        // otherwise set the cancelBubble property of the original event to true (IE)
        e.cancelBubble = true;
    },
    stopImmediatePropagation:function(){
        this.isImmediatePropagationStopped = returnTrue;
        this.stopPropagation();
    },
    isDefaultPrevented: returnFalse,
    isPropagationStopped: returnFalse,
    isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function(event) {
    // Check if mouse(over|out) are still within the same parent element
    var parent = event.relatedTarget;
    // Traverse up the tree
    while ( parent && parent != this )
        try { parent = parent.parentNode; }
        catch(e) { parent = this; }
    
    if( parent != this ){
        // set the correct event type
        event.type = event.data;
        // handle event if we actually just moused on to a non sub-element
        jQuery.event.handle.apply( this, arguments );
    }
};
    
jQuery.each({ 
    mouseover: 'mouseenter', 
    mouseout: 'mouseleave'
}, function( orig, fix ){
    jQuery.event.special[ fix ] = {
        setup: function(){
            jQuery.event.add( this, orig, withinElement, fix );
        },
        teardown: function(){
            jQuery.event.remove( this, orig, withinElement );
        }
    };             
});

jQuery.fn.extend({
    bind: function( type, data, fn ) {
        return type == "unload" ? this.one(type, data, fn) : this.each(function(){
            jQuery.event.add( this, type, fn || data, fn && data );
        });
    },

    one: function( type, data, fn ) {
        var one = jQuery.event.proxy( fn || data, function(event) {
            jQuery(this).unbind(event, one);
            return (fn || data).apply( this, arguments );
        });
        return this.each(function(){
            jQuery.event.add( this, type, one, fn && data);
        });
    },

    unbind: function( type, fn ) {
        return this.each(function(){
            jQuery.event.remove( this, type, fn );
        });
    },

    trigger: function( type, data ) {
        return this.each(function(){
            jQuery.event.trigger( type, data, this );
        });
    },

    triggerHandler: function( type, data ) {
        if( this[0] ){
            var event = jQuery.Event(type);
            event.preventDefault();
            event.stopPropagation();
            jQuery.event.trigger( event, data, this[0] );
            return event.result;
        }       
    },

    toggle: function( fn ) {
        // Save reference to arguments for access in closure
        var args = arguments, i = 1;

        // link all the functions, so any of them can unbind this click handler
        while( i < args.length )
            jQuery.event.proxy( fn, args[i++] );

        return this.click( jQuery.event.proxy( fn, function(event) {
            // Figure out which function to execute
            this.lastToggle = ( this.lastToggle || 0 ) % i;

            // Make sure that clicks stop
            event.preventDefault();

            // and execute the function
            return args[ this.lastToggle++ ].apply( this, arguments ) || false;
        }));
    },

    hover: function(fnOver, fnOut) {
        return this.mouseenter(fnOver).mouseleave(fnOut);
    },

    ready: function(fn) {
        // Attach the listeners
        bindReady();

        // If the DOM is already ready
        if ( jQuery.isReady )
            // Execute the function immediately
            fn.call( document, jQuery );

        // Otherwise, remember the function for later
        else
            // Add the function to the wait list
            jQuery.readyList.push( fn );

        return this;
    },
    
    live: function( type, fn ){
        var proxy = jQuery.event.proxy( fn );
        proxy.guid += this.selector + type;

        jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy );

        return this;
    },
    
    die: function( type, fn ){
        jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
        return this;
    }
});

function liveHandler( event ){
    var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
        stop = true,
        elems = [];

    jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
        if ( check.test(fn.type) ) {
            var elem = jQuery(event.target).closest(fn.data)[0];
            if ( elem )
                elems.push({ elem: elem, fn: fn });
        }
    });

    jQuery.each(elems, function(){
        if ( this.fn.call(this.elem, event, this.fn.data) === false )
            stop = false;
    });

    return stop;
}

function liveConvert(type, selector){
    return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
}

jQuery.extend({
    isReady: false,
    readyList: [],
    // Handle when the DOM is ready
    ready: function() {
        // Make sure that the DOM is not already loaded
        if ( !jQuery.isReady ) {
            // Remember that the DOM is ready
            jQuery.isReady = true;

            // If there are functions bound, to execute
            if ( jQuery.readyList ) {
                // Execute all of them
                jQuery.each( jQuery.readyList, function(){
                    this.call( document, jQuery );
                });

                // Reset the list of functions
                jQuery.readyList = null;
            }

            // Trigger any bound ready events
            jQuery(document).triggerHandler("ready");
        }
    }
});

var readyBound = false;

function bindReady(){
    if ( readyBound ) return;
    readyBound = true;

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){
            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
            jQuery.ready();
        }, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {
        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );
                jQuery.ready();
            }
        });

        // If IE and not an iframe
        // continually check to see if the document is ready
        if ( document.documentElement.doScroll && typeof window.frameElement === "undefined" ) (function(){
            if ( jQuery.isReady ) return;

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch( error ) {
                setTimeout( arguments.callee, 0 );
                return;
            }

            // and execute any waiting functions
            jQuery.ready();
        })();
    }

    // A fallback to window.onload, that will always work
    jQuery.event.add( window, "load", jQuery.ready );
}

jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
    "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
    "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){

    // Handle event binding
    jQuery.fn[name] = function(fn){
        return fn ? this.bind(name, fn) : this.trigger(name);
    };
});

// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery( window ).bind( 'unload', function(){ 
    for ( var id in jQuery.cache )
        // Skip the window
        if ( id != 1 && jQuery.cache[ id ].handle )
            jQuery.event.remove( jQuery.cache[ id ].handle.elem );
}); 
(function(){

    jQuery.support = {};

    var root = document.documentElement,
        script = document.createElement("script"),
        div = document.createElement("div"),
        id = "script" + (new Date).getTime();

    div.style.display = "none";
    div.innerHTML = '   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';

    var all = div.getElementsByTagName("*"),
        a = div.getElementsByTagName("a")[0];

    // Can't get basic test support
    if ( !all || !all.length || !a ) {
        return;
    }

    jQuery.support = {
        // IE strips leading whitespace when .innerHTML is used
        leadingWhitespace: div.firstChild.nodeType == 3,
        
        // Make sure that tbody elements aren't automatically inserted
        // IE will insert them into empty tables
        tbody: !div.getElementsByTagName("tbody").length,
        
        // Make sure that you can get all elements in an <object> element
        // IE 7 always returns no results
        objectAll: !!div.getElementsByTagName("object")[0]
            .getElementsByTagName("*").length,
        
        // Make sure that link elements get serialized correctly by innerHTML
        // This requires a wrapper element in IE
        htmlSerialize: !!div.getElementsByTagName("link").length,
        
        // Get the style information from getAttribute
        // (IE uses .cssText insted)
        style: /red/.test( a.getAttribute("style") ),
        
        // Make sure that URLs aren't manipulated
        // (IE normalizes it by default)
        hrefNormalized: a.getAttribute("href") === "/a",
        
        // Make sure that element opacity exists
        // (IE uses filter instead)
        opacity: a.style.opacity === "0.5",
        
        // Verify style float existence
        // (IE uses styleFloat instead of cssFloat)
        cssFloat: !!a.style.cssFloat,

        // Will be defined later
        scriptEval: false,
        noCloneEvent: true,
        boxModel: null
    };
    
    script.type = "text/javascript";
    try {
        script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
    } catch(e){}

    root.insertBefore( script, root.firstChild );
    
    // Make sure that the execution of code works by injecting a script
    // tag with appendChild/createTextNode
    // (IE doesn't support this, fails, and uses .text instead)
    if ( window[ id ] ) {
        jQuery.support.scriptEval = true;
        delete window[ id ];
    }

    root.removeChild( script );

    if ( div.attachEvent && div.fireEvent ) {
        div.attachEvent("onclick", function(){
            // Cloning a node shouldn't copy over any
            // bound event handlers (IE does this)
            jQuery.support.noCloneEvent = false;
            div.detachEvent("onclick", arguments.callee);
        });
        div.cloneNode(true).fireEvent("onclick");
    }

    // Figure out if the W3C box model works as expected
    // document.body must exist before we can do this
    jQuery(function(){
        var div = document.createElement("div");
        div.style.width = "1px";
        div.style.paddingLeft = "1px";

        document.body.appendChild( div );
        jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
        document.body.removeChild( div );
    });
})();

var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";

jQuery.props = {
    "for": "htmlFor",
    "class": "className",
    "float": styleFloat,
    cssFloat: styleFloat,
    styleFloat: styleFloat,
    readonly: "readOnly",
    maxlength: "maxLength",
    cellspacing: "cellSpacing",
    rowspan: "rowSpan",
    tabindex: "tabIndex"
};
jQuery.fn.extend({
    // Keep a copy of the old load
    _load: jQuery.fn.load,

    load: function( url, params, callback ) {
        if ( typeof url !== "string" )
            return this._load( url );

        var off = url.indexOf(" ");
        if ( off >= 0 ) {
            var selector = url.slice(off, url.length);
            url = url.slice(0, off);
        }

        // Default to a GET request
        var type = "GET";

        // If the second parameter was provided
        if ( params )
            // If it's a function
            if ( jQuery.isFunction( params ) ) {
                // We assume that it's the callback
                callback = params;
                params = null;

            // Otherwise, build a param string
            } else if( typeof params === "object" ) {
                params = jQuery.param( params );
                type = "POST";
            }

        var self = this;

        // Request the remote document
        jQuery.ajax({
            url: url,
            type: type,
            dataType: "html",
            data: params,
            complete: function(res, status){
                // If successful, inject the HTML into all the matched elements
                if ( status == "success" || status == "notmodified" )
                    // See if a selector was specified
                    self.html( selector ?
                        // Create a dummy div to hold the results
                        jQuery("<div/>")
                            // inject the contents of the document in, removing the scripts
                            // to avoid any 'Permission Denied' errors in IE
                            .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))

                            // Locate the specified elements
                            .find(selector) :

                        // If not, just inject the full result
                        res.responseText );

                if( callback )
                    self.each( callback, [res.responseText, status, res] );
            }
        });
        return this;
    },

    serialize: function() {
        return jQuery.param(this.serializeArray());
    },
    serializeArray: function() {
        return this.map(function(){
            return this.elements ? jQuery.makeArray(this.elements) : this;
        })
        .filter(function(){
            return this.name && !this.disabled &&
                (this.checked || /select|textarea/i.test(this.nodeName) ||
                    /text|hidden|password/i.test(this.type));
        })
        .map(function(i, elem){
            var val = jQuery(this).val();
            return val == null ? null :
                jQuery.isArray(val) ?
                    jQuery.map( val, function(val, i){
                        return {name: elem.name, value: val};
                    }) :
                    {name: elem.name, value: val};
        }).get();
    }
});

// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
    jQuery.fn[o] = function(f){
        return this.bind(o, f);
    };
});

var jsc = now();

jQuery.extend({
  
    get: function( url, data, callback, type ) {
        // shift arguments if data argument was ommited
        if ( jQuery.isFunction( data ) ) {
            callback = data;
            data = null;
        }

        return jQuery.ajax({
            type: "GET",
            url: url,
            data: data,
            success: callback,
            dataType: type
        });
    },

    getScript: function( url, callback ) {
        return jQuery.get(url, null, callback, "script");
    },

    getJSON: function( url, data, callback ) {
        return jQuery.get(url, data, callback, "json");
    },

    post: function( url, data, callback, type ) {
        if ( jQuery.isFunction( data ) ) {
            callback = data;
            data = {};
        }

        return jQuery.ajax({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            dataType: type
        });
    },

    ajaxSetup: function( settings ) {
        jQuery.extend( jQuery.ajaxSettings, settings );
    },

    ajaxSettings: {
        url: location.href,
        global: true,
        type: "GET",
        contentType: "application/x-www-form-urlencoded",
        processData: true,
        async: true,
        /*
        timeout: 0,
        data: null,
        username: null,
        password: null,
        */
        // Create the request object; Microsoft failed to properly
        // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
        // This function can be overriden by calling jQuery.ajaxSetup
        xhr:function(){
            return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
        },
        accepts: {
            xml: "application/xml, text/xml",
            html: "text/html",
            script: "text/javascript, application/javascript",
            json: "application/json, text/javascript",
            text: "text/plain",
            _default: "*/*"
        }
    },

    // Last-Modified header cache for next request
    lastModified: {},

    ajax: function( s ) {
        // Extend the settings, but re-extend 's' so that it can be
        // checked again later (in the test suite, specifically)
        s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));

        var jsonp, jsre = /=\?(&|$)/g, status, data,
            type = s.type.toUpperCase();

        // convert data if not already a string
        if ( s.data && s.processData && typeof s.data !== "string" )
            s.data = jQuery.param(s.data);

        // Handle JSONP Parameter Callbacks
        if ( s.dataType == "jsonp" ) {
            if ( type == "GET" ) {
                if ( !s.url.match(jsre) )
                    s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
            } else if ( !s.data || !s.data.match(jsre) )
                s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
            s.dataType = "json";
        }

        // Build temporary JSONP function
        if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
            jsonp = "jsonp" + jsc++;

            // Replace the =? sequence both in the query string and the data
            if ( s.data )
                s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
            s.url = s.url.replace(jsre, "=" + jsonp + "$1");

            // We need to make sure
            // that a JSONP style response is executed properly
            s.dataType = "script";

            // Handle JSONP-style loading
            window[ jsonp ] = function(tmp){
                data = tmp;
                success();
                complete();
                // Garbage collect
                window[ jsonp ] = undefined;
                try{ delete window[ jsonp ]; } catch(e){}
                if ( head )
                    head.removeChild( script );
            };
        }

        if ( s.dataType == "script" && s.cache == null )
            s.cache = false;

        if ( s.cache === false && type == "GET" ) {
            var ts = now();
            // try replacing _= if it is there
            var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
            // if nothing was replaced, add timestamp to the end
            s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
        }

        // If data is available, append data to url for get requests
        if ( s.data && type == "GET" ) {
            s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;

            // IE likes to send both get and post data, prevent this
            s.data = null;
        }

        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
            jQuery.event.trigger( "ajaxStart" );

        // Matches an absolute URL, and saves the domain
        var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );

        // If we're requesting a remote document
        // and trying to load JSON or Script with a GET
        if ( s.dataType == "script" && type == "GET" && parts
            && ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){

            var head = document.getElementsByTagName("head")[0];
            var script = document.createElement("script");
            script.src = s.url;
            if (s.scriptCharset)
                script.charset = s.scriptCharset;

            // Handle Script loading
            if ( !jsonp ) {
                var done = false;

                // Attach handlers for all browsers
                script.onload = script.onreadystatechange = function(){
                    if ( !done && (!this.readyState ||
                            this.readyState == "loaded" || this.readyState == "complete") ) {
                        done = true;
                        success();
                        complete();
                        head.removeChild( script );
                    }
                };
            }

            head.appendChild(script);

            // We handle everything using the script element injection
            return undefined;
        }

        var requestDone = false;

        // Create the request object
        var xhr = s.xhr();

        // Open the socket
        // Passing null username, generates a login popup on Opera (#2865)
        if( s.username )
            xhr.open(type, s.url, s.async, s.username, s.password);
        else
            xhr.open(type, s.url, s.async);

        // Need an extra try/catch for cross domain requests in Firefox 3
        try {
            // Set the correct header, if data is being sent
            if ( s.data )
                xhr.setRequestHeader("Content-Type", s.contentType);

            // Set the If-Modified-Since header, if ifModified mode.
            if ( s.ifModified )
                xhr.setRequestHeader("If-Modified-Since",
                    jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );

            // Set header so the called script knows that it's an XMLHttpRequest
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

            // Set the Accepts header for the server, depending on the dataType
            xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
                s.accepts[ s.dataType ] + ", */*" :
                s.accepts._default );
        } catch(e){}

        // Allow custom headers/mimetypes and early abort
        if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
            // Handle the global AJAX counter
            if ( s.global && ! --jQuery.active )
                jQuery.event.trigger( "ajaxStop" );
            // close opended socket
            xhr.abort();
            return false;
        }

        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xhr, s]);

        // Wait for a response to come back
        var onreadystatechange = function(isTimeout){
            // The request was aborted, clear the interval and decrement jQuery.active
            if (xhr.readyState == 0) {
                if (ival) {
                    // clear poll interval
                    clearInterval(ival);
                    ival = null;
                    // Handle the global AJAX counter
                    if ( s.global && ! --jQuery.active )
                        jQuery.event.trigger( "ajaxStop" );
                }
            // The transfer is complete and the data is available, or the request timed out
            } else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
                requestDone = true;

                // clear poll interval
                if (ival) {
                    clearInterval(ival);
                    ival = null;
                }

                status = isTimeout == "timeout" ? "timeout" :
                    !jQuery.httpSuccess( xhr ) ? "error" :
                    s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
                    "success";

                if ( status == "success" ) {
                    // Watch for, and catch, XML document parse errors
                    try {
                        // process the data (runs the xml through httpData regardless of callback)
                        data = jQuery.httpData( xhr, s.dataType, s );
                    } catch(e) {
                        status = "parsererror";
                    }
                }

                // Make sure that the request was successful or notmodified
                if ( status == "success" ) {
                    // Cache Last-Modified header, if ifModified mode.
                    var modRes;
                    try {
                        modRes = xhr.getResponseHeader("Last-Modified");
                    } catch(e) {} // swallow exception thrown by FF if header is not available

                    if ( s.ifModified && modRes )
                        jQuery.lastModified[s.url] = modRes;

                    // JSONP handles its own success callback
                    if ( !jsonp )
                        success();
                } else
                    jQuery.handleError(s, xhr, status);

                // Fire the complete handlers
                complete();

                if ( isTimeout )
                    xhr.abort();

                // Stop memory leaks
                if ( s.async )
                    xhr = null;
            }
        };

        if ( s.async ) {
            // don't attach the handler to the request, just poll it instead
            var ival = setInterval(onreadystatechange, 13);

            // Timeout checker
            if ( s.timeout > 0 )
                setTimeout(function(){
                    // Check to see if the request is still happening
                    if ( xhr && !requestDone )
                        onreadystatechange( "timeout" );
                }, s.timeout);
        }

        // Send the data
        try {
            xhr.send(s.data);
        } catch(e) {
            jQuery.handleError(s, xhr, null, e);
        }

        // firefox 1.5 doesn't fire statechange for sync requests
        if ( !s.async )
            onreadystatechange();

        function success(){
            // If a local callback was specified, fire it and pass it the data
            if ( s.success )
                s.success( data, status );

            // Fire the global callback
            if ( s.global )
                jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
        }

        function complete(){
            // Process result
            if ( s.complete )
                s.complete(xhr, status);

            // The request was completed
            if ( s.global )
                jQuery.event.trigger( "ajaxComplete", [xhr, s] );

            // Handle the global AJAX counter
            if ( s.global && ! --jQuery.active )
                jQuery.event.trigger( "ajaxStop" );
        }

        // return XMLHttpRequest to allow aborting the request etc.
        return xhr;
    },

    handleError: function( s, xhr, status, e ) {
        // If a local callback was specified, fire it
        if ( s.error ) s.error( xhr, status, e );

        // Fire the global callback
        if ( s.global )
            jQuery.event.trigger( "ajaxError", [xhr, s, e] );
    },

    // Counter for holding the number of active queries
    active: 0,

    // Determines if an XMLHttpRequest was successful or not
    httpSuccess: function( xhr ) {
        try {
            // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
            return !xhr.status && location.protocol == "file:" ||
                ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
        } catch(e){}
        return false;
    },

    // Determines if an XMLHttpRequest returns NotModified
    httpNotModified: function( xhr, url ) {
        try {
            var xhrRes = xhr.getResponseHeader("Last-Modified");

            // Firefox always returns 200. check Last-Modified date
            return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
        } catch(e){}
        return false;
    },

    httpData: function( xhr, type, s ) {
        var ct = xhr.getResponseHeader("content-type"),
            xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
            data = xml ? xhr.responseXML : xhr.responseText;

        if ( xml && data.documentElement.tagName == "parsererror" )
            throw "parsererror";
            
        // Allow a pre-filtering function to sanitize the response
        // s != null is checked to keep backwards compatibility
        if( s && s.dataFilter )
            data = s.dataFilter( data, type );

        // The filter can actually parse the response
        if( typeof data === "string" ){

            // If the type is "script", eval it in global context
            if ( type == "script" )
                jQuery.globalEval( data );

            // Get the JavaScript object, if JSON is used.
            if ( type == "json" )
                data = window["eval"]("(" + data + ")");
        }
        
        return data;
    },

    // Serialize an array of form elements or a set of
    // key/values into a query string
    param: function( a ) {
        var s = [ ];

        function add( key, value ){
            s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
        };

        // If an array was passed in, assume that it is an array
        // of form elements
        if ( jQuery.isArray(a) || a.jquery )
            // Serialize the form elements
            jQuery.each( a, function(){
                add( this.name, this.value );
            });

        // Otherwise, assume that it's an object of key/value pairs
        else
            // Serialize the key/values
            for ( var j in a )
                // If the value is an array then the key names need to be repeated
                if ( jQuery.isArray(a[j]) )
                    jQuery.each( a[j], function(){
                        add( j, this );
                    });
                else
                    add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );

        // Return the resulting serialization
        return s.join("&").replace(/%20/g, "+");
    }

});
var elemdisplay = {},
    timerId,
    fxAttrs = [
        // height animations
        [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
        // width animations
        [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
        // opacity animations
        [ "opacity" ]
    ];

function genFx( type, num ){
    var obj = {};
    jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){
        obj[ this ] = type;
    });
    return obj;
}

jQuery.fn.extend({
    show: function(speed,callback){
        if ( speed ) {
            return this.animate( genFx("show", 3), speed, callback);
        } else {
            for ( var i = 0, l = this.length; i < l; i++ ){
                var old = jQuery.data(this[i], "olddisplay");
                
                this[i].style.display = old || "";
                
                if ( jQuery.css(this[i], "display") === "none" ) {
                    var tagName = this[i].tagName, display;
                    
                    if ( elemdisplay[ tagName ] ) {
                        display = elemdisplay[ tagName ];
                    } else {
                        var elem = jQuery("<" + tagName + " />").appendTo("body");
                        
                        display = elem.css("display");
                        if ( display === "none" )
                            display = "block";
                        
                        elem.remove();
                        
                        elemdisplay[ tagName ] = display;
                    }
                    
                    this[i].style.display = jQuery.data(this[i], "olddisplay", display);
                }
            }
            
            return this;
        }
    },

    hide: function(speed,callback){
        if ( speed ) {
            return this.animate( genFx("hide", 3), speed, callback);
        } else {
            for ( var i = 0, l = this.length; i < l; i++ ){
                var old = jQuery.data(this[i], "olddisplay");
                if ( !old && old !== "none" )
                    jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
                this[i].style.display = "none";
            }
            return this;
        }
    },

    // Save the old toggle function
    _toggle: jQuery.fn.toggle,

    toggle: function( fn, fn2 ){
        var bool = typeof fn === "boolean";

        return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
            this._toggle.apply( this, arguments ) :
            fn == null || bool ?
                this.each(function(){
                    var state = bool ? fn : jQuery(this).is(":hidden");
                    jQuery(this)[ state ? "show" : "hide" ]();
                }) :
                this.animate(genFx("toggle", 3), fn, fn2);
    },

    fadeTo: function(speed,to,callback){
        return this.animate({opacity: to}, speed, callback);
    },

    animate: function( prop, speed, easing, callback ) {
        var optall = jQuery.speed(speed, easing, callback);

        return this[ optall.queue === false ? "each" : "queue" ](function(){
        
            var opt = jQuery.extend({}, optall), p,
                hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
                self = this;
    
            for ( p in prop ) {
                if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
                    return opt.complete.call(this);

                if ( ( p == "height" || p == "width" ) && this.style ) {
                    // Store display property
                    opt.display = jQuery.css(this, "display");

                    // Make sure that nothing sneaks out
                    opt.overflow = this.style.overflow;
                }
            }

            if ( opt.overflow != null )
                this.style.overflow = "hidden";

            opt.curAnim = jQuery.extend({}, prop);

            jQuery.each( prop, function(name, val){
                var e = new jQuery.fx( self, opt, name );

                if ( /toggle|show|hide/.test(val) )
                    e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
                else {
                    var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
                        start = e.cur(true) || 0;

                    if ( parts ) {
                        var end = parseFloat(parts[2]),
                            unit = parts[3] || "px";

                        // We need to compute starting value
                        if ( unit != "px" ) {
                            self.style[ name ] = (end || 1) + unit;
                            start = ((end || 1) / e.cur(true)) * start;
                            self.style[ name ] = start + unit;
                        }

                        // If a +=/-= token was provided, we're doing a relative animation
                        if ( parts[1] )
                            end = ((parts[1] == "-=" ? -1 : 1) * end) + start;

                        e.custom( start, end, unit );
                    } else
                        e.custom( start, val, "" );
                }
            });

            // For JS strict compliance
            return true;
        });
    },

    stop: function(clearQueue, gotoEnd){
        var timers = jQuery.timers;

        if (clearQueue)
            this.queue([]);

        this.each(function(){
            // go in reverse order so anything added to the queue during the loop is ignored
            for ( var i = timers.length - 1; i >= 0; i-- )
                if ( timers[i].elem == this ) {
                    if (gotoEnd)
                        // force the next step to be the last
                        timers[i](true);
                    timers.splice(i, 1);
                }
        });

        // start the next in the queue if the last step wasn't forced
        if (!gotoEnd)
            this.dequeue();

        return this;
    }

});

// Generate shortcuts for custom animations
jQuery.each({
    slideDown: genFx("show", 1),
    slideUp: genFx("hide", 1),
    slideToggle: genFx("toggle", 1),
    fadeIn: { opacity: "show" },
    fadeOut: { opacity: "hide" }
}, function( name, props ){
    jQuery.fn[ name ] = function( speed, callback ){
        return this.animate( props, speed, callback );
    };
});

jQuery.extend({

    speed: function(speed, easing, fn) {
        var opt = typeof speed === "object" ? speed : {
            complete: fn || !fn && easing ||
                jQuery.isFunction( speed ) && speed,
            duration: speed,
            easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
        };

        opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
            jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;

        // Queueing
        opt.old = opt.complete;
        opt.complete = function(){
            if ( opt.queue !== false )
                jQuery(this).dequeue();
            if ( jQuery.isFunction( opt.old ) )
                opt.old.call( this );
        };

        return opt;
    },

    easing: {
        linear: function( p, n, firstNum, diff ) {
            return firstNum + diff * p;
        },
        swing: function( p, n, firstNum, diff ) {
            return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
        }
    },

    timers: [],

    fx: function( elem, options, prop ){
        this.options = options;
        this.elem = elem;
        this.prop = prop;

        if ( !options.orig )
            options.orig = {};
    }

});

jQuery.fx.prototype = {

    // Simple function for setting a style value
    update: function(){
        if ( this.options.step )
            this.options.step.call( this.elem, this.now, this );

        (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );

        // Set display property to block for height/width animations
        if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
            this.elem.style.display = "block";
    },

    // Get the current size
    cur: function(force){
        if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) )
            return this.elem[ this.prop ];

        var r = parseFloat(jQuery.css(this.elem, this.prop, force));
        return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
    },

    // Start an animation from one number to another
    custom: function(from, to, unit){
        this.startTime = now();
        this.start = from;
        this.end = to;
        this.unit = unit || this.unit || "px";
        this.now = this.start;
        this.pos = this.state = 0;

        var self = this;
        function t(gotoEnd){
            return self.step(gotoEnd);
        }

        t.elem = this.elem;

        if ( t() && jQuery.timers.push(t) == 1 ) {
            timerId = setInterval(function(){
                var timers = jQuery.timers;

                for ( var i = 0; i < timers.length; i++ )
                    if ( !timers[i]() )
                        timers.splice(i--, 1);

                if ( !timers.length ) {
                    clearInterval( timerId );
                }
            }, 13);
        }
    },

    // Simple 'show' function
    show: function(){
        // Remember where we started, so that we can go back to it later
        this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
        this.options.show = true;

        // Begin the animation
        // Make sure that we start at a small width/height to avoid any
        // flash of content
        this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur());

        // Start by showing the element
        jQuery(this.elem).show();
    },

    // Simple 'hide' function
    hide: function(){
        // Remember where we started, so that we can go back to it later
        this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
        this.options.hide = true;

        // Begin the animation
        this.custom(this.cur(), 0);
    },

    // Each step of an animation
    step: function(gotoEnd){
        var t = now();

        if ( gotoEnd || t >= this.options.duration + this.startTime ) {
            this.now = this.end;
            this.pos = this.state = 1;
            this.update();

            this.options.curAnim[ this.prop ] = true;

            var done = true;
            for ( var i in this.options.curAnim )
                if ( this.options.curAnim[i] !== true )
                    done = false;

            if ( done ) {
                if ( this.options.display != null ) {
                    // Reset the overflow
                    this.elem.style.overflow = this.options.overflow;

                    // Reset the display
                    this.elem.style.display = this.options.display;
                    if ( jQuery.css(this.elem, "display") == "none" )
                        this.elem.style.display = "block";
                }

                // Hide the element if the "hide" operation was done
                if ( this.options.hide )
                    jQuery(this.elem).hide();

                // Reset the properties, if the item has been hidden or shown
                if ( this.options.hide || this.options.show )
                    for ( var p in this.options.curAnim )
                        jQuery.attr(this.elem.style, p, this.options.orig[p]);
                    
                // Execute the complete function
                this.options.complete.call( this.elem );
            }

            return false;
        } else {
            var n = t - this.startTime;
            this.state = n / this.options.duration;

            // Perform the easing function, defaults to swing
            this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
            this.now = this.start + ((this.end - this.start) * this.pos);

            // Perform the next step of the animation
            this.update();
        }

        return true;
    }

};

jQuery.extend( jQuery.fx, {
    speeds:{
        slow: 600,
        fast: 200,
        // Default speed
        _default: 400
    },
    step: {

        opacity: function(fx){
            jQuery.attr(fx.elem.style, "opacity", fx.now);
        },

        _default: function(fx){
            if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
                fx.elem.style[ fx.prop ] = fx.now + fx.unit;
            else
                fx.elem[ fx.prop ] = fx.now;
        }
    }
});
if ( document.documentElement["getBoundingClientRect"] )
    jQuery.fn.offset = function() {
        if ( !this[0] ) return { top: 0, left: 0 };
        if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
        var box  = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
            clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
            top  = box.top  + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop  || body.scrollTop ) - clientTop,
            left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
        return { top: top, left: left };
    };
else 
    jQuery.fn.offset = function() {
        if ( !this[0] ) return { top: 0, left: 0 };
        if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
        jQuery.offset.initialized || jQuery.offset.initialize();

        var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
            doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
            body = doc.body, defaultView = doc.defaultView,
            prevComputedStyle = defaultView.getComputedStyle(elem, null),
            top = elem.offsetTop, left = elem.offsetLeft;

        while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
            computedStyle = defaultView.getComputedStyle(elem, null);
            top -= elem.scrollTop, left -= elem.scrollLeft;
            if ( elem === offsetParent ) {
                top += elem.offsetTop, left += elem.offsetLeft;
                if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
                    top  += parseInt( computedStyle.borderTopWidth,  10) || 0,
                    left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
                prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
            }
            if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
                top  += parseInt( computedStyle.borderTopWidth,  10) || 0,
                left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
            prevComputedStyle = computedStyle;
        }

        if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
            top  += body.offsetTop,
            left += body.offsetLeft;

        if ( prevComputedStyle.position === "fixed" )
            top  += Math.max(docElem.scrollTop, body.scrollTop),
            left += Math.max(docElem.scrollLeft, body.scrollLeft);

        return { top: top, left: left };
    };

jQuery.offset = {
    initialize: function() {
        if ( this.initialized ) return;
        var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
            html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';

        rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
        for ( prop in rules ) container.style[prop] = rules[prop];

        container.innerHTML = html;
        body.insertBefore(container, body.firstChild);
        innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;

        this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
        this.doesAddBorderForTableAndCells = (td.offsetTop === 5);

        innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
        this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);

        body.style.marginTop = '1px';
        this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
        body.style.marginTop = bodyMarginTop;

        body.removeChild(container);
        this.initialized = true;
    },

    bodyOffset: function(body) {
        jQuery.offset.initialized || jQuery.offset.initialize();
        var top = body.offsetTop, left = body.offsetLeft;
        if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
            top  += parseInt( jQuery.curCSS(body, 'marginTop',  true), 10 ) || 0,
            left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0;
        return { top: top, left: left };
    }
};


jQuery.fn.extend({
    position: function() {
        var left = 0, top = 0, results;

        if ( this[0] ) {
            // Get *real* offsetParent
            var offsetParent = this.offsetParent(),

            // Get correct offsets
            offset       = this.offset(),
            parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();

            // Subtract element margins
            // note: when an element has margin: auto the offsetLeft and marginLeft 
            // are the same in Safari causing offset.left to incorrectly be 0
            offset.top  -= num( this, 'marginTop'  );
            offset.left -= num( this, 'marginLeft' );

            // Add offsetParent borders
            parentOffset.top  += num( offsetParent, 'borderTopWidth'  );
            parentOffset.left += num( offsetParent, 'borderLeftWidth' );

            // Subtract the two offsets
            results = {
                top:  offset.top  - parentOffset.top,
                left: offset.left - parentOffset.left
            };
        }

        return results;
    },

    offsetParent: function() {
        var offsetParent = this[0].offsetParent || document.body;
        while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
            offsetParent = offsetParent.offsetParent;
        return jQuery(offsetParent);
    }
});


// Create scrollLeft and scrollTop methods
jQuery.each( ['Left', 'Top'], function(i, name) {
    var method = 'scroll' + name;
    
    jQuery.fn[ method ] = function(val) {
        if (!this[0]) return null;

        return val !== undefined ?

            // Set the scroll offset
            this.each(function() {
                this == window || this == document ?
                    window.scrollTo(
                        !i ? val : jQuery(window).scrollLeft(),
                         i ? val : jQuery(window).scrollTop()
                    ) :
                    this[ method ] = val;
            }) :

            // Return the scroll offset
            this[0] == window || this[0] == document ?
                self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
                    jQuery.boxModel && document.documentElement[ method ] ||
                    document.body[ method ] :
                this[0][ method ];
    };
});
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function(i, name){

    var tl = i ? "Left"  : "Top",  // top or left
        br = i ? "Right" : "Bottom"; // bottom or right

    // innerHeight and innerWidth
    jQuery.fn["inner" + name] = function(){
        return this[ name.toLowerCase() ]() +
            num(this, "padding" + tl) +
            num(this, "padding" + br);
    };

    // outerHeight and outerWidth
    jQuery.fn["outer" + name] = function(margin) {
        return this["inner" + name]() +
            num(this, "border" + tl + "Width") +
            num(this, "border" + br + "Width") +
            (margin ?
                num(this, "margin" + tl) + num(this, "margin" + br) : 0);
    };
    
    var type = name.toLowerCase();

    jQuery.fn[ type ] = function( size ) {
        // Get window width or height
        return this[0] == window ?
            // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
            document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
            document.body[ "client" + name ] :

            // Get document width or height
            this[0] == document ?
                // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
                Math.max(
                    document.documentElement["client" + name],
                    document.body["scroll" + name], document.documentElement["scroll" + name],
                    document.body["offset" + name], document.documentElement["offset" + name]
                ) :

                // Get or set width or height on the element
                size === undefined ?
                    // Get width or height on the element
                    (this.length ? jQuery.css( this[0], type ) : null) :

                    // Set the width or height on the element (default to pixels if value is unitless)
                    this.css( type, typeof size === "string" ? size : size + "px" );
    };

});})();

jQuery.noConflict(); //B:
/*
 * jQuery UI 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;(function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

//Helper functions and ui object
$.ui = {

	version: "1.6",

	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

	contains: function(a, b) {
		var safari2 = $.browser.safari && $.browser.version < 522;
	    if (a.contains && !safari2) {
	        return a.contains(b);
	    }
	    if (a.compareDocumentPosition)
	        return !!(a.compareDocumentPosition(b) & 16);
	    while (b = b.parentNode)
	          if (b == a) return true;
	    return false;
	},

	cssCache: {},
	css: function(name) {
		if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
		var tmp = $('<div class="ui-gen">').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');

		//if (!$.browser.safari)
			//tmp.appendTo('body');

		//Opera and Safari set width and height to 0px instead of auto
		//Safari returns rgba(0,0,0,0) when bgcolor is not set
		$.ui.cssCache[name] = !!(
			(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) ||
			!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
		);
		try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
		return $.ui.cssCache[name];
	},

	hasScroll: function(el, a) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(el).css('overflow') == 'hidden') { return false; }

		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		//Determines when x coordinate is over "b" element axis
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	keyCode: {
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}

};

// WAI-ARIA normalization
if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

//jQuery plugins
$.fn.extend({

	remove: function() {
		// Safari has a native remove event which actually removes DOM elements,
		// so we have to use triggerHandler instead of trigger (#3037).
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {

		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;


	}

});


//Additional selectors
$.extend($.expr[':'], {

	data: function(a, i, m) {
		return $.data(a, m[3]);
	},

	// TODO: add support for object, area
	tabbable: function(a, i, m) {

		var nodeName = a.nodeName.toLowerCase();
		function isVisible(element) {
			return !($(element).is(':hidden') || $(element).parents(':hidden').length);
		}

		return (
			// in tab order
			a.tabIndex >= 0 &&

			( // filter node types that participate in the tab order

				// anchor tag
				('a' == nodeName && a.href) ||

				// enabled form element
				(/input|select|textarea|button/.test(nodeName) &&
					'hidden' != a.type && !a.disabled)
			) &&

			// visible on page
			isVisible(a)
		);

	}

});


// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}

	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options)));

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	// create widget constructor
	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(event, key, value) {
				return self._setData(key, value);
			})
			.bind('getData.' + name, function(event, key) {
				return self._getData(key);
			})
			.bind('remove', function() {
				return self.destroy();
			});

		this._init();
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName);
	},

	option: function(key, value) {
		var options = key,
			self = this;

		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}

		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element[value ? 'addClass' : 'removeClass'](
				this.widgetBaseClass + '-disabled');
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var eventName = (type == this.widgetEventPrefix
			? type : this.widgetEventPrefix + type);
		event = event || $.event.fix({ type: eventName, target: this.element[0] });
		return this.element.triggerHandler(eventName, [event, data], this.options[type]);
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					return false;
				}
			});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		if(!$.browser.safari) event.preventDefault();
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = true;
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
/*
 * jQuery UI Draggable 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.draggable", $.extend({}, $.ui.mouse, {

	_init: function() {

		if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
			this.element[0].style.position = 'relative';

		(this.options.cssNamespace && this.element.addClass(this.options.cssNamespace+"-draggable"));
		(this.options.disabled && this.element.addClass('ui-draggable-disabled'));

		this._mouseInit();

	},

	destroy: function() {
		if(!this.element.data('draggable')) return;
		this.element.removeData("draggable").unbind(".draggable").removeClass('ui-draggable ui-draggable-dragging ui-draggable-disabled');
		this._mouseDestroy();
	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle'))
			return false;

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle)
			return false;

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css("position");
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.element.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		if(o.cursorAt)
			this._adjustOffsetFromHelper(o.cursorAt);

		//Generate the original position
		this.originalPosition = this._generatePosition(event);

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		//Call plugins and callbacks
		this._propagate("start", event);

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.helper.addClass("ui-draggable-dragging");
		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;
	},

	_mouseDrag: function(event, noPropagation) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if(!noPropagation) this.position = this._propagate("drag", event) || this.position;

		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			var dropped = $.ui.ddmanager.drop(this, event);

		if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			var self = this;
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				self._propagate("stop", event);
				self._clear();
			});
		} else {
			this._propagate("stop", event);
			this._clear();
		}

		return false;
	},

	_getHandle: function(event) {

		var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
		$(this.options.handle, this.element)
			.find("*")
			.andSelf()
			.each(function() {
				if(this == event.target) handle = true;
			});

		return handle;

	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone() : this.element);

		if(!helper.parents('body').length)
			helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

		if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
			helper.css("position", "absolute");

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
		if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
		if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
	},

	_getParentOffset: function() {

		this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset();			//Get the offsetParent and cache its position

		if((this.offsetParent[0] == document.body && $.browser.mozilla)	//Ugly FF3 fix
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.element.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"),10) || 0),
			top: (parseInt(this.element.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			0 - this.offset.relative.left - this.offset.parent.left,
			0 - this.offset.relative.top - this.offset.parent.top,
			$(o.containment == 'document' ? document : window).width() - this.offset.relative.left - this.offset.parent.left - this.helperProportions.width - this.margins.left - (parseInt(this.element.css("marginRight"),10) || 0),
			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.offset.relative.top - this.offset.parent.top - this.helperProportions.height - this.margins.top - (parseInt(this.element.css("marginBottom"),10) || 0)
		];

		if(!(/^(document|window|parent)$/).test(o.containment)) {
			var ce = $(o.containment)[0];
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top - this.helperProportions.height - this.margins.top
			];
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var scroll = this[(this.cssPosition == 'absolute' ? 'offset' : 'scroll')+'Parent'], scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// the calculated relative position
				+ this.offset.relative.top	* mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod
				+ this.margins.top * mod												//Add the margin (you don't want the margin counting in intersection methods)
			),
			left: (
				pos.left																// the calculated relative position
				+ this.offset.relative.left	* mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : ( scrollIsRootNode ? 0 : scroll.scrollLeft() ) ) * mod
				+ this.margins.left * mod												//Add the margin (you don't want the margin counting in intersection methods)
			)
		};
	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this[(this.cssPosition == 'absolute' ? 'offset' : 'scroll')+'Parent'], scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		var position = {
			top: (
				event.pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )
			),
			left: (
				event.pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )
			)
		};

		if(!this.originalPosition) return position;										//If we are not dragging yet, we won't check for options

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */
		if(this.containment) {
			if(position.left < this.containment[0]) position.left = this.containment[0];
			if(position.top < this.containment[1]) position.top = this.containment[1];
			if(position.left > this.containment[2]) position.left = this.containment[2];
			if(position.top > this.containment[3]) position.top = this.containment[3];
		}

		if(o.grid) {
			var top = this.originalPosition.top + Math.round((position.top - this.originalPosition.top) / o.grid[1]) * o.grid[1];
			position.top = this.containment ? (!(top < this.containment[1] || top > this.containment[3]) ? top : (!(top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

			var left = this.originalPosition.left + Math.round((position.left - this.originalPosition.left) / o.grid[0]) * o.grid[0];
			position.left = this.containment ? (!(left < this.containment[0] || left > this.containment[2]) ? left : (!(left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
		}

		return position;
	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove();
		//if($.ui.ddmanager) $.ui.ddmanager.current = null;
		this.helper = null;
		this.cancelHelperRemoval = false;
	},

	// From now on bulk stuff - mainly helpers

	_propagate: function(n, event) {
		$.ui.plugin.call(this, n, [event, this._uiHash()]);
		if(n == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
		return this.element.triggerHandler(n == "drag" ? n : "drag"+n, [event, this._uiHash()], this.options[n]);
	},

	plugins: {},

	_uiHash: function(event) {
		return {
			helper: this.helper,
			position: this.position,
			absolutePosition: this.positionAbs,
			options: this.options
		};
	}

}));

$.extend($.ui.draggable, {
	version: "1.6",
	defaults: {
		appendTo: "parent",
		axis: false,
		cancel: ":input",
		connectToSortable: false,
		containment: false,
		cssNamespace: "ui",
		cursor: "default",
		cursorAt: null,
		delay: 0,
		distance: 1,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: 1,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: null
	}
});

$.ui.plugin.add("draggable", "connectToSortable", {
	start: function(event, ui) {

		var inst = $(this).data("draggable");
		inst.sortables = [];
		$(ui.options.connectToSortable).each(function() {
			// 'this' points to a string, and should therefore resolved as query, but instead, if the string is assigned to a variable, it loops through the strings properties,
			// so we have to append '' to make it anonymous again
			$(this+'').each(function() {
				if($.data(this, 'sortable')) {
					var sortable = $.data(this, 'sortable');
					inst.sortables.push({
						instance: sortable,
						shouldRevert: sortable.options.revert
					});
					sortable._refreshItems();	//Do a one-time refresh at start to refresh the containerCache
					sortable._propagate("activate", event, inst);
				}
			});
		});

	},
	stop: function(event, ui) {

		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
		var inst = $(this).data("draggable");

		$.each(inst.sortables, function() {
			if(this.instance.isOver) {
				this.instance.isOver = 0;
				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
				if(this.shouldRevert) this.instance.options.revert = true; //revert here
				this.instance._mouseStop(event);

				//Also propagate receive event, since the sortable is actually receiving a element
				this.instance.element.triggerHandler("sortreceive", [event, $.extend(this.instance._ui(), { sender: inst.element })], this.instance.options["receive"]);

				this.instance.options.helper = this.instance.options._helper;
				
				if(inst.options.helper == 'original') {
					this.instance.currentItem.css({ top: 'auto', left: 'auto' });
				}

			} else {
				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
				this.instance._propagate("deactivate", event, inst);
			}

		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), self = this;

		var checkPos = function(o) {
			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
			var itemHeight = o.height, itemWidth = o.width;
			var itemTop = o.top, itemLeft = o.left;

			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
		};

		$.each(inst.sortables, function(i) {

			if(checkPos.call(inst, this.instance.containerCache)) {

				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
				if(!this.instance.isOver) {
					this.instance.isOver = 1;
					//Now we fake the start of dragging for the sortable instance,
					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
					this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
					this.instance.options.helper = function() { return ui.helper[0]; };

					event.target = this.instance.currentItem[0];
					this.instance._mouseCapture(event, true);
					this.instance._mouseStart(event, true, true);

					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
					this.instance.offset.click.top = inst.offset.click.top;
					this.instance.offset.click.left = inst.offset.click.left;
					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;

					inst._propagate("toSortable", event);

				}

				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
				if(this.instance.currentItem) this.instance._mouseDrag(event);

			} else {

				//If it doesn't intersect with the sortable, and it intersected before,
				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
				if(this.instance.isOver) {
					this.instance.isOver = 0;
					this.instance.cancelHelperRemoval = true;
					this.instance.options.revert = false; //No revert here
					this.instance._mouseStop(event, true);
					this.instance.options.helper = this.instance.options._helper;

					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
					this.instance.currentItem.remove();
					if(this.instance.placeholder) this.instance.placeholder.remove();

					inst._propagate("fromSortable", event);
				}

			};

		});

	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function(event, ui) {
		var t = $('body');
		if (t.css("cursor")) ui.options._cursor = t.css("cursor");
		t.css("cursor", ui.options.cursor);
	},
	stop: function(event, ui) {
		if (ui.options._cursor) $('body').css("cursor", ui.options._cursor);
	}
});

$.ui.plugin.add("draggable", "iframeFix", {
	start: function(event, ui) {
		$(ui.options.iframeFix === true ? "iframe" : ui.options.iframeFix).each(function() {
			$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
			.css({
				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
				position: "absolute", opacity: "0.001", zIndex: 1000
			})
			.css($(this).offset())
			.appendTo("body");
		});
	},
	stop: function(event, ui) {
		$("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function(event, ui) {
		var t = $(ui.helper);
		if(t.css("opacity")) ui.options._opacity = t.css("opacity");
		t.css('opacity', ui.options.opacity);
	},
	stop: function(event, ui) {
		if(ui.options._opacity) $(ui.helper).css('opacity', ui.options._opacity);
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function(event, ui) {
		var o = ui.options;
		var i = $(this).data("draggable");

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();

	},
	drag: function(event, ui) {

		var o = ui.options, scrolled = false;
		var i = $(this).data("draggable");

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {

			if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
				i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
			else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
				i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;

			if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
				i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
			else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
				i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;

		} else {

			if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
				scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
			else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
				scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);

			if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
				scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
			else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
				scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);

		}

		if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(i, event);



		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(scrolled !== false && i.cssPosition == 'absolute' && i.scrollParent[0] != document && $.ui.contains(i.scrollParent[0], i.offsetParent[0])) {
			i.offset.parent = i._getParentOffset();
			
		}
		
		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(scrolled !== false && i.cssPosition == 'relative' && !(i.scrollParent[0] != document && i.scrollParent[0] != i.offsetParent[0])) {
			i.offset.relative = i._getRelativeOffset();
		}
		

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function(event, ui) {

		var inst = $(this).data("draggable");
		inst.snapElements = [];

		$(ui.options.snap.constructor != String ? ( ui.options.snap.items || ':data(draggable)' ) : ui.options.snap).each(function() {
			var $t = $(this); var $o = $t.offset();
			if(this != inst.element[0]) inst.snapElements.push({
				item: this,
				width: $t.outerWidth(), height: $t.outerHeight(),
				top: $o.top, left: $o.left
			});
		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable");
		var d = ui.options.snapTolerance;

		var x1 = ui.absolutePosition.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.absolutePosition.top, y2 = y1 + inst.helperProportions.height;

		for (var i = inst.snapElements.length - 1; i >= 0; i--){

			var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
				t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;

			//Yes, I know, this is insane ;)
			if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
				if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				inst.snapElements[i].snapping = false;
				continue;
			}

			if(ui.options.snapMode != 'inner') {
				var ts = Math.abs(t - y2) <= d;
				var bs = Math.abs(b - y1) <= d;
				var ls = Math.abs(l - x2) <= d;
				var rs = Math.abs(r - x1) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left;
			}

			var first = (ts || bs || ls || rs);

			if(ui.options.snapMode != 'outer') {
				var ts = Math.abs(t - y1) <= d;
				var bs = Math.abs(b - y2) <= d;
				var ls = Math.abs(l - x1) <= d;
				var rs = Math.abs(r - x2) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left;
			}

			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		};

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function(event, ui) {
		var group = $.makeArray($(ui.options.stack.group)).sort(function(a,b) {
			return (parseInt($(a).css("zIndex"),10) || ui.options.stack.min) - (parseInt($(b).css("zIndex"),10) || ui.options.stack.min);
		});

		$(group).each(function(i) {
			this.style.zIndex = ui.options.stack.min + i;
		});

		this[0].style.zIndex = ui.options.stack.min + group.length;
	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function(event, ui) {
		var t = $(ui.helper);
		if(t.css("zIndex")) ui.options._zIndex = t.css("zIndex");
		t.css('zIndex', ui.options.zIndex);
	},
	stop: function(event, ui) {
		if(ui.options._zIndex) $(ui.helper).css('zIndex', ui.options._zIndex);
	}
});

})(jQuery);
/*
 * jQuery UI Resizable 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Resizables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.resizable", $.extend({}, $.ui.mouse, {

	_init: function() {

		var self = this, o = this.options;

		var elpos = this.element.css('position');

		this.originalElement = this.element;

		// simulate .ui-resizable { position: relative; }
		this.element.addClass("ui-resizable").css({ position: /static/.test(elpos) ? 'relative' : elpos });

		$.extend(o, {
			_aspectRatio: !!(o.aspectRatio),
			helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null,
			knobHandles: o.knobHandles === true ? 'ui-resizable-knob-handle' : o.knobHandles
		});

		//Default Theme
		var aBorder = '1px solid #DEDEDE';

		o.defaultTheme = {
			'ui-resizable': { display: 'block' },
			'ui-resizable-handle': { position: 'absolute', background: '#F2F2F2', fontSize: '0.1px' },
			'ui-resizable-n': { cursor: 'n-resize', height: '4px', left: '0px', right: '0px', borderTop: aBorder },
			'ui-resizable-s': { cursor: 's-resize', height: '4px', left: '0px', right: '0px', borderBottom: aBorder },
			'ui-resizable-e': { cursor: 'e-resize', width: '4px', top: '0px', bottom: '0px', borderRight: aBorder },
			'ui-resizable-w': { cursor: 'w-resize', width: '4px', top: '0px', bottom: '0px', borderLeft: aBorder },
			'ui-resizable-se': { cursor: 'se-resize', width: '4px', height: '4px', borderRight: aBorder, borderBottom: aBorder },
			'ui-resizable-sw': { cursor: 'sw-resize', width: '4px', height: '4px', borderBottom: aBorder, borderLeft: aBorder },
			'ui-resizable-ne': { cursor: 'ne-resize', width: '4px', height: '4px', borderRight: aBorder, borderTop: aBorder },
			'ui-resizable-nw': { cursor: 'nw-resize', width: '4px', height: '4px', borderLeft: aBorder, borderTop: aBorder }
		};

		o.knobTheme = {
			'ui-resizable-handle': { background: '#F2F2F2', border: '1px solid #808080', height: '8px', width: '8px' },
			'ui-resizable-n': { cursor: 'n-resize', top: '0px', left: '45%' },
			'ui-resizable-s': { cursor: 's-resize', bottom: '0px', left: '45%' },
			'ui-resizable-e': { cursor: 'e-resize', right: '0px', top: '45%' },
			'ui-resizable-w': { cursor: 'w-resize', left: '0px', top: '45%' },
			'ui-resizable-se': { cursor: 'se-resize', right: '0px', bottom: '0px' },
			'ui-resizable-sw': { cursor: 'sw-resize', left: '0px', bottom: '0px' },
			'ui-resizable-nw': { cursor: 'nw-resize', left: '0px', top: '0px' },
			'ui-resizable-ne': { cursor: 'ne-resize', right: '0px', top: '0px' }
		};

		o._nodeName = this.element[0].nodeName;

		//Wrap the element if it cannot hold child nodes
		if(o._nodeName.match(/canvas|textarea|input|select|button|img/i)) {
			var el = this.element;

			//Opera fixing relative position
			if (/relative/.test(el.css('position')) && $.browser.opera)
				el.css({ position: 'relative', top: 'auto', left: 'auto' });

			//Create a wrapper element and set the wrapper to the new current internal element
			el.wrap(
				$('<div class="ui-wrapper"	style="overflow: hidden;"></div>').css( {
					position: el.css('position'),
					width: el.outerWidth(),
					height: el.outerHeight(),
					top: el.css('top'),
					left: el.css('left')
				})
			);

			var oel = this.element; this.element = this.element.parent();

			// store instance on wrapper
			this.element.data('resizable', this);

			//Move margins to the wrapper
			this.element.css({ marginLeft: oel.css("marginLeft"), marginTop: oel.css("marginTop"),
				marginRight: oel.css("marginRight"), marginBottom: oel.css("marginBottom")
			});

			oel.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});

			//Prevent Safari textarea resize
			if ($.browser.safari && o.preventDefault) oel.css('resize', 'none');

			o.proportionallyResize = oel.css({ position: 'static', zoom: 1, display: 'block' });

			// avoid IE jump
			this.element.css({ margin: oel.css('margin') });

			// fix handlers offset
			this._proportionallyResize();
		}

		if(!o.handles) o.handles = !$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' };
		if(o.handles.constructor == String) {

			o.zIndex = o.zIndex || 1000;

			if(o.handles == 'all') o.handles = 'n,e,s,w,se,sw,ne,nw';

			var n = o.handles.split(","); o.handles = {};

			// insertions are applied when don't have theme loaded
			var insertionsDefault = {
				handle: 'position: absolute; display: none; overflow:hidden;',
				n: 'top: 0pt; width:100%;',
				e: 'right: 0pt; height:100%;',
				s: 'bottom: 0pt; width:100%;',
				w: 'left: 0pt; height:100%;',
				se: 'bottom: 0pt; right: 0px;',
				sw: 'bottom: 0pt; left: 0px;',
				ne: 'top: 0pt; right: 0px;',
				nw: 'top: 0pt; left: 0px;'
			};

			for(var i = 0; i < n.length; i++) {
				var handle = $.trim(n[i]), dt = o.defaultTheme, hname = 'ui-resizable-'+handle, loadDefault = !$.ui.css(hname) && !o.knobHandles, userKnobClass = $.ui.css('ui-resizable-knob-handle'),
							allDefTheme = $.extend(dt[hname], dt['ui-resizable-handle']), allKnobTheme = $.extend(o.knobTheme[hname], !userKnobClass ? o.knobTheme['ui-resizable-handle'] : {});

				// increase zIndex of sw, se, ne, nw axis
				var applyZIndex = /sw|se|ne|nw/.test(handle) ? { zIndex: ++o.zIndex } : {};

				var defCss = (loadDefault ? insertionsDefault[handle] : ''),
					axis = $(['<div class="ui-resizable-handle ', hname, '" style="', defCss, insertionsDefault.handle, '"></div>'].join('')).css( applyZIndex );
				o.handles[handle] = '.ui-resizable-'+handle;

				this.element.append(
					//Theme detection, if not loaded, load o.defaultTheme
					axis.css( loadDefault ? allDefTheme : {} )
						// Load the knobHandle css, fix width, height, top, left...
						.css( o.knobHandles ? allKnobTheme : {} ).addClass(o.knobHandles ? 'ui-resizable-knob-handle' : '').addClass(o.knobHandles)
				);
			}

			if (o.knobHandles) this.element.addClass('ui-resizable-knob').css( !$.ui.css('ui-resizable-knob') ? { /*border: '1px #fff dashed'*/ } : {} );
		}

		this._renderAxis = function(target) {
			target = target || this.element;

			for(var i in o.handles) {
				if(o.handles[i].constructor == String)
					o.handles[i] = $(o.handles[i], this.element).show();

				if (o.transparent)
					o.handles[i].css({opacity:0});

				//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
				if (this.element.is('.ui-wrapper') &&
					o._nodeName.match(/textarea|input|select|button/i)) {

					var axis = $(o.handles[i], this.element), padWrapper = 0;

					//Checking the correct pad and border
					padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();

					//The padding type i have to apply...
					var padPos = [ 'padding',
						/ne|nw|n/.test(i) ? 'Top' :
						/se|sw|s/.test(i) ? 'Bottom' :
						/^e$/.test(i) ? 'Right' : 'Left' ].join("");

					if (!o.transparent)
						target.css(padPos, padWrapper);

					this._proportionallyResize();
				}
				if(!$(o.handles[i]).length) continue;
			}
		};

		this._renderAxis(this.element);
		o._handles = $('.ui-resizable-handle', self.element);

		if (o.disableSelection)
			o._handles.disableSelection();

		//Matching axis name
		o._handles.mouseover(function() {
			if (!o.resizing) {
				if (this.className)
					var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
				//Axis, default = se
				self.axis = o.axis = axis && axis[1] ? axis[1] : 'se';
			}
		});

		//If we want to auto hide the elements
		if (o.autoHide) {
			o._handles.hide();
			$(self.element).addClass("ui-resizable-autohide").hover(function() {
				$(this).removeClass("ui-resizable-autohide");
				o._handles.show();
			},
			function(){
				if (!o.resizing) {
					$(this).addClass("ui-resizable-autohide");
					o._handles.hide();
				}
			});
		}

		this._mouseInit();
	},

	destroy: function() {
		var el = this.element, wrapped = el.children(".ui-resizable").get(0);

		this._mouseDestroy();

		var _destroy = function(exp) {
			$(exp).removeClass("ui-resizable ui-resizable-disabled")
				.removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove();
		};

		_destroy(el);

		if (el.is('.ui-wrapper') && wrapped) {
			el.parent().append(
				$(wrapped).css({
					position: el.css('position'),
					width: el.outerWidth(),
					height: el.outerHeight(),
					top: el.css('top'),
					left: el.css('left')
				})
			).end().remove();

			_destroy(wrapped);
		}
	},

	_mouseCapture: function(event) {

		if(this.options.disabled) return false;

		var handle = false;
		for(var i in this.options.handles) {
			if($(this.options.handles[i])[0] == event.target) handle = true;
		}
		if (!handle) return false;

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options, iniPos = this.element.position(), el = this.element,
			ie6 = $.browser.msie && $.browser.version < 7;
		o.resizing = true;
		o.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() };

		// bugfix #1749
		if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) {

			// sOffset decides if document scrollOffset will be added to the top/left of the resizable element
			var sOffset = $.browser.msie && !o.containment && (/absolute/).test(el.css('position')) && !(/relative/).test(el.parent().css('position'));
			var dscrollt = sOffset ? this.documentScroll.top : 0, dscrolll = sOffset ? this.documentScroll.left : 0;

			el.css({ position: 'absolute', top: (iniPos.top + dscrollt), left: (iniPos.left + dscrolll) });
		}

		//Opera fixing relative position
		if ($.browser.opera && (/relative/).test(el.css('position')))
			el.css({ position: 'relative', top: 'auto', left: 'auto' });

		this._renderProxy();

		var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top'));

		if (o.containment) {
			curleft += $(o.containment).scrollLeft()||0;
			curtop += $(o.containment).scrollTop()||0;
		}

		//Store needed variables
		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };
		this.size = o.helper || ie6 ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalSize = o.helper || ie6 ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalPosition = { left: curleft, top: curtop };
		this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		//Aspect Ratio
		o.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height)||1);

		if (o.preserveCursor) {
		    var cursor = $('.ui-resizable-' + this.axis).css('cursor');
		    $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor);
		}

		this._propagate("start", event);
		return true;
	},

	_mouseDrag: function(event) {

		//Increase performance, avoid regex
		var el = this.helper, o = this.options, props = {},
			self = this, smp = this.originalMousePosition, a = this.axis;

		var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0;
		var trigger = this._change[a];
		if (!trigger) return false;

		// Calculate the attrs that will be change
		var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff;

		if (o._aspectRatio || event.shiftKey)
			data = this._updateRatio(data, event);

		data = this._respectSize(data, event);

		// plugins callbacks need to be called first
		this._propagate("resize", event);

		el.css({
			top: this.position.top + "px", left: this.position.left + "px",
			width: this.size.width + "px", height: this.size.height + "px"
		});

		if (!o.helper && o.proportionallyResize)
			this._proportionallyResize();

		this._updateCache(data);

		// calling the user callback at the end
		this.element.triggerHandler("resize", [event, this.ui()], this.options["resize"]);

		return false;
	},

	_mouseStop: function(event) {

		this.options.resizing = false;
		var o = this.options, self = this;

		if(o.helper) {
			var pr = o.proportionallyResize, ista = pr && (/textarea/i).test(pr.get(0).nodeName),
						soffseth = ista && $.ui.hasScroll(pr.get(0), 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
							soffsetw = ista ? 0 : self.sizeDiff.width;

			var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
				left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
				top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;

			if (!o.animate)
				this.element.css($.extend(s, { top: top, left: left }));

			if (o.helper && !o.animate) this._proportionallyResize();
		}

		if (o.preserveCursor)
			$('body').css('cursor', 'auto');

		this._propagate("stop", event);

		if (o.helper) this.helper.remove();

		return false;
	},

	_updateCache: function(data) {
		var o = this.options;
		this.offset = this.helper.offset();
		if (data.left) this.position.left = data.left;
		if (data.top) this.position.top = data.top;
		if (data.height) this.size.height = data.height;
		if (data.width) this.size.width = data.width;
	},

	_updateRatio: function(data, event) {

		var o = this.options, cpos = this.position, csize = this.size, a = this.axis;

		if (data.height) data.width = (csize.height * o.aspectRatio);
		else if (data.width) data.height = (csize.width / o.aspectRatio);

		if (a == 'sw') {
			data.left = cpos.left + (csize.width - data.width);
			data.top = null;
		}
		if (a == 'nw') {
			data.top = cpos.top + (csize.height - data.height);
			data.left = cpos.left + (csize.width - data.width);
		}

		return data;
	},

	_respectSize: function(data, event) {

		var el = this.helper, o = this.options, pRatio = o._aspectRatio || event.shiftKey, a = this.axis,
				ismaxw = data.width && o.maxWidth && o.maxWidth < data.width, ismaxh = data.height && o.maxHeight && o.maxHeight < data.height,
					isminw = data.width && o.minWidth && o.minWidth > data.width, isminh = data.height && o.minHeight && o.minHeight > data.height;

		if (isminw) data.width = o.minWidth;
		if (isminh) data.height = o.minHeight;
		if (ismaxw) data.width = o.maxWidth;
		if (ismaxh) data.height = o.maxHeight;

		var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height;
		var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);

		if (isminw && cw) data.left = dw - o.minWidth;
		if (ismaxw && cw) data.left = dw - o.maxWidth;
		if (isminh && ch)	data.top = dh - o.minHeight;
		if (ismaxh && ch)	data.top = dh - o.maxHeight;

		// fixing jump error on top/left - bug #2330
		var isNotwh = !data.width && !data.height;
		if (isNotwh && !data.left && data.top) data.top = null;
		else if (isNotwh && !data.top && data.left) data.left = null;

		return data;
	},

	_proportionallyResize: function() {
		var o = this.options;
		if (!o.proportionallyResize) return;
		var prel = o.proportionallyResize, el = this.helper || this.element;

		if (!o.borderDif) {
			var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')],
				p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')];

			o.borderDif = $.map(b, function(v, i) {
				var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0;
				return border + padding;
			});
		}
		prel.css({
			height: (el.height() - o.borderDif[0] - o.borderDif[2]) + "px",
			width: (el.width() - o.borderDif[1] - o.borderDif[3]) + "px"
		});
	},

	_renderProxy: function() {
		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if(o.helper) {
			this.helper = this.helper || $('<div style="overflow:hidden;"></div>');

			// fix ie6 offset
			var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0),
			pxyoffset = ( ie6 ? 2 : -1 );

			this.helper.addClass(o.helper).css({
				width: el.outerWidth() + pxyoffset,
				height: el.outerHeight() + pxyoffset,
				position: 'absolute',
				left: this.elementOffset.left - ie6offset +'px',
				top: this.elementOffset.top - ie6offset +'px',
				zIndex: ++o.zIndex
			});

			this.helper.appendTo("body");

			if (o.disableSelection)
				this.helper.disableSelection();

		} else {
			this.helper = el;
		}
	},

	_change: {
		e: function(event, dx, dy) {
			return { width: this.originalSize.width + dx };
		},
		w: function(event, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function(event, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function(event, dx, dy) {
			return { height: this.originalSize.height + dy };
		},
		se: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
		},
		sw: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
		},
		ne: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
		},
		nw: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
		}
	},

	_propagate: function(n, event) {
		$.ui.plugin.call(this, n, [event, this.ui()]);
		if (n != "resize") this.element.triggerHandler(["resize", n].join(""), [event, this.ui()], this.options[n]);
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			options: this.options,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

}));

$.extend($.ui.resizable, {
	version: "1.6",
	defaults: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		cancel: ":input",
		containment: false,
		disableSelection: true,
		distance: 1,
		delay: 0,
		ghost: false,
		grid: false,
		knobHandles: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,
		preserveCursor: true,
		preventDefault: true,
		proportionallyResize: false,
		transparent: false
	}
});

/*
 * Resizable Extensions
 */

$.ui.plugin.add("resizable", "alsoResize", {

	start: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable"),

		_store = function(exp) {
			$(exp).each(function() {
				$(this).data("resizable-alsoresize", {
					width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10),
					left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10)
				});
			});
		};

		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) {
			if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0];	_store(o.alsoResize); }
			else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); }
		}else{
			_store(o.alsoResize);
		}
	},

	resize: function(event, ui){
		var o = ui.options, self = $(this).data("resizable"), os = self.originalSize, op = self.originalPosition;

		var delta = {
			height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0,
			top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0
		},

		_alsoResize = function(exp, c) {
			$(exp).each(function() {
				var start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left'];

				$.each(css || ['width', 'height', 'top', 'left'], function(i, prop) {
					var sum = (start[prop]||0) + (delta[prop]||0);
					if (sum && sum >= 0)
						style[prop] = sum || null;
				});
				$(this).css(style);
			});
		};

		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) {
			$.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); });
		}else{
			_alsoResize(o.alsoResize);
		}
	},

	stop: function(event, ui){
		$(this).removeData("resizable-alsoresize-start");
	}
});

$.ui.plugin.add("resizable", "animate", {

	stop: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable");

		var pr = o.proportionallyResize, ista = pr && (/textarea/i).test(pr.get(0).nodeName),
						soffseth = ista && $.ui.hasScroll(pr.get(0), 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
							soffsetw = ista ? 0 : self.sizeDiff.width;

		var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
					left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
						top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;

		self.element.animate(
			$.extend(style, top && left ? { top: top, left: left } : {}), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseInt(self.element.css('width'), 10),
						height: parseInt(self.element.css('height'), 10),
						top: parseInt(self.element.css('top'), 10),
						left: parseInt(self.element.css('left'), 10)
					};

					if (pr) pr.css({ width: data.width, height: data.height });

					// propagating resize, and updating values for each animation step
					self._updateCache(data);
					self._propagate("animate", event);

				}
			}
		);
	}

});

$.ui.plugin.add("resizable", "containment", {

	start: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable"), el = self.element;
		var oc = o.containment,	ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
		if (!ce) return;

		self.containerElement = $(ce);

		if (/document/.test(oc) || oc == document) {
			self.containerOffset = { left: 0, top: 0 };
			self.containerPosition = { left: 0, top: 0 };

			self.parentData = {
				element: $(document), left: 0, top: 0,
				width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
			};
		}

		// i'm a node, so compute top, left, right, bottom
		else{
			var element = $(ce), p = [];
			$([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });

			self.containerOffset = element.offset();
			self.containerPosition = element.position();
			self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };

			var co = self.containerOffset, ch = self.containerSize.height,	cw = self.containerSize.width,
						width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);

			self.parentData = {
				element: ce, left: co.left, top: co.top, width: width, height: height
			};
		}
	},

	resize: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable"),
				ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position,
				pRatio = o._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement;

		if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co;

		if (cp.left < (o.helper ? co.left : 0)) {
			self.size.width = self.size.width + (o.helper ? (self.position.left - co.left) : (self.position.left - cop.left));
			if (pRatio) self.size.height = self.size.width / o.aspectRatio;
			self.position.left = o.helper ? co.left : 0;
		}

		if (cp.top < (o.helper ? co.top : 0)) {
			self.size.height = self.size.height + (o.helper ? (self.position.top - co.top) : self.position.top);
			if (pRatio) self.size.width = self.size.height * o.aspectRatio;
			self.position.top = o.helper ? co.top : 0;
		}

		self.offset.left = self.parentData.left+self.position.left;
		self.offset.top = self.parentData.top+self.position.top;

		var woset = Math.abs( (o.helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ),
					hoset = Math.abs( (o.helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height );

		var isParent = self.containerElement.get(0) == self.element.parent().get(0),
		    isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position'));

		if(isParent && isOffsetRelative) woset -= self.parentData.left;

		if (woset + self.size.width >= self.parentData.width) {
			self.size.width = self.parentData.width - woset;
			if (pRatio) self.size.height = self.size.width / o.aspectRatio;
		}

		if (hoset + self.size.height >= self.parentData.height) {
			self.size.height = self.parentData.height - hoset;
			if (pRatio) self.size.width = self.size.height * o.aspectRatio;
		}
	},

	stop: function(event, ui){
		var o = ui.options, self = $(this).data("resizable"), cp = self.position,
				co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement;

		var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height;

		if (o.helper && !o.animate && (/relative/).test(ce.css('position')))
			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });

		if (o.helper && !o.animate && (/static/).test(ce.css('position')))
			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });

	}
});

$.ui.plugin.add("resizable", "ghost", {

	start: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize, cs = self.size;

		if (!pr) self.ghost = self.element.clone();
		else self.ghost = pr.clone();

		self.ghost.css(
			{ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }
		)
		.addClass('ui-resizable-ghost').addClass(typeof o.ghost == 'string' ? o.ghost : '');

		self.ghost.appendTo(self.helper);

	},

	resize: function(event, ui){
		var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize;

		if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width });

	},

	stop: function(event, ui){
		var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize;
		if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0));
	}

});

$.ui.plugin.add("resizable", "grid", {

	resize: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable"), cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey;
		o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid;
		var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1);

		if (/^(se|s|e)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
		}
		else if (/^(ne)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
		}
		else if (/^(sw)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.left = op.left - ox;
		}
		else {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
			self.position.left = op.left - ox;
		}
	}

});

var num = function(v) {
	return parseInt(v, 10) || 0;
};

})(jQuery);
/*
 * jQuery UI Dialog 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 *	ui.resizable.js
 */
(function($) {

var setDataSwitch = {
	dragStart: "start.draggable",
	drag: "drag.draggable",
	dragStop: "stop.draggable",
	maxHeight: "maxHeight.resizable",
	minHeight: "minHeight.resizable",
	maxWidth: "maxWidth.resizable",
	minWidth: "minWidth.resizable",
	resizeStart: "start.resizable",
	resize: "drag.resizable",
	resizeStop: "stop.resizable"
};

$.widget("ui.dialog", {

	_init: function() {
		this.originalTitle = this.element.attr('title');
		this.options.title = this.options.title || this.originalTitle;

		var self = this,
			options = this.options,

			uiDialogContent = this.element
				.removeAttr('title')
				.addClass('ui-dialog-content')
				.wrap('<div></div>')
				.wrap('<div></div>'),

			uiDialogContainer = (this.uiDialogContainer = uiDialogContent.parent())
				.addClass('ui-dialog-container')
				.css({
					position: 'relative',
					width: '100%',
					height: '100%'
				}),

			uiDialogTitlebar = (this.uiDialogTitlebar = $('<div></div>'))
				.addClass('ui-dialog-titlebar')
				.mousedown(function() {
					self.moveToTop();
				})
				.prependTo(uiDialogContainer),

			uiDialogTitlebarClose = $('<a href="#"/>')
				.addClass('ui-dialog-titlebar-close')
				.attr('role', 'button')
				.appendTo(uiDialogTitlebar),

			uiDialogTitlebarCloseText = (this.uiDialogTitlebarCloseText = $('<span/>'))
				.text(options.closeText)
				.appendTo(uiDialogTitlebarClose),

			title = options.title || '&nbsp;',
			titleId = $.ui.dialog.getTitleId(this.element),
			uiDialogTitle = $('<span/>')
				.addClass('ui-dialog-title')
				.attr('id', titleId)
				.html(title)
				.prependTo(uiDialogTitlebar),

			uiDialog = (this.uiDialog = uiDialogContainer.parent())
				.appendTo(document.body)
				.hide()
				.addClass('ui-dialog')
				.addClass(options.dialogClass)
				.css({
					position: 'absolute',
					width: options.width,
					height: options.height,
					overflow: 'hidden',
					zIndex: options.zIndex
				})
				// setting tabIndex makes the div focusable
				// setting outline to 0 prevents a border on focus in Mozilla
				.attr('tabIndex', -1).css('outline', 0).keydown(function(ev) {
					(options.closeOnEscape && ev.keyCode
						&& ev.keyCode == $.ui.keyCode.ESCAPE && self.close());
				})
				.attr({
					role: 'dialog',
					'aria-labelledby': titleId
				})
				.mouseup(function() {
					self.moveToTop();
				}),

			uiDialogButtonPane = (this.uiDialogButtonPane = $('<div></div>'))
				.addClass('ui-dialog-buttonpane')
				.css({
					position: 'absolute',
					bottom: 0
				})
				.appendTo(uiDialog),

			uiDialogTitlebarClose = $('.ui-dialog-titlebar-close', uiDialogTitlebar)
				.hover(
					function() {
						$(this).addClass('ui-dialog-titlebar-close-hover');
					},
					function() {
						$(this).removeClass('ui-dialog-titlebar-close-hover');
					}
				)
				.mousedown(function(ev) {
					ev.stopPropagation();
				})
				.click(function() {
					self.close();
					return false;
				});

		uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection();

		(options.draggable && $.fn.draggable && this._makeDraggable());
		(options.resizable && $.fn.resizable && this._makeResizable());

		this._createButtons(options.buttons);
		this._isOpen = false;

		(options.bgiframe && $.fn.bgiframe && uiDialog.bgiframe());
		(options.autoOpen && this.open());
	},

	destroy: function() {
		(this.overlay && this.overlay.destroy());
		this.uiDialog.hide();
		this.element
			.unbind('.dialog')
			.removeData('dialog')
			.removeClass('ui-dialog-content')
			.hide().appendTo('body');
		this.uiDialog.remove();

		(this.originalTitle && this.element.attr('title', this.originalTitle));
	},

	close: function() {
		if (false === this._trigger('beforeclose', null, { options: this.options })) {
			return;
		}

		(this.overlay && this.overlay.destroy());
		this.uiDialog
			.hide(this.options.hide)
			.unbind('keypress.ui-dialog');

		this._trigger('close', null, { options: this.options });
		$.ui.dialog.overlay.resize();

		this._isOpen = false;
	},

	isOpen: function() {
		return this._isOpen;
	},

	// the force parameter allows us to move modal dialogs to their correct
	// position on open
	moveToTop: function(force) {

		if ((this.options.modal && !force)
			|| (!this.options.stack && !this.options.modal)) {
			return this._trigger('focus', null, { options: this.options });
		}

		var maxZ = this.options.zIndex, options = this.options;
		$('.ui-dialog:visible').each(function() {
			maxZ = Math.max(maxZ, parseInt($(this).css('z-index'), 10) || options.zIndex);
		});
		(this.overlay && this.overlay.$el.css('z-index', ++maxZ));

		//Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed.
		//  http://ui.jquery.com/bugs/ticket/3193
		var saveScroll = { scrollTop: this.element.attr('scrollTop'), scrollLeft: this.element.attr('scrollLeft') };
		this.uiDialog.css('z-index', ++maxZ);
		this.element.attr(saveScroll);
		this._trigger('focus', null, { options: this.options });
	},

	open: function() {
		if (this._isOpen) { return; }

		this.overlay = this.options.modal ? new $.ui.dialog.overlay(this) : null;
		(this.uiDialog.next().length && this.uiDialog.appendTo('body'));
		this._position(this.options.position);
		this.uiDialog.show(this.options.show);
		(this.options.autoResize && this._size());
		this.moveToTop(true);

		// prevent tabbing out of modal dialogs
		(this.options.modal && this.uiDialog.bind('keypress.ui-dialog', function(event) {
			if (event.keyCode != $.ui.keyCode.TAB) {
				return;
			}

			var tabbables = $(':tabbable', this),
				first = tabbables.filter(':first')[0],
				last  = tabbables.filter(':last')[0];

			if (event.target == last && !event.shiftKey) {
				setTimeout(function() {
					first.focus();
				}, 1);
			} else if (event.target == first && event.shiftKey) {
				setTimeout(function() {
					last.focus();
				}, 1);
			}
		}));

		this.uiDialog.find(':tabbable:first').focus();
		this._trigger('open', null, { options: this.options });
		this._isOpen = true;
	},

	_createButtons: function(buttons) {
		var self = this,
			hasButtons = false,
			uiDialogButtonPane = this.uiDialogButtonPane;

		// remove any existing buttons
		uiDialogButtonPane.empty().hide();

		$.each(buttons, function() { return !(hasButtons = true); });
		if (hasButtons) {
			uiDialogButtonPane.show();
			$.each(buttons, function(name, fn) {
				$('<button type="button"></button>')
					.text(name)
					.click(function() { fn.apply(self.element[0], arguments); })
					.appendTo(uiDialogButtonPane);
			});
		}
	},

	_makeDraggable: function() {
		var self = this,
			options = this.options;

		this.uiDialog.draggable({
			cancel: '.ui-dialog-content',
			helper: options.dragHelper,
			handle: '.ui-dialog-titlebar',
			start: function() {
				self.moveToTop();
				(options.dragStart && options.dragStart.apply(self.element[0], arguments));
			},
			drag: function() {
				(options.drag && options.drag.apply(self.element[0], arguments));
			},
			stop: function() {
				(options.dragStop && options.dragStop.apply(self.element[0], arguments));
				$.ui.dialog.overlay.resize();
			}
		});
	},

	_makeResizable: function(handles) {
		handles = (handles === undefined ? this.options.resizable : handles);
		var self = this,
			options = this.options,
			resizeHandles = typeof handles == 'string'
				? handles
				: 'n,e,s,w,se,sw,ne,nw';

		this.uiDialog.resizable({
			cancel: '.ui-dialog-content',
			helper: options.resizeHelper,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: options.minHeight,
			start: function() {
				(options.resizeStart && options.resizeStart.apply(self.element[0], arguments));
			},
			resize: function() {
				(options.autoResize && self._size.apply(self));
				(options.resize && options.resize.apply(self.element[0], arguments));
			},
			handles: resizeHandles,
			stop: function() {
				(options.autoResize && self._size.apply(self));
				(options.resizeStop && options.resizeStop.apply(self.element[0], arguments));
				$.ui.dialog.overlay.resize();
			}
		});
	},

	_position: function(pos) {
		var wnd = $(window), doc = $(document),
			pTop = doc.scrollTop(), pLeft = doc.scrollLeft(),
			minTop = pTop;

		if ($.inArray(pos, ['center','top','right','bottom','left']) >= 0) {
			pos = [
				pos == 'right' || pos == 'left' ? pos : 'center',
				pos == 'top' || pos == 'bottom' ? pos : 'middle'
			];
		}
		if (pos.constructor != Array) {
			pos = ['center', 'middle'];
		}
		if (pos[0].constructor == Number) {
			pLeft += pos[0];
		} else {
			switch (pos[0]) {
				case 'left':
					pLeft += 0;
					break;
				case 'right':
					pLeft += wnd.width() - this.uiDialog.outerWidth();
					break;
				default:
				case 'center':
					pLeft += (wnd.width() - this.uiDialog.outerWidth()) / 2;
			}
		}
		if (pos[1].constructor == Number) {
			pTop += pos[1];
		} else {
			switch (pos[1]) {
				case 'top':
					pTop += 0;
					break;
				case 'bottom':
					// Opera check fixes #3564, can go away with jQuery 1.3
					pTop += ($.browser.opera ? window.innerHeight : wnd.height()) - this.uiDialog.outerHeight();
					break;
				default:
				case 'middle':
					// Opera check fixes #3564, can go away with jQuery 1.3
					pTop += (($.browser.opera ? window.innerHeight : wnd.height()) - this.uiDialog.outerHeight()) / 2;
			}
		}

		// prevent the dialog from being too high (make sure the titlebar
		// is accessible)
		pTop = Math.max(pTop, minTop);
		this.uiDialog.css({top: pTop, left: pLeft});
	},

	_setData: function(key, value){
		(setDataSwitch[key] && this.uiDialog.data(setDataSwitch[key], value));
		switch (key) {
			case "buttons":
				this._createButtons(value);
				break;
			case "closeText":
				this.uiDialogTitlebarCloseText.text(value);
				break;
			case "draggable":
				(value
					? this._makeDraggable()
					: this.uiDialog.draggable('destroy'));
				break;
			case "height":
				this.uiDialog.height(value);
				break;
			case "position":
				this._position(value);
				break;
			case "resizable":
				var uiDialog = this.uiDialog,
					isResizable = this.uiDialog.is(':data(resizable)');

				// currently resizable, becoming non-resizable
				(isResizable && !value && uiDialog.resizable('destroy'));

				// currently resizable, changing handles
				(isResizable && typeof value == 'string' &&
					uiDialog.resizable('option', 'handles', value));

				// currently non-resizable, becoming resizable
				(isResizable || this._makeResizable(value));

				break;
			case "title":
				$(".ui-dialog-title", this.uiDialogTitlebar).html(value || '&nbsp;');
				break;
			case "width":
				this.uiDialog.width(value);
				break;
		}

		$.widget.prototype._setData.apply(this, arguments);
	},

	_size: function() {
		var container = this.uiDialogContainer,
			titlebar = this.uiDialogTitlebar,
			content = this.element,
			tbMargin = (parseInt(content.css('margin-top'), 10) || 0)
				+ (parseInt(content.css('margin-bottom'), 10) || 0),
			lrMargin = (parseInt(content.css('margin-left'), 10) || 0)
				+ (parseInt(content.css('margin-right'), 10) || 0);
		content.height(container.height() - titlebar.outerHeight() - tbMargin);
		content.width(container.width() - lrMargin);
	}

});

$.extend($.ui.dialog, {
	version: "1.6",
	defaults: {
		autoOpen: true,
		autoResize: true,
		bgiframe: false,
		buttons: {},
		closeOnEscape: true,
		closeText: 'close',
		draggable: true,
		height: 200,
		minHeight: 100,
		minWidth: 150,
		modal: false,
		overlay: {},
		position: 'center',
		resizable: true,
		stack: true,
		width: 300,
		zIndex: 1000
	},

	getter: 'isOpen',

	uuid: 0,

	getTitleId: function($el) {
		return 'ui-dialog-title-' + ($el.attr('id') || ++this.uuid);
	},

	overlay: function(dialog) {
		this.$el = $.ui.dialog.overlay.create(dialog);
	}
});

$.extend($.ui.dialog.overlay, {
	instances: [],
	events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
		function(event) { return event + '.dialog-overlay'; }).join(' '),
	create: function(dialog) {
		if (this.instances.length === 0) {
			// prevent use of anchors and inputs
			// we use a setTimeout in case the overlay is created from an
			// event that we're going to be cancelling (see #2804)
			setTimeout(function() {
				$('a, :input').bind($.ui.dialog.overlay.events, function() {
					// allow use of the element if inside a dialog and
					// - there are no modal dialogs
					// - there are modal dialogs, but we are in front of the topmost modal
					var allow = false;
					var $dialog = $(this).parents('.ui-dialog');
					if ($dialog.length) {
						var $overlays = $('.ui-dialog-overlay');
						if ($overlays.length) {
							var maxZ = parseInt($overlays.css('z-index'), 10);
							$overlays.each(function() {
								maxZ = Math.max(maxZ, parseInt($(this).css('z-index'), 10));
							});
							allow = parseInt($dialog.css('z-index'), 10) > maxZ;
						} else {
							allow = true;
						}
					}
					return allow;
				});
			}, 1);

			// allow closing by pressing the escape key
			$(document).bind('keydown.dialog-overlay', function(event) {
				(dialog.options.closeOnEscape && event.keyCode
						&& event.keyCode == $.ui.keyCode.ESCAPE && dialog.close());
			});

			// handle window resize
			$(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
		}

		var $el = $('<div></div>').appendTo(document.body)
			.addClass('ui-dialog-overlay').css($.extend({
				borderWidth: 0, margin: 0, padding: 0,
				position: 'absolute', top: 0, left: 0,
				width: this.width(),
				height: this.height()
			}, dialog.options.overlay));

		(dialog.options.bgiframe && $.fn.bgiframe && $el.bgiframe());

		this.instances.push($el);
		return $el;
	},

	destroy: function($el) {
		this.instances.splice($.inArray(this.instances, $el), 1);

		if (this.instances.length === 0) {
			$('a, :input').add([document, window]).unbind('.dialog-overlay');
		}

		$el.remove();
	},

	height: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollHeight = Math.max(
				document.documentElement.scrollHeight,
				document.body.scrollHeight
			);
			var offsetHeight = Math.max(
				document.documentElement.offsetHeight,
				document.body.offsetHeight
			);

			if (scrollHeight < offsetHeight) {
				return $(window).height() + 'px';
			} else {
				return scrollHeight + 'px';
			}
		// handle Opera
		} else if ($.browser.opera) {
			return Math.max(
				window.innerHeight,
				$(document).height()
			) + 'px';
		// handle "good" browsers
		} else {
			return $(document).height() + 'px';
		}
	},

	width: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollWidth = Math.max(
				document.documentElement.scrollWidth,
				document.body.scrollWidth
			);
			var offsetWidth = Math.max(
				document.documentElement.offsetWidth,
				document.body.offsetWidth
			);

			if (scrollWidth < offsetWidth) {
				return $(window).width() + 'px';
			} else {
				return scrollWidth + 'px';
			}
		// handle Opera
		} else if ($.browser.opera) {
			return Math.max(
				window.innerWidth,
				$(document).width()
			) + 'px';
		// handle "good" browsers
		} else {
			return $(document).width() + 'px';
		}
	},

	resize: function() {
		/* If the dialog is draggable and the user drags it past the
		 * right edge of the window, the document becomes wider so we
		 * need to stretch the overlay. If the user then drags the
		 * dialog back to the left, the document will become narrower,
		 * so we need to shrink the overlay to the appropriate size.
		 * This is handled by shrinking the overlay before setting it
		 * to the full document size.
		 */
		var $overlays = $([]);
		$.each($.ui.dialog.overlay.instances, function() {
			$overlays = $overlays.add(this);
		});

		$overlays.css({
			width: 0,
			height: 0
		}).css({
			width: $.ui.dialog.overlay.width(),
			height: $.ui.dialog.overlay.height()
		});
	}
});

$.extend($.ui.dialog.overlay.prototype, {
	destroy: function() {
		$.ui.dialog.overlay.destroy(this.$el);
	}
});

})(jQuery);
/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}
/*
 * jQuery UI 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;(function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

//Helper functions and ui object
$.ui = {

	version: "1.6",

	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

	contains: function(a, b) {
		var safari2 = $.browser.safari && $.browser.version < 522;
	    if (a.contains && !safari2) {
	        return a.contains(b);
	    }
	    if (a.compareDocumentPosition)
	        return !!(a.compareDocumentPosition(b) & 16);
	    while (b = b.parentNode)
	          if (b == a) return true;
	    return false;
	},

	cssCache: {},
	css: function(name) {
		if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
		var tmp = $('<div class="ui-gen">').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');

		//if (!$.browser.safari)
			//tmp.appendTo('body');

		//Opera and Safari set width and height to 0px instead of auto
		//Safari returns rgba(0,0,0,0) when bgcolor is not set
		$.ui.cssCache[name] = !!(
			(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) ||
			!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
		);
		try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
		return $.ui.cssCache[name];
	},

	hasScroll: function(el, a) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(el).css('overflow') == 'hidden') { return false; }

		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		//Determines when x coordinate is over "b" element axis
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	keyCode: {
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}

};

// WAI-ARIA normalization
if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

//jQuery plugins
$.fn.extend({

	remove: function() {
		// Safari has a native remove event which actually removes DOM elements,
		// so we have to use triggerHandler instead of trigger (#3037).
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {

		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;


	}

});


//Additional selectors
$.extend($.expr[':'], {

	data: function(a, i, m) {
		return $.data(a, m[3]);
	},

	// TODO: add support for object, area
	tabbable: function(a, i, m) {

		var nodeName = a.nodeName.toLowerCase();
		function isVisible(element) {
			return !($(element).is(':hidden') || $(element).parents(':hidden').length);
		}

		return (
			// in tab order
			a.tabIndex >= 0 &&

			( // filter node types that participate in the tab order

				// anchor tag
				('a' == nodeName && a.href) ||

				// enabled form element
				(/input|select|textarea|button/.test(nodeName) &&
					'hidden' != a.type && !a.disabled)
			) &&

			// visible on page
			isVisible(a)
		);

	}

});


// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}

	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options)));

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	// create widget constructor
	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(event, key, value) {
				return self._setData(key, value);
			})
			.bind('getData.' + name, function(event, key) {
				return self._getData(key);
			})
			.bind('remove', function() {
				return self.destroy();
			});

		this._init();
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName);
	},

	option: function(key, value) {
		var options = key,
			self = this;

		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}

		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element[value ? 'addClass' : 'removeClass'](
				this.widgetBaseClass + '-disabled');
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var eventName = (type == this.widgetEventPrefix
			? type : this.widgetEventPrefix + type);
		event = event || $.event.fix({ type: eventName, target: this.element[0] });
		return this.element.triggerHandler(eventName, [event, data], this.options[type]);
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					return false;
				}
			});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		if(!$.browser.safari) event.preventDefault();
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = true;
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
/*
 * jQuery UI Draggable 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.draggable", $.extend({}, $.ui.mouse, {

	_init: function() {

		if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
			this.element[0].style.position = 'relative';

		(this.options.cssNamespace && this.element.addClass(this.options.cssNamespace+"-draggable"));
		(this.options.disabled && this.element.addClass('ui-draggable-disabled'));

		this._mouseInit();

	},

	destroy: function() {
		if(!this.element.data('draggable')) return;
		this.element.removeData("draggable").unbind(".draggable").removeClass('ui-draggable ui-draggable-dragging ui-draggable-disabled');
		this._mouseDestroy();
	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle'))
			return false;

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle)
			return false;

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css("position");
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.element.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		if(o.cursorAt)
			this._adjustOffsetFromHelper(o.cursorAt);

		//Generate the original position
		this.originalPosition = this._generatePosition(event);

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		//Call plugins and callbacks
		this._propagate("start", event);

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.helper.addClass("ui-draggable-dragging");
		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;
	},

	_mouseDrag: function(event, noPropagation) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if(!noPropagation) this.position = this._propagate("drag", event) || this.position;

		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			var dropped = $.ui.ddmanager.drop(this, event);

		if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			var self = this;
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				self._propagate("stop", event);
				self._clear();
			});
		} else {
			this._propagate("stop", event);
			this._clear();
		}

		return false;
	},

	_getHandle: function(event) {

		var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
		$(this.options.handle, this.element)
			.find("*")
			.andSelf()
			.each(function() {
				if(this == event.target) handle = true;
			});

		return handle;

	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone() : this.element);

		if(!helper.parents('body').length)
			helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

		if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
			helper.css("position", "absolute");

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
		if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
		if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
	},

	_getParentOffset: function() {

		this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset();			//Get the offsetParent and cache its position

		if((this.offsetParent[0] == document.body && $.browser.mozilla)	//Ugly FF3 fix
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.element.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"),10) || 0),
			top: (parseInt(this.element.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			0 - this.offset.relative.left - this.offset.parent.left,
			0 - this.offset.relative.top - this.offset.parent.top,
			$(o.containment == 'document' ? document : window).width() - this.offset.relative.left - this.offset.parent.left - this.helperProportions.width - this.margins.left - (parseInt(this.element.css("marginRight"),10) || 0),
			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.offset.relative.top - this.offset.parent.top - this.helperProportions.height - this.margins.top - (parseInt(this.element.css("marginBottom"),10) || 0)
		];

		if(!(/^(document|window|parent)$/).test(o.containment)) {
			var ce = $(o.containment)[0];
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top - this.helperProportions.height - this.margins.top
			];
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var scroll = this[(this.cssPosition == 'absolute' ? 'offset' : 'scroll')+'Parent'], scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// the calculated relative position
				+ this.offset.relative.top	* mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod
				+ this.margins.top * mod												//Add the margin (you don't want the margin counting in intersection methods)
			),
			left: (
				pos.left																// the calculated relative position
				+ this.offset.relative.left	* mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : ( scrollIsRootNode ? 0 : scroll.scrollLeft() ) ) * mod
				+ this.margins.left * mod												//Add the margin (you don't want the margin counting in intersection methods)
			)
		};
	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this[(this.cssPosition == 'absolute' ? 'offset' : 'scroll')+'Parent'], scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		var position = {
			top: (
				event.pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )
			),
			left: (
				event.pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )
			)
		};

		if(!this.originalPosition) return position;										//If we are not dragging yet, we won't check for options

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */
		if(this.containment) {
			if(position.left < this.containment[0]) position.left = this.containment[0];
			if(position.top < this.containment[1]) position.top = this.containment[1];
			if(position.left > this.containment[2]) position.left = this.containment[2];
			if(position.top > this.containment[3]) position.top = this.containment[3];
		}

		if(o.grid) {
			var top = this.originalPosition.top + Math.round((position.top - this.originalPosition.top) / o.grid[1]) * o.grid[1];
			position.top = this.containment ? (!(top < this.containment[1] || top > this.containment[3]) ? top : (!(top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

			var left = this.originalPosition.left + Math.round((position.left - this.originalPosition.left) / o.grid[0]) * o.grid[0];
			position.left = this.containment ? (!(left < this.containment[0] || left > this.containment[2]) ? left : (!(left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
		}

		return position;
	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove();
		//if($.ui.ddmanager) $.ui.ddmanager.current = null;
		this.helper = null;
		this.cancelHelperRemoval = false;
	},

	// From now on bulk stuff - mainly helpers

	_propagate: function(n, event) {
		$.ui.plugin.call(this, n, [event, this._uiHash()]);
		if(n == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
		return this.element.triggerHandler(n == "drag" ? n : "drag"+n, [event, this._uiHash()], this.options[n]);
	},

	plugins: {},

	_uiHash: function(event) {
		return {
			helper: this.helper,
			position: this.position,
			absolutePosition: this.positionAbs,
			options: this.options
		};
	}

}));

$.extend($.ui.draggable, {
	version: "1.6",
	defaults: {
		appendTo: "parent",
		axis: false,
		cancel: ":input",
		connectToSortable: false,
		containment: false,
		cssNamespace: "ui",
		cursor: "default",
		cursorAt: null,
		delay: 0,
		distance: 1,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: 1,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: null
	}
});

$.ui.plugin.add("draggable", "connectToSortable", {
	start: function(event, ui) {

		var inst = $(this).data("draggable");
		inst.sortables = [];
		$(ui.options.connectToSortable).each(function() {
			// 'this' points to a string, and should therefore resolved as query, but instead, if the string is assigned to a variable, it loops through the strings properties,
			// so we have to append '' to make it anonymous again
			$(this+'').each(function() {
				if($.data(this, 'sortable')) {
					var sortable = $.data(this, 'sortable');
					inst.sortables.push({
						instance: sortable,
						shouldRevert: sortable.options.revert
					});
					sortable._refreshItems();	//Do a one-time refresh at start to refresh the containerCache
					sortable._propagate("activate", event, inst);
				}
			});
		});

	},
	stop: function(event, ui) {

		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
		var inst = $(this).data("draggable");

		$.each(inst.sortables, function() {
			if(this.instance.isOver) {
				this.instance.isOver = 0;
				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
				if(this.shouldRevert) this.instance.options.revert = true; //revert here
				this.instance._mouseStop(event);

				//Also propagate receive event, since the sortable is actually receiving a element
				this.instance.element.triggerHandler("sortreceive", [event, $.extend(this.instance._ui(), { sender: inst.element })], this.instance.options["receive"]);

				this.instance.options.helper = this.instance.options._helper;
				
				if(inst.options.helper == 'original') {
					this.instance.currentItem.css({ top: 'auto', left: 'auto' });
				}

			} else {
				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
				this.instance._propagate("deactivate", event, inst);
			}

		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), self = this;

		var checkPos = function(o) {
			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
			var itemHeight = o.height, itemWidth = o.width;
			var itemTop = o.top, itemLeft = o.left;

			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
		};

		$.each(inst.sortables, function(i) {

			if(checkPos.call(inst, this.instance.containerCache)) {

				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
				if(!this.instance.isOver) {
					this.instance.isOver = 1;
					//Now we fake the start of dragging for the sortable instance,
					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
					this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
					this.instance.options.helper = function() { return ui.helper[0]; };

					event.target = this.instance.currentItem[0];
					this.instance._mouseCapture(event, true);
					this.instance._mouseStart(event, true, true);

					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
					this.instance.offset.click.top = inst.offset.click.top;
					this.instance.offset.click.left = inst.offset.click.left;
					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;

					inst._propagate("toSortable", event);

				}

				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
				if(this.instance.currentItem) this.instance._mouseDrag(event);

			} else {

				//If it doesn't intersect with the sortable, and it intersected before,
				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
				if(this.instance.isOver) {
					this.instance.isOver = 0;
					this.instance.cancelHelperRemoval = true;
					this.instance.options.revert = false; //No revert here
					this.instance._mouseStop(event, true);
					this.instance.options.helper = this.instance.options._helper;

					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
					this.instance.currentItem.remove();
					if(this.instance.placeholder) this.instance.placeholder.remove();

					inst._propagate("fromSortable", event);
				}

			};

		});

	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function(event, ui) {
		var t = $('body');
		if (t.css("cursor")) ui.options._cursor = t.css("cursor");
		t.css("cursor", ui.options.cursor);
	},
	stop: function(event, ui) {
		if (ui.options._cursor) $('body').css("cursor", ui.options._cursor);
	}
});

$.ui.plugin.add("draggable", "iframeFix", {
	start: function(event, ui) {
		$(ui.options.iframeFix === true ? "iframe" : ui.options.iframeFix).each(function() {
			$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
			.css({
				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
				position: "absolute", opacity: "0.001", zIndex: 1000
			})
			.css($(this).offset())
			.appendTo("body");
		});
	},
	stop: function(event, ui) {
		$("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function(event, ui) {
		var t = $(ui.helper);
		if(t.css("opacity")) ui.options._opacity = t.css("opacity");
		t.css('opacity', ui.options.opacity);
	},
	stop: function(event, ui) {
		if(ui.options._opacity) $(ui.helper).css('opacity', ui.options._opacity);
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function(event, ui) {
		var o = ui.options;
		var i = $(this).data("draggable");

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();

	},
	drag: function(event, ui) {

		var o = ui.options, scrolled = false;
		var i = $(this).data("draggable");

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {

			if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
				i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
			else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
				i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;

			if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
				i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
			else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
				i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;

		} else {

			if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
				scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
			else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
				scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);

			if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
				scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
			else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
				scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);

		}

		if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(i, event);



		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(scrolled !== false && i.cssPosition == 'absolute' && i.scrollParent[0] != document && $.ui.contains(i.scrollParent[0], i.offsetParent[0])) {
			i.offset.parent = i._getParentOffset();
			
		}
		
		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(scrolled !== false && i.cssPosition == 'relative' && !(i.scrollParent[0] != document && i.scrollParent[0] != i.offsetParent[0])) {
			i.offset.relative = i._getRelativeOffset();
		}
		

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function(event, ui) {

		var inst = $(this).data("draggable");
		inst.snapElements = [];

		$(ui.options.snap.constructor != String ? ( ui.options.snap.items || ':data(draggable)' ) : ui.options.snap).each(function() {
			var $t = $(this); var $o = $t.offset();
			if(this != inst.element[0]) inst.snapElements.push({
				item: this,
				width: $t.outerWidth(), height: $t.outerHeight(),
				top: $o.top, left: $o.left
			});
		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable");
		var d = ui.options.snapTolerance;

		var x1 = ui.absolutePosition.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.absolutePosition.top, y2 = y1 + inst.helperProportions.height;

		for (var i = inst.snapElements.length - 1; i >= 0; i--){

			var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
				t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;

			//Yes, I know, this is insane ;)
			if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
				if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				inst.snapElements[i].snapping = false;
				continue;
			}

			if(ui.options.snapMode != 'inner') {
				var ts = Math.abs(t - y2) <= d;
				var bs = Math.abs(b - y1) <= d;
				var ls = Math.abs(l - x2) <= d;
				var rs = Math.abs(r - x1) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left;
			}

			var first = (ts || bs || ls || rs);

			if(ui.options.snapMode != 'outer') {
				var ts = Math.abs(t - y1) <= d;
				var bs = Math.abs(b - y2) <= d;
				var ls = Math.abs(l - x1) <= d;
				var rs = Math.abs(r - x2) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left;
			}

			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		};

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function(event, ui) {
		var group = $.makeArray($(ui.options.stack.group)).sort(function(a,b) {
			return (parseInt($(a).css("zIndex"),10) || ui.options.stack.min) - (parseInt($(b).css("zIndex"),10) || ui.options.stack.min);
		});

		$(group).each(function(i) {
			this.style.zIndex = ui.options.stack.min + i;
		});

		this[0].style.zIndex = ui.options.stack.min + group.length;
	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function(event, ui) {
		var t = $(ui.helper);
		if(t.css("zIndex")) ui.options._zIndex = t.css("zIndex");
		t.css('zIndex', ui.options.zIndex);
	},
	stop: function(event, ui) {
		if(ui.options._zIndex) $(ui.helper).css('zIndex', ui.options._zIndex);
	}
});

})(jQuery);
/*
 * jQuery UI Droppable 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Droppables
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 */
(function($) {

$.widget("ui.droppable", {

	_init: function() {

		var o = this.options, accept = o.accept;
		this.isover = 0; this.isout = 1;

		this.options.accept = this.options.accept && $.isFunction(this.options.accept) ? this.options.accept : function(d) {
			return d.is(accept);
		};

		//Store the droppable's proportions
		this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };

		// Add the reference and positions to the manager
		$.ui.ddmanager.droppables[this.options.scope] = $.ui.ddmanager.droppables[this.options.scope] || [];
		$.ui.ddmanager.droppables[this.options.scope].push(this);

		(this.options.cssNamespace && this.element.addClass(this.options.cssNamespace+"-droppable"));

	},

	destroy: function() {
		var drop = $.ui.ddmanager.droppables[this.options.scope];
		for ( var i = 0; i < drop.length; i++ )
			if ( drop[i] == this )
				drop.splice(i, 1);

		this.element
			.removeClass("ui-droppable-disabled")
			.removeData("droppable")
			.unbind(".droppable");
	},

	_setData: function(key, value) {

		if(key == 'accept') {
			this.options.accept = value && $.isFunction(value) ? value : function(d) {
				return d.is(accept);
			};
		} else {
			$.widget.prototype._setData.apply(this, arguments);
		}

	},

	_activate: function(event) {

		var draggable = $.ui.ddmanager.current;
		$.ui.plugin.call(this, 'activate', [event, this.ui(draggable)]);
		if(draggable) this.element.triggerHandler("dropactivate", [event, this.ui(draggable)], this.options.activate);

	},

	_deactivate: function(event) {

		var draggable = $.ui.ddmanager.current;
		$.ui.plugin.call(this, 'deactivate', [event, this.ui(draggable)]);
		if(draggable) this.element.triggerHandler("dropdeactivate", [event, this.ui(draggable)], this.options.deactivate);

	},

	_over: function(event) {

		var draggable = $.ui.ddmanager.current;
		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element

		if (this.options.accept.call(this.element,(draggable.currentItem || draggable.element))) {
			$.ui.plugin.call(this, 'over', [event, this.ui(draggable)]);
			this.element.triggerHandler("dropover", [event, this.ui(draggable)], this.options.over);
		}

	},

	_out: function(event) {

		var draggable = $.ui.ddmanager.current;
		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element

		if (this.options.accept.call(this.element,(draggable.currentItem || draggable.element))) {
			$.ui.plugin.call(this, 'out', [event, this.ui(draggable)]);
			this.element.triggerHandler("dropout", [event, this.ui(draggable)], this.options.out);
		}

	},

	_drop: function(event,custom) {

		var draggable = custom || $.ui.ddmanager.current;
		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element

		var childrenIntersection = false;
		this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() {
			var inst = $.data(this, 'droppable');
			if(inst.options.greedy && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)) {
				childrenIntersection = true; return false;
			}
		});
		if(childrenIntersection) return false;

		if(this.options.accept.call(this.element,(draggable.currentItem || draggable.element))) {
			$.ui.plugin.call(this, 'drop', [event, this.ui(draggable)]);
			this.element.triggerHandler("drop", [event, this.ui(draggable)], this.options.drop);
			return this.element;
		}

		return false;

	},

	plugins: {},

	ui: function(c) {
		return {
			draggable: (c.currentItem || c.element),
			helper: c.helper,
			position: c.position,
			absolutePosition: c.positionAbs,
			options: this.options,
			element: this.element
		};
	}

});

$.extend($.ui.droppable, {
	version: "1.6",
	defaults: {
		accept: '*',
		activeClass: null,
		cssNamespace: 'ui',
		greedy: false,
		hoverClass: null,
		scope: 'default',
		tolerance: 'intersect'
	}
});

$.ui.intersect = function(draggable, droppable, toleranceMode) {

	if (!droppable.offset) return false;

	var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
		y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height;
	var l = droppable.offset.left, r = l + droppable.proportions.width,
		t = droppable.offset.top, b = t + droppable.proportions.height;

	switch (toleranceMode) {
		case 'fit':
			return (l < x1 && x2 < r
				&& t < y1 && y2 < b);
			break;
		case 'intersect':
			return (l < x1 + (draggable.helperProportions.width / 2) // Right Half
				&& x2 - (draggable.helperProportions.width / 2) < r // Left Half
				&& t < y1 + (draggable.helperProportions.height / 2) // Bottom Half
				&& y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
			break;
		case 'pointer':
			var draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left),
				draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top),
				isOver = $.ui.isOver(draggableTop, draggableLeft, t, l, droppable.proportions.height, droppable.proportions.width);
			return isOver;
			break;
		case 'touch':
			return (
					(y1 >= t && y1 <= b) ||	// Top edge touching
					(y2 >= t && y2 <= b) ||	// Bottom edge touching
					(y1 < t && y2 > b)		// Surrounded vertically
				) && (
					(x1 >= l && x1 <= r) ||	// Left edge touching
					(x2 >= l && x2 <= r) ||	// Right edge touching
					(x1 < l && x2 > r)		// Surrounded horizontally
				);
			break;
		default:
			return false;
			break;
		}

};

/*
	This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
	current: null,
	droppables: { 'default': [] },
	prepareOffsets: function(t, event) {

		var m = $.ui.ddmanager.droppables[t.options.scope];
		var type = event ? event.type : null; // workaround for #2317
		var list = (t.currentItem || t.element).find(":data(droppable)").andSelf();

		droppablesLoop: for (var i = 0; i < m.length; i++) {

			if(m[i].options.disabled || (t && !m[i].options.accept.call(m[i].element,(t.currentItem || t.element)))) continue;	//No disabled and non-accepted
			for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item
			m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; 									//If the element is not visible, continue

			m[i].offset = m[i].element.offset();
			m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight };

			if(type == "dragstart" || type == "sortactivate") m[i]._activate.call(m[i], event); 										//Activate the droppable if used directly from draggables

		}

	},
	drop: function(draggable, event) {

		var dropped = false;
		$.each($.ui.ddmanager.droppables[draggable.options.scope], function() {

			if(!this.options) return;
			if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance))
				dropped = this._drop.call(this, event);

			if (!this.options.disabled && this.visible && this.options.accept.call(this.element,(draggable.currentItem || draggable.element))) {
				this.isout = 1; this.isover = 0;
				this._deactivate.call(this, event);
			}

		});
		return dropped;

	},
	drag: function(draggable, event) {

		//If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
		if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event);

		//Run through all droppables and check their positions based on specific tolerance options

		$.each($.ui.ddmanager.droppables[draggable.options.scope], function() {

			if(this.options.disabled || this.greedyChild || !this.visible) return;
			var intersects = $.ui.intersect(draggable, this, this.options.tolerance);

			var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null);
			if(!c) return;

			var parentInstance;
			if (this.options.greedy) {
				var parent = this.element.parents(':data(droppable):eq(0)');
				if (parent.length) {
					parentInstance = $.data(parent[0], 'droppable');
					parentInstance.greedyChild = (c == 'isover' ? 1 : 0);
				}
			}

			// we just moved into a greedy child
			if (parentInstance && c == 'isover') {
				parentInstance['isover'] = 0;
				parentInstance['isout'] = 1;
				parentInstance._out.call(parentInstance, event);
			}

			this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0;
			this[c == "isover" ? "_over" : "_out"].call(this, event);

			// we just moved out of a greedy child
			if (parentInstance && c == 'isout') {
				parentInstance['isout'] = 0;
				parentInstance['isover'] = 1;
				parentInstance._over.call(parentInstance, event);
			}
		});

	}
};

/*
 * Droppable Extensions
 */

$.ui.plugin.add("droppable", "activeClass", {
	activate: function(event, ui) {
		$(this).addClass(ui.options.activeClass);
	},
	deactivate: function(event, ui) {
		$(this).removeClass(ui.options.activeClass);
	},
	drop: function(event, ui) {
		$(this).removeClass(ui.options.activeClass);
	}
});

$.ui.plugin.add("droppable", "hoverClass", {
	over: function(event, ui) {
		$(this).addClass(ui.options.hoverClass);
	},
	out: function(event, ui) {
		$(this).removeClass(ui.options.hoverClass);
	},
	drop: function(event, ui) {
		$(this).removeClass(ui.options.hoverClass);
	}
});

})(jQuery);
/*
 * jQuery UI Resizable 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Resizables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.resizable", $.extend({}, $.ui.mouse, {

	_init: function() {

		var self = this, o = this.options;

		var elpos = this.element.css('position');

		this.originalElement = this.element;

		// simulate .ui-resizable { position: relative; }
		this.element.addClass("ui-resizable").css({ position: /static/.test(elpos) ? 'relative' : elpos });

		$.extend(o, {
			_aspectRatio: !!(o.aspectRatio),
			helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null,
			knobHandles: o.knobHandles === true ? 'ui-resizable-knob-handle' : o.knobHandles
		});

		//Default Theme
		var aBorder = '1px solid #DEDEDE';

		o.defaultTheme = {
			'ui-resizable': { display: 'block' },
			'ui-resizable-handle': { position: 'absolute', background: '#F2F2F2', fontSize: '0.1px' },
			'ui-resizable-n': { cursor: 'n-resize', height: '4px', left: '0px', right: '0px', borderTop: aBorder },
			'ui-resizable-s': { cursor: 's-resize', height: '4px', left: '0px', right: '0px', borderBottom: aBorder },
			'ui-resizable-e': { cursor: 'e-resize', width: '4px', top: '0px', bottom: '0px', borderRight: aBorder },
			'ui-resizable-w': { cursor: 'w-resize', width: '4px', top: '0px', bottom: '0px', borderLeft: aBorder },
			'ui-resizable-se': { cursor: 'se-resize', width: '4px', height: '4px', borderRight: aBorder, borderBottom: aBorder },
			'ui-resizable-sw': { cursor: 'sw-resize', width: '4px', height: '4px', borderBottom: aBorder, borderLeft: aBorder },
			'ui-resizable-ne': { cursor: 'ne-resize', width: '4px', height: '4px', borderRight: aBorder, borderTop: aBorder },
			'ui-resizable-nw': { cursor: 'nw-resize', width: '4px', height: '4px', borderLeft: aBorder, borderTop: aBorder }
		};

		o.knobTheme = {
			'ui-resizable-handle': { background: '#F2F2F2', border: '1px solid #808080', height: '8px', width: '8px' },
			'ui-resizable-n': { cursor: 'n-resize', top: '0px', left: '45%' },
			'ui-resizable-s': { cursor: 's-resize', bottom: '0px', left: '45%' },
			'ui-resizable-e': { cursor: 'e-resize', right: '0px', top: '45%' },
			'ui-resizable-w': { cursor: 'w-resize', left: '0px', top: '45%' },
			'ui-resizable-se': { cursor: 'se-resize', right: '0px', bottom: '0px' },
			'ui-resizable-sw': { cursor: 'sw-resize', left: '0px', bottom: '0px' },
			'ui-resizable-nw': { cursor: 'nw-resize', left: '0px', top: '0px' },
			'ui-resizable-ne': { cursor: 'ne-resize', right: '0px', top: '0px' }
		};

		o._nodeName = this.element[0].nodeName;

		//Wrap the element if it cannot hold child nodes
		if(o._nodeName.match(/canvas|textarea|input|select|button|img/i)) {
			var el = this.element;

			//Opera fixing relative position
			if (/relative/.test(el.css('position')) && $.browser.opera)
				el.css({ position: 'relative', top: 'auto', left: 'auto' });

			//Create a wrapper element and set the wrapper to the new current internal element
			el.wrap(
				$('<div class="ui-wrapper"	style="overflow: hidden;"></div>').css( {
					position: el.css('position'),
					width: el.outerWidth(),
					height: el.outerHeight(),
					top: el.css('top'),
					left: el.css('left')
				})
			);

			var oel = this.element; this.element = this.element.parent();

			// store instance on wrapper
			this.element.data('resizable', this);

			//Move margins to the wrapper
			this.element.css({ marginLeft: oel.css("marginLeft"), marginTop: oel.css("marginTop"),
				marginRight: oel.css("marginRight"), marginBottom: oel.css("marginBottom")
			});

			oel.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});

			//Prevent Safari textarea resize
			if ($.browser.safari && o.preventDefault) oel.css('resize', 'none');

			o.proportionallyResize = oel.css({ position: 'static', zoom: 1, display: 'block' });

			// avoid IE jump
			this.element.css({ margin: oel.css('margin') });

			// fix handlers offset
			this._proportionallyResize();
		}

		if(!o.handles) o.handles = !$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' };
		if(o.handles.constructor == String) {

			o.zIndex = o.zIndex || 1000;

			if(o.handles == 'all') o.handles = 'n,e,s,w,se,sw,ne,nw';

			var n = o.handles.split(","); o.handles = {};

			// insertions are applied when don't have theme loaded
			var insertionsDefault = {
				handle: 'position: absolute; display: none; overflow:hidden;',
				n: 'top: 0pt; width:100%;',
				e: 'right: 0pt; height:100%;',
				s: 'bottom: 0pt; width:100%;',
				w: 'left: 0pt; height:100%;',
				se: 'bottom: 0pt; right: 0px;',
				sw: 'bottom: 0pt; left: 0px;',
				ne: 'top: 0pt; right: 0px;',
				nw: 'top: 0pt; left: 0px;'
			};

			for(var i = 0; i < n.length; i++) {
				var handle = $.trim(n[i]), dt = o.defaultTheme, hname = 'ui-resizable-'+handle, loadDefault = !$.ui.css(hname) && !o.knobHandles, userKnobClass = $.ui.css('ui-resizable-knob-handle'),
							allDefTheme = $.extend(dt[hname], dt['ui-resizable-handle']), allKnobTheme = $.extend(o.knobTheme[hname], !userKnobClass ? o.knobTheme['ui-resizable-handle'] : {});

				// increase zIndex of sw, se, ne, nw axis
				var applyZIndex = /sw|se|ne|nw/.test(handle) ? { zIndex: ++o.zIndex } : {};

				var defCss = (loadDefault ? insertionsDefault[handle] : ''),
					axis = $(['<div class="ui-resizable-handle ', hname, '" style="', defCss, insertionsDefault.handle, '"></div>'].join('')).css( applyZIndex );
				o.handles[handle] = '.ui-resizable-'+handle;

				this.element.append(
					//Theme detection, if not loaded, load o.defaultTheme
					axis.css( loadDefault ? allDefTheme : {} )
						// Load the knobHandle css, fix width, height, top, left...
						.css( o.knobHandles ? allKnobTheme : {} ).addClass(o.knobHandles ? 'ui-resizable-knob-handle' : '').addClass(o.knobHandles)
				);
			}

			if (o.knobHandles) this.element.addClass('ui-resizable-knob').css( !$.ui.css('ui-resizable-knob') ? { /*border: '1px #fff dashed'*/ } : {} );
		}

		this._renderAxis = function(target) {
			target = target || this.element;

			for(var i in o.handles) {
				if(o.handles[i].constructor == String)
					o.handles[i] = $(o.handles[i], this.element).show();

				if (o.transparent)
					o.handles[i].css({opacity:0});

				//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
				if (this.element.is('.ui-wrapper') &&
					o._nodeName.match(/textarea|input|select|button/i)) {

					var axis = $(o.handles[i], this.element), padWrapper = 0;

					//Checking the correct pad and border
					padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();

					//The padding type i have to apply...
					var padPos = [ 'padding',
						/ne|nw|n/.test(i) ? 'Top' :
						/se|sw|s/.test(i) ? 'Bottom' :
						/^e$/.test(i) ? 'Right' : 'Left' ].join("");

					if (!o.transparent)
						target.css(padPos, padWrapper);

					this._proportionallyResize();
				}
				if(!$(o.handles[i]).length) continue;
			}
		};

		this._renderAxis(this.element);
		o._handles = $('.ui-resizable-handle', self.element);

		if (o.disableSelection)
			o._handles.disableSelection();

		//Matching axis name
		o._handles.mouseover(function() {
			if (!o.resizing) {
				if (this.className)
					var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
				//Axis, default = se
				self.axis = o.axis = axis && axis[1] ? axis[1] : 'se';
			}
		});

		//If we want to auto hide the elements
		if (o.autoHide) {
			o._handles.hide();
			$(self.element).addClass("ui-resizable-autohide").hover(function() {
				$(this).removeClass("ui-resizable-autohide");
				o._handles.show();
			},
			function(){
				if (!o.resizing) {
					$(this).addClass("ui-resizable-autohide");
					o._handles.hide();
				}
			});
		}

		this._mouseInit();
	},

	destroy: function() {
		var el = this.element, wrapped = el.children(".ui-resizable").get(0);

		this._mouseDestroy();

		var _destroy = function(exp) {
			$(exp).removeClass("ui-resizable ui-resizable-disabled")
				.removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove();
		};

		_destroy(el);

		if (el.is('.ui-wrapper') && wrapped) {
			el.parent().append(
				$(wrapped).css({
					position: el.css('position'),
					width: el.outerWidth(),
					height: el.outerHeight(),
					top: el.css('top'),
					left: el.css('left')
				})
			).end().remove();

			_destroy(wrapped);
		}
	},

	_mouseCapture: function(event) {

		if(this.options.disabled) return false;

		var handle = false;
		for(var i in this.options.handles) {
			if($(this.options.handles[i])[0] == event.target) handle = true;
		}
		if (!handle) return false;

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options, iniPos = this.element.position(), el = this.element,
			ie6 = $.browser.msie && $.browser.version < 7;
		o.resizing = true;
		o.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() };

		// bugfix #1749
		if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) {

			// sOffset decides if document scrollOffset will be added to the top/left of the resizable element
			var sOffset = $.browser.msie && !o.containment && (/absolute/).test(el.css('position')) && !(/relative/).test(el.parent().css('position'));
			var dscrollt = sOffset ? this.documentScroll.top : 0, dscrolll = sOffset ? this.documentScroll.left : 0;

			el.css({ position: 'absolute', top: (iniPos.top + dscrollt), left: (iniPos.left + dscrolll) });
		}

		//Opera fixing relative position
		if ($.browser.opera && (/relative/).test(el.css('position')))
			el.css({ position: 'relative', top: 'auto', left: 'auto' });

		this._renderProxy();

		var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top'));

		if (o.containment) {
			curleft += $(o.containment).scrollLeft()||0;
			curtop += $(o.containment).scrollTop()||0;
		}

		//Store needed variables
		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };
		this.size = o.helper || ie6 ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalSize = o.helper || ie6 ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalPosition = { left: curleft, top: curtop };
		this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		//Aspect Ratio
		o.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height)||1);

		if (o.preserveCursor) {
		    var cursor = $('.ui-resizable-' + this.axis).css('cursor');
		    $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor);
		}

		this._propagate("start", event);
		return true;
	},

	_mouseDrag: function(event) {

		//Increase performance, avoid regex
		var el = this.helper, o = this.options, props = {},
			self = this, smp = this.originalMousePosition, a = this.axis;

		var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0;
		var trigger = this._change[a];
		if (!trigger) return false;

		// Calculate the attrs that will be change
		var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff;

		if (o._aspectRatio || event.shiftKey)
			data = this._updateRatio(data, event);

		data = this._respectSize(data, event);

		// plugins callbacks need to be called first
		this._propagate("resize", event);

		el.css({
			top: this.position.top + "px", left: this.position.left + "px",
			width: this.size.width + "px", height: this.size.height + "px"
		});

		if (!o.helper && o.proportionallyResize)
			this._proportionallyResize();

		this._updateCache(data);

		// calling the user callback at the end
		this.element.triggerHandler("resize", [event, this.ui()], this.options["resize"]);

		return false;
	},

	_mouseStop: function(event) {

		this.options.resizing = false;
		var o = this.options, self = this;

		if(o.helper) {
			var pr = o.proportionallyResize, ista = pr && (/textarea/i).test(pr.get(0).nodeName),
						soffseth = ista && $.ui.hasScroll(pr.get(0), 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
							soffsetw = ista ? 0 : self.sizeDiff.width;

			var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
				left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
				top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;

			if (!o.animate)
				this.element.css($.extend(s, { top: top, left: left }));

			if (o.helper && !o.animate) this._proportionallyResize();
		}

		if (o.preserveCursor)
			$('body').css('cursor', 'auto');

		this._propagate("stop", event);

		if (o.helper) this.helper.remove();

		return false;
	},

	_updateCache: function(data) {
		var o = this.options;
		this.offset = this.helper.offset();
		if (data.left) this.position.left = data.left;
		if (data.top) this.position.top = data.top;
		if (data.height) this.size.height = data.height;
		if (data.width) this.size.width = data.width;
	},

	_updateRatio: function(data, event) {

		var o = this.options, cpos = this.position, csize = this.size, a = this.axis;

		if (data.height) data.width = (csize.height * o.aspectRatio);
		else if (data.width) data.height = (csize.width / o.aspectRatio);

		if (a == 'sw') {
			data.left = cpos.left + (csize.width - data.width);
			data.top = null;
		}
		if (a == 'nw') {
			data.top = cpos.top + (csize.height - data.height);
			data.left = cpos.left + (csize.width - data.width);
		}

		return data;
	},

	_respectSize: function(data, event) {

		var el = this.helper, o = this.options, pRatio = o._aspectRatio || event.shiftKey, a = this.axis,
				ismaxw = data.width && o.maxWidth && o.maxWidth < data.width, ismaxh = data.height && o.maxHeight && o.maxHeight < data.height,
					isminw = data.width && o.minWidth && o.minWidth > data.width, isminh = data.height && o.minHeight && o.minHeight > data.height;

		if (isminw) data.width = o.minWidth;
		if (isminh) data.height = o.minHeight;
		if (ismaxw) data.width = o.maxWidth;
		if (ismaxh) data.height = o.maxHeight;

		var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height;
		var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);

		if (isminw && cw) data.left = dw - o.minWidth;
		if (ismaxw && cw) data.left = dw - o.maxWidth;
		if (isminh && ch)	data.top = dh - o.minHeight;
		if (ismaxh && ch)	data.top = dh - o.maxHeight;

		// fixing jump error on top/left - bug #2330
		var isNotwh = !data.width && !data.height;
		if (isNotwh && !data.left && data.top) data.top = null;
		else if (isNotwh && !data.top && data.left) data.left = null;

		return data;
	},

	_proportionallyResize: function() {
		var o = this.options;
		if (!o.proportionallyResize) return;
		var prel = o.proportionallyResize, el = this.helper || this.element;

		if (!o.borderDif) {
			var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')],
				p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')];

			o.borderDif = $.map(b, function(v, i) {
				var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0;
				return border + padding;
			});
		}
		prel.css({
			height: (el.height() - o.borderDif[0] - o.borderDif[2]) + "px",
			width: (el.width() - o.borderDif[1] - o.borderDif[3]) + "px"
		});
	},

	_renderProxy: function() {
		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if(o.helper) {
			this.helper = this.helper || $('<div style="overflow:hidden;"></div>');

			// fix ie6 offset
			var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0),
			pxyoffset = ( ie6 ? 2 : -1 );

			this.helper.addClass(o.helper).css({
				width: el.outerWidth() + pxyoffset,
				height: el.outerHeight() + pxyoffset,
				position: 'absolute',
				left: this.elementOffset.left - ie6offset +'px',
				top: this.elementOffset.top - ie6offset +'px',
				zIndex: ++o.zIndex
			});

			this.helper.appendTo("body");

			if (o.disableSelection)
				this.helper.disableSelection();

		} else {
			this.helper = el;
		}
	},

	_change: {
		e: function(event, dx, dy) {
			return { width: this.originalSize.width + dx };
		},
		w: function(event, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function(event, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function(event, dx, dy) {
			return { height: this.originalSize.height + dy };
		},
		se: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
		},
		sw: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
		},
		ne: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
		},
		nw: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
		}
	},

	_propagate: function(n, event) {
		$.ui.plugin.call(this, n, [event, this.ui()]);
		if (n != "resize") this.element.triggerHandler(["resize", n].join(""), [event, this.ui()], this.options[n]);
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			options: this.options,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

}));

$.extend($.ui.resizable, {
	version: "1.6",
	defaults: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		cancel: ":input",
		containment: false,
		disableSelection: true,
		distance: 1,
		delay: 0,
		ghost: false,
		grid: false,
		knobHandles: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,
		preserveCursor: true,
		preventDefault: true,
		proportionallyResize: false,
		transparent: false
	}
});

/*
 * Resizable Extensions
 */

$.ui.plugin.add("resizable", "alsoResize", {

	start: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable"),

		_store = function(exp) {
			$(exp).each(function() {
				$(this).data("resizable-alsoresize", {
					width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10),
					left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10)
				});
			});
		};

		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) {
			if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0];	_store(o.alsoResize); }
			else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); }
		}else{
			_store(o.alsoResize);
		}
	},

	resize: function(event, ui){
		var o = ui.options, self = $(this).data("resizable"), os = self.originalSize, op = self.originalPosition;

		var delta = {
			height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0,
			top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0
		},

		_alsoResize = function(exp, c) {
			$(exp).each(function() {
				var start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left'];

				$.each(css || ['width', 'height', 'top', 'left'], function(i, prop) {
					var sum = (start[prop]||0) + (delta[prop]||0);
					if (sum && sum >= 0)
						style[prop] = sum || null;
				});
				$(this).css(style);
			});
		};

		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) {
			$.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); });
		}else{
			_alsoResize(o.alsoResize);
		}
	},

	stop: function(event, ui){
		$(this).removeData("resizable-alsoresize-start");
	}
});

$.ui.plugin.add("resizable", "animate", {

	stop: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable");

		var pr = o.proportionallyResize, ista = pr && (/textarea/i).test(pr.get(0).nodeName),
						soffseth = ista && $.ui.hasScroll(pr.get(0), 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
							soffsetw = ista ? 0 : self.sizeDiff.width;

		var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
					left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
						top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;

		self.element.animate(
			$.extend(style, top && left ? { top: top, left: left } : {}), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseInt(self.element.css('width'), 10),
						height: parseInt(self.element.css('height'), 10),
						top: parseInt(self.element.css('top'), 10),
						left: parseInt(self.element.css('left'), 10)
					};

					if (pr) pr.css({ width: data.width, height: data.height });

					// propagating resize, and updating values for each animation step
					self._updateCache(data);
					self._propagate("animate", event);

				}
			}
		);
	}

});

$.ui.plugin.add("resizable", "containment", {

	start: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable"), el = self.element;
		var oc = o.containment,	ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
		if (!ce) return;

		self.containerElement = $(ce);

		if (/document/.test(oc) || oc == document) {
			self.containerOffset = { left: 0, top: 0 };
			self.containerPosition = { left: 0, top: 0 };

			self.parentData = {
				element: $(document), left: 0, top: 0,
				width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
			};
		}

		// i'm a node, so compute top, left, right, bottom
		else{
			var element = $(ce), p = [];
			$([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });

			self.containerOffset = element.offset();
			self.containerPosition = element.position();
			self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };

			var co = self.containerOffset, ch = self.containerSize.height,	cw = self.containerSize.width,
						width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);

			self.parentData = {
				element: ce, left: co.left, top: co.top, width: width, height: height
			};
		}
	},

	resize: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable"),
				ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position,
				pRatio = o._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement;

		if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co;

		if (cp.left < (o.helper ? co.left : 0)) {
			self.size.width = self.size.width + (o.helper ? (self.position.left - co.left) : (self.position.left - cop.left));
			if (pRatio) self.size.height = self.size.width / o.aspectRatio;
			self.position.left = o.helper ? co.left : 0;
		}

		if (cp.top < (o.helper ? co.top : 0)) {
			self.size.height = self.size.height + (o.helper ? (self.position.top - co.top) : self.position.top);
			if (pRatio) self.size.width = self.size.height * o.aspectRatio;
			self.position.top = o.helper ? co.top : 0;
		}

		self.offset.left = self.parentData.left+self.position.left;
		self.offset.top = self.parentData.top+self.position.top;

		var woset = Math.abs( (o.helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ),
					hoset = Math.abs( (o.helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height );

		var isParent = self.containerElement.get(0) == self.element.parent().get(0),
		    isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position'));

		if(isParent && isOffsetRelative) woset -= self.parentData.left;

		if (woset + self.size.width >= self.parentData.width) {
			self.size.width = self.parentData.width - woset;
			if (pRatio) self.size.height = self.size.width / o.aspectRatio;
		}

		if (hoset + self.size.height >= self.parentData.height) {
			self.size.height = self.parentData.height - hoset;
			if (pRatio) self.size.width = self.size.height * o.aspectRatio;
		}
	},

	stop: function(event, ui){
		var o = ui.options, self = $(this).data("resizable"), cp = self.position,
				co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement;

		var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height;

		if (o.helper && !o.animate && (/relative/).test(ce.css('position')))
			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });

		if (o.helper && !o.animate && (/static/).test(ce.css('position')))
			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });

	}
});

$.ui.plugin.add("resizable", "ghost", {

	start: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize, cs = self.size;

		if (!pr) self.ghost = self.element.clone();
		else self.ghost = pr.clone();

		self.ghost.css(
			{ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }
		)
		.addClass('ui-resizable-ghost').addClass(typeof o.ghost == 'string' ? o.ghost : '');

		self.ghost.appendTo(self.helper);

	},

	resize: function(event, ui){
		var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize;

		if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width });

	},

	stop: function(event, ui){
		var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize;
		if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0));
	}

});

$.ui.plugin.add("resizable", "grid", {

	resize: function(event, ui) {
		var o = ui.options, self = $(this).data("resizable"), cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey;
		o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid;
		var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1);

		if (/^(se|s|e)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
		}
		else if (/^(ne)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
		}
		else if (/^(sw)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.left = op.left - ox;
		}
		else {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
			self.position.left = op.left - ox;
		}
	}

});

var num = function(v) {
	return parseInt(v, 10) || 0;
};

})(jQuery);
/*
 * jQuery UI Selectable 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Selectables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.selectable", $.extend({}, $.ui.mouse, {

	_init: function() {
		var self = this;

		this.element.addClass("ui-selectable");

		this.dragged = false;

		// cache selectee children based on filter
		var selectees;
		this.refresh = function() {
			selectees = $(self.options.filter, self.element[0]);
			selectees.each(function() {
				var $this = $(this);
				var pos = $this.offset();
				$.data(this, "selectable-item", {
					element: this,
					$element: $this,
					left: pos.left,
					top: pos.top,
					right: pos.left + $this.width(),
					bottom: pos.top + $this.height(),
					startselected: false,
					selected: $this.hasClass('ui-selected'),
					selecting: $this.hasClass('ui-selecting'),
					unselecting: $this.hasClass('ui-unselecting')
				});
			});
		};
		this.refresh();

		this.selectees = selectees.addClass("ui-selectee");

		this._mouseInit();

		this.helper = $(document.createElement('div'))
			.css({border:'1px dotted black'})
			.addClass("ui-selectable-helper");
	},

	destroy: function() {
		this.element
			.removeClass("ui-selectable ui-selectable-disabled")
			.removeData("selectable")
			.unbind(".selectable");
		this._mouseDestroy();
	},

	_mouseStart: function(event) {
		var self = this;

		this.opos = [event.pageX, event.pageY];

		if (this.options.disabled)
			return;

		var options = this.options;

		this.selectees = $(options.filter, this.element[0]);

		// selectable START callback
		this.element.triggerHandler("selectablestart", [event, {
			"selectable": this.element[0],
			"options": options
		}], options.start);

		$('body').append(this.helper);
		// position helper (lasso)
		this.helper.css({
			"z-index": 100,
			"position": "absolute",
			"left": event.clientX,
			"top": event.clientY,
			"width": 0,
			"height": 0
		});

		if (options.autoRefresh) {
			this.refresh();
		}

		this.selectees.filter('.ui-selected').each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.startselected = true;
			if (!event.metaKey) {
				selectee.$element.removeClass('ui-selected');
				selectee.selected = false;
				selectee.$element.addClass('ui-unselecting');
				selectee.unselecting = true;
				// selectable UNSELECTING callback
				self.element.triggerHandler("selectableunselecting", [event, {
					selectable: self.element[0],
					unselecting: selectee.element,
					options: options
				}], options.unselecting);
			}
		});

		var isSelectee = false;
		$(event.target).parents().andSelf().each(function() {
			if($.data(this, "selectable-item")) isSelectee = true;
		});
		return this.options.keyboard ? !isSelectee : true;
	},

	_mouseDrag: function(event) {
		var self = this;
		this.dragged = true;

		if (this.options.disabled)
			return;

		var options = this.options;

		var x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY;
		if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; }
		if (y1 > y2) { var tmp = y2; y2 = y1; y1 = tmp; }
		this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1});

		this.selectees.each(function() {
			var selectee = $.data(this, "selectable-item");
			//prevent helper from being selected if appendTo: selectable
			if (!selectee || selectee.element == self.element[0])
				return;
			var hit = false;
			if (options.tolerance == 'touch') {
				hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
			} else if (options.tolerance == 'fit') {
				hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
			}

			if (hit) {
				// SELECT
				if (selectee.selected) {
					selectee.$element.removeClass('ui-selected');
					selectee.selected = false;
				}
				if (selectee.unselecting) {
					selectee.$element.removeClass('ui-unselecting');
					selectee.unselecting = false;
				}
				if (!selectee.selecting) {
					selectee.$element.addClass('ui-selecting');
					selectee.selecting = true;
					// selectable SELECTING callback
					self.element.triggerHandler("selectableselecting", [event, {
						selectable: self.element[0],
						selecting: selectee.element,
						options: options
					}], options.selecting);
				}
			} else {
				// UNSELECT
				if (selectee.selecting) {
					if (event.metaKey && selectee.startselected) {
						selectee.$element.removeClass('ui-selecting');
						selectee.selecting = false;
						selectee.$element.addClass('ui-selected');
						selectee.selected = true;
					} else {
						selectee.$element.removeClass('ui-selecting');
						selectee.selecting = false;
						if (selectee.startselected) {
							selectee.$element.addClass('ui-unselecting');
							selectee.unselecting = true;
						}
						// selectable UNSELECTING callback
						self.element.triggerHandler("selectableunselecting", [event, {
							selectable: self.element[0],
							unselecting: selectee.element,
							options: options
						}], options.unselecting);
					}
				}
				if (selectee.selected) {
					if (!event.metaKey && !selectee.startselected) {
						selectee.$element.removeClass('ui-selected');
						selectee.selected = false;

						selectee.$element.addClass('ui-unselecting');
						selectee.unselecting = true;
						// selectable UNSELECTING callback
						self.element.triggerHandler("selectableunselecting", [event, {
							selectable: self.element[0],
							unselecting: selectee.element,
							options: options
						}], options.unselecting);
					}
				}
			}
		});

		return false;
	},

	_mouseStop: function(event) {
		var self = this;

		this.dragged = false;

		var options = this.options;

		$('.ui-unselecting', this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.$element.removeClass('ui-unselecting');
			selectee.unselecting = false;
			selectee.startselected = false;
			self.element.triggerHandler("selectableunselected", [event, {
				selectable: self.element[0],
				unselected: selectee.element,
				options: options
			}], options.unselected);
		});
		$('.ui-selecting', this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.$element.removeClass('ui-selecting').addClass('ui-selected');
			selectee.selecting = false;
			selectee.selected = true;
			selectee.startselected = true;
			self.element.triggerHandler("selectableselected", [event, {
				selectable: self.element[0],
				selected: selectee.element,
				options: options
			}], options.selected);
		});
		this.element.triggerHandler("selectablestop", [event, {
			selectable: self.element[0],
			options: this.options
		}], this.options.stop);

		this.helper.remove();

		return false;
	}

}));

$.extend($.ui.selectable, {
	version: "1.6",
	defaults: {
		appendTo: 'body',
		autoRefresh: true,
		cancel: ":input",
		delay: 0,
		distance: 1,
		filter: '*',
		tolerance: 'touch'
	}
});

})(jQuery);
/*
 * jQuery UI Sortable 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Sortables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.sortable", $.extend({}, $.ui.mouse, {
	_init: function() {

		var o = this.options;
		this.containerCache = {};
		this.element.addClass("ui-sortable");

		//Get the items
		this.refresh();

		//Let's determine if the items are floating
		this.floating = this.items.length ? (/left|right/).test(this.items[0].item.css('float')) : false;

		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();

	},

	destroy: function() {
		this.element
			.removeClass("ui-sortable ui-sortable-disabled")
			.removeData("sortable")
			.unbind(".sortable");
		this._mouseDestroy();

		for ( var i = this.items.length - 1; i >= 0; i-- )
			this.items[i].item.removeData("sortable-item");
	},

	_mouseCapture: function(event, overrideHandle) {

		if (this.reverting) {
			return false;
		}

		if(this.options.disabled || this.options.type == 'static') return false;

		//We have to refresh the items data once first
		this._refreshItems(event);

		//Find out if the clicked node (or one of its parents) is a actual item in this.items
		var currentItem = null, self = this, nodes = $(event.target).parents().each(function() {
			if($.data(this, 'sortable-item') == self) {
				currentItem = $(this);
				return false;
			}
		});
		if($.data(event.target, 'sortable-item') == self) currentItem = $(event.target);

		if(!currentItem) return false;
		if(this.options.handle && !overrideHandle) {
			var validHandle = false;

			$(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; });
			if(!validHandle) return false;
		}

		this.currentItem = currentItem;
		this._removeCurrentsFromItems();
		return true;

	},

	_mouseStart: function(event, overrideHandle, noActivation) {

		var o = this.options;
		this.currentContainer = this;

		//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
		this.refreshPositions();

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Get the next scrolling parent
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.currentItem.offset();

		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		// Only after we got the offset, we can change the helper's position to absolute
		// TODO: Still need to figure out a way to make relative sorting possible
		this.helper.css("position", "absolute");
		this.cssPosition = this.helper.css("position");

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		if(o.cursorAt)
			this._adjustOffsetFromHelper(o.cursorAt);

		//Generate the original position
		this.originalPosition = this._generatePosition(event);

		//Cache the former DOM position
		this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };

		//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
		if(this.helper[0] != this.currentItem[0]) {
			this.currentItem.hide();
		}

		//Create the placeholder
		this._createPlaceholder();

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		//Call plugins and callbacks
		this._propagate("start", event);

		//Recache the helper size
		if(!this._preserveHelperProportions)
			this._cacheHelperProportions();


		//Post 'activate' events to possible containers
		if(!noActivation) {
			 for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._propagate("activate", event, this); }
		}

		//Prepare possible droppables
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.dragging = true;

		this.helper.addClass('ui-sortable-helper');
		this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;

	},

	_mouseDrag: function(event) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		if (!this.lastPositionAbs) {
			this.lastPositionAbs = this.positionAbs;
		}

		//Call the internal plugins
		$.ui.plugin.call(this, "sort", [event, this._ui()]);

		//Regenerate the absolute position used for position checks
		this.positionAbs = this._convertPositionTo("absolute");

		//Set the helper position
		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';

		//Rearrange
		for (var i = this.items.length - 1; i >= 0; i--) {

			//Cache variables and intersection, continue if no intersection
			var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
			if (!intersection) continue;

			if(itemElement != this.currentItem[0] //cannot intersect with itself
				&&	this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
				&&	!$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
				&& (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
			) {

				this.direction = intersection == 1 ? "down" : "up";

				if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
					this.options.sortIndicator.call(this, event, item);
				} else {
					break;
				}

				this._propagate("change", event); //Call plugins and callbacks
				break;
			}
		}

		//Post events to containers
		this._contactContainers(event);

		//Interconnect with droppables
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		//Call callbacks
		this._trigger('sort', event, this._ui());

		this.lastPositionAbs = this.positionAbs;
		return false;

	},

	_mouseStop: function(event, noPropagation) {

		if(!event) return;

		//If we are using droppables, inform the manager about the drop
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			$.ui.ddmanager.drop(this, event);

		if(this.options.revert) {
			var self = this;
			var cur = self.placeholder.offset();

			self.reverting = true;

			$(this.helper).animate({
				left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
				top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
			}, parseInt(this.options.revert, 10) || 500, function() {
				self._clear(event);
			});
		} else {
			this._clear(event, noPropagation);
		}

		return false;

	},

	cancel: function() {

		if(this.dragging) {

			this._mouseUp();

			if(this.options.helper == "original")
				this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
			else
				this.currentItem.show();

			//Post deactivating events to containers
			for (var i = this.containers.length - 1; i >= 0; i--){
				this.containers[i]._propagate("deactivate", null, this);
				if(this.containers[i].containerCache.over) {
					this.containers[i]._propagate("out", null, this);
					this.containers[i].containerCache.over = 0;
				}
			}

		}

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
		if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
		if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove();

		$.extend(this, {
			helper: null,
			dragging: false,
			reverting: false,
			_noFinalSort: null
		});

		if(this.domPosition.prev) {
			$(this.domPosition.prev).after(this.currentItem);
		} else {
			$(this.domPosition.parent).prepend(this.currentItem);
		}

		return true;

	},

	serialize: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected);
		var str = []; o = o || {};

		$(items).each(function() {
			var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
			if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
		});

		return str.join('&');

	},

	toArray: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected);
		var ret = []; o = o || {};

		items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); });
		return ret;

	},

	/* Be careful with the following core functions */
	_intersectsWith: function(item) {

		var x1 = this.positionAbs.left,
			x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top,
			y2 = y1 + this.helperProportions.height;

		var l = item.left,
			r = l + item.width,
			t = item.top,
			b = t + item.height;

		var dyClick = this.offset.click.top,
			dxClick = this.offset.click.left;

		var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;

		if(	   this.options.tolerance == "pointer"
			|| this.options.forcePointerForContainers
			|| (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])
		) {
			return isOverElement;
		} else {

			return (l < x1 + (this.helperProportions.width / 2) // Right Half
				&& x2 - (this.helperProportions.width / 2) < r // Left Half
				&& t < y1 + (this.helperProportions.height / 2) // Bottom Half
				&& y2 - (this.helperProportions.height / 2) < b ); // Top Half

		}
	},

	_intersectsWithPointer: function(item) {

		var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
			isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
			isOverElement = isOverElementHeight && isOverElementWidth,
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (!isOverElement)
			return false;

		return this.floating ?
			( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 )
			: ( verticalDirection && (verticalDirection == "down" ? 2 : 1) );

	},

	_intersectsWithSides: function(item) {

		var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
			isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (this.floating && horizontalDirection) {
			return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf));
		} else {
			return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf));
		}

	},

	_getDragVerticalDirection: function() {
		var delta = this.positionAbs.top - this.lastPositionAbs.top;
		return delta != 0 && (delta > 0 ? "down" : "up");
	},

	_getDragHorizontalDirection: function() {
		var delta = this.positionAbs.left - this.lastPositionAbs.left;
		return delta != 0 && (delta > 0 ? "right" : "left");
	},

	refresh: function(event) {
		this._refreshItems(event);
		this.refreshPositions();
	},

	_getItemsAsjQuery: function(connected) {

		var self = this;
		var items = [];
		var queries = [];

		if(this.options.connectWith && connected) {
			for (var i = this.options.connectWith.length - 1; i >= 0; i--){
				var cur = $(this.options.connectWith[i]);
				for (var j = cur.length - 1; j >= 0; j--){
					var inst = $.data(cur[j], 'sortable');
					if(inst && inst != this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper"), inst]);
					}
				};
			};
		}

		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper"), this]);

		for (var i = queries.length - 1; i >= 0; i--){
			queries[i][0].each(function() {
				items.push(this);
			});
		};

		return $(items);

	},

	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find(":data(sortable-item)");

		for (var i=0; i < this.items.length; i++) {

			for (var j=0; j < list.length; j++) {
				if(list[j] == this.items[i].item[0])
					this.items.splice(i,1);
			};

		};

	},

	_refreshItems: function(event) {

		this.items = [];
		this.containers = [this];
		var items = this.items;
		var self = this;
		var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]];

		if(this.options.connectWith) {
			for (var i = this.options.connectWith.length - 1; i >= 0; i--){
				var cur = $(this.options.connectWith[i]);
				for (var j = cur.length - 1; j >= 0; j--){
					var inst = $.data(cur[j], 'sortable');
					if(inst && inst != this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
						this.containers.push(inst);
					}
				};
			};
		}

		for (var i = queries.length - 1; i >= 0; i--) {
			var targetData = queries[i][1];
			var _queries = queries[i][0];

			for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
				var item = $(_queries[j]);

				item.data('sortable-item', targetData); // Data for target checking (mouse manager)

				items.push({
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				});
			};
		};

	},

	refreshPositions: function(fast) {

		//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
		if(this.offsetParent && this.helper) {
			this.offset.parent = this._getParentOffset();
		}

		for (var i = this.items.length - 1; i >= 0; i--){
			var item = this.items[i];

			//We ignore calculating positions of all connected containers when we're not over them
			if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0])
				continue;

			var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;

			if (!fast) {
				if (this.options.accurateIntersection) {
					item.width = t.outerWidth();
					item.height = t.outerHeight();
				}
				else {
					item.width = t[0].offsetWidth;
					item.height = t[0].offsetHeight;
				}
			}

			var p = t.offset();
			item.left = p.left;
			item.top = p.top;
		};

		if(this.options.custom && this.options.custom.refreshContainers) {
			this.options.custom.refreshContainers.call(this);
		} else {
			for (var i = this.containers.length - 1; i >= 0; i--){
				var p = this.containers[i].element.offset();
				this.containers[i].containerCache.left = p.left;
				this.containers[i].containerCache.top = p.top;
				this.containers[i].containerCache.width	= this.containers[i].element.outerWidth();
				this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
			};
		}

	},

	_createPlaceholder: function(that) {

		var self = that || this, o = self.options;

		if(!o.placeholder || o.placeholder.constructor == String) {
			var className = o.placeholder;
			o.placeholder = {
				element: function() {

					var el = $(document.createElement(self.currentItem[0].nodeName))
						.addClass(className || self.currentItem[0].className+" ui-sortable-placeholder")
						.removeClass('ui-sortable-helper')[0];

					if(!className) {
						el.style.visibility = "hidden";
						document.body.appendChild(el);
						// Name attributes are removed, otherwice causes elements to be unchecked
						// Expando attributes also have to be removed because of stupid IE (no condition, doesn't hurt in other browsers)
						el.innerHTML = self.currentItem[0].innerHTML.replace(/name\=\"[^\"\']+\"/g, '').replace(/jQuery[0-9]+\=\"[^\"\']+\"/g, '');
						document.body.removeChild(el);
					};

					return el;
				},
				update: function(container, p) {
					if(className && !o.forcePlaceholderSize) return;
					if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); };
					if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); };
				}
			};
		}

		//Create the placeholder
		self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem));

		//Append it after the actual current item
		self.currentItem.after(self.placeholder);

		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
		o.placeholder.update(self, self.placeholder);

	},

	_contactContainers: function(event) {
		for (var i = this.containers.length - 1; i >= 0; i--){

			if(this._intersectsWith(this.containers[i].containerCache)) {
				if(!this.containers[i].containerCache.over) {

					if(this.currentContainer != this.containers[i]) {

						//When entering a new container, we will find the item with the least distance and append our item near it
						var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[i].floating ? 'left' : 'top'];
						for (var j = this.items.length - 1; j >= 0; j--) {
							if(!$.ui.contains(this.containers[i].element[0], this.items[j].item[0])) continue;
							var cur = this.items[j][this.containers[i].floating ? 'left' : 'top'];
							if(Math.abs(cur - base) < dist) {
								dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
							}
						}

						if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled
							continue;

						this.currentContainer = this.containers[i];
						itemWithLeastDistance ? this.options.sortIndicator.call(this, event, itemWithLeastDistance, null, true) : this.options.sortIndicator.call(this, event, null, this.containers[i].element, true);
						this._propagate("change", event); //Call plugins and callbacks
						this.containers[i]._propagate("change", event, this); //Call plugins and callbacks

						//Update the placeholder
						this.options.placeholder.update(this.currentContainer, this.placeholder);

					}

					this.containers[i]._propagate("over", event, this);
					this.containers[i].containerCache.over = 1;
				}
			} else {
				if(this.containers[i].containerCache.over) {
					this.containers[i]._propagate("out", event, this);
					this.containers[i].containerCache.over = 0;
				}
			}

		};
	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem);

		if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already
			$(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);

		if(helper[0] == this.currentItem[0])
			this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };

		if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width());
		if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height());

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
		if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
		if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset();

		if((this.offsetParent[0] == document.body && $.browser.mozilla)	//Ugly FF3 fix
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.currentItem.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
			top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			0 - this.offset.relative.left - this.offset.parent.left,
			0 - this.offset.relative.top - this.offset.parent.top,
			$(o.containment == 'document' ? document : window).width() - this.offset.relative.left - this.offset.parent.left - this.margins.left - (parseInt(this.currentItem.css("marginRight"),10) || 0),
			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.offset.relative.top - this.offset.parent.top - this.margins.top - (parseInt(this.currentItem.css("marginBottom"),10) || 0)
		];

		if(!(/^(document|window|parent)$/).test(o.containment)) {
			var ce = $(o.containment)[0];
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top - this.margins.top,
				co.left + (over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left - this.margins.left,
				co.top + (over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top - this.margins.top
			];
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var scroll = this[(this.cssPosition == 'absolute' ? 'offset' : 'scroll')+'Parent'], scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// the calculated relative position
				+ this.offset.relative.top	* mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod
				+ this.margins.top * mod												//Add the margin (you don't want the margin counting in intersection methods)
			),
			left: (
				pos.left																// the calculated relative position
				+ this.offset.relative.left	* mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : ( scrollIsRootNode ? 0 : scroll.scrollLeft() ) ) * mod
				+ this.margins.left * mod												//Add the margin (you don't want the margin counting in intersection methods)
			)
		};
	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this[(this.cssPosition == 'absolute' ? 'offset' : 'scroll')+'Parent'], scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		var position = {
			top: (
				event.pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )
			),
			left: (
				event.pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : ( scrollIsRootNode ? 0 : scroll.scrollLeft() ) )
			)
		};

		if(!this.originalPosition) return position;										//If we are not dragging yet, we won't check for options

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */
		if(this.containment) {
			if(position.left < this.containment[0]) position.left = this.containment[0];
			if(position.top < this.containment[1]) position.top = this.containment[1];
			if(position.left + this.helperProportions.width > this.containment[2]) position.left = this.containment[2] - this.helperProportions.width;
			if(position.top + this.helperProportions.height > this.containment[3]) position.top = this.containment[3] - this.helperProportions.height;
		}

		if(o.grid) {
			var top = this.originalPosition.top + Math.round((position.top - this.originalPosition.top) / o.grid[1]) * o.grid[1];
			position.top = this.containment ? (!(top < this.containment[1] || top > this.containment[3]) ? top : (!(top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

			var left = this.originalPosition.left + Math.round((position.left - this.originalPosition.left) / o.grid[0]) * o.grid[0];
			position.left = this.containment ? (!(left < this.containment[0] || left > this.containment[2]) ? left : (!(left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
		}

		return position;
	},

	_rearrange: function(event, i, a, hardRefresh) {

		a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));

		//Various things done here to improve the performance:
		// 1. we create a setTimeout, that calls refreshPositions
		// 2. on the instance, we have a counter variable, that get's higher after every append
		// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
		// 4. this lets only the last addition to the timeout stack through
		this.counter = this.counter ? ++this.counter : 1;
		var self = this, counter = this.counter;

		window.setTimeout(function() {
			if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
		},0);

	},

	_clear: function(event, noPropagation) {

		this.reverting = false;

		//We first have to update the dom position of the actual currentItem
		if(!this._noFinalSort) this.placeholder.before(this.currentItem);
		this._noFinalSort = null;

		if(this.helper[0] == this.currentItem[0]) {
			for(var i in this._storedCSS) {
				if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = '';
			}
			this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
		} else {
			this.currentItem.show();
		}

		if(this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) this._propagate("update", event, null, noPropagation); //Trigger update callback if the DOM position has changed
		if(!$.ui.contains(this.element[0], this.currentItem[0])) { //Node was moved out of the current element
			this._propagate("remove", event, null, noPropagation);
			for (var i = this.containers.length - 1; i >= 0; i--){
				if($.ui.contains(this.containers[i].element[0], this.currentItem[0])) {
					this.containers[i]._propagate("update", event, this, noPropagation);
					this.containers[i]._propagate("receive", event, this, noPropagation);
				}
			};
		};

		//Post events to containers
		for (var i = this.containers.length - 1; i >= 0; i--){
			this.containers[i]._propagate("deactivate", event, this, noPropagation);
			if(this.containers[i].containerCache.over) {
				this.containers[i]._propagate("out", event, this);
				this.containers[i].containerCache.over = 0;
			}
		}

		this.dragging = false;
		if(this.cancelHelperRemoval) {
			this._propagate("beforeStop", event, null, noPropagation);
			this._propagate("stop", event, null, noPropagation);
			return false;
		}

		this._propagate("beforeStop", event, null, noPropagation);

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
		this.placeholder[0].parentNode.removeChild(this.placeholder[0]);

		if(this.options.helper != "original") this.helper.remove(); this.helper = null;
		this._propagate("stop", event, null, noPropagation);

		return true;

	},

	_propagate: function(n, event, inst, noPropagation) {
		$.ui.plugin.call(this, n, [event, this._ui(inst)]);
		var dontCancel = !noPropagation ? this.element.triggerHandler(n == "sort" ? n : "sort"+n, [event, this._ui(inst)], this.options[n]) : true;
		if(dontCancel === false) this.cancel();
	},

	plugins: {},

	_ui: function(inst) {
		var self = inst || this;
		return {
			helper: self.helper,
			placeholder: self.placeholder || $([]),
			position: self.position,
			absolutePosition: self.positionAbs,
			item: self.currentItem,
			sender: inst ? inst.element : null
		};
	}

}));

$.extend($.ui.sortable, {
	getter: "serialize toArray",
	version: "1.6",
	defaults: {
		accurateIntersection: true,
		appendTo: "parent",
		cancel: ":input",
		delay: 0,
		distance: 1,
		dropOnEmpty: true,
		forcePlaceholderSize: false,
		forceHelperSize: false,
		helper: "original",
		items: '> *',
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		sortIndicator: $.ui.sortable.prototype._rearrange,
		tolerance: "default",
		zIndex: 1000
	}
});

/*
 * Sortable Extensions
 */

$.ui.plugin.add("sortable", "cursor", {
	start: function(event, ui) {
		var t = $('body'), i = $(this).data('sortable');
		if (t.css("cursor")) i.options._cursor = t.css("cursor");
		t.css("cursor", i.options.cursor);
	},
	beforeStop: function(event, ui) {
		var i = $(this).data('sortable');
		if (i.options._cursor) $('body').css("cursor", i.options._cursor);
	}
});

$.ui.plugin.add("sortable", "opacity", {
	start: function(event, ui) {
		var t = ui.helper, i = $(this).data('sortable');
		if(t.css("opacity")) i.options._opacity = t.css("opacity");
		t.css('opacity', i.options.opacity);
	},
	beforeStop: function(event, ui) {
		var i = $(this).data('sortable');
		if(i.options._opacity) $(ui.helper).css('opacity', i.options._opacity);
	}
});

$.ui.plugin.add("sortable", "scroll", {
	start: function(event, ui) {
		var i = $(this).data("sortable"), o = i.options;
		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();
	},
	sort: function(event, ui) {

		var i = $(this).data("sortable"), o = i.options, scrolled = false;

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {

			if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
				i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
			else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
				i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;

			if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
				i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
			else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
				i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;

		} else {

			if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
				scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
			else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
				scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);

			if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
				scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
			else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
				scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);

		}

		if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(i, event);



		//This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(scrolled !== false && i.cssPosition == 'absolute' && i.scrollParent[0] != document && $.ui.contains(i.scrollParent[0], i.offsetParent[0])) {
			i.offset.parent = i._getParentOffset();
		}
		
		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(scrolled !== false && i.cssPosition == 'relative' && !(i.scrollParent[0] != document && i.scrollParent[0] != i.offsetParent[0])) {
			i.offset.relative = i._getRelativeOffset();
		}

	}
});

$.ui.plugin.add("sortable", "zIndex", {
	start: function(event, ui) {
		var t = ui.helper, i = $(this).data('sortable');
		if(t.css("zIndex")) i.options._zIndex = t.css("zIndex");
		t.css('zIndex', i.options.zIndex);
	},
	beforeStop: function(event, ui) {
		var i = $(this).data('sortable');
		if(i.options._zIndex) $(ui.helper).css('zIndex', i.options._zIndex == 'auto' ? '' : i.options._zIndex);
	}
});

})(jQuery);
/*
 * jQuery UI Accordion 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Accordion
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.accordion", {

	_init: function() {
		var options = this.options;

		if ( options.navigation ) {
			var current = this.element.find("a").filter(options.navigationFilter);
			if ( current.length ) {
				if ( current.filter(options.header).length ) {
					options.active = current;
				} else {
					options.active = current.parent().parent().prev();
					current.addClass("current");
				}
			}
		}

		// calculate active if not specified, using the first header
		options.headers = this.element.find(options.header);
		options.active = findActive(options.headers, options.active);

		// IE7-/Win - Extra vertical space in Lists fixed
		if ($.browser.msie) {
			this.element.find('a').css('zoom', '1');
		}

		if (!this.element.hasClass("ui-accordion")) {
			this.element.addClass("ui-accordion");
			$('<span class="ui-accordion-left"></span>').insertBefore(options.headers);
			$('<span class="ui-accordion-right"></span>').appendTo(options.headers);
			options.headers.addClass("ui-accordion-header");
		}

		var maxHeight;
		if ( options.fillSpace ) {
			maxHeight = this.element.parent().height();
			options.headers.each(function() {
				maxHeight -= $(this).outerHeight();
			});
			var maxPadding = 0;
			options.headers.next().each(function() {
				maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height());
			}).height(maxHeight - maxPadding);
		} else if ( options.autoHeight ) {
			maxHeight = 0;
			options.headers.next().each(function() {
				maxHeight = Math.max(maxHeight, $(this).outerHeight());
			}).height(maxHeight);
		}

		this.element.attr('role','tablist');

		var self=this;
		options.headers
			.attr('role','tab')
			.bind('keydown', function(event) { return self._keydown(event); })
			.next()
			.attr('role','tabpanel');

		options.headers
			.not(options.active || "")
			.attr('aria-expanded','false')
			.attr("tabIndex", "-1")
			.next()
			.hide();

		// make sure at least one header is in the tab order
		if (!options.active.length) {
			options.headers.eq(0).attr('tabIndex','0');
		} else {
			options.active
				.attr('aria-expanded','true')
				.attr("tabIndex", "0")
				.parent().andSelf().addClass(options.selectedClass);
		}

		// only need links in taborder for Safari
		if (!$.browser.safari)
			options.headers.find('a').attr('tabIndex','-1');

		if (options.event) {
			this.element.bind((options.event) + ".accordion", clickHandler);
		}
	},

	destroy: function() {
		this.options.headers.parent().andSelf().removeClass(this.options.selectedClass);
		this.options.headers.prev(".ui-accordion-left").remove();
		this.options.headers.children(".ui-accordion-right").remove();
		this.options.headers.next().css("display", "");
		if ( this.options.fillSpace || this.options.autoHeight ) {
			this.options.headers.next().css("height", "");
		}
		$.removeData(this.element[0], "accordion");

		this.element.removeClass("ui-accordion").unbind(".accordion");
	},

	_keydown: function(event) {
		if (this.options.disabled || event.altKey || event.ctrlKey)
			return;

		var keyCode = $.ui.keyCode;

		var length = this.options.headers.length;
		var currentIndex = this.options.headers.index(event.target);
		var toFocus = false;

		switch(event.keyCode) {
			case keyCode.RIGHT:
			case keyCode.DOWN:
				toFocus = this.options.headers[(currentIndex + 1) % length];
				break;
			case keyCode.LEFT:
			case keyCode.UP:
				toFocus = this.options.headers[(currentIndex - 1 + length) % length];
				break;
			case keyCode.SPACE:
			case keyCode.ENTER:
				return clickHandler.call(this.element[0], { target: event.target });
		}

		if (toFocus) {
			$(event.target).attr('tabIndex','-1');
			$(toFocus).attr('tabIndex','0');
			toFocus.focus();
			return false;
		}

		return true;
	},

	activate: function(index) {
		// call clickHandler with custom event
		clickHandler.call(this.element[0], {
			target: findActive( this.options.headers, index )[0]
		});
	}

});

function scopeCallback(callback, scope) {
	return function() {
		return callback.apply(scope, arguments);
	};
};

function completed(cancel) {
	// if removed while animated data can be empty
	if (!$.data(this, "accordion")) {
		return;
	}

	var instance = $.data(this, "accordion");
	var options = instance.options;
	options.running = cancel ? 0 : --options.running;
	if ( options.running ) {
		return;
	}
	if ( options.clearStyle ) {
		options.toShow.add(options.toHide).css({
			height: "",
			overflow: ""
		});
	}
	instance._trigger('change', null, options.data);
}

function toggle(toShow, toHide, data, clickedActive, down) {
	var options = $.data(this, "accordion").options;
	options.toShow = toShow;
	options.toHide = toHide;
	options.data = data;
	var complete = scopeCallback(completed, this);

	$.data(this, "accordion")._trigger("changestart", null, options.data);

	// count elements to animate
	options.running = toHide.size() === 0 ? toShow.size() : toHide.size();

	if ( options.animated ) {
		var animOptions = {};

		if ( !options.alwaysOpen && clickedActive ) {
			animOptions = {
				toShow: $([]),
				toHide: toHide,
				complete: complete,
				down: down,
				autoHeight: options.autoHeight
			};
		} else {
			animOptions = {
				toShow: toShow,
				toHide: toHide,
				complete: complete,
				down: down,
				autoHeight: options.autoHeight
			};
		}

		if (!options.proxied) {
			options.proxied = options.animated;
		}

		if (!options.proxiedDuration) {
			options.proxiedDuration = options.duration;
		}

		options.animated = $.isFunction(options.proxied) ?
			options.proxied(animOptions) : options.proxied;

		options.duration = $.isFunction(options.proxiedDuration) ?
			options.proxiedDuration(animOptions) : options.proxiedDuration;

		var animations = $.ui.accordion.animations,
			duration = options.duration,
			easing = options.animated;

		if (!animations[easing]) {
			animations[easing] = function(options) {
				this.slide(options, {
					easing: easing,
					duration: duration || 700
				});
			};
		}

		animations[easing](animOptions);

	} else {
		if ( !options.alwaysOpen && clickedActive ) {
			toShow.toggle();
		} else {
			toHide.hide();
			toShow.show();
		}
		complete(true);
	}
	toHide.prev().attr('aria-expanded','false').attr("tabIndex", "-1");
	toShow.prev().attr('aria-expanded','true').attr("tabIndex", "0").focus();;
}

function clickHandler(event) {
	var options = $.data(this, "accordion").options;
	if (options.disabled) {
		return false;
	}

	// called only when using activate(false) to close all parts programmatically
	if ( !event.target && !options.alwaysOpen ) {
		options.active.parent().andSelf().toggleClass(options.selectedClass);
		var toHide = options.active.next(),
			data = {
				options: options,
				newHeader: $([]),
				oldHeader: options.active,
				newContent: $([]),
				oldContent: toHide
			},
			toShow = (options.active = $([]));
		toggle.call(this, toShow, toHide, data );
		return false;
	}
	// get the click target
	var clicked = $(event.target);

	// due to the event delegation model, we have to check if one
	// of the parent elements is our actual header, and find that
	// otherwise stick with the initial target
	clicked = $( clicked.parents(options.header)[0] || clicked );

	var clickedActive = clicked[0] == options.active[0];

	// if animations are still active, or the active header is the target, ignore click
	if (options.running || (options.alwaysOpen && clickedActive)) {
		return false;
	}
	if (!clicked.is(options.header)) {
		return;
	}

	// switch classes
	options.active.parent().andSelf().toggleClass(options.selectedClass);
	if ( !clickedActive ) {
		clicked.parent().andSelf().addClass(options.selectedClass);
	}

	// find elements to show and hide
	var toShow = clicked.next(),
		toHide = options.active.next(),
		data = {
			options: options,
			newHeader: clickedActive && !options.alwaysOpen ? $([]) : clicked,
			oldHeader: options.active,
			newContent: clickedActive && !options.alwaysOpen ? $([]) : toShow,
			oldContent: toHide
		},
		down = options.headers.index( options.active[0] ) > options.headers.index( clicked[0] );

	options.active = clickedActive ? $([]) : clicked;
	toggle.call(this, toShow, toHide, data, clickedActive, down );

	return false;
};

function findActive(headers, selector) {
	return selector
		? typeof selector == "number"
			? headers.filter(":eq(" + selector + ")")
			: headers.not(headers.not(selector))
		: selector === false
			? $([])
			: headers.filter(":eq(0)");
}

$.extend($.ui.accordion, {
	version: "1.6",
	defaults: {
		autoHeight: true,
		alwaysOpen: true,
		animated: 'slide',
		event: "click",
		header: "a",
		navigationFilter: function() {
			return this.href.toLowerCase() == location.href.toLowerCase();
		},
		running: 0,
		selectedClass: "selected"
	},
	animations: {
		slide: function(options, additions) {
			options = $.extend({
				easing: "swing",
				duration: 300
			}, options, additions);
			if ( !options.toHide.size() ) {
				options.toShow.animate({height: "show"}, options);
				return;
			}
			var hideHeight = options.toHide.height(),
				showHeight = options.toShow.height(),
				difference = showHeight / hideHeight,
				padding = options.toShow.outerHeight() - options.toShow.height(),
				margin = options.toShow.css('marginBottom'),
				overflow = options.toShow.css('overflow')
				tmargin = options.toShow.css('marginTop');
			options.toShow.css({ height: 0, overflow: 'hidden', marginTop: 0, marginBottom: -padding }).show();
			options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate({height:"hide"},{
				step: function(now) {
					var current = (hideHeight - now) * difference;
					if ($.browser.msie || $.browser.opera) {
						current = Math.ceil(current);
					}
					options.toShow.height( current );
				},
				duration: options.duration,
				easing: options.easing,
				complete: function() {
					if ( !options.autoHeight ) {
						options.toShow.css("height", "auto");
					}
					options.toShow.css({marginTop: tmargin, marginBottom: margin, overflow: overflow});
					options.complete();
				}
			});
		},
		bounceslide: function(options) {
			this.slide(options, {
				easing: options.down ? "easeOutBounce" : "swing",
				duration: options.down ? 1000 : 200
			});
		},
		easeslide: function(options) {
			this.slide(options, {
				easing: "easeinout",
				duration: 700
			});
		}
	}
});

})(jQuery);
/*
 * jQuery UI Dialog 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 *	ui.resizable.js
 */
(function($) {

var setDataSwitch = {
	dragStart: "start.draggable",
	drag: "drag.draggable",
	dragStop: "stop.draggable",
	maxHeight: "maxHeight.resizable",
	minHeight: "minHeight.resizable",
	maxWidth: "maxWidth.resizable",
	minWidth: "minWidth.resizable",
	resizeStart: "start.resizable",
	resize: "drag.resizable",
	resizeStop: "stop.resizable"
};

$.widget("ui.dialog", {

	_init: function() {
		this.originalTitle = this.element.attr('title');
		this.options.title = this.options.title || this.originalTitle;

		var self = this,
			options = this.options,

			uiDialogContent = this.element
				.removeAttr('title')
				.addClass('ui-dialog-content')
				.wrap('<div></div>')
				.wrap('<div></div>'),

			uiDialogContainer = (this.uiDialogContainer = uiDialogContent.parent())
				.addClass('ui-dialog-container')
				.css({
					position: 'relative',
					width: '100%',
					height: '100%'
				}),

			uiDialogTitlebar = (this.uiDialogTitlebar = $('<div></div>'))
				.addClass('ui-dialog-titlebar')
				.mousedown(function() {
					self.moveToTop();
				})
				.prependTo(uiDialogContainer),

			uiDialogTitlebarClose = $('<a href="#"/>')
				.addClass('ui-dialog-titlebar-close')
				.attr('role', 'button')
				.appendTo(uiDialogTitlebar),

			uiDialogTitlebarCloseText = (this.uiDialogTitlebarCloseText = $('<span/>'))
				.text(options.closeText)
				.appendTo(uiDialogTitlebarClose),

			title = options.title || '&nbsp;',
			titleId = $.ui.dialog.getTitleId(this.element),
			uiDialogTitle = $('<span/>')
				.addClass('ui-dialog-title')
				.attr('id', titleId)
				.html(title)
				.prependTo(uiDialogTitlebar),

			uiDialog = (this.uiDialog = uiDialogContainer.parent())
				.appendTo(document.body)
				.hide()
				.addClass('ui-dialog')
				.addClass(options.dialogClass)
				.css({
					position: 'absolute',
					width: options.width,
					height: options.height,
					overflow: 'hidden',
					zIndex: options.zIndex
				})
				// setting tabIndex makes the div focusable
				// setting outline to 0 prevents a border on focus in Mozilla
				.attr('tabIndex', -1).css('outline', 0).keydown(function(ev) {
					(options.closeOnEscape && ev.keyCode
						&& ev.keyCode == $.ui.keyCode.ESCAPE && self.close());
				})
				.attr({
					role: 'dialog',
					'aria-labelledby': titleId
				})
				.mouseup(function() {
					self.moveToTop();
				}),

			uiDialogButtonPane = (this.uiDialogButtonPane = $('<div></div>'))
				.addClass('ui-dialog-buttonpane')
				.css({
					position: 'absolute',
					bottom: 0
				})
				.appendTo(uiDialog),

			uiDialogTitlebarClose = $('.ui-dialog-titlebar-close', uiDialogTitlebar)
				.hover(
					function() {
						$(this).addClass('ui-dialog-titlebar-close-hover');
					},
					function() {
						$(this).removeClass('ui-dialog-titlebar-close-hover');
					}
				)
				.mousedown(function(ev) {
					ev.stopPropagation();
				})
				.click(function() {
					self.close();
					return false;
				});

		uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection();

		(options.draggable && $.fn.draggable && this._makeDraggable());
		(options.resizable && $.fn.resizable && this._makeResizable());

		this._createButtons(options.buttons);
		this._isOpen = false;

		(options.bgiframe && $.fn.bgiframe && uiDialog.bgiframe());
		(options.autoOpen && this.open());
	},

	destroy: function() {
		(this.overlay && this.overlay.destroy());
		this.uiDialog.hide();
		this.element
			.unbind('.dialog')
			.removeData('dialog')
			.removeClass('ui-dialog-content')
			.hide().appendTo('body');
		this.uiDialog.remove();

		(this.originalTitle && this.element.attr('title', this.originalTitle));
	},

	close: function() {
		if (false === this._trigger('beforeclose', null, { options: this.options })) {
			return;
		}

		(this.overlay && this.overlay.destroy());
		this.uiDialog
			.hide(this.options.hide)
			.unbind('keypress.ui-dialog');

		this._trigger('close', null, { options: this.options });
		$.ui.dialog.overlay.resize();

		this._isOpen = false;
	},

	isOpen: function() {
		return this._isOpen;
	},

	// the force parameter allows us to move modal dialogs to their correct
	// position on open
	moveToTop: function(force) {

		if ((this.options.modal && !force)
			|| (!this.options.stack && !this.options.modal)) {
			return this._trigger('focus', null, { options: this.options });
		}

		var maxZ = this.options.zIndex, options = this.options;
		$('.ui-dialog:visible').each(function() {
			maxZ = Math.max(maxZ, parseInt($(this).css('z-index'), 10) || options.zIndex);
		});
		(this.overlay && this.overlay.$el.css('z-index', ++maxZ));

		//Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed.
		//  http://ui.jquery.com/bugs/ticket/3193
		var saveScroll = { scrollTop: this.element.attr('scrollTop'), scrollLeft: this.element.attr('scrollLeft') };
		this.uiDialog.css('z-index', ++maxZ);
		this.element.attr(saveScroll);
		this._trigger('focus', null, { options: this.options });
	},

	open: function() {
		if (this._isOpen) { return; }

		this.overlay = this.options.modal ? new $.ui.dialog.overlay(this) : null;
		(this.uiDialog.next().length && this.uiDialog.appendTo('body'));
		this._position(this.options.position);
		this.uiDialog.show(this.options.show);
		(this.options.autoResize && this._size());
		this.moveToTop(true);

		// prevent tabbing out of modal dialogs
		(this.options.modal && this.uiDialog.bind('keypress.ui-dialog', function(event) {
			if (event.keyCode != $.ui.keyCode.TAB) {
				return;
			}

			var tabbables = $(':tabbable', this),
				first = tabbables.filter(':first')[0],
				last  = tabbables.filter(':last')[0];

			if (event.target == last && !event.shiftKey) {
				setTimeout(function() {
					first.focus();
				}, 1);
			} else if (event.target == first && event.shiftKey) {
				setTimeout(function() {
					last.focus();
				}, 1);
			}
		}));

		this.uiDialog.find(':tabbable:first').focus();
		this._trigger('open', null, { options: this.options });
		this._isOpen = true;
	},

	_createButtons: function(buttons) {
		var self = this,
			hasButtons = false,
			uiDialogButtonPane = this.uiDialogButtonPane;

		// remove any existing buttons
		uiDialogButtonPane.empty().hide();

		$.each(buttons, function() { return !(hasButtons = true); });
		if (hasButtons) {
			uiDialogButtonPane.show();
			$.each(buttons, function(name, fn) {
				$('<button type="button"></button>')
					.text(name)
					.click(function() { fn.apply(self.element[0], arguments); })
					.appendTo(uiDialogButtonPane);
			});
		}
	},

	_makeDraggable: function() {
		var self = this,
			options = this.options;

		this.uiDialog.draggable({
			cancel: '.ui-dialog-content',
			helper: options.dragHelper,
			handle: '.ui-dialog-titlebar',
			start: function() {
				self.moveToTop();
				(options.dragStart && options.dragStart.apply(self.element[0], arguments));
			},
			drag: function() {
				(options.drag && options.drag.apply(self.element[0], arguments));
			},
			stop: function() {
				(options.dragStop && options.dragStop.apply(self.element[0], arguments));
				$.ui.dialog.overlay.resize();
			}
		});
	},

	_makeResizable: function(handles) {
		handles = (handles === undefined ? this.options.resizable : handles);
		var self = this,
			options = this.options,
			resizeHandles = typeof handles == 'string'
				? handles
				: 'n,e,s,w,se,sw,ne,nw';

		this.uiDialog.resizable({
			cancel: '.ui-dialog-content',
			helper: options.resizeHelper,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: options.minHeight,
			start: function() {
				(options.resizeStart && options.resizeStart.apply(self.element[0], arguments));
			},
			resize: function() {
				(options.autoResize && self._size.apply(self));
				(options.resize && options.resize.apply(self.element[0], arguments));
			},
			handles: resizeHandles,
			stop: function() {
				(options.autoResize && self._size.apply(self));
				(options.resizeStop && options.resizeStop.apply(self.element[0], arguments));
				$.ui.dialog.overlay.resize();
			}
		});
	},

	_position: function(pos) {
		var wnd = $(window), doc = $(document),
			pTop = doc.scrollTop(), pLeft = doc.scrollLeft(),
			minTop = pTop;

		if ($.inArray(pos, ['center','top','right','bottom','left']) >= 0) {
			pos = [
				pos == 'right' || pos == 'left' ? pos : 'center',
				pos == 'top' || pos == 'bottom' ? pos : 'middle'
			];
		}
		if (pos.constructor != Array) {
			pos = ['center', 'middle'];
		}
		if (pos[0].constructor == Number) {
			pLeft += pos[0];
		} else {
			switch (pos[0]) {
				case 'left':
					pLeft += 0;
					break;
				case 'right':
					pLeft += wnd.width() - this.uiDialog.outerWidth();
					break;
				default:
				case 'center':
					pLeft += (wnd.width() - this.uiDialog.outerWidth()) / 2;
			}
		}
		if (pos[1].constructor == Number) {
			pTop += pos[1];
		} else {
			switch (pos[1]) {
				case 'top':
					pTop += 0;
					break;
				case 'bottom':
					// Opera check fixes #3564, can go away with jQuery 1.3
					pTop += ($.browser.opera ? window.innerHeight : wnd.height()) - this.uiDialog.outerHeight();
					break;
				default:
				case 'middle':
					// Opera check fixes #3564, can go away with jQuery 1.3
					pTop += (($.browser.opera ? window.innerHeight : wnd.height()) - this.uiDialog.outerHeight()) / 2;
			}
		}

		// prevent the dialog from being too high (make sure the titlebar
		// is accessible)
		pTop = Math.max(pTop, minTop);
		this.uiDialog.css({top: pTop, left: pLeft});
	},

	_setData: function(key, value){
		(setDataSwitch[key] && this.uiDialog.data(setDataSwitch[key], value));
		switch (key) {
			case "buttons":
				this._createButtons(value);
				break;
			case "closeText":
				this.uiDialogTitlebarCloseText.text(value);
				break;
			case "draggable":
				(value
					? this._makeDraggable()
					: this.uiDialog.draggable('destroy'));
				break;
			case "height":
				this.uiDialog.height(value);
				break;
			case "position":
				this._position(value);
				break;
			case "resizable":
				var uiDialog = this.uiDialog,
					isResizable = this.uiDialog.is(':data(resizable)');

				// currently resizable, becoming non-resizable
				(isResizable && !value && uiDialog.resizable('destroy'));

				// currently resizable, changing handles
				(isResizable && typeof value == 'string' &&
					uiDialog.resizable('option', 'handles', value));

				// currently non-resizable, becoming resizable
				(isResizable || this._makeResizable(value));

				break;
			case "title":
				$(".ui-dialog-title", this.uiDialogTitlebar).html(value || '&nbsp;');
				break;
			case "width":
				this.uiDialog.width(value);
				break;
		}

		$.widget.prototype._setData.apply(this, arguments);
	},

	_size: function() {
		var container = this.uiDialogContainer,
			titlebar = this.uiDialogTitlebar,
			content = this.element,
			tbMargin = (parseInt(content.css('margin-top'), 10) || 0)
				+ (parseInt(content.css('margin-bottom'), 10) || 0),
			lrMargin = (parseInt(content.css('margin-left'), 10) || 0)
				+ (parseInt(content.css('margin-right'), 10) || 0);
		content.height(container.height() - titlebar.outerHeight() - tbMargin);
		content.width(container.width() - lrMargin);
	}

});

$.extend($.ui.dialog, {
	version: "1.6",
	defaults: {
		autoOpen: true,
		autoResize: true,
		bgiframe: false,
		buttons: {},
		closeOnEscape: true,
		closeText: 'close',
		draggable: true,
		height: 200,
		minHeight: 100,
		minWidth: 150,
		modal: false,
		overlay: {},
		position: 'center',
		resizable: true,
		stack: true,
		width: 300,
		zIndex: 1000
	},

	getter: 'isOpen',

	uuid: 0,

	getTitleId: function($el) {
		return 'ui-dialog-title-' + ($el.attr('id') || ++this.uuid);
	},

	overlay: function(dialog) {
		this.$el = $.ui.dialog.overlay.create(dialog);
	}
});

$.extend($.ui.dialog.overlay, {
	instances: [],
	events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
		function(event) { return event + '.dialog-overlay'; }).join(' '),
	create: function(dialog) {
		if (this.instances.length === 0) {
			// prevent use of anchors and inputs
			// we use a setTimeout in case the overlay is created from an
			// event that we're going to be cancelling (see #2804)
			setTimeout(function() {
				$('a, :input').bind($.ui.dialog.overlay.events, function() {
					// allow use of the element if inside a dialog and
					// - there are no modal dialogs
					// - there are modal dialogs, but we are in front of the topmost modal
					var allow = false;
					var $dialog = $(this).parents('.ui-dialog');
					if ($dialog.length) {
						var $overlays = $('.ui-dialog-overlay');
						if ($overlays.length) {
							var maxZ = parseInt($overlays.css('z-index'), 10);
							$overlays.each(function() {
								maxZ = Math.max(maxZ, parseInt($(this).css('z-index'), 10));
							});
							allow = parseInt($dialog.css('z-index'), 10) > maxZ;
						} else {
							allow = true;
						}
					}
					return allow;
				});
			}, 1);

			// allow closing by pressing the escape key
			$(document).bind('keydown.dialog-overlay', function(event) {
				(dialog.options.closeOnEscape && event.keyCode
						&& event.keyCode == $.ui.keyCode.ESCAPE && dialog.close());
			});

			// handle window resize
			$(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
		}

		var $el = $('<div></div>').appendTo(document.body)
			.addClass('ui-dialog-overlay').css($.extend({
				borderWidth: 0, margin: 0, padding: 0,
				position: 'absolute', top: 0, left: 0,
				width: this.width(),
				height: this.height()
			}, dialog.options.overlay));

		(dialog.options.bgiframe && $.fn.bgiframe && $el.bgiframe());

		this.instances.push($el);
		return $el;
	},

	destroy: function($el) {
		this.instances.splice($.inArray(this.instances, $el), 1);

		if (this.instances.length === 0) {
			$('a, :input').add([document, window]).unbind('.dialog-overlay');
		}

		$el.remove();
	},

	height: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollHeight = Math.max(
				document.documentElement.scrollHeight,
				document.body.scrollHeight
			);
			var offsetHeight = Math.max(
				document.documentElement.offsetHeight,
				document.body.offsetHeight
			);

			if (scrollHeight < offsetHeight) {
				return $(window).height() + 'px';
			} else {
				return scrollHeight + 'px';
			}
		// handle Opera
		} else if ($.browser.opera) {
			return Math.max(
				window.innerHeight,
				$(document).height()
			) + 'px';
		// handle "good" browsers
		} else {
			return $(document).height() + 'px';
		}
	},

	width: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollWidth = Math.max(
				document.documentElement.scrollWidth,
				document.body.scrollWidth
			);
			var offsetWidth = Math.max(
				document.documentElement.offsetWidth,
				document.body.offsetWidth
			);

			if (scrollWidth < offsetWidth) {
				return $(window).width() + 'px';
			} else {
				return scrollWidth + 'px';
			}
		// handle Opera
		} else if ($.browser.opera) {
			return Math.max(
				window.innerWidth,
				$(document).width()
			) + 'px';
		// handle "good" browsers
		} else {
			return $(document).width() + 'px';
		}
	},

	resize: function() {
		/* If the dialog is draggable and the user drags it past the
		 * right edge of the window, the document becomes wider so we
		 * need to stretch the overlay. If the user then drags the
		 * dialog back to the left, the document will become narrower,
		 * so we need to shrink the overlay to the appropriate size.
		 * This is handled by shrinking the overlay before setting it
		 * to the full document size.
		 */
		var $overlays = $([]);
		$.each($.ui.dialog.overlay.instances, function() {
			$overlays = $overlays.add(this);
		});

		$overlays.css({
			width: 0,
			height: 0
		}).css({
			width: $.ui.dialog.overlay.width(),
			height: $.ui.dialog.overlay.height()
		});
	}
});

$.extend($.ui.dialog.overlay.prototype, {
	destroy: function() {
		$.ui.dialog.overlay.destroy(this.$el);
	}
});

})(jQuery);
/*
 * jQuery UI Slider 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.fn.unwrap = $.fn.unwrap || function(expr) {
  return this.each(function(){
     $(this).parents(expr).eq(0).after(this).remove();
  });
};

$.widget("ui.slider", {

	_init: function() {

		var self = this;
		this.element.addClass("ui-slider");
		this._initBoundaries();

		// Initialize mouse and key events for interaction
		this.handle = $(this.options.handle, this.element);
		if (!this.handle.length) {
			self.handle = self.generated = $(self.options.handles || [0]).map(function() {
				var handle = $("<div/>").addClass("ui-slider-handle").appendTo(self.element);
				if (this.id)
					handle.attr("id", this.id);
				return handle[0];
			});
		}

		var handleclass = function(el) {
			this.element = $(el);
			this.element.data("mouse", this);
			this.options = self.options;

			this.element.bind("mousedown", function() {
				if(self.currentHandle) this.blur(self.currentHandle);
				self._focus(this, true);
			});

			this._mouseInit();
		};

		$.extend(handleclass.prototype, $.ui.mouse, {
			_mouseCapture: function() { return true; },
			_mouseStart: function(event) { return self._start.call(self, event, this.element[0]); },
			_mouseDrag: function(event) { return self._drag.call(self, event, this.element[0]); },
			_mouseStop: function(event) { return self._stop.call(self, event, this.element[0]); },
			trigger: function(event) { this._mouseDown(event); }
		});

		$(this.handle)
			.each(function() {
				new handleclass(this);
			})
			.wrap('<a href="#" style="outline:none;border:none;"></a>')
			.parent()
				.bind('click', function() { return false; })
				.bind('focus', function(event) { self._focus(this.firstChild); })
				.bind('blur', function(event) { self._blur(this.firstChild); })
				.bind('keydown', function(event) { if(!self.options.noKeyboard) return self._keydown(event.keyCode, this.firstChild); })
		;

		// Bind the click to the slider itself
		this.element.bind('mousedown.slider', function(event) {

			if($(event.target).is('.ui-slider-handle')) return;

			//Go to the actual clicked posiion, apply a click
			self._click.apply(self, [event]);

			//initiate a handle drag, so we can click+drag somewhere
			 self.currentHandle.data("mouse").trigger(event);

			 //This is for always triggering the change event
			self.firstValue = self.firstValue + 1;

		});

		// Move the first handle to the startValue
		$.each(this.options.handles || [], function(index, handle) {
			self.moveTo(handle.start, index, true);
		});
		if (!isNaN(this.options.startValue))
			this.moveTo(this.options.startValue, 0, true);

		this.previousHandle = $(this.handle[0]); //set the previous handle to the first to allow clicking before selecting the handle
		if(this.handle.length == 2 && this.options.range) this._createRange();

	},

	destroy: function() {

		this.element
			.removeClass("ui-slider ui-slider-disabled")
			.removeData("slider")
			.unbind(".slider");

		if(this.handle && this.handle.length) {
			this.handle
				.unwrap("a");
			this.handle.each(function() {
				var mouse = $(this).data("mouse");
				mouse && mouse._mouseDestroy();
			});
		}

		this.generated && this.generated.remove();

	},

	_start: function(event, handle) {

		var o = this.options;
		if(o.disabled) return false;

		// Prepare the outer size
		this.actualSize = { width: this.element.outerWidth() , height: this.element.outerHeight() };

		// This is a especially ugly fix for strange blur events happening on mousemove events
		if (!this.currentHandle)
			this._focus(this.previousHandle, true);

		this.offset = this.element.offset();

		this.handleOffset = this.currentHandle.offset();
		this.clickOffset = { top: event.pageY - this.handleOffset.top, left: event.pageX - this.handleOffset.left };

		this.firstValue = this.value();

		this._propagate('start', event);
		this._drag(event, handle);
		return true;

	},

	_drag: function(event, handle) {

		var o = this.options;

		var position = { top: event.pageY - this.offset.top - this.clickOffset.top, left: event.pageX - this.offset.left - this.clickOffset.left};
		if(!this.currentHandle) this._focus(this.previousHandle, true); //This is a especially ugly fix for strange blur events happening on mousemove events

		position.left = this._translateLimits(position.left, "x");
		position.top = this._translateLimits(position.top, "y");

		if (o.stepping.x) {
			var value = this._convertValue(position.left, "x");
			value = this._round(value / o.stepping.x) * o.stepping.x;
			position.left = this._translateValue(value, "x");
		}
		if (o.stepping.y) {
			var value = this._convertValue(position.top, "y");
			value = this._round(value / o.stepping.y) * o.stepping.y;
			position.top = this._translateValue(value, "y");
		}

		position.left = this._translateRange(position.left, "x");
		position.top = this._translateRange(position.top, "y");

		if(o.axis != "vertical") this.currentHandle.css({ left: position.left });
		if(o.axis != "horizontal") this.currentHandle.css({ top: position.top });

		//Store the slider's value
		this.currentHandle.data("mouse").sliderValue = {
			x: this._round(this._convertValue(position.left, "x")) || 0,
			y: this._round(this._convertValue(position.top, "y")) || 0
		};

		if (this.rangeElement)
			this._updateRange();
		this._propagate('slide', event);
		return false;

	},

	_stop: function(event) {

		this._propagate('stop', event);

		if (this.firstValue != this.value())
			this._propagate('change', event);

		// This is a especially ugly fix for strange blur events happening on mousemove events
		this._focus(this.currentHandle, true);

		return false;

	},

	_round: function(value) {

		return this.options.round ? parseInt(value,10) : parseFloat(value);

	},

	_setData: function(key, value) {

		$.widget.prototype._setData.apply(this, arguments);

		if (/min|max|steps/.test(key)) {
			this._initBoundaries();
		}

		if(key == "range") {
			value ? this.handle.length == 2 && this._createRange() : this._removeRange();
		}

	},

	_initBoundaries: function() {

		var element = this.element[0], o = this.options;
		this.actualSize = { width: this.element.outerWidth() , height: this.element.outerHeight() };

		$.extend(o, {
			axis: o.axis || (element.offsetWidth < element.offsetHeight ? 'vertical' : 'horizontal'),
			max: !isNaN(parseInt(o.max,10)) ? { x: parseInt(o.max, 10), y: parseInt(o.max, 10) } : ({ x: o.max && o.max.x || 100, y: o.max && o.max.y || 100 }),
			min: !isNaN(parseInt(o.min,10)) ? { x: parseInt(o.min, 10), y: parseInt(o.min, 10) } : ({ x: o.min && o.min.x || 0, y: o.min && o.min.y || 0 })
		});
		//Prepare the real maxValue
		o.realMax = {
			x: o.max.x - o.min.x,
			y: o.max.y - o.min.y
		};
		//Calculate stepping based on steps
		o.stepping = {
			x: o.stepping && o.stepping.x || parseInt(o.stepping, 10) || (o.steps ? o.realMax.x/(o.steps.x || parseInt(o.steps, 10) || o.realMax.x) : 0),
			y: o.stepping && o.stepping.y || parseInt(o.stepping, 10) || (o.steps ? o.realMax.y/(o.steps.y || parseInt(o.steps, 10) || o.realMax.y) : 0)
		};

	},

	_keydown: function(keyCode, handle) {

		if (this.options.disabled)
			return;

		var k = keyCode;
		if(/(33|34|35|36|37|38|39|40)/.test(k)) {
			var o = this.options, xpos, ypos;
			if (/(35|36)/.test(k)) {
				xpos = (k == 35) ? o.max.x : o.min.x;
				ypos = (k == 35) ? o.max.y : o.min.y;
			} else {
				var oper = /(34|37|40)/.test(k) ? "-=" : "+=";
				var step = /(37|38|39|40)/.test(k) ? "_oneStep" : "_pageStep";
				xpos = oper + this[step]("x");
				ypos = oper + this[step]("y");
			}
			this.moveTo({
				x: xpos,
				y: ypos
			}, handle);
			return false;
		}
		return true;

	},

	_focus: function(handle,hard) {

		this.currentHandle = $(handle).addClass('ui-slider-handle-active');

		if (hard)
			this.currentHandle.parent()[0].focus();

	},

	_blur: function(handle) {

		$(handle).removeClass('ui-slider-handle-active');

		if(this.currentHandle && this.currentHandle[0] == handle) {
			this.previousHandle = this.currentHandle;
			this.currentHandle = null;
		};

	},

	_click: function(event) {

		// This method is only used if:
		// - The user didn't click a handle
		// - The Slider is not disabled
		// - There is a current, or previous selected handle (otherwise we wouldn't know which one to move)

		var pointer = [event.pageX, event.pageY];

		var clickedHandle = false;
		this.handle.each(function() {
			if(this == event.target)
				clickedHandle = true;
		});
		if (clickedHandle || this.options.disabled || !(this.currentHandle || this.previousHandle))
			return;

		// If a previous handle was focussed, focus it again
		if (!this.currentHandle && this.previousHandle)
			this._focus(this.previousHandle, true);

		// propagate only for distance > 0, otherwise propagation is done my drag
		this.offset = this.element.offset();

		this.moveTo({
			y: this._convertValue(event.pageY - this.offset.top - this.currentHandle[0].offsetHeight/2, "y"),
			x: this._convertValue(event.pageX - this.offset.left - this.currentHandle[0].offsetWidth/2, "x")
		}, null, !this.options.distance);

	},

	_createRange: function() {

		if(this.rangeElement) return;
		this.rangeElement = $('<div></div>')
			.addClass('ui-slider-range')
			.css({ position: 'absolute' })
			.appendTo(this.element);
		this._updateRange();

	},

	_removeRange: function() {

		this.rangeElement.remove();
		this.rangeElement = null;

	},

	_updateRange: function() {

		var prop = this.options.axis == "vertical" ? "top" : "left";
		var size = this.options.axis == "vertical" ? "height" : "width";

		this.rangeElement.css(prop, (this._round($(this.handle[0]).css(prop)) || 0) + this._handleSize(0, this.options.axis == "vertical" ? "y" : "x")/2);
		this.rangeElement.css(size, (this._round($(this.handle[1]).css(prop)) || 0) - (this._round($(this.handle[0]).css(prop)) || 0));

	},

	_getRange: function() {

		return this.rangeElement ? this._convertValue(this._round(this.rangeElement.css(this.options.axis == "vertical" ? "height" : "width")), this.options.axis == "vertical" ? "y" : "x") : null;

	},

	_handleIndex: function() {

		return this.handle.index(this.currentHandle[0]);

	},

	value: function(handle, axis) {

		if(this.handle.length == 1) this.currentHandle = this.handle;
		if(!axis) axis = this.options.axis == "vertical" ? "y" : "x";

		var curHandle = $(handle != undefined && handle !== null ? this.handle[handle] || handle : this.currentHandle);

		if(curHandle.data("mouse").sliderValue) {
			return this._round(curHandle.data("mouse").sliderValue[axis]);
		} else {
			return this._round(((this._round(curHandle.css(axis == "x" ? "left" : "top")) / (this.actualSize[axis == "x" ? "width" : "height"] - this._handleSize(handle,axis))) * this.options.realMax[axis]) + this.options.min[axis]);
		}

	},

	_convertValue: function(value,axis) {

		return this.options.min[axis] + (value / (this.actualSize[axis == "x" ? "width" : "height"] - this._handleSize(null,axis))) * this.options.realMax[axis];

	},

	_translateValue: function(value,axis) {

		return ((value - this.options.min[axis]) / this.options.realMax[axis]) * (this.actualSize[axis == "x" ? "width" : "height"] - this._handleSize(null,axis));

	},

	_translateRange: function(value,axis) {

		if (this.rangeElement) {
			if (this.currentHandle[0] == this.handle[0] && value >= this._translateValue(this.value(1),axis))
				value = this._translateValue(this.value(1,axis) - this._oneStep(axis), axis);
			if (this.currentHandle[0] == this.handle[1] && value <= this._translateValue(this.value(0),axis))
				value = this._translateValue(this.value(0,axis) + this._oneStep(axis), axis);
		}

		if (this.options.handles) {
			var handle = this.options.handles[this._handleIndex()];
			if (value < this._translateValue(handle.min,axis)) {
				value = this._translateValue(handle.min,axis);
			} else if (value > this._translateValue(handle.max,axis)) {
				value = this._translateValue(handle.max,axis);
			}
		}

		return value;

	},

	_translateLimits: function(value,axis) {

		if (value >= this.actualSize[axis == "x" ? "width" : "height"] - this._handleSize(null,axis))
			value = this.actualSize[axis == "x" ? "width" : "height"] - this._handleSize(null,axis);

		if (value <= 0)
			value = 0;

		return value;

	},

	_handleSize: function(handle,axis) {

		return $(handle != undefined && handle !== null ? this.handle[handle] : this.currentHandle)[0]["offset"+(axis == "x" ? "Width" : "Height")];

	},

	_oneStep: function(axis) {

		return this.options.stepping[axis] || 1;

	},

	_pageStep: function(axis) {

		return /* this.options.paging[axis] ||*/ 10;

	},

	moveTo: function(value, handle, noPropagation) {

		var o = this.options;

		// Prepare the outer size
		this.actualSize = { width: this.element.outerWidth() , height: this.element.outerHeight() };

		//If no handle has been passed, no current handle is available and we have multiple handles, return false
		if (handle == undefined && !this.currentHandle && this.handle.length != 1)
			return false;

		//If only one handle is available, use it
		if (handle == undefined && !this.currentHandle)
			handle = 0;

		if (handle != undefined)
			this.currentHandle = this.previousHandle = $(this.handle[handle] || handle);

		if(value.x !== undefined && value.y !== undefined) {
			var x = value.x, y = value.y;
		} else {
			var x = value, y = value;
		}

		if(x !== undefined && x.constructor != Number) {
			var me = /^\-\=/.test(x), pe = /^\+\=/.test(x);
			if(me || pe) {
				x = this.value(null, "x") + this._round(x.replace(me ? '=' : '+=', ''));
			} else {
				x = isNaN(this._round(x)) ? undefined : this._round(x);
			}
		}

		if(y !== undefined && y.constructor != Number) {
			var me = /^\-\=/.test(y), pe = /^\+\=/.test(y);
			if(me || pe) {
				y = this.value(null, "y") + this._round(y.replace(me ? '=' : '+=', ''));
			} else {
				y = isNaN(this._round(y)) ? undefined : this._round(y);
			}
		}

		if(o.axis != "vertical" && x !== undefined) {
			if(o.stepping.x) x = this._round(x / o.stepping.x) * o.stepping.x;
			x = this._translateValue(x, "x");
			x = this._translateLimits(x, "x");
			x = this._translateRange(x, "x");

			o.animate ? this.currentHandle.stop().animate({ left: x }, (Math.abs(parseInt(this.currentHandle.css("left"),10) - x)) * (!isNaN(parseInt(o.animate,10)) ? o.animate : 5)) : this.currentHandle.css({ left: x });
		}

		if(o.axis != "horizontal" && y !== undefined) {
			if(o.stepping.y) y = this._round(y / o.stepping.y) * o.stepping.y;
			y = this._translateValue(y, "y");
			y = this._translateLimits(y, "y");
			y = this._translateRange(y, "y");
			o.animate ? this.currentHandle.stop().animate({ top: y }, (Math.abs(parseInt(this.currentHandle.css("top"),10) - y)) * (!isNaN(parseInt(o.animate,10)) ? o.animate : 5)) : this.currentHandle.css({ top: y });
		}

		if (this.rangeElement)
			this._updateRange();

		//Store the slider's value
		this.currentHandle.data("mouse").sliderValue = {
			x: this._round(this._convertValue(x, "x")) || 0,
			y: this._round(this._convertValue(y, "y")) || 0
		};

		if (!noPropagation) {
			this._propagate('start', null);
			this._propagate("slide", null);
			this._propagate('stop', null);
			this._propagate('change', null);
		}

	},

	_propagate: function(n, event) {

		$.ui.plugin.call(this, n, [event, this.ui()]);
		this.element.triggerHandler(n == "slide" ? n : "slide"+n, [event, this.ui()], this.options[n]);

	},

	plugins: {},

	ui: function(event) {
		return {
			options: this.options,
			handle: this.currentHandle,
			value: this.options.axis != "both" || !this.options.axis ?
				this._round(this.value(null, this.options.axis == "vertical" ? "y" : "x")) :
				{
					x: this._round(this.value(null, "x")),
					y: this._round(this.value(null, "y"))
				},
			range: this._getRange()
		};
	}

});

$.extend($.ui.slider, {
	getter: "value",
	version: "1.6",
	defaults: {
		animate: false,
		distance: 1,
		handle: ".ui-slider-handle",
		round: true
	}
});

})(jQuery);
/*
 * jQuery UI Tabs 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.tabs", {

	_init: function() {
		// create tabs
		this._tabify(true);
	},

	destroy: function() {
		var o = this.options;
		this.element.unbind('.tabs')
			.removeClass(o.navClass).removeData('tabs');
		this.$tabs.each(function() {
			var href = $.data(this, 'href.tabs');
			if (href)
				this.href = href;
			var $this = $(this).unbind('.tabs');
			$.each(['href', 'load', 'cache'], function(i, prefix) {
				$this.removeData(prefix + '.tabs');
			});
		});
		this.$lis.add(this.$panels).each(function() {
			if ($.data(this, 'destroy.tabs'))
				$(this).remove();
			else
				$(this).removeClass([o.selectedClass, o.deselectableClass,
					o.disabledClass, o.panelClass, o.hideClass].join(' '));
		});
		if (o.cookie)
			this._cookie(null, o.cookie);
	},

	_setData: function(key, value) {
		if ((/^selected/).test(key))
			this.select(value);
		else {
			this.options[key] = value;
			this._tabify();
		}
	},

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

	_tabId: function(a) {
		return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '')
			|| this.options.idPrefix + $.data(a);
	},

	_sanitizeSelector: function(hash) {
		return hash.replace(/:/g, '\\:'); // we need this because an id may contain a ":"
	},

	_cookie: function() {
		var cookie = this.cookie || (this.cookie = 'ui-tabs-' + $.data(this.element[0]));
		return $.cookie.apply(null, [cookie].concat($.makeArray(arguments)));
	},

	_tabify: function(init) {

		this.$lis = $('li:has(a[href])', this.element);
		this.$tabs = this.$lis.map(function() { return $('a', this)[0]; });
		this.$panels = $([]);

		var self = this, o = this.options;

		this.$tabs.each(function(i, a) {
			// inline tab
			if (a.hash && a.hash.replace('#', '')) // Safari 2 reports '#' for an empty hash
				self.$panels = self.$panels.add(self._sanitizeSelector(a.hash));
			// remote tab
			else if ($(a).attr('href') != '#') { // prevent loading the page itself if href is just "#"
				$.data(a, 'href.tabs', a.href); // required for restore on destroy
				$.data(a, 'load.tabs', a.href); // mutable
				var id = self._tabId(a);
				a.href = '#' + id;
				var $panel = $('#' + id);
				if (!$panel.length) {
					$panel = $(o.panelTemplate).attr('id', id).addClass(o.panelClass)
						.insertAfter(self.$panels[i - 1] || self.element);
					$panel.data('destroy.tabs', true);
				}
				self.$panels = self.$panels.add($panel);
			}
			// invalid tab href
			else
				o.disabled.push(i + 1);
		});

		// initialization from scratch
		if (init) {

			// attach necessary classes for styling if not present
			this.element.addClass(o.navClass);
			this.$panels.addClass(o.panelClass);

			// Selected tab
			// use "selected" option or try to retrieve:
			// 1. from fragment identifier in url
			// 2. from cookie
			// 3. from selected class attribute on <li>
			if (o.selected === undefined) {
				if (location.hash) {
					this.$tabs.each(function(i, a) {
						if (a.hash == location.hash) {
							o.selected = i;
							return false; // break
						}
					});
				}
				else if (o.cookie) {
					var index = parseInt(self._cookie(), 10);
					if (index && self.$tabs[index]) o.selected = index;
				}
				else if (self.$lis.filter('.' + o.selectedClass).length)
					o.selected = self.$lis.index( self.$lis.filter('.' + o.selectedClass)[0] );
			}
			o.selected = o.selected === null || o.selected !== undefined ? o.selected : 0; // first tab selected by default

			// Take disabling tabs via class attribute from HTML
			// into account and update option properly.
			// A selected tab cannot become disabled.
			o.disabled = $.unique(o.disabled.concat(
				$.map(this.$lis.filter('.' + o.disabledClass),
					function(n, i) { return self.$lis.index(n); } )
			)).sort();
			if ($.inArray(o.selected, o.disabled) != -1)
				o.disabled.splice($.inArray(o.selected, o.disabled), 1);

			// highlight selected tab
			this.$panels.addClass(o.hideClass);
			this.$lis.removeClass(o.selectedClass);
			if (o.selected !== null) {
				this.$panels.eq(o.selected).removeClass(o.hideClass);
				var classes = [o.selectedClass];
				if (o.deselectable) classes.push(o.deselectableClass);
				this.$lis.eq(o.selected).addClass(classes.join(' '));

				// seems to be expected behavior that the show callback is fired
				var onShow = function() {
					self._trigger('show', null,
						self.ui(self.$tabs[o.selected], self.$panels[o.selected]));
				};

				// load if remote tab
				if ($.data(this.$tabs[o.selected], 'load.tabs'))
					this.load(o.selected, onShow);
				// just trigger show event
				else onShow();
			}

			// clean up to avoid memory leaks in certain versions of IE 6
			$(window).bind('unload', function() {
				self.$tabs.unbind('.tabs');
				self.$lis = self.$tabs = self.$panels = null;
			});

		}
		// update selected after add/remove
		else
			o.selected = this.$lis.index( this.$lis.filter('.' + o.selectedClass)[0] );

		// set or update cookie after init and add/remove respectively
		if (o.cookie) this._cookie(o.selected, o.cookie);

		// disable tabs
		for (var i = 0, li; li = this.$lis[i]; i++)
			$(li)[$.inArray(i, o.disabled) != -1 && !$(li).hasClass(o.selectedClass) ? 'addClass' : 'removeClass'](o.disabledClass);

		// reset cache if switching from cached to not cached
		if (o.cache === false) this.$tabs.removeData('cache.tabs');

		// set up animations
		var hideFx, showFx;
		if (o.fx) {
			if (o.fx.constructor == Array) {
				hideFx = o.fx[0];
				showFx = o.fx[1];
			}
			else hideFx = showFx = o.fx;
		}

		// Reset certain styles left over from animation
		// and prevent IE's ClearType bug...
		function resetStyle($el, fx) {
			$el.css({ display: '' });
			if ($.browser.msie && fx.opacity) $el[0].style.removeAttribute('filter');
		}

		// Show a tab...
		var showTab = showFx ?
			function(clicked, $show) {
				$show.animate(showFx, showFx.duration || 'normal', function() {
					$show.removeClass(o.hideClass);
					resetStyle($show, showFx);
					self._trigger('show', null, self.ui(clicked, $show[0]));
				});
			} :
			function(clicked, $show) {
				$show.removeClass(o.hideClass);
				self._trigger('show', null, self.ui(clicked, $show[0]));
			};

		// Hide a tab, $show is optional...
		var hideTab = hideFx ?
			function(clicked, $hide, $show) {
				$hide.animate(hideFx, hideFx.duration || 'normal', function() {
					$hide.addClass(o.hideClass);
					resetStyle($hide, hideFx);
					if ($show) showTab(clicked, $show, $hide);
				});
			} :
			function(clicked, $hide, $show) {
				$hide.addClass(o.hideClass);
				if ($show) showTab(clicked, $show);
			};

		// Switch a tab...
		function switchTab(clicked, $li, $hide, $show) {
			var classes = [o.selectedClass];
			if (o.deselectable) classes.push(o.deselectableClass);
			$li.addClass(classes.join(' ')).siblings().removeClass(classes.join(' '));
			hideTab(clicked, $hide, $show);
		}

		// attach tab event handler, unbind to avoid duplicates from former tabifying...
		this.$tabs.unbind('.tabs').bind(o.event + '.tabs', function() {

			//var trueClick = event.clientX; // add to history only if true click occured, not a triggered click
			var $li = $(this).parents('li:eq(0)'),
				$hide = self.$panels.filter(':visible'),
				$show = $(self._sanitizeSelector(this.hash));

			// If tab is already selected and not deselectable or tab disabled or
			// or is already loading or click callback returns false stop here.
			// Check if click handler returns false last so that it is not executed
			// for a disabled or loading tab!
			if (($li.hasClass(o.selectedClass) && !o.deselectable)
				|| $li.hasClass(o.disabledClass)
				|| $(this).hasClass(o.loadingClass)
				|| self._trigger('select', null, self.ui(this, $show[0])) === false
				) {
				this.blur();
				return false;
			}

			o.selected = self.$tabs.index(this);

			// if tab may be closed
			if (o.deselectable) {
				if ($li.hasClass(o.selectedClass)) {
					self.options.selected = null;
					$li.removeClass([o.selectedClass, o.deselectableClass].join(' '));
					self.$panels.stop();
					hideTab(this, $hide);
					this.blur();
					return false;
				} else if (!$hide.length) {
					self.$panels.stop();
					var a = this;
					self.load(self.$tabs.index(this), function() {
						$li.addClass([o.selectedClass, o.deselectableClass].join(' '));
						showTab(a, $show);
					});
					this.blur();
					return false;
				}
			}

			if (o.cookie) self._cookie(o.selected, o.cookie);

			// stop possibly running animations
			self.$panels.stop();

			// show new tab
			if ($show.length) {
				var a = this;
				self.load(self.$tabs.index(this), $hide.length ?
					function() {
						switchTab(a, $li, $hide, $show);
					} :
					function() {
						$li.addClass(o.selectedClass);
						showTab(a, $show);
					}
				);
			} else
				throw 'jQuery UI Tabs: Mismatching fragment identifier.';

			// Prevent IE from keeping other link focussed when using the back button
			// and remove dotted border from clicked link. This is controlled via CSS
			// in modern browsers; blur() removes focus from address bar in Firefox
			// which can become a usability and annoying problem with tabs('rotate').
			if ($.browser.msie) this.blur();

			return false;

		});

		// disable click if event is configured to something else
		if (o.event != 'click') this.$tabs.bind('click.tabs', function(){return false;});

	},

	add: function(url, label, index) {
		if (index == undefined)
			index = this.$tabs.length; // append by default

		var o = this.options;
		var $li = $(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label));
		$li.data('destroy.tabs', true);

		var id = url.indexOf('#') == 0 ? url.replace('#', '') : this._tabId( $('a:first-child', $li)[0] );

		// try to find an existing element before creating a new one
		var $panel = $('#' + id);
		if (!$panel.length) {
			$panel = $(o.panelTemplate).attr('id', id)
				.addClass(o.hideClass)
				.data('destroy.tabs', true);
		}
		$panel.addClass(o.panelClass);
		if (index >= this.$lis.length) {
			$li.appendTo(this.element);
			$panel.appendTo(this.element[0].parentNode);
		} else {
			$li.insertBefore(this.$lis[index]);
			$panel.insertBefore(this.$panels[index]);
		}

		o.disabled = $.map(o.disabled,
			function(n, i) { return n >= index ? ++n : n });

		this._tabify();

		if (this.$tabs.length == 1) {
			$li.addClass(o.selectedClass);
			$panel.removeClass(o.hideClass);
			var href = $.data(this.$tabs[0], 'load.tabs');
			if (href)
				this.load(index, href);
		}

		// callback
		this._trigger('add', null, this.ui(this.$tabs[index], this.$panels[index]));
	},

	remove: function(index) {
		var o = this.options, $li = this.$lis.eq(index).remove(),
			$panel = this.$panels.eq(index).remove();

		// If selected tab was removed focus tab to the right or
		// in case the last tab was removed the tab to the left.
		if ($li.hasClass(o.selectedClass) && this.$tabs.length > 1)
			this.select(index + (index + 1 < this.$tabs.length ? 1 : -1));

		o.disabled = $.map($.grep(o.disabled, function(n, i) { return n != index; }),
			function(n, i) { return n >= index ? --n : n });

		this._tabify();

		// callback
		this._trigger('remove', null, this.ui($li.find('a')[0], $panel[0]));
	},

	enable: function(index) {
		var o = this.options;
		if ($.inArray(index, o.disabled) == -1)
			return;

		var $li = this.$lis.eq(index).removeClass(o.disabledClass);
		if ($.browser.safari) { // fix disappearing tab (that used opacity indicating disabling) after enabling in Safari 2...
			$li.css('display', 'inline-block');
			setTimeout(function() {
				$li.css('display', 'block');
			}, 0);
		}

		o.disabled = $.grep(o.disabled, function(n, i) { return n != index; });

		// callback
		this._trigger('enable', null, this.ui(this.$tabs[index], this.$panels[index]));
	},

	disable: function(index) {
		var self = this, o = this.options;
		if (index != o.selected) { // cannot disable already selected tab
			this.$lis.eq(index).addClass(o.disabledClass);

			o.disabled.push(index);
			o.disabled.sort();

			// callback
			this._trigger('disable', null, this.ui(this.$tabs[index], this.$panels[index]));
		}
	},

	select: function(index) {
		// TODO make null as argument work
		if (typeof index == 'string')
			index = this.$tabs.index( this.$tabs.filter('[href$=' + index + ']')[0] );
		this.$tabs.eq(index).trigger(this.options.event + '.tabs');
	},

	load: function(index, callback) { // callback is for internal usage only

		var self = this, o = this.options, $a = this.$tabs.eq(index), a = $a[0],
				bypassCache = callback == undefined || callback === false, url = $a.data('load.tabs');

		callback = callback || function() {};

		// no remote or from cache - just finish with callback
		if (!url || !bypassCache && $.data(a, 'cache.tabs')) {
			callback();
			return;
		}

		// load remote from here on

		var inner = function(parent) {
			var $parent = $(parent), $inner = $parent.find('*:last');
			return $inner.length && $inner.is(':not(img)') && $inner || $parent;
		};
		var cleanup = function() {
			self.$tabs.filter('.' + o.loadingClass).removeClass(o.loadingClass)
					.each(function() {
						if (o.spinner)
							inner(this).parent().html(inner(this).data('label.tabs'));
					});
			self.xhr = null;
		};

		if (o.spinner) {
			var label = inner(a).html();
			inner(a).wrapInner('<em></em>')
				.find('em').data('label.tabs', label).html(o.spinner);
		}

		var ajaxOptions = $.extend({}, o.ajaxOptions, {
			url: url,
			success: function(r, s) {
				$(self._sanitizeSelector(a.hash)).html(r);
				cleanup();

				if (o.cache)
					$.data(a, 'cache.tabs', true); // if loaded once do not load them again

				// callbacks
				self._trigger('load', null, self.ui(self.$tabs[index], self.$panels[index]));
				try {
					o.ajaxOptions.success(r, s);
				}
				catch (event) {}

				// This callback is required because the switch has to take
				// place after loading has completed. Call last in order to
				// fire load before show callback...
				callback();
			}
		});
		if (this.xhr) {
			// terminate pending requests from other tabs and restore tab label
			this.xhr.abort();
			cleanup();
		}
		$a.addClass(o.loadingClass);
		self.xhr = $.ajax(ajaxOptions);
	},

	url: function(index, url) {
		this.$tabs.eq(index).removeData('cache.tabs').data('load.tabs', url);
	},

	ui: function(tab, panel) {
		return {
			options: this.options,
			tab: tab,
			panel: panel,
			index: this.$tabs.index(tab)
		};
	}

});

$.extend($.ui.tabs, {
	version: '1.6',
	getter: 'length',
	defaults: {
		ajaxOptions: null,
		cache: false,
		cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
		deselectable: false,
		deselectableClass: 'ui-tabs-deselectable',
		disabled: [],
		disabledClass: 'ui-tabs-disabled',
		event: 'click',
		fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 }
		hideClass: 'ui-tabs-hide',
		idPrefix: 'ui-tabs-',
		loadingClass: 'ui-tabs-loading',
		navClass: 'ui-tabs-nav',
		panelClass: 'ui-tabs-panel',
		panelTemplate: '<div></div>',
		selectedClass: 'ui-tabs-selected',
		spinner: 'Loading&#8230;',
		tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>'
	}
});

/*
 * Tabs Extensions
 */

/*
 * Rotate
 */
$.extend($.ui.tabs.prototype, {
	rotation: null,
	rotate: function(ms, continuing) {

		continuing = continuing || false;

		var self = this, t = this.options.selected;

		function start() {
			self.rotation = setInterval(function() {
				t = ++t < self.$tabs.length ? t : 0;
				self.select(t);
			}, ms);
		}

		function stop(event) {
			if (!event || event.clientX) { // only in case of a true click
				clearInterval(self.rotation);
			}
		}

		// start interval
		if (ms) {
			start();
			if (!continuing)
				this.$tabs.bind(this.options.event + '.tabs', stop);
			else
				this.$tabs.bind(this.options.event + '.tabs', function() {
					stop();
					t = self.options.selected;
					start();
				});
		}
		// stop interval
		else {
			stop();
			this.$tabs.unbind(this.options.event + '.tabs', stop);
		}
	}
});

})(jQuery);
/*
 * jQuery UI Datepicker 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	ui.core.js
 */

(function($) { // hide the namespace

$.extend($.ui, { datepicker: { version: "1.6" } });

var PROP_NAME = 'datepicker';

/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this.debug = false; // Change this to true to start debugging
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
	this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
	this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
	this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
	this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
	this._promptClass = 'ui-datepicker-prompt'; // The name of the dialog prompt marker class
	this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
	this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
	this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
	this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
	this._weekOverClass = 'ui-datepicker-week-over'; // The name of the week hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[''] = { // Default regional settings
		clearText: 'Clear', // Display text for clear link
		clearStatus: 'Erase the current date', // Status text for clear link
		closeText: 'Close', // Display text for close link
		closeStatus: 'Close without change', // Status text for close link
		prevText: '&#x3c;Prev', // Display text for previous month link
		prevStatus: 'Show the previous month', // Status text for previous month link
		prevBigText: '&#x3c;&#x3c;', // Display text for previous year link
		prevBigStatus: 'Show the previous year', // Status text for previous year link
		nextText: 'Next&#x3e;', // Display text for next month link
		nextStatus: 'Show the next month', // Status text for next month link
		nextBigText: '&#x3e;&#x3e;', // Display text for next year link
		nextBigStatus: 'Show the next year', // Status text for next year link
		currentText: 'Today', // Display text for current month link
		currentStatus: 'Show the current month', // Status text for current month link
		monthNames: ['January','February','March','April','May','June',
			'July','August','September','October','November','December'], // Names of months for drop-down and formatting
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
		monthStatus: 'Show a different month', // Status text for selecting a month
		yearStatus: 'Show a different year', // Status text for selecting a year
		weekHeader: 'Wk', // Header for the week of the year column
		weekStatus: 'Week of the year', // Status text for the week of the year column
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
		dayStatus: 'Set DD as first week day', // Status text for the day of the week selection
		dateStatus: 'Select DD, M d', // Status text for the date selection
		dateFormat: 'mm/dd/yy', // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		initStatus: 'Select a date', // Initial Status text on opening
		isRTL: false // True if right-to-left language, false if left-to-right
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: 'focus', // 'focus' for popup on focus,
			// 'button' for trigger button, or 'both' for either
		showAnim: 'show', // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: '', // Display text following the input box, e.g. showing the format
		buttonText: '...', // Text for trigger button
		buttonImage: '', // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		closeAtTop: true, // True to have the clear/close at the top,
			// false to have them at the bottom
		mandatory: false, // True to hide the Clear link, false to include it
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		showBigPrevNext: false, // True to show big prev/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: true, // True if month can be selected directly, false if only prev/next
		changeYear: true, // True if year can be selected directly, false if only prev/next
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearRange: '-10:+10', // Range of years to display in drop-down,
			// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
		changeFirstDay: true, // True to click on day name to change, false to remain as set
		highlightWeek: false, // True to highlight the selected week
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		showWeeks: false, // True to show week of the year, false to omit
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: '+10', // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with '+' for current year + value
		showStatus: false, // True to show status bar at bottom, false to not show it
		statusForDate: this.dateStatus, // Function to provide status text for a date -
			// takes date and instance as parameters, returns display text
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: 'normal', // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		rangeSelect: false, // Allows for selecting a date range on one date picker
		rangeSeparator: ' - ', // Text between two dates in a range
		altField: '', // Selector for an alternate field to store selected dates into
		altFormat: '', // The date format to use for the alternate field
		constrainInput: true // The input is constrained by the current date format
	};
	$.extend(this._defaults, this.regional['']);
	this.dpDiv = $('<div id="' + this._mainDivId + '" style="display: none;"></div>');
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: 'hasDatepicker',

	/* Debug logging (if enabled). */
	log: function () {
		if (this.debug)
			console.log.apply('', arguments);
	},

	/* Override the default settings for all instances of the date picker.
	   @param  settings  object - the new settings to use as defaults (anonymous object)
	   @return the manager object */
	setDefaults: function(settings) {
		extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span
	   @param  settings  object - the new settings to use for this date picker instance (anonymous) */
	_attachDatepicker: function(target, settings) {
		// check for settings on the control itself - in namespace 'date:'
		var inlineSettings = null;
		for (var attrName in this._defaults) {
			var attrValue = target.getAttribute('date:' + attrName);
			if (attrValue) {
				inlineSettings = inlineSettings || {};
				try {
					inlineSettings[attrName] = eval(attrValue);
				} catch (err) {
					inlineSettings[attrName] = attrValue;
				}
			}
		}
		var nodeName = target.nodeName.toLowerCase();
		var inline = (nodeName == 'div' || nodeName == 'span');
		if (!target.id)
			target.id = 'dp' + (++this.uuid);
		var inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {}, inlineSettings || {});
		if (nodeName == 'input') {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			$('<div class="' + this._inlineClass + '"></div>'))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);
		if (input.hasClass(this.markerClassName))
			return;
		var appendText = this._get(inst, 'appendText');
		var isRTL = this._get(inst, 'isRTL');
		if (appendText)
			input[isRTL ? 'before' : 'after']('<span class="' + this._appendClass + '">' + appendText + '</span>');
		var showOn = this._get(inst, 'showOn');
		if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
			input.focus(this._showDatepicker);
		if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
			var buttonText = this._get(inst, 'buttonText');
			var buttonImage = this._get(inst, 'buttonImage');
			var trigger = $(this._get(inst, 'buttonImageOnly') ?
				$('<img/>').addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$('<button type="button"></button>').addClass(this._triggerClass).
					html(buttonImage == '' ? buttonText : $('<img/>').attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? 'before' : 'after'](trigger);
			trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target)
					$.datepicker._hideDatepicker();
				else
					$.datepicker._showDatepicker(target);
				return false;
			});
		}
		input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).
			bind("setData.datepicker", function(event, key, value) {
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key) {
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName))
			return;
		divSpan.addClass(this.markerClassName).append(inst.dpDiv).
			bind("setData.datepicker", function(event, key, value){
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key){
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
		this._setDate(inst, this._getDefaultDate(inst));
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
	},

	/* Pop-up the date picker in a "dialog" box.
	   @param  input     element - ignored
	   @param  dateText  string - the initial date to display (in the current format)
	   @param  onSelect  function - the function(dateText) to call when a date is selected
	   @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	   @param  pos       int[2] - coordinates for the dialog's position within the screen or
	                     event - with x/y coordinates or
	                     leave empty for default (screen centre)
	   @return the manager object */
	_dialogDatepicker: function(input, dateText, onSelect, settings, pos) {
		var inst = this._dialogInst; // internal instance
		if (!inst) {
			var id = 'dp' + (++this.uuid);
			this._dialogInput = $('<input type="text" id="' + id +
				'" size="1" style="position: absolute; top: -100px;"/>');
			this._dialogInput.keydown(this._doKeyDown);
			$('body').append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], PROP_NAME, inst);
		}
		extendRemove(inst.settings, settings || {});
		this._dialogInput.val(dateText);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			var browserWidth = window.innerWidth || document.documentElement.clientWidth ||	document.body.clientWidth;
			var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI)
			$.blockUI(this.dpDiv);
		$.data(this._dialogInput[0], PROP_NAME, inst);
		return this;
	},

	/* Detach a datepicker from its control.
	   @param  target    element - the target input field or division or span */
	_destroyDatepicker: function(target) {
		var $target = $(target);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		$.removeData(target, PROP_NAME);
		if (nodeName == 'input') {
			$target.siblings('.' + this._appendClass).remove().end().
				siblings('.' + this._triggerClass).remove().end().
				removeClass(this.markerClassName).
				unbind('focus', this._showDatepicker).
				unbind('keydown', this._doKeyDown).
				unbind('keypress', this._doKeyPress);
		} else if (nodeName == 'div' || nodeName == 'span')
			$target.removeClass(this.markerClassName).empty();
	},

	/* Enable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_enableDatepicker: function(target) {
		var $target = $(target);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = false;
			$target.siblings('button.' + this._triggerClass).
			each(function() { this.disabled = false; }).end().
				siblings('img.' + this._triggerClass).
				css({opacity: '1.0', cursor: ''});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			$target.children('.' + this._disableClass).remove();
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_disableDatepicker: function(target) {
		var $target = $(target);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = true;
			$target.siblings('button.' + this._triggerClass).
			each(function() { this.disabled = true; }).end().
				siblings('img.' + this._triggerClass).
				css({opacity: '0.5', cursor: 'default'});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			var offset = inline.offset();
			var relOffset = {left: 0, top: 0};
			inline.parents().each(function() {
				if ($(this).css('position') == 'relative') {
					relOffset = $(this).offset();
					return false;
				}
			});
			$target.prepend('<div class="' + this._disableClass + '" style="' +
				($.browser.msie ? 'background-color: transparent; ' : '') +
				'width: ' + inline.width() + 'px; height: ' + inline.height() +
				'px; left: ' + (offset.left - relOffset.left) +
				'px; top: ' + (offset.top - relOffset.top) + 'px;"></div>');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	   @param  target    element - the target input field or division or span
	   @return boolean - true if disabled, false if enabled */
	_isDisabledDatepicker: function(target) {
		if (!target)
			return false;
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] == target)
				return true;
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	   @param  target  element - the target input field or division or span
	   @return  object - the associated instance data
	   @throws  error if a jQuery problem getting data */
	_getInst: function(target) {
		try {
			return $.data(target, PROP_NAME);
		}
		catch (err) {
			throw 'Missing instance data for this datepicker';
		}
	},

	/* Update the settings for a date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span
	   @param  name    object - the new settings to update or
	                   string - the name of the setting to change or
	   @param  value   any - the new value for the setting (omit if above is an object) */
	_optionDatepicker: function(target, name, value) {
		var settings = name || {};
		if (typeof name == 'string') {
			settings = {};
			settings[name] = value;
		}
		var inst = this._getInst(target);
		if (inst) {
			if (this._curInst == inst) {
				this._hideDatepicker(null);
			}
			extendRemove(inst.settings, settings);
			var date = new Date();
			extendRemove(inst, {rangeStart: null, // start of range
				endDay: null, endMonth: null, endYear: null, // end of range
				selectedDay: date.getDate(), selectedMonth: date.getMonth(),
				selectedYear: date.getFullYear(), // starting point
				currentDay: date.getDate(), currentMonth: date.getMonth(),
				currentYear: date.getFullYear(), // current selection
				drawMonth: date.getMonth(), drawYear: date.getFullYear()}); // month being drawn
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span */
	_refreshDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	   @param  target   element - the target input field or division or span
	   @param  date     Date - the new date
	   @param  endDate  Date - the new end date for a range (optional) */
	_setDateDatepicker: function(target, date, endDate) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date, endDate);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	   @param  target  element - the target input field or division or span
	   @return Date - the current date or
	           Date[2] - the current dates for a range */
	_getDateDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst && !inst.inline)
			this._setDateFromField(inst);
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var inst = $.datepicker._getInst(event.target);
		var handled = true;
		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing)
			switch (event.keyCode) {
				case 9:  $.datepicker._hideDatepicker(null, '');
						break; // hide on tab out
				case 13: var sel = $('td.' + $.datepicker._dayOverClass +
							', td.' + $.datepicker._currentClass, inst.dpDiv);
						if (sel[0])
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						else
							$.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						return false; // don't submit the form
						break; // select the value on enter
				case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, 'stepBigMonths') :
							-$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, 'stepBigMonths') :
							+$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -1, 'D');
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									-$.datepicker._get(inst, 'stepBigMonths') :
									-$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +1, 'D');
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									+$.datepicker._get(inst, 'stepBigMonths') :
									+$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		else {
			handled = false;
		}
		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var inst = $.datepicker._getInst(event.target);
		if ($.datepicker._get(inst, 'constrainInput')) {
			var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
			var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
			return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Pop-up the date picker for a given input field.
	   @param  input  element - the input field attached to the date picker or
	                  event - if triggered by focus */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
			input = $('input', input.parentNode)[0];
		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
			return;
		var inst = $.datepicker._getInst(input);
		var beforeShow = $.datepicker._get(inst, 'beforeShow');
		extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
		$.datepicker._hideDatepicker(null, '');
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);
		if ($.datepicker._inDialog) // hide cursor
			input.value = '';
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}
		var isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css('position') == 'fixed';
			return !isFixed;
		});
		if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
			$.datepicker._pos[0] -= document.documentElement.scrollLeft;
			$.datepicker._pos[1] -= document.documentElement.scrollTop;
		}
		var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
		$.datepicker._pos = null;
		inst.rangeStart = null;
		// determine sizing offscreen
		inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		inst.dpDiv.width($.datepicker._getNumberOfMonths(inst)[1] *
			$('.ui-datepicker', inst.dpDiv[0])[0].offsetWidth);
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
			left: offset.left + 'px', top: offset.top + 'px'});
		if (!inst.inline) {
			var showAnim = $.datepicker._get(inst, 'showAnim') || 'show';
			var duration = $.datepicker._get(inst, 'duration');
			var postProcess = function() {
				$.datepicker._datepickerShowing = true;
				if ($.browser.msie && parseInt($.browser.version,10) < 7) // fix IE < 7 select problems
					$('iframe.ui-datepicker-cover').css({width: inst.dpDiv.width() + 4,
						height: inst.dpDiv.height() + 4});
			};
			if ($.effects && $.effects[showAnim])
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
			else
				inst.dpDiv[showAnim](duration, postProcess);
			if (duration == '')
				postProcess();
			if (inst.input[0].type != 'hidden')
				inst.input[0].focus();
			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		var dims = {width: inst.dpDiv.width() + 4,
			height: inst.dpDiv.height() + 4};
		inst.dpDiv.empty().append(this._generateHTML(inst)).
			find('iframe.ui-datepicker-cover').
			css({width: dims.width, height: dims.height});
		var numMonths = this._getNumberOfMonths(inst);
		inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
			'Class']('ui-datepicker-multi');
		inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
			'Class']('ui-datepicker-rtl');
		if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst)
			$(inst.input[0]).focus();
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var pos = inst.input ? this._findPos(inst.input[0]) : null;
		var browserWidth = window.innerWidth || (document.documentElement ?
			document.documentElement.clientWidth : document.body.clientWidth);
		var browserHeight = window.innerHeight || (document.documentElement ?
			document.documentElement.clientHeight : document.body.clientHeight);
		var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
		var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
		// reposition date picker horizontally if outside the browser window
		if (this._get(inst, 'isRTL') || (offset.left + inst.dpDiv.width() - scrollX) > browserWidth)
			offset.left = Math.max((isFixed ? 0 : scrollX),
				pos[0] + (inst.input ? inst.input.width() : 0) - (isFixed ? scrollX : 0) - inst.dpDiv.width() -
				(isFixed && $.browser.opera ? document.documentElement.scrollLeft : 0));
		else
			offset.left -= (isFixed ? scrollX : 0);
		// reposition date picker vertically if outside the browser window
		if ((offset.top + inst.dpDiv.height() - scrollY) > browserHeight)
			offset.top = Math.max((isFixed ? 0 : scrollY),
				pos[1] - (isFixed ? scrollY : 0) - (this._inDialog ? 0 : inst.dpDiv.height()) -
				(isFixed && $.browser.opera ? document.documentElement.scrollTop : 0));
		else
			offset.top -= (isFixed ? scrollY : 0);
		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
        while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
            obj = obj.nextSibling;
        }
        var position = $(obj).offset();
	    return [position.left, position.top];
	},

	/* Hide the date picker from view.
	   @param  input  element - the input field attached to the date picker
	   @param  duration  string - the duration over which to close the date picker */
	_hideDatepicker: function(input, duration) {
		var inst = this._curInst;
		if (!inst || (input && inst != $.data(input, PROP_NAME)))
			return;
		var rangeSelect = this._get(inst, 'rangeSelect');
		if (rangeSelect && inst.stayOpen)
			this._selectDate('#' + inst.id, this._formatDate(inst,
				inst.currentDay, inst.currentMonth, inst.currentYear));
		inst.stayOpen = false;
		if (this._datepickerShowing) {
			duration = (duration != null ? duration : this._get(inst, 'duration'));
			var showAnim = this._get(inst, 'showAnim');
			var postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};
			if (duration != '' && $.effects && $.effects[showAnim])
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'),
					duration, postProcess);
			else
				inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' :
					(showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess);
			if (duration == '')
				this._tidyDialog(inst);
			var onClose = this._get(inst, 'onClose');
			if (onClose)
				onClose.apply((inst.input ? inst.input[0] : null),
					[(inst.input ? inst.input.val() : ''), inst]);  // trigger custom callback
			this._datepickerShowing = false;
			this._lastInput = null;
			inst.settings.prompt = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
				if ($.blockUI) {
					$.unblockUI();
					$('body').append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
		this._curInst = null;
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker');
		$('.' + this._promptClass, inst.dpDiv).remove();
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst)
			return;
		var $target = $(event.target);
		if (($target.parents('#' + $.datepicker._mainDivId).length == 0) &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.hasClass($.datepicker._triggerClass) &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
			$.datepicker._hideDatepicker(null, '');
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		this._adjustInstDate(inst, offset, period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		}
		else {
		var date = new Date();
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst._selectingMonthYear = false;
		inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
		inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
			parseInt(select.options[select.selectedIndex].value,10);
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Restore input focus after not changing month/year. */
	_clickMonthYear: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (inst.input && inst._selectingMonthYear && !$.browser.msie)
			inst.input[0].focus();
		inst._selectingMonthYear = !inst._selectingMonthYear;
	},

	/* Action for changing the first week day. */
	_changeFirstDay: function(id, day) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst.settings.firstDay = day;
		this._updateDatepicker(inst);
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		if ($(td).hasClass(this._unselectableClass))
			return;
		var target = $(id);
		var inst = this._getInst(target[0]);
		var rangeSelect = this._get(inst, 'rangeSelect');
		if (rangeSelect) {
			inst.stayOpen = !inst.stayOpen;
			if (inst.stayOpen) {
				$('.ui-datepicker td', inst.dpDiv).removeClass(this._currentClass);
				$(td).addClass(this._currentClass);
			}
		}
		inst.selectedDay = inst.currentDay = $('a', td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		if (inst.stayOpen) {
			inst.endDay = inst.endMonth = inst.endYear = null;
		}
		else if (rangeSelect) {
			inst.endDay = inst.currentDay;
			inst.endMonth = inst.currentMonth;
			inst.endYear = inst.currentYear;
		}
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
		if (inst.stayOpen) {
			inst.rangeStart = this._daylightSavingAdjust(
				new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
			this._updateDatepicker(inst);
		}
		else if (rangeSelect) {
			inst.selectedDay = inst.currentDay = inst.rangeStart.getDate();
			inst.selectedMonth = inst.currentMonth = inst.rangeStart.getMonth();
			inst.selectedYear = inst.currentYear = inst.rangeStart.getFullYear();
			inst.rangeStart = null;
			if (inst.inline)
				this._updateDatepicker(inst);
		}
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._get(inst, 'mandatory'))
			return;
		inst.stayOpen = false;
		inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null;
		this._selectDate(target, '');
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (this._get(inst, 'rangeSelect') && dateStr)
			dateStr = (inst.rangeStart ? this._formatDate(inst, inst.rangeStart) :
				dateStr) + this._get(inst, 'rangeSeparator') + dateStr;
		if (inst.input)
			inst.input.val(dateStr);
		this._updateAlternate(inst);
		var onSelect = this._get(inst, 'onSelect');
		if (onSelect)
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		else if (inst.input)
			inst.input.trigger('change'); // fire the change event
		if (inst.inline)
			this._updateDatepicker(inst);
		else if (!inst.stayOpen) {
			this._hideDatepicker(null, this._get(inst, 'duration'));
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) != 'object')
				inst.input[0].focus(); // restore focus
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {
		var altField = this._get(inst, 'altField');
		if (altField) { // update alternate field too
			var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
			var date = this._getDate(inst);
			dateStr = (isArray(date) ? (!date[0] && !date[1] ? '' :
				this.formatDate(altFormat, date[0], this._getFormatConfig(inst)) +
				this._get(inst, 'rangeSeparator') + this.formatDate(
				altFormat, date[1] || date[0], this._getFormatConfig(inst))) :
				this.formatDate(altFormat, date, this._getFormatConfig(inst)));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	   @param  date  Date - the date to customise
	   @return [boolean, string] - is this date selectable?, what is its CSS class? */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ''];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	   @param  date  Date - the date to get the week for
	   @return  number - the number of the week within the year that contains this date */
	iso8601Week: function(date) {
		var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
		var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
		var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
		firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
		if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
			checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
			return $.datepicker.iso8601Week(checkDate);
		} else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
			firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
			if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
				return 1;
			}
		}
		return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
	},

	/* Provide status text for a particular date.
	   @param  date  the date to get the status for
	   @param  inst  the current datepicker instance
	   @return  the status display text for this date */
	dateStatus: function(date, inst) {
		return $.datepicker.formatDate($.datepicker._get(inst, 'dateStatus'),
			date, $.datepicker._getFormatConfig(inst));
	},

	/* Parse a string value into a date object.
	   See formatDate below for the possible formats.

	   @param  format    string - the expected format of the date
	   @param  value     string - the date in the above format
	   @param  settings  Object - attributes include:
	                     shortYearCutoff  number - the cutoff year for determining the century (optional)
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  Date - the extracted date value or null if value is blank */
	parseDate: function (format, value, settings) {
		if (format == null || value == null)
			throw 'Invalid arguments';
		value = (typeof value == 'object' ? value.toString() : value + '');
		if (value == '')
			return null;
		var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		var year = -1;
		var month = -1;
		var day = -1;
		var doy = -1;
		var literal = false;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Extract a number from the string value
		var getNumber = function(match) {
			lookAhead(match);
			var origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)));
			var size = origSize;
			var num = 0;
			while (size > 0 && iValue < value.length &&
					value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') {
				num = num * 10 + parseInt(value.charAt(iValue++),10);
				size--;
			}
			if (size == origSize)
				throw 'Missing number at position ' + iValue;
			return num;
		};
		// Extract a name from the string value and convert to an index
		var getName = function(match, shortNames, longNames) {
			var names = (lookAhead(match) ? longNames : shortNames);
			var size = 0;
			for (var j = 0; j < names.length; j++)
				size = Math.max(size, names[j].length);
			var name = '';
			var iInit = iValue;
			while (size > 0 && iValue < value.length) {
				name += value.charAt(iValue++);
				for (var i = 0; i < names.length; i++)
					if (name == names[i])
						return i + 1;
				size--;
			}
			throw 'Unknown name at position ' + iInit;
		};
		// Confirm that a literal character matches the string value
		var checkLiteral = function() {
			if (value.charAt(iValue) != format.charAt(iFormat))
				throw 'Unexpected literal at position ' + iValue;
			iValue++;
		};
		var iValue = 0;
		for (var iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					checkLiteral();
			else
				switch (format.charAt(iFormat)) {
					case 'd':
						day = getNumber('d');
						break;
					case 'D':
						getName('D', dayNamesShort, dayNames);
						break;
					case 'o':
						doy = getNumber('o');
						break;
					case 'm':
						month = getNumber('m');
						break;
					case 'M':
						month = getName('M', monthNamesShort, monthNames);
						break;
					case 'y':
						year = getNumber('y');
						break;
					case '@':
						var date = new Date(getNumber('@'));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'"))
							checkLiteral();
						else
							literal = true;
						break;
					default:
						checkLiteral();
				}
		}
		if (year == -1)
			year = new Date().getFullYear();
		else if (year < 100)
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				var dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim)
					break;
				month++;
				day -= dim;
			} while (true);
		}
		var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
			throw 'Invalid date'; // E.g. 31/02/*
		return date;
	},

	/* Standard date formats. */
	ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
	COOKIE: 'D, dd M yy',
	ISO_8601: 'yy-mm-dd',
	RFC_822: 'D, d M y',
	RFC_850: 'DD, dd-M-y',
	RFC_1036: 'D, d M y',
	RFC_1123: 'D, d M yy',
	RFC_2822: 'D, d M yy',
	RSS: 'D, d M y', // RFC 822
	TIMESTAMP: '@',
	W3C: 'yy-mm-dd', // ISO 8601

	/* Format a date object into a string value.
	   The format can be combinations of the following:
	   d  - day of month (no leading zero)
	   dd - day of month (two digit)
	   o  - day of year (no leading zeros)
	   oo - day of year (three digit)
	   D  - day name short
	   DD - day name long
	   m  - month of year (no leading zero)
	   mm - month of year (two digit)
	   M  - month name short
	   MM - month name long
	   y  - year (two digit)
	   yy - year (four digit)
	   @ - Unix timestamp (ms since 01/01/1970)
	   '...' - literal text
	   '' - single quote

	   @param  format    string - the desired format of the date
	   @param  date      Date - the date value to format
	   @param  settings  Object - attributes include:
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  string - the date in the above format */
	formatDate: function (format, date, settings) {
		if (!date)
			return '';
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match))
				while (num.length < len)
					num = '0' + num;
			return num;
		};
		// Format a name, short or long as requested
		var formatName = function(match, value, shortNames, longNames) {
			return (lookAhead(match) ? longNames[value] : shortNames[value]);
		};
		var output = '';
		var literal = false;
		if (date)
			for (var iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal)
					if (format.charAt(iFormat) == "'" && !lookAhead("'"))
						literal = false;
					else
						output += format.charAt(iFormat);
				else
					switch (format.charAt(iFormat)) {
						case 'd':
							output += formatNumber('d', date.getDate(), 2);
							break;
						case 'D':
							output += formatName('D', date.getDay(), dayNamesShort, dayNames);
							break;
						case 'o':
							var doy = date.getDate();
							for (var m = date.getMonth() - 1; m >= 0; m--)
								doy += this._getDaysInMonth(date.getFullYear(), m);
							output += formatNumber('o', doy, 3);
							break;
						case 'm':
							output += formatNumber('m', date.getMonth() + 1, 2);
							break;
						case 'M':
							output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
							break;
						case 'y':
							output += (lookAhead('y') ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
							break;
						case '@':
							output += date.getTime();
							break;
						case "'":
							if (lookAhead("'"))
								output += "'";
							else
								literal = true;
							break;
						default:
							output += format.charAt(iFormat);
					}
			}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var chars = '';
		var literal = false;
		for (var iFormat = 0; iFormat < format.length; iFormat++)
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					chars += format.charAt(iFormat);
			else
				switch (format.charAt(iFormat)) {
					case 'd': case 'm': case 'y': case '@':
						chars += '0123456789';
						break;
					case 'D': case 'M':
						return null; // Accept anything
					case "'":
						if (lookAhead("'"))
							chars += "'";
						else
							literal = true;
						break;
					default:
						chars += format.charAt(iFormat);
				}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst) {
		var dateFormat = this._get(inst, 'dateFormat');
		var dates = inst.input ? inst.input.val().split(this._get(inst, 'rangeSeparator')) : null;
		inst.endDay = inst.endMonth = inst.endYear = null;
		var date = defaultDate = this._getDefaultDate(inst);
		if (dates.length > 0) {
			var settings = this._getFormatConfig(inst);
			if (dates.length > 1) {
				date = this.parseDate(dateFormat, dates[1], settings) || defaultDate;
				inst.endDay = date.getDate();
				inst.endMonth = date.getMonth();
				inst.endYear = date.getFullYear();
			}
			try {
				date = this.parseDate(dateFormat, dates[0], settings) || defaultDate;
			} catch (event) {
				this.log(event);
				date = defaultDate;
			}
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates[0] ? date.getDate() : 0);
		inst.currentMonth = (dates[0] ? date.getMonth() : 0);
		inst.currentYear = (dates[0] ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		var date = this._determineDate(this._get(inst, 'defaultDate'), new Date());
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		return date;
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(date, defaultDate) {
		var offsetNumeric = function(offset) {
			var date = new Date();
			date.setDate(date.getDate() + offset);
			return date;
		};
		var offsetString = function(offset, getDaysInMonth) {
			var date = new Date();
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
			var matches = pattern.exec(offset);
			while (matches) {
				switch (matches[2] || 'd') {
					case 'd' : case 'D' :
						day += parseInt(matches[1],10); break;
					case 'w' : case 'W' :
						day += parseInt(matches[1],10) * 7; break;
					case 'm' : case 'M' :
						month += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
					case 'y': case 'Y' :
						year += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
				}
				matches = pattern.exec(offset);
			}
			return new Date(year, month, day);
		};
		date = (date == null ? defaultDate :
			(typeof date == 'string' ? offsetString(date, this._getDaysInMonth) :
			(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
		date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
		if (date) {
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(date);
	},

	/* Handle switch to/from daylight saving.
	   Hours may be non-zero on daylight saving cut-over:
	   > 12 when midnight changeover, but then cannot generate
	   midnight datetime, so jump to 1AM, otherwise reset.
	   @param  date  (Date) the date to check
	   @return  (Date) the corrected date */
	_daylightSavingAdjust: function(date) {
		if (!date) return null;
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, endDate) {
		var clear = !(date);
		var origMonth = inst.selectedMonth;
		var origYear = inst.selectedYear;
		date = this._determineDate(date, new Date());
		inst.selectedDay = inst.currentDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
		if (this._get(inst, 'rangeSelect')) {
			if (endDate) {
				endDate = this._determineDate(endDate, null);
				inst.endDay = endDate.getDate();
				inst.endMonth = endDate.getMonth();
				inst.endYear = endDate.getFullYear();
			} else {
				inst.endDay = inst.currentDay;
				inst.endMonth = inst.currentMonth;
				inst.endYear = inst.currentYear;
			}
		}
		if (origMonth != inst.selectedMonth || origYear != inst.selectedYear)
			this._notifyChange(inst);
		this._adjustInstDate(inst);
		if (inst.input)
			inst.input.val(clear ? '' : this._formatDate(inst) +
				(!this._get(inst, 'rangeSelect') ? '' : this._get(inst, 'rangeSeparator') +
				this._formatDate(inst, inst.endDay, inst.endMonth, inst.endYear)));
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
		if (this._get(inst, 'rangeSelect')) {
			return [inst.rangeStart || startDate,
				(!inst.endYear ? inst.rangeStart || startDate :
				this._daylightSavingAdjust(new Date(inst.endYear, inst.endMonth, inst.endDay)))];
		} else
			return startDate;
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var today = new Date();
		today = this._daylightSavingAdjust(
			new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
		var showStatus = this._get(inst, 'showStatus');
		var initStatus = this._get(inst, 'initStatus') || '&#xa0;';
		var isRTL = this._get(inst, 'isRTL');
		// build the date picker HTML
		var clear = (this._get(inst, 'mandatory') ? '' :
			'<div class="ui-datepicker-clear"><a onclick="jQuery.datepicker._clearDate(\'#' + inst.id + '\');"' +
			this._addStatus(showStatus, inst.id, this._get(inst, 'clearStatus'), initStatus) + '>' +
			this._get(inst, 'clearText') + '</a></div>');
		var controls = '<div class="ui-datepicker-control">' + (isRTL ? '' : clear) +
			'<div class="ui-datepicker-close"><a onclick="jQuery.datepicker._hideDatepicker();"' +
			this._addStatus(showStatus, inst.id, this._get(inst, 'closeStatus'), initStatus) + '>' +
			this._get(inst, 'closeText') + '</a></div>' + (isRTL ? clear : '')  + '</div>';
		var prompt = this._get(inst, 'prompt');
		var closeAtTop = this._get(inst, 'closeAtTop');
		var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
		var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
		var showBigPrevNext = this._get(inst, 'showBigPrevNext');
		var numMonths = this._getNumberOfMonths(inst);
		var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
		var stepMonths = this._get(inst, 'stepMonths');
		var stepBigMonths = this._get(inst, 'stepBigMonths');
		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
		var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
			new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		var drawMonth = inst.drawMonth - showCurrentAtPos;
		var drawYear = inst.drawYear;
		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		// controls and links
		var prevText = this._get(inst, 'prevText');
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));
		var prevBigText = (showBigPrevNext ? this._get(inst, 'prevBigText') : '');
		prevBigText = (!navigationAsDateFormat ? prevBigText : this.formatDate(prevBigText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepBigMonths, 1)),
			this._getFormatConfig(inst)));
		var prev = '<div class="ui-datepicker-prev">' + (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			(showBigPrevNext ? '<a onclick="jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepBigMonths + ', \'M\');"' +
			this._addStatus(showStatus, inst.id, this._get(inst, 'prevBigStatus'), initStatus) + '>' + prevBigText + '</a>' : '') +
			'<a onclick="jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
			this._addStatus(showStatus, inst.id, this._get(inst, 'prevStatus'), initStatus) + '>' + prevText + '</a>' :
			(hideIfNoPrevNext ? '' : (showBigPrevNext ? '<label>' + prevBigText + '</label>' : '') +
			'<label>' + prevText + '</label>')) + '</div>';
		var nextText = this._get(inst, 'nextText');
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));
		var nextBigText = (showBigPrevNext ? this._get(inst, 'nextBigText') : '');
		nextBigText = (!navigationAsDateFormat ? nextBigText : this.formatDate(nextBigText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepBigMonths, 1)),
			this._getFormatConfig(inst)));
		var next = '<div class="ui-datepicker-next">' + (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			'<a onclick="jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
			this._addStatus(showStatus, inst.id, this._get(inst, 'nextStatus'), initStatus) + '>' + nextText + '</a>' +
			(showBigPrevNext ? '<a onclick="jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepBigMonths + ', \'M\');"' +
			this._addStatus(showStatus, inst.id, this._get(inst, 'nextBigStatus'), initStatus) + '>' + nextBigText + '</a>' : '') :
			(hideIfNoPrevNext ? '' : '<label>' + nextText + '</label>' +
			(showBigPrevNext ? '<label>' + nextBigText + '</label>' : ''))) + '</div>';
		var currentText = this._get(inst, 'currentText');
		var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
		var html = (closeAtTop && !inst.inline ? controls : '') +
			'<div class="ui-datepicker-links">' + (isRTL ? next : prev) +
			(this._isInRange(inst, gotoDate) ? '<div class="ui-datepicker-current">' +
			'<a onclick="jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' +
			this._addStatus(showStatus, inst.id, this._get(inst, 'currentStatus'), initStatus) + '>' +
			currentText + '</a></div>' : '') + (isRTL ? prev : next) + '</div>' +
			(prompt ? '<div class="' + this._promptClass + '"><span>' + prompt + '</span></div>' : '');
		var firstDay = parseInt(this._get(inst, 'firstDay'));
		firstDay = (isNaN(firstDay) ? 0 : firstDay);
		var changeFirstDay = this._get(inst, 'changeFirstDay');
		var dayNames = this._get(inst, 'dayNames');
		var dayNamesShort = this._get(inst, 'dayNamesShort');
		var dayNamesMin = this._get(inst, 'dayNamesMin');
		var monthNames = this._get(inst, 'monthNames');
		var beforeShowDay = this._get(inst, 'beforeShowDay');
		var highlightWeek = this._get(inst, 'highlightWeek');
		var showOtherMonths = this._get(inst, 'showOtherMonths');
		var showWeeks = this._get(inst, 'showWeeks');
		var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
		var weekStatus = this._get(inst, 'weekStatus');
		var status = (showStatus ? this._get(inst, 'dayStatus') || initStatus : '');
		var dateStatus = this._get(inst, 'statusForDate') || this.dateStatus;
		var endDate = inst.endDay ? this._daylightSavingAdjust(
			new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate;
		var defaultDate = this._getDefaultDate(inst);
		for (var row = 0; row < numMonths[0]; row++)
			for (var col = 0; col < numMonths[1]; col++) {
				var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				html += '<div class="ui-datepicker-one-month' + (col == 0 ? ' ui-datepicker-new-row' : '') + '">' +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					selectedDate, row > 0 || col > 0, showStatus, initStatus, monthNames) + // draw month headers
					'<table class="ui-datepicker" cellpadding="0" cellspacing="0"><thead>' +
					'<tr class="ui-datepicker-title-row">' +
					(showWeeks ? '<td' + this._addStatus(showStatus, inst.id, weekStatus, initStatus) + '>' +
					this._get(inst, 'weekHeader') + '</td>' : '');
				for (var dow = 0; dow < 7; dow++) { // days of the week
					var day = (dow + firstDay) % 7;
					var dayStatus = (status.indexOf('DD') > -1 ? status.replace(/DD/, dayNames[day]) :
						status.replace(/D/, dayNamesShort[day]));
					html += '<td' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end-cell"' : '') + '>' +
						(!changeFirstDay ? '<span' :
						'<a onclick="jQuery.datepicker._changeFirstDay(\'#' + inst.id + '\', ' + day + ');"') +
						this._addStatus(showStatus, inst.id, dayStatus, initStatus) + ' title="' + dayNames[day] + '">' +
						dayNamesMin[day] + (changeFirstDay ? '</a>' : '</span>') + '</td>';
				}
				html += '</tr></thead><tbody>';
				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
				var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					html += '<tr class="ui-datepicker-days-row">' +
						(showWeeks ? '<td class="ui-datepicker-week-col"' +
						this._addStatus(showStatus, inst.id, weekStatus, initStatus) + '>' +
						calculateWeek(printDate) + '</td>' : '');
					for (var dow = 0; dow < 7; dow++) { // create date picker days
						var daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
						var otherMonth = (printDate.getMonth() != drawMonth);
						var unselectable = otherMonth || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						html += '<td class="ui-datepicker-days-cell' +
							((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end-cell' : '') + // highlight weekends
							(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
							((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							' ' + $.datepicker._dayOverClass : '') + // highlight selected day
							(unselectable ? ' ' + this._unselectableClass : '') +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ' + this._currentClass : '') + // highlight selected day
							(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
							(unselectable ? (highlightWeek ? ' onmouseover="jQuery(this).parent().addClass(\'' + this._weekOverClass + '\');"' + // highlight selection week
							' onmouseout="jQuery(this).parent().removeClass(\'' + this._weekOverClass + '\');"' : '') : // unhighlight selection week
							' onmouseover="jQuery(this).addClass(\'' + this._dayOverClass + '\')' + // highlight selection
							(highlightWeek ? '.parent().addClass(\'' + this._weekOverClass + '\')' : '') + ';' + // highlight selection week
							(!showStatus || (otherMonth && !showOtherMonths) ? '' : 'jQuery(\'#ui-datepicker-status-' +
							inst.id + '\').html(\'' + (dateStatus.apply((inst.input ? inst.input[0] : null),
							[printDate, inst]) || initStatus) +'\');') + '"' +
							' onmouseout="jQuery(this).removeClass(\'' + this._dayOverClass + '\')' + // unhighlight selection
							(highlightWeek ? '.parent().removeClass(\'' + this._weekOverClass + '\')' : '') + ';' + // unhighlight selection week
							(!showStatus || (otherMonth && !showOtherMonths) ? '' : 'jQuery(\'#ui-datepicker-status-' +
							inst.id + '\').html(\'' + initStatus + '\');') + '" onclick="jQuery.datepicker._selectDay(\'#' +
							inst.id + '\',' + drawMonth + ',' + drawYear + ', this);"') + '>' + // actions
							(otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months
							(unselectable ? printDate.getDate() : '<a>' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					html += '</tr>';
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				html += '</tbody></table></div>';
			}
		html += (showStatus ? '<div style="clear: both;"></div><div id="ui-datepicker-status-' + inst.id +
			'" class="ui-datepicker-status">' + initStatus + '</div>' : '') +
			(!closeAtTop && !inst.inline ? controls : '') +
			'<div style="clear: both;"></div>' +
			($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
			'<iframe src="javascript:false;" class="ui-datepicker-cover"></iframe>' : '');
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			selectedDate, secondary, showStatus, initStatus, monthNames) {
		minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
		var changeMonth = this._get(inst, 'changeMonth');
		var changeYear = this._get(inst, 'changeYear');
		var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
		var html = '<div class="ui-datepicker-header">';
		var monthHtml = '';
		// month selection
		if (secondary || !changeMonth)
			monthHtml += monthNames[drawMonth];
		else {
			var inMinYear = (minDate && minDate.getFullYear() == drawYear);
			var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
			monthHtml += '<select class="ui-datepicker-new-month" ' +
				'onchange="jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
				'onclick="jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
				this._addStatus(showStatus, inst.id, this._get(inst, 'monthStatus'), initStatus) + '>';
			for (var month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) &&
						(!inMaxYear || month <= maxDate.getMonth()))
					monthHtml += '<option value="' + month + '"' +
						(month == drawMonth ? ' selected="selected"' : '') +
						'>' + monthNames[month] + '</option>';
			}
			monthHtml += '</select>';
		}
		if (!showMonthAfterYear)
			html += monthHtml + (secondary || changeMonth || changeYear ? '&#xa0;' : '');
		// year selection
		if (secondary || !changeYear)
			html += drawYear;
		else {
			// determine range of years to display
			var years = this._get(inst, 'yearRange').split(':');
			var year = 0;
			var endYear = 0;
			if (years.length != 2) {
				year = drawYear - 10;
				endYear = drawYear + 10;
			} else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
				year = endYear = new Date().getFullYear();
				year += parseInt(years[0], 10);
				endYear += parseInt(years[1], 10);
			} else {
				year = parseInt(years[0], 10);
				endYear = parseInt(years[1], 10);
			}
			year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
			endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
			html += '<select class="ui-datepicker-new-year" ' +
				'onchange="jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
				'onclick="jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
				this._addStatus(showStatus, inst.id, this._get(inst, 'yearStatus'), initStatus) + '>';
			for (; year <= endYear; year++) {
				html += '<option value="' + year + '"' +
					(year == drawYear ? ' selected="selected"' : '') +
					'>' + year + '</option>';
			}
			html += '</select>';
		}
		if (showMonthAfterYear)
			html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml;
		html += '</div>'; // Close datepicker_header
		return html;
	},

	/* Provide code to set and clear the status panel. */
	_addStatus: function(showStatus, id, text, initStatus) {
		return (showStatus ? ' onmouseover="jQuery(\'#ui-datepicker-status-' + id +
			'\').html(\'' + (text || initStatus) + '\');" ' +
			'onmouseout="jQuery(\'#ui-datepicker-status-' + id +
			'\').html(\'' + initStatus + '\');"' : '');
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period == 'Y' ? offset : 0);
		var month = inst.drawMonth + (period == 'M' ? offset : 0);
		var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
			(period == 'D' ? offset : 0);
		var date = this._daylightSavingAdjust(new Date(year, month, day));
		// ensure it is within the bounds set
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period == 'M' || period == 'Y')
			this._notifyChange(inst);
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, 'onChangeMonthYear');
		if (onChange)
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, 'numberOfMonths');
		return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
	_getMinMaxDate: function(inst, minMax, checkRange) {
		var date = this._determineDate(this._get(inst, minMax + 'Date'), null);
		return (!checkRange || !inst.rangeStart ? date :
			(!date || inst.rangeStart > date ? inst.rangeStart : date));
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - new Date(year, month, 32).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst);
		var date = this._daylightSavingAdjust(new Date(
			curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1));
		if (offset < 0)
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		// during range selection, use minimum of selected date and range start
		var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust(
			new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)));
		newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate);
		var minDate = newMinDate || this._getMinMaxDate(inst, 'min');
		var maxDate = this._getMinMaxDate(inst, 'max');
		return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, 'shortYearCutoff');
		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
			monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day == 'object' ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
	}
});

/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props)
		if (props[name] == null || props[name] == undefined)
			target[name] = props[name];
	return target;
};

/* Determine whether an object is an array. */
function isArray(a) {
	return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
		(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
                    Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){

	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document.body).append($.datepicker.dpDiv).
			mousedown($.datepicker._checkExternalClick);
		$.datepicker.initialized = true;
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate'))
		return $.datepicker['_' + options + 'Datepicker'].
			apply($.datepicker, [this[0]].concat(otherArgs));
	return this.each(function() {
		typeof options == 'string' ?
			$.datepicker['_' + options + 'Datepicker'].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.6";

})(jQuery);
/*
 * jQuery UI Effects 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/
 */
;(function($) {

$.effects = $.effects || {}; //Add the 'effects' scope

$.extend($.effects, {
	version: "1.6",
	save: function(el, set) {
		for(var i=0;i<set.length;i++) {
			if(set[i] !== null) $.data(el[0], "ec.storage."+set[i], el[0].style[set[i]]);
		}
	},
	restore: function(el, set) {
		for(var i=0;i<set.length;i++) {
			if(set[i] !== null) el.css(set[i], $.data(el[0], "ec.storage."+set[i]));
		}
	},
	setMode: function(el, mode) {
		if (mode == 'toggle') mode = el.is(':hidden') ? 'show' : 'hide'; // Set for toggle
		return mode;
	},
	getBaseline: function(origin, original) { // Translates a [top,left] array into a baseline value
		// this should be a little more flexible in the future to handle a string & hash
		var y, x;
		switch (origin[0]) {
			case 'top': y = 0; break;
			case 'middle': y = 0.5; break;
			case 'bottom': y = 1; break;
			default: y = origin[0] / original.height;
		};
		switch (origin[1]) {
			case 'left': x = 0; break;
			case 'center': x = 0.5; break;
			case 'right': x = 1; break;
			default: x = origin[1] / original.width;
		};
		return {x: x, y: y};
	},
	createWrapper: function(el) {
		if (el.parent().attr('id') == 'fxWrapper')
			return el;
		var props = {width: el.outerWidth({margin:true}), height: el.outerHeight({margin:true}), 'float': el.css('float')};
		el.wrap('<div id="fxWrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>');
		var wrapper = el.parent();
		if (el.css('position') == 'static'){
			wrapper.css({position: 'relative'});
			el.css({position: 'relative'});
		} else {
			var top = el.css('top'); if(isNaN(parseInt(top))) top = 'auto';
			var left = el.css('left'); if(isNaN(parseInt(left))) left = 'auto';
			wrapper.css({ position: el.css('position'), top: top, left: left, zIndex: el.css('z-index') }).show();
			el.css({position: 'relative', top:0, left:0});
		}
		wrapper.css(props);
		return wrapper;
	},
	removeWrapper: function(el) {
		if (el.parent().attr('id') == 'fxWrapper')
			return el.parent().replaceWith(el);
		return el;
	},
	setTransition: function(el, list, factor, val) {
		val = val || {};
		$.each(list,function(i, x){
			unit = el.cssUnit(x);
			if (unit[0] > 0) val[x] = unit[0] * factor + unit[1];
		});
		return val;
	},
	animateClass: function(value, duration, easing, callback) {

		var cb = (typeof easing == "function" ? easing : (callback ? callback : null));
		var ea = (typeof easing == "object" ? easing : null);

		return this.each(function() {

			var offset = {}; var that = $(this); var oldStyleAttr = that.attr("style") || '';
			if(typeof oldStyleAttr == 'object') oldStyleAttr = oldStyleAttr["cssText"]; /* Stupidly in IE, style is a object.. */
			if(value.toggle) { that.hasClass(value.toggle) ? value.remove = value.toggle : value.add = value.toggle; }

			//Let's get a style offset
			var oldStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle));
			if(value.add) that.addClass(value.add); if(value.remove) that.removeClass(value.remove);
			var newStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle));
			if(value.add) that.removeClass(value.add); if(value.remove) that.addClass(value.remove);

			// The main function to form the object for animation
			for(var n in newStyle) {
				if( typeof newStyle[n] != "function" && newStyle[n] /* No functions and null properties */
				&& n.indexOf("Moz") == -1 && n.indexOf("length") == -1 /* No mozilla spezific render properties. */
				&& newStyle[n] != oldStyle[n] /* Only values that have changed are used for the animation */
				&& (n.match(/color/i) || (!n.match(/color/i) && !isNaN(parseInt(newStyle[n],10)))) /* Only things that can be parsed to integers or colors */
				&& (oldStyle.position != "static" || (oldStyle.position == "static" && !n.match(/left|top|bottom|right/))) /* No need for positions when dealing with static positions */
				) offset[n] = newStyle[n];
			}

			that.animate(offset, duration, ea, function() { // Animate the newly constructed offset object
				// Change style attribute back to original. For stupid IE, we need to clear the damn object.
				if(typeof $(this).attr("style") == 'object') { $(this).attr("style")["cssText"] = ""; $(this).attr("style")["cssText"] = oldStyleAttr; } else $(this).attr("style", oldStyleAttr);
				if(value.add) $(this).addClass(value.add); if(value.remove) $(this).removeClass(value.remove);
				if(cb) cb.apply(this, arguments);
			});

		});
	}
});

//Extend the methods of jQuery
$.fn.extend({
	//Save old methods
	_show: $.fn.show,
	_hide: $.fn.hide,
	__toggle: $.fn.toggle,
	_addClass: $.fn.addClass,
	_removeClass: $.fn.removeClass,
	_toggleClass: $.fn.toggleClass,
	// New ec methods
	effect: function(fx,o,speed,callback) {
		return $.effects[fx] ? $.effects[fx].call(this, {method: fx, options: o || {}, duration: speed, callback: callback }) : null;
	},
	show: function() {
		if(!arguments[0] || (arguments[0].constructor == Number || /(slow|normal|fast)/.test(arguments[0])))
			return this._show.apply(this, arguments);
		else {
			var o = arguments[1] || {}; o['mode'] = 'show';
			return this.effect.apply(this, [arguments[0], o, arguments[2] || o.duration, arguments[3] || o.callback]);
		}
	},
	hide: function() {
		if(!arguments[0] || (arguments[0].constructor == Number || /(slow|normal|fast)/.test(arguments[0])))
			return this._hide.apply(this, arguments);
		else {
			var o = arguments[1] || {}; o['mode'] = 'hide';
			return this.effect.apply(this, [arguments[0], o, arguments[2] || o.duration, arguments[3] || o.callback]);
		}
	},
	toggle: function(){
		if(!arguments[0] || (arguments[0].constructor == Number || /(slow|normal|fast)/.test(arguments[0])) || (arguments[0].constructor == Function))
			return this.__toggle.apply(this, arguments);
		else {
			var o = arguments[1] || {}; o['mode'] = 'toggle';
			return this.effect.apply(this, [arguments[0], o, arguments[2] || o.duration, arguments[3] || o.callback]);
		}
	},
	addClass: function(classNames,speed,easing,callback) {
		return speed ? $.effects.animateClass.apply(this, [{ add: classNames },speed,easing,callback]) : this._addClass(classNames);
	},
	removeClass: function(classNames,speed,easing,callback) {
		return speed ? $.effects.animateClass.apply(this, [{ remove: classNames },speed,easing,callback]) : this._removeClass(classNames);
	},
	toggleClass: function(classNames,speed,easing,callback) {
		return speed ? $.effects.animateClass.apply(this, [{ toggle: classNames },speed,easing,callback]) : this._toggleClass(classNames);
	},
	morph: function(remove,add,speed,easing,callback) {
		return $.effects.animateClass.apply(this, [{ add: add, remove: remove },speed,easing,callback]);
	},
	switchClass: function() {
		return this.morph.apply(this, arguments);
	},
	// helper functions
	cssUnit: function(key) {
		var style = this.css(key), val = [];
		$.each( ['em','px','%','pt'], function(i, unit){
			if(style.indexOf(unit) > 0)
				val = [parseFloat(style), unit];
		});
		return val;
	}
});

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

// We override the animation for all of these color styles
$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		$.fx.step[attr] = function(fx){
				if ( fx.state == 0 ) {
						fx.start = getColor( fx.elem, attr );
						fx.end = getRGB( fx.end );
				}

				fx.elem.style[attr] = "rgb(" + [
						Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
						Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
						Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
				].join(",") + ")";
		}
});

// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/

// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
				return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
				return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
				return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
				return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
				return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
		if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
				return colors['transparent'];

		// Otherwise, we're most likely dealing with a named color
		return colors[$.trim(color).toLowerCase()];
}

function getColor(elem, attr) {
		var color;

		do {
				color = $.curCSS(elem, attr);

				// Keep going until we find an element that has color, or we hit the body
				if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") )
						break;

				attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
};

// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/

var colors = {
	aqua:[0,255,255],
	azure:[240,255,255],
	beige:[245,245,220],
	black:[0,0,0],
	blue:[0,0,255],
	brown:[165,42,42],
	cyan:[0,255,255],
	darkblue:[0,0,139],
	darkcyan:[0,139,139],
	darkgrey:[169,169,169],
	darkgreen:[0,100,0],
	darkkhaki:[189,183,107],
	darkmagenta:[139,0,139],
	darkolivegreen:[85,107,47],
	darkorange:[255,140,0],
	darkorchid:[153,50,204],
	darkred:[139,0,0],
	darksalmon:[233,150,122],
	darkviolet:[148,0,211],
	fuchsia:[255,0,255],
	gold:[255,215,0],
	green:[0,128,0],
	indigo:[75,0,130],
	khaki:[240,230,140],
	lightblue:[173,216,230],
	lightcyan:[224,255,255],
	lightgreen:[144,238,144],
	lightgrey:[211,211,211],
	lightpink:[255,182,193],
	lightyellow:[255,255,224],
	lime:[0,255,0],
	magenta:[255,0,255],
	maroon:[128,0,0],
	navy:[0,0,128],
	olive:[128,128,0],
	orange:[255,165,0],
	pink:[255,192,203],
	purple:[128,0,128],
	violet:[128,0,128],
	red:[255,0,0],
	silver:[192,192,192],
	white:[255,255,255],
	yellow:[255,255,0],
	transparent: [255,255,255]
};

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 *
 * Open source under the BSD License.
 *
 * Copyright  2008 George McGinley Smith
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
$.easing.jswing = $.easing.swing;

$.extend($.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert($.easing.default);
		return $.easing[$.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - $.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return $.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return $.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

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

})(jQuery);
/*
 * jQuery UI Effects Blind 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Blind
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.blind = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var direction = o.options.direction || 'vertical'; // Default direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var ref = (direction == 'vertical') ? 'height' : 'width';
		var distance = (direction == 'vertical') ? wrapper.height() : wrapper.width();
		if(mode == 'show') wrapper.css(ref, 0); // Shift

		// Animation
		var animation = {};
		animation[ref] = mode == 'show' ? distance : 0;

		// Animate
		wrapper.animate(animation, o.duration, o.options.easing, function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Bounce 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Bounce
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.bounce = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var direction = o.options.direction || 'up'; // Default direction
		var distance = o.options.distance || 20; // Default distance
		var times = o.options.times || 5; // Default # of times
		var speed = o.duration || 250; // Default speed per bounce
		if (/show|hide/.test(mode)) props.push('opacity'); // Avoid touching opacity to prevent clearType and PNG issues in IE

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
		var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 3 : el.outerWidth({margin:true}) / 3);
		if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift
		if (mode == 'hide') distance = distance / (times * 2);
		if (mode != 'hide') times--;

		// Animate
		if (mode == 'show') { // Show Bounce
			var animation = {opacity: 1};
			animation[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
			el.animate(animation, speed / 2, o.options.easing);
			distance = distance / 2;
			times--;
		};
		for (var i = 0; i < times; i++) { // Bounces
			var animation1 = {}, animation2 = {};
			animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
			animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
			el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing);
			distance = (mode == 'hide') ? distance * 2 : distance / 2;
		};
		if (mode == 'hide') { // Last Bounce
			var animation = {opacity: 0};
			animation[ref] = (motion == 'pos' ? '-=' : '+=')  + distance;
			el.animate(animation, speed / 2, o.options.easing, function(){
				el.hide(); // Hide
				$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		} else {
			var animation1 = {}, animation2 = {};
			animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
			animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
			el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing, function(){
				$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		};
		el.queue('fx', function() { el.dequeue(); });
		el.dequeue();
	});

};

})(jQuery);
/*
 * jQuery UI Effects Clip 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Clip
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.clip = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left','height','width'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var direction = o.options.direction || 'vertical'; // Default direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var animate = el[0].tagName == 'IMG' ? wrapper : el;
		var ref = {
			size: (direction == 'vertical') ? 'height' : 'width',
			position: (direction == 'vertical') ? 'top' : 'left'
		};
		var distance = (direction == 'vertical') ? animate.height() : animate.width();
		if(mode == 'show') { animate.css(ref.size, 0); animate.css(ref.position, distance / 2); } // Shift

		// Animation
		var animation = {};
		animation[ref.size] = mode == 'show' ? distance : 0;
		animation[ref.position] = mode == 'show' ? 0 : distance / 2;

		// Animate
		animate.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Drop 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Drop
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.drop = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left','opacity'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var direction = o.options.direction || 'left'; // Default Direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
		var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 2 : el.outerWidth({margin:true}) / 2);
		if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift

		// Animation
		var animation = {opacity: mode == 'show' ? 1 : 0};
		animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance;

		// Animate
		el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Explode 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Explode
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.explode = function(o) {

	return this.queue(function() {

	var rows = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3;
	var cells = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3;

	o.options.mode = o.options.mode == 'toggle' ? ($(this).is(':visible') ? 'hide' : 'show') : o.options.mode;
	var el = $(this).show().css('visibility', 'hidden');
	var offset = el.offset();

	//Substract the margins - not fixing the problem yet.
	offset.top -= parseInt(el.css("marginTop")) || 0;
	offset.left -= parseInt(el.css("marginLeft")) || 0;

	var width = el.outerWidth(true);
	var height = el.outerHeight(true);

	for(var i=0;i<rows;i++) { // =
		for(var j=0;j<cells;j++) { // ||
			el
				.clone()
				.appendTo('body')
				.wrap('<div></div>')
				.css({
					position: 'absolute',
					visibility: 'visible',
					left: -j*(width/cells),
					top: -i*(height/rows)
				})
				.parent()
				.addClass('effects-explode')
				.css({
					position: 'absolute',
					overflow: 'hidden',
					width: width/cells,
					height: height/rows,
					left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? (j-Math.floor(cells/2))*(width/cells) : 0),
					top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? (i-Math.floor(rows/2))*(height/rows) : 0),
					opacity: o.options.mode == 'show' ? 0 : 1
				}).animate({
					left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? 0 : (j-Math.floor(cells/2))*(width/cells)),
					top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? 0 : (i-Math.floor(rows/2))*(height/rows)),
					opacity: o.options.mode == 'show' ? 1 : 0
				}, o.duration || 500);
		}
	}

	// Set a timeout, to call the callback approx. when the other animations have finished
	setTimeout(function() {

		o.options.mode == 'show' ? el.css({ visibility: 'visible' }) : el.css({ visibility: 'visible' }).hide();
				if(o.callback) o.callback.apply(el[0]); // Callback
				el.dequeue();

				$('.effects-explode').remove();

	}, o.duration || 500);


	});

};

})(jQuery);
/*
 * jQuery UI Effects Fold 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Fold
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.fold = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var size = o.options.size || 15; // Default fold size
		var horizFirst = !(!o.options.horizFirst); // Ensure a boolean value

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var widthFirst = ((mode == 'show') != horizFirst);
		var ref = widthFirst ? ['width', 'height'] : ['height', 'width'];
		var distance = widthFirst ? [wrapper.width(), wrapper.height()] : [wrapper.height(), wrapper.width()];
		var percent = /([0-9]+)%/.exec(size);
		if(percent) size = parseInt(percent[1]) / 100 * distance[mode == 'hide' ? 0 : 1];
		if(mode == 'show') wrapper.css(horizFirst ? {height: 0, width: size} : {height: size, width: 0}); // Shift

		// Animation
		var animation1 = {}, animation2 = {};
		animation1[ref[0]] = mode == 'show' ? distance[0] : size;
		animation2[ref[1]] = mode == 'show' ? distance[1] : 0;

		// Animate
		wrapper.animate(animation1, o.duration / 2, o.options.easing)
		.animate(animation2, o.duration / 2, o.options.easing, function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Highlight 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Highlight
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.highlight = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['backgroundImage','backgroundColor','opacity'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
		var color = o.options.color || "#ffff99"; // Default highlight color
		var oldColor = el.css("backgroundColor");

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		el.css({backgroundImage: 'none', backgroundColor: color}); // Shift

		// Animation
		var animation = {backgroundColor: oldColor };
		if (mode == "hide") animation['opacity'] = 0;

		// Animate
		el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == "hide") el.hide();
			$.effects.restore(el, props);
		if (mode == "show" && $.browser.msie) this.style.removeAttribute('filter');
			if(o.callback) o.callback.apply(this, arguments);
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Pulsate 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Pulsate
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.pulsate = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this);

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
		var times = o.options.times || 5; // Default # of times

		// Adjust
		if (mode == 'hide') times--;
		if (el.is(':hidden')) { // Show fadeIn
			el.css('opacity', 0);
			el.show(); // Show
			el.animate({opacity: 1}, o.duration / 2, o.options.easing);
			times = times-2;
		}

		// Animate
		for (var i = 0; i < times; i++) { // Pulsate
			el.animate({opacity: 0}, o.duration / 2, o.options.easing).animate({opacity: 1}, o.duration / 2, o.options.easing);
		};
		if (mode == 'hide') { // Last Pulse
			el.animate({opacity: 0}, o.duration / 2, o.options.easing, function(){
				el.hide(); // Hide
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		} else {
			el.animate({opacity: 0}, o.duration / 2, o.options.easing).animate({opacity: 1}, o.duration / 2, o.options.easing, function(){
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		};
		el.queue('fx', function() { el.dequeue(); });
		el.dequeue();
	});

};

})(jQuery);
/*
 * jQuery UI Effects Scale 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Scale
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.puff = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this);

		// Set options
		var options = $.extend(true, {}, o.options);
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var percent = parseInt(o.options.percent) || 150; // Set default puff percent
		options.fade = true; // It's not a puff if it doesn't fade! :)
		var original = {height: el.height(), width: el.width()}; // Save original

		// Adjust
		var factor = percent / 100;
		el.from = (mode == 'hide') ? original : {height: original.height * factor, width: original.width * factor};

		// Animation
		options.from = el.from;
		options.percent = (mode == 'hide') ? percent : 100;
		options.mode = mode;

		// Animate
		el.effect('scale', options, o.duration, o.callback);
		el.dequeue();
	});

};

$.effects.scale = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this);

		// Set options
		var options = $.extend(true, {}, o.options);
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var percent = parseInt(o.options.percent) || (parseInt(o.options.percent) == 0 ? 0 : (mode == 'hide' ? 0 : 100)); // Set default scaling percent
		var direction = o.options.direction || 'both'; // Set default axis
		var origin = o.options.origin; // The origin of the scaling
		if (mode != 'effect') { // Set default origin and restore for show/hide
			options.origin = origin || ['middle','center'];
			options.restore = true;
		}
		var original = {height: el.height(), width: el.width()}; // Save original
		el.from = o.options.from || (mode == 'show' ? {height: 0, width: 0} : original); // Default from state

		// Adjust
		var factor = { // Set scaling factor
			y: direction != 'horizontal' ? (percent / 100) : 1,
			x: direction != 'vertical' ? (percent / 100) : 1
		};
		el.to = {height: original.height * factor.y, width: original.width * factor.x}; // Set to state

		if (o.options.fade) { // Fade option to support puff
			if (mode == 'show') {el.from.opacity = 0; el.to.opacity = 1;};
			if (mode == 'hide') {el.from.opacity = 1; el.to.opacity = 0;};
		};

		// Animation
		options.from = el.from; options.to = el.to; options.mode = mode;

		// Animate
		el.effect('size', options, o.duration, o.callback);
		el.dequeue();
	});

};

$.effects.size = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left','width','height','overflow','opacity'];
		var props1 = ['position','top','left','overflow','opacity']; // Always restore
		var props2 = ['width','height','overflow']; // Copy for children
		var cProps = ['fontSize'];
		var vProps = ['borderTopWidth', 'borderBottomWidth', 'paddingTop', 'paddingBottom'];
		var hProps = ['borderLeftWidth', 'borderRightWidth', 'paddingLeft', 'paddingRight'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var restore = o.options.restore || false; // Default restore
		var scale = o.options.scale || 'both'; // Default scale mode
		var origin = o.options.origin; // The origin of the sizing
		var original = {height: el.height(), width: el.width()}; // Save original
		el.from = o.options.from || original; // Default from state
		el.to = o.options.to || original; // Default to state
		// Adjust
		if (origin) { // Calculate baseline shifts
			var baseline = $.effects.getBaseline(origin, original);
			el.from.top = (original.height - el.from.height) * baseline.y;
			el.from.left = (original.width - el.from.width) * baseline.x;
			el.to.top = (original.height - el.to.height) * baseline.y;
			el.to.left = (original.width - el.to.width) * baseline.x;
		};
		var factor = { // Set scaling factor
			from: {y: el.from.height / original.height, x: el.from.width / original.width},
			to: {y: el.to.height / original.height, x: el.to.width / original.width}
		};
		if (scale == 'box' || scale == 'both') { // Scale the css box
			if (factor.from.y != factor.to.y) { // Vertical props scaling
				props = props.concat(vProps);
				el.from = $.effects.setTransition(el, vProps, factor.from.y, el.from);
				el.to = $.effects.setTransition(el, vProps, factor.to.y, el.to);
			};
			if (factor.from.x != factor.to.x) { // Horizontal props scaling
				props = props.concat(hProps);
				el.from = $.effects.setTransition(el, hProps, factor.from.x, el.from);
				el.to = $.effects.setTransition(el, hProps, factor.to.x, el.to);
			};
		};
		if (scale == 'content' || scale == 'both') { // Scale the content
			if (factor.from.y != factor.to.y) { // Vertical props scaling
				props = props.concat(cProps);
				el.from = $.effects.setTransition(el, cProps, factor.from.y, el.from);
				el.to = $.effects.setTransition(el, cProps, factor.to.y, el.to);
			};
		};
		$.effects.save(el, restore ? props : props1); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		el.css('overflow','hidden').css(el.from); // Shift

		// Animate
		if (scale == 'content' || scale == 'both') { // Scale the children
			vProps = vProps.concat(['marginTop','marginBottom']).concat(cProps); // Add margins/font-size
			hProps = hProps.concat(['marginLeft','marginRight']); // Add margins
			props2 = props.concat(vProps).concat(hProps); // Concat
			el.find("*[width]").each(function(){
				child = $(this);
				if (restore) $.effects.save(child, props2);
				var c_original = {height: child.height(), width: child.width()}; // Save original
				child.from = {height: c_original.height * factor.from.y, width: c_original.width * factor.from.x};
				child.to = {height: c_original.height * factor.to.y, width: c_original.width * factor.to.x};
				if (factor.from.y != factor.to.y) { // Vertical props scaling
					child.from = $.effects.setTransition(child, vProps, factor.from.y, child.from);
					child.to = $.effects.setTransition(child, vProps, factor.to.y, child.to);
				};
				if (factor.from.x != factor.to.x) { // Horizontal props scaling
					child.from = $.effects.setTransition(child, hProps, factor.from.x, child.from);
					child.to = $.effects.setTransition(child, hProps, factor.to.x, child.to);
				};
				child.css(child.from); // Shift children
				child.animate(child.to, o.duration, o.options.easing, function(){
					if (restore) $.effects.restore(child, props2); // Restore children
				}); // Animate children
			});
		};

		// Animate
		el.animate(el.to, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, restore ? props : props1); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Shake 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Shake
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.shake = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var direction = o.options.direction || 'left'; // Default direction
		var distance = o.options.distance || 20; // Default distance
		var times = o.options.times || 3; // Default # of times
		var speed = o.duration || o.options.duration || 140; // Default speed per shake

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';

		// Animation
		var animation = {}, animation1 = {}, animation2 = {};
		animation[ref] = (motion == 'pos' ? '-=' : '+=')  + distance;
		animation1[ref] = (motion == 'pos' ? '+=' : '-=')  + distance * 2;
		animation2[ref] = (motion == 'pos' ? '-=' : '+=')  + distance * 2;

		// Animate
		el.animate(animation, speed, o.options.easing);
		for (var i = 1; i < times; i++) { // Shakes
			el.animate(animation1, speed, o.options.easing).animate(animation2, speed, o.options.easing);
		};
		el.animate(animation1, speed, o.options.easing).
		animate(animation, speed / 2, o.options.easing, function(){ // Last shake
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
		});
		el.queue('fx', function() { el.dequeue(); });
		el.dequeue();
	});

};

})(jQuery);
/*
 * jQuery UI Effects Slide 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Slide
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.slide = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
		var direction = o.options.direction || 'left'; // Default Direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
		var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) : el.outerWidth({margin:true}));
		if (mode == 'show') el.css(ref, motion == 'pos' ? -distance : distance); // Shift

		// Animation
		var animation = {};
		animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance;

		// Animate
		el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Transfer 1.6
 *
 * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Transfer
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.transfer = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this);

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var target = $(o.options.to); // Find Target
		var position = el.offset();
		var transfer = $('<div class="ui-effects-transfer"></div>').appendTo(document.body);
		if(o.options.className) transfer.addClass(o.options.className);

		// Set target css
		transfer.addClass(o.options.className);
		transfer.css({
			top: position.top,
			left: position.left,
			height: el.outerHeight() - parseInt(transfer.css('borderTopWidth')) - parseInt(transfer.css('borderBottomWidth')),
			width: el.outerWidth() - parseInt(transfer.css('borderLeftWidth')) - parseInt(transfer.css('borderRightWidth')),
			position: 'absolute'
		});

		// Animation
		position = target.offset();
		animation = {
			top: position.top,
			left: position.left,
			height: target.outerHeight() - parseInt(transfer.css('borderTopWidth')) - parseInt(transfer.css('borderBottomWidth')),
			width: target.outerWidth() - parseInt(transfer.css('borderLeftWidth')) - parseInt(transfer.css('borderRightWidth'))
		};

		// Animate
		transfer.animate(animation, o.duration, o.options.easing, function() {
			transfer.remove(); // Remove div
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		});

	});

};

})(jQuery);
/* Hungarian initialisation for the jQuery UI date picker plugin. */
/* Written by Istvan Karaszi (jquerycalendar@spam.raszi.hu). */
jQuery(function($){
    $.datepicker.regional['hu'] = {
        clearText: 'törlés', clearStatus: '',
        closeText: 'bezárás', closeStatus: '',
        prevText: '&laquo;&nbsp;', prevStatus: '',
        prevBigText: '&#x3c;&#x3c;', prevBigStatus: '',
        nextText: '&nbsp;&raquo;', nextStatus: '',
        nextBigText: '&#x3e;&#x3e;', nextBigStatus: '',
        currentText: 'ma', currentStatus: '',
        monthNames: ['Január ', 'Február ', 'Március ', 'Április ', 'Május ', 'Június ',
        'Július ', 'Augusztus ', 'Szeptember ', 'Október ', 'November ', 'December '],
        monthNamesShort: ['Jan', 'Feb', 'Már', 'Ápr', 'Máj', 'Jún',
        'Júl', 'Aug', 'Szep', 'Okt', 'Nov', 'Dec'],
        monthStatus: '', yearStatus: '',
        weekHeader: 'Hé', weekStatus: '',
        dayNames: ['Vasámap', 'Hétfö', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat'],
        dayNamesShort: ['Vas', 'Hét', 'Ked', 'Sze', 'Csü', 'Pén', 'Szo'],
        dayNamesMin: ['V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo'],
        dayStatus: 'DD', dateStatus: 'D, M d',
        dateFormat: 'yy-mm-dd', firstDay: 1,
        initStatus: '', isRTL: false};
    $.datepicker.setDefaults($.datepicker.regional['hu']);
});
/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
          
var tb_pathToImage = "/images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
jQuery(document).ready(function(){   
    tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
    imgLoader = new Image();// preload image
    imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
    jQuery(domChunk).click(function(e){
        var t = this.title || this.name || null;
        var a = this.href || this.alt;
        var g = this.rel || false;
        tb_show(t,a,g);
        this.blur();
        return false;
    });
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

    try {
        if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
            jQuery("body","html").css({height: "100%", width: "100%"});
            jQuery("html").css("overflow","hidden");
            if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
                jQuery("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
                jQuery("#TB_overlay").click(tb_remove);
            }
        }else{//all others
            if(document.getElementById("TB_overlay") === null){
                jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
                jQuery("#TB_overlay").click(tb_remove);
            }
        }
        
        if(tb_detectMacXFF()){
            jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
        }else{
            jQuery("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
        }
        
        if(caption===null){caption="";}
        jQuery("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
        jQuery('#TB_load').show();//show loader
        
        var baseURL;
       if(url.indexOf("?")!==-1){ //ff there is a query string involved
            baseURL = url.substr(0, url.indexOf("?"));
       }else{ 
            baseURL = url;
       }
       
       var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
       var urlType = baseURL.toLowerCase().match(urlString);

        if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
                
            TB_PrevCaption = "";
            TB_PrevURL = "";
            TB_PrevHTML = "";
            TB_NextCaption = "";
            TB_NextURL = "";
            TB_NextHTML = "";
            TB_imageCount = "";
            TB_FoundURL = false;
            if(imageGroup){
                TB_TempArray = jQuery("a[@rel="+imageGroup+"]").get();
                for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
                    var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
                        if (!(TB_TempArray[TB_Counter].href == url)) {                      
                            if (TB_FoundURL) {
                                TB_NextCaption = TB_TempArray[TB_Counter].title;
                                TB_NextURL = TB_TempArray[TB_Counter].href;
                                TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
                            } else {
                                TB_PrevCaption = TB_TempArray[TB_Counter].title;
                                TB_PrevURL = TB_TempArray[TB_Counter].href;
                                TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
                            }
                        } else {
                            TB_FoundURL = true;
                            TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);                                         
                        }
                }
            }

            imgPreloader = new Image();
            imgPreloader.onload = function(){       
            imgPreloader.onload = null;
                
            // Resizing large images - orginal by Christian Montoya edited by me.
            var pagesize = tb_getPageSize();
            var x = pagesize[0] - 150;
            var y = pagesize[1] - 150;
            var imageWidth = imgPreloader.width;
            var imageHeight = imgPreloader.height;
            if (imageWidth > x) {
                imageHeight = imageHeight * (x / imageWidth); 
                imageWidth = x; 
                if (imageHeight > y) { 
                    imageWidth = imageWidth * (y / imageHeight); 
                    imageHeight = y; 
                }
            } else if (imageHeight > y) { 
                imageWidth = imageWidth * (y / imageHeight); 
                imageHeight = y; 
                if (imageWidth > x) { 
                    imageHeight = imageHeight * (x / imageWidth); 
                    imageWidth = x;
                }
            }
            // End Resizing
            
            TB_WIDTH = imageWidth + 30;
            TB_HEIGHT = imageHeight + 60;
            jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
            
            jQuery("#TB_closeWindowButton").click(tb_remove);
            
            if (!(TB_PrevHTML === "")) {
                function goPrev(){
                    if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);}
                    jQuery("#TB_window").remove();
                    jQuery("body").append("<div id='TB_window'></div>");
                    tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
                    return false;   
                }
                jQuery("#TB_prev").click(goPrev);
            }
            
            if (!(TB_NextHTML === "")) {        
                function goNext(){
                    jQuery("#TB_window").remove();
                    jQuery("body").append("<div id='TB_window'></div>");
                    tb_show(TB_NextCaption, TB_NextURL, imageGroup);                
                    return false;   
                }
                jQuery("#TB_next").click(goNext);
                
            }

            document.onkeydown = function(e){   
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                if(keycode == 27){ // close
                    tb_remove();
                } else if(keycode == 190){ // display previous image
                    if(!(TB_NextHTML == "")){
                        document.onkeydown = "";
                        goNext();
                    }
                } else if(keycode == 188){ // display next image
                    if(!(TB_PrevHTML == "")){
                        document.onkeydown = "";
                        goPrev();
                    }
                }   
            };
            
            tb_position();
            jQuery("#TB_load").remove();
            jQuery("#TB_ImageOff").click(tb_remove);
            jQuery("#TB_window").css({display:"block"}); //for safari using css instead of show
            };
            
            imgPreloader.src = url;
        }else{//code to show html
            
            var queryString = url.replace(/^[^\?]+\??/,'');
            var params = tb_parseQuery( queryString );

            TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
            TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
            ajaxContentW = TB_WIDTH - 30;
            ajaxContentH = TB_HEIGHT - 45;
            
            if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window      
                    urlNoQuery = url.split('TB_');
                    jQuery("#TB_iframeContent").remove();
                    if(params['modal'] != "true"){//iframe no modal
                        jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
                    }else{//iframe modal
                    jQuery("#TB_overlay").unbind();
                        jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
                    }
            }else{// not an iframe, ajax
                    if(jQuery("#TB_window").css("display") != "block"){
                        if(params['modal'] != "true"){//ajax no modal
                        jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
                        }else{//ajax modal
                        jQuery("#TB_overlay").unbind();
                        jQuery("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); 
                        }
                    }else{//this means the window is already up, we are just loading new content via ajax
                        jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
                        jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
                        jQuery("#TB_ajaxContent")[0].scrollTop = 0;
                        jQuery("#TB_ajaxWindowTitle").html(caption);
                    }
            }
                    
            jQuery("#TB_closeWindowButton").click(tb_remove);
            
                if(url.indexOf('TB_inline') != -1){ 
                    jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children());
                    jQuery("#TB_window").unload(function () {
                        jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished
                    });
                    tb_position();
                    jQuery("#TB_load").remove();
                    jQuery("#TB_window").css({display:"block"}); 
                }else if(url.indexOf('TB_iframe') != -1){
                    tb_position();
                    if($.browser.safari){//safari needs help because it will not fire iframe onload
                        jQuery("#TB_load").remove();
                        jQuery("#TB_window").css({display:"block"});
                    }
                }else{
                    jQuery("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
                        tb_position();
                        jQuery("#TB_load").remove();
                        tb_init("#TB_ajaxContent a.thickbox");
                        jQuery("#TB_window").css({display:"block"});
                    });
                }
            
        }

        if(!params['modal']){
            document.onkeyup = function(e){     
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                if(keycode == 27){ // close
                    tb_remove();
                }   
            };
        }
        
    } catch(e) {
        //nothing here
    }
}

//helper functions below
function tb_showIframe(){
    jQuery("#TB_load").remove();
    jQuery("#TB_window").css({display:"block"});
}

function tb_remove() {
    jQuery("#TB_imageOff").unbind("click");
    jQuery("#TB_closeWindowButton").unbind("click");
//    jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
    jQuery("#TB_window").hide();
    jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();

    jQuery("#TB_load").remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
        jQuery("body","html").css({height: "auto", width: "auto"});
        jQuery("html").css("overflow","");
    }
    document.onkeydown = "";
    document.onkeyup = "";
    return false;
}

function tb_position() {
jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
    if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
        jQuery("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
    }
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
    arrayPageSize = [w,h];
    return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


/*
 * Date prototype extensions. Doesn't depend on any
 * other code. Doens't overwrite existing methods.
 *
 * Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
 * isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
 * setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
 *
 * Copyright (c) 2006 Jörn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 *
 * Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
 * I've added my name to these methods so you know who to blame if they are broken!
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * An Array of day names starting with Sunday.
 * 
 * @example dayNames[0]
 * @result 'Sunday'
 *
 * @name dayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

/**
 * An Array of abbreviated day names starting with Sun.
 * 
 * @example abbrDayNames[0]
 * @result 'Sun'
 *
 * @name abbrDayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

/**
 * An Array of month names starting with Janurary.
 * 
 * @example monthNames[0]
 * @result 'January'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

/**
 * An Array of abbreviated month names starting with Jan.
 * 
 * @example abbrMonthNames[0]
 * @result 'Jan'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

/**
 * The first day of the week for this locale.
 *
 * @name firstDayOfWeek
 * @type Number
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.firstDayOfWeek = 1;

/**
 * The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.format = 'dd/mm/yyyy';
//Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';

/**
 * The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
 * only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.fullYearStart = '20';

(function() {

    /**
     * Adds a given method under the given name 
     * to the Date prototype if it doesn't
     * currently exist.
     *
     * @private
     */
    function add(name, method) {
        if( !Date.prototype[name] ) {
            Date.prototype[name] = method;
        }
    };
    
    /**
     * Checks if the year is a leap year.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.isLeapYear();
     * @result true
     *
     * @name isLeapYear
     * @type Boolean
     * @cat Plugins/Methods/Date
     */
    add("isLeapYear", function() {
        var y = this.getFullYear();
        return (y%4==0 && y%100!=0) || y%400==0;
    });
    
    /**
     * Checks if the day is a weekend day (Sat or Sun).
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.isWeekend();
     * @result false
     *
     * @name isWeekend
     * @type Boolean
     * @cat Plugins/Methods/Date
     */
    add("isWeekend", function() {
        return this.getDay()==0 || this.getDay()==6;
    });
    
    /**
     * Check if the day is a day of the week (Mon-Fri)
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.isWeekDay();
     * @result false
     * 
     * @name isWeekDay
     * @type Boolean
     * @cat Plugins/Methods/Date
     */
    add("isWeekDay", function() {
        return !this.isWeekend();
    });
    
    /**
     * Gets the number of days in the month.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.getDaysInMonth();
     * @result 31
     * 
     * @name getDaysInMonth
     * @type Number
     * @cat Plugins/Methods/Date
     */
    add("getDaysInMonth", function() {
        return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
    });
    
    /**
     * Gets the name of the day.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.getDayName();
     * @result 'Saturday'
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.getDayName(true);
     * @result 'Sat'
     * 
     * @param abbreviated Boolean When set to true the name will be abbreviated.
     * @name getDayName
     * @type String
     * @cat Plugins/Methods/Date
     */
    add("getDayName", function(abbreviated) {
        return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
    });

    /**
     * Gets the name of the month.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.getMonthName();
     * @result 'Janurary'
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.getMonthName(true);
     * @result 'Jan'
     * 
     * @param abbreviated Boolean When set to true the name will be abbreviated.
     * @name getDayName
     * @type String
     * @cat Plugins/Methods/Date
     */
    add("getMonthName", function(abbreviated) {
        return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
    });

    /**
     * Get the number of the day of the year.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.getDayOfYear();
     * @result 11
     * 
     * @name getDayOfYear
     * @type Number
     * @cat Plugins/Methods/Date
     */
    add("getDayOfYear", function() {
        var tmpdtm = new Date("1/1/" + this.getFullYear());
        return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
    });
    
    /**
     * Get the number of the week of the year.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.getWeekOfYear();
     * @result 2
     * 
     * @name getWeekOfYear
     * @type Number
     * @cat Plugins/Methods/Date
     */
    add("getWeekOfYear", function() {
        return Math.ceil(this.getDayOfYear() / 7);
    });

    /**
     * Set the day of the year.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.setDayOfYear(1);
     * dtm.toString();
     * @result 'Tue Jan 01 2008 00:00:00'
     * 
     * @name setDayOfYear
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("setDayOfYear", function(day) {
        this.setMonth(0);
        this.setDate(day);
        return this;
    });
    
    /**
     * Add a number of years to the date object.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.addYears(1);
     * dtm.toString();
     * @result 'Mon Jan 12 2009 00:00:00'
     * 
     * @name addYears
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addYears", function(num) {
        this.setFullYear(this.getFullYear() + num);
        return this;
    });
    
    /**
     * Add a number of months to the date object.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.addMonths(1);
     * dtm.toString();
     * @result 'Tue Feb 12 2008 00:00:00'
     * 
     * @name addMonths
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addMonths", function(num) {
        var tmpdtm = this.getDate();
        
        this.setMonth(this.getMonth() + num);
        
        if (tmpdtm > this.getDate())
            this.addDays(-this.getDate());
        
        return this;
    });
    
    /**
     * Add a number of days to the date object.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.addDays(1);
     * dtm.toString();
     * @result 'Sun Jan 13 2008 00:00:00'
     * 
     * @name addDays
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addDays", function(num) {
        //this.setDate(this.getDate() + num);
        this.setTime(this.getTime() + (num*86400000) );
        return this;
    });
    
    /**
     * Add a number of hours to the date object.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.addHours(24);
     * dtm.toString();
     * @result 'Sun Jan 13 2008 00:00:00'
     * 
     * @name addHours
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addHours", function(num) {
        this.setHours(this.getHours() + num);
        return this;
    });

    /**
     * Add a number of minutes to the date object.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.addMinutes(60);
     * dtm.toString();
     * @result 'Sat Jan 12 2008 01:00:00'
     * 
     * @name addMinutes
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addMinutes", function(num) {
        this.setMinutes(this.getMinutes() + num);
        return this;
    });
    
    /**
     * Add a number of seconds to the date object.
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.addSeconds(60);
     * dtm.toString();
     * @result 'Sat Jan 12 2008 00:01:00'
     * 
     * @name addSeconds
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addSeconds", function(num) {
        this.setSeconds(this.getSeconds() + num);
        return this;
    });
    
    /**
     * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
     * 
     * @example var dtm = new Date();
     * dtm.zeroTime();
     * dtm.toString();
     * @result 'Sat Jan 12 2008 00:01:00'
     * 
     * @name zeroTime
     * @type Date
     * @cat Plugins/Methods/Date
     * @author Kelvin Luck
     */
    add("zeroTime", function() {
        this.setMilliseconds(0);
        this.setSeconds(0);
        this.setMinutes(0);
        this.setHours(0);
        return this;
    });
    
    /**
     * Returns a string representation of the date object according to Date.format.
     * (Date.toString may be used in other places so I purposefully didn't overwrite it)
     * 
     * @example var dtm = new Date("01/12/2008");
     * dtm.asString();
     * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
     * 
     * @name asString
     * @type Date
     * @cat Plugins/Methods/Date
     * @author Kelvin Luck
     */
    add("asString", function(format) {
        var r = format || Date.format;
        if (r.split('mm').length>1) { // ugly workaround to make sure we don't replace the m's in e.g. noveMber
            r = r.split('mmmm').join(this.getMonthName(false))
                .split('mmm').join(this.getMonthName(true))
                .split('mm').join(_zeroPad(this.getMonth()+1))
        } else {
            r = r.split('m').join(this.getMonth()+1);
        }
        r = r.split('yyyy').join(this.getFullYear())
            .split('yy').join((this.getFullYear() + '').substring(2))
            .split('dd').join(_zeroPad(this.getDate()))
            .split('d').join(this.getDate());
        return r;
    });
    
    /**
     * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
     * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
     *
     * @example var dtm = Date.fromString("12/01/2008");
     * dtm.toString();
     * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
     * 
     * @name fromString
     * @type Date
     * @cat Plugins/Methods/Date
     * @author Kelvin Luck
     */
    Date.fromString = function(s)
    {
        var f = Date.format;
        
        var d = new Date('01/01/1970');
        
        if (s == '') return d;

        s = s.toLowerCase();
        var matcher = '';
        var order = [];
        var r = /(dd?d?|mm?m?|yy?yy?)+([^(m|d|y)])?/g;
        var results;
        while ((results = r.exec(f)) != null)
        {
            switch (results[1]) {
                case 'd':
                case 'dd':
                case 'm':
                case 'mm':
                case 'yy':
                case 'yyyy':
                    matcher += '(\\d+\\d?\\d?\\d?)+';
                    order.push(results[1].substr(0, 1));
                    break;
                case 'mmm':
                    matcher += '([a-z]{3})';
                    order.push('M');
                    break;
            }
            if (results[2]) {
                matcher += results[2];
            }
            
        }
        var dm = new RegExp(matcher);
        var result = s.match(dm);
        for (var i=0; i<order.length; i++) {
            var res = result[i+1];
            switch(order[i]) {
                case 'd':
                    d.setDate(res);
                    break;
                case 'm':
                    d.setMonth(Number(res)-1);
                    break;
                case 'M':
                    for (var j=0; j<Date.abbrMonthNames.length; j++) {
                        if (Date.abbrMonthNames[j].toLowerCase() == res) break;
                    }
                    d.setMonth(j);
                    break;
                case 'y':
                    d.setYear(res);
                    break;
            }
        }

        return d;
    };
    
    // utility method
    var _zeroPad = function(num) {
        var s = '0'+num;
        return s.substring(s.length-2)
        //return ('0'+num).substring(-2); // doesn't work on IE :(
    };
    
})();/*
 * Input Floating Hint Box - jQuery plugin 1.1 Beta
 *
 * Copyright (c) 2008 Nicolae Namolovan (nicolae.namolovan gmail.com)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: 20
 *
 */
 /**
  * Home page http://nicolae.namolovan.googlepages.com/jquery.inputHintBox.html
  * Demo http://nicolae.namolovan.googlepages.com/jquery.inputHintBox.demo.html
  **/

/**
 * Provide an automatic box hint in the right side of a input when user click it, it disapear when focus change (blur)
 *
 * Depends on dimensions plugin's offset method for correct positioning of the hint box element
 *
 * The source(@source) of the text/html can be an attribute (title for example), or a pure html.
 * Attribute can contain escaped html, example: title="This will be &lt;b&gt;Bold&lt;/b&gt;"
 *
 * All hints can use one div element(@div option) with your custom design, and only some subelement of 
 * this @div will change (according to source).
 *
 * You can provide only the @className, and for each input a separate <div> element will be created
 * with @className as class.
 *
 * If user click on the box to select some text (for copy/paste for example), box will not disappear.
 *
 * If you need to make the box appear in more left, use incrementLeft, same for top - incrementTop,
 * you can use - sign if you want to decrement.
 **/

/**
 * Example, you have a shiny div and you want to use it as a Shell for hint messages
 * <div id="shiny_box">
 *  <span id="round-tleft"><span id="round-tright">
 *  <div class="shiny_box_body"></div>
 *  <span id="round-bleft"><span id="round-bright">
 * </div>
 *
 * You have a inputs like:
 * <input name="username" type="text" class="titleHintBox" title="Only letters &lt;b&gt;(a-z)&lt;/b&gt;, numbers (0-9), and periods (.) are allowed">
 * <input name="password" type="text" class="titleHintBox" title="Minimum of 8 characters in length">
 *
 * Here is an example of js to use:
 * $('.titleHintBox').inputHintBox({div:$('#shiny_box'),div_sub:'.shiny_box_body',source:'attr',attr:'title',incrementLeft:12,incrementTop:-12});
 **/

/**
 * Provide a hint box near input as a absolute positioned div.
 * @name InputHintBox
 * @cat Plugins/Forms
 * @type $
 * @param Map options Optional settings
 * @option jQueryDom @div box to show, if this is set then className do not apply
 * @option String @div_sub css selector, use this when you need to write the Dynamic html into a element Inside the @div box,
                            example: .body, this will search for .body in context of @div
 * @option String @className This class will be added to the dynamic created div box. Default: "input_hint_box"
 * @option String @source Source of box message text html: attr | html, Default: "attr"
 * @option String @attr If @source = "attr" then html will be taken from the attribute named @attr. Default: "title"
 * @option String @html If @source = "html" them html will be taken from @html
 * @option Integer @incrementLeft This value will be incremented to the left property of the absolute positioned hint box. Default: 10
 * @option Integer @incrementTop This value will be incremented to the top property of the absolute positioned hint box. Default: 10
 * @option String @attachTo Hint box will be appended to this. Default: "body"
 */

(function($) {
$.fn.inputHintBox = function(options) {
    options = $.extend({}, $.inputHintBoxer.defaults, options);
    
    this.each(function(){
        new $.inputHintBoxer(this,options);
    });
    return this;
}

$.inputHintBoxer = function(input, options) {
    var $guideObject,$input = $guideObject = $(input), box, boxMouseDown = false;
    
    //$guideObject - in left of this object hint box will be positioned
    
    // If @type=radio then it must be inside a label and we should put the hint box in the right side of the label
    if ( ($input.attr('type') == 'radio' || $input.attr('type') == 'checkbox') && $input.parent().is('label') ) {
        $guideObject = $( $input.parent() );
    }
    

    function init() {
        var boxHtml = options.html != ''?options.html:
                        options.source == 'attr'?$input.attr(options.attr): '';
            
        if (typeof boxHtml === "undefined") boxHtml = '';
        box = options.div != '' ? options.div.clone() : $("<div/>").addClass(options.className);
        box = box.css('display','none').addClass('_hintBox').appendTo(options.attachTo);
        
        if (options.div_sub == '') box.html(boxHtml);
        else $(options.div_sub,box).html(boxHtml);
        
        if (!options.noshowonfocus) {
            $input.focus(function() {
                $('body').mousedown(global_mousedown_listener);
                show();
            });
        }
        $input.blur(function(){
            prepare_hide();
        });

        input.showhint=function() {
            $('body').mousedown(global_mousedown_listener);
            show();
        };
    }
    
    // This is evaluated each time to prevent probs with elements with display none
    function align() {
        var offsets = $guideObject.position(),
            left = offsets.left + $guideObject.width() + options.incrementLeft + 5 + ($.browser.safari?5:($.browser.msie?10:($.browser.mozilla?6:0))),
            top = offsets.top + options.incrementTop + ($.browser.msie?14:($.browser.mozilla?8:0));
        box.css({position:"absolute",top:top,left:left});
    }
    
    function show() {
        align();
        box.fadeIn('slow');
    }
    
    function prepare_hide() {
        // We want to allow user to select and copy/paste content from the box
        // So delay a bit to see where user click
        /*
        $('body').click(global_click_listener);
        if (boxMouseDown) return;
        $.inputHintBoxer.mostRecentHideTimer = setTimeout(function(){hide()},300);
        */
        //B: 090622: nem engedünk szöveget kimásolni és pont
        hide();
    }
    
    var global_click_listener = function(e) {
        var $e = $(e.target),c='._hintBox';
        clearTimeout($.inputHintBoxer.mostRecentHideTimer);
        if ($e.parents(c).length == 0 && $e.is(c) == false) hide();
    };
    
    // Prevent hiding when selecting..
    // When user Select a text to select, a Mousedown is fired BEFORE blur of input
    // This why we need to know when a Mousedown is done to our object
    var global_mousedown_listener = function(e) {
        var $e = $(e.target),c='._hintBox';
        boxMouseDown = ($e.parents(c).length != 0 || $e.is(c) != false);
    }
    
    function hide() {
        $('body').unbind('click',global_click_listener);
        $('body').unbind('mousedown',global_mousedown_listener);
        align();
        box.fadeOut('slow');
    }
    
    init();
    return {}
};

$.inputHintBoxer.mostRecentHideTimer = 0;

$.inputHintBoxer.defaults = {
    div: '',
    className: 'input_hint_box',
    source: 'attr', // attr or html
    div_sub: '', // Where to write
    attr: 'title',
    html: '',
    incrementLeft: 5,
    incrementTop: 0,
    attachTo: 'body'
}

})(jQuery);            function ReformatMessage(msg)
            {
                if ((msg.indexOf("<br")!=-1)) {    //TODO: erre regexp-et
                    return msg;
                } else {
                    return msg.gsub("\n","<br/>");
                }

            }

            function isMultiLine(msg)
            {
                return (msg.indexOf("<br")!=-1) || (msg.indexOf("\n")!=-1); //TODO: erre regexp-et
            }

            function navigateto(newurl)
            {
                window.location=newurl;
            }

            function MessageDialogKeypress(data)
            {
                if (data.keyCode==27) {
                    MessageDialogClose();
                }
            }

            /**
             * Display a simple modal dialog
             *
             * @param msg    Message to display to the user.
             * @param title  Title of the message box.
             * @param button string (Button caption) or object
             *               (.Caption:button caption,.OnClick:button
             *               onclick)
             */
            function MessageDialog(msg,title,button,denyescape)
            {
                MessageConfirm(msg,title,button?(button.length>1?button:new Array(button)):new Array({Caption:"Ok",OnClick:MessageDialogClose}),null,null,denyescape);
            }

            function MessageConfirm(msg,title,buttons,width,height,denyescape,url,urlloadedfunction) {

                jQuery("#dialog_tobbgombos #dialog_tobbgombos_container_inner").empty();
                if (url) {
                    jQuery("#dialog_tobbgombos_container_inner_wait").show();
                    jQuery("#dialog_tobbgombos_container #dialog_tobbgombos_container_inner").load(url,null,function() {
                                                                                                                            jQuery("#dialog_tobbgombos_container_inner_wait").hide();
                                                                                                                            if (urlloadedfunction) {
                                                                                                                                eval(urlloadedfunction+'()');
                                                                                                                            }
                                                                                                                        });
                }

                if (title) {
                    jQuery(jQuery("#dialog_tobbgombos h2")[0]).text(title);
                } else {
                    jQuery(jQuery("#dialog_tobbgombos h2")[0]).text("Üzenet");
                }

                if (msg) {
                    jQuery("#dialog_tobbgombos #dialog_tobbgombos_uzenet").show();

                    var messagelabel=jQuery("#dialog_tobbgombos #dialog_tobbgombos_uzenet");
                    messagelabel.html('');

                    if (isMultiLine(msg.strip())) {
                        messagelabel.css("textAlign",'justify');
                    } else {
                        messagelabel.css("textAlign",'center');
                    }

                    msg=ReformatMessage(msg);
                    messagelabel.html(msg);
                    //jQuery(messagelabel).show();
                } else {
                    jQuery("#dialog_tobbgombos #dialog_tobbgombos_uzenet").hide();
                }

                if ((buttons!=null) && (buttons.length>0)) {

                    jQuery("#dialog_tobbgombos .newkindbutton").hide();
                    jQuery("#dialog_tobbgombos .newkindbutton a").text("Ok");

                    jQuery("#dialog_tobbgombos #dialog_tobbgombos_container_buttons").show();

                    for (var i=0;i<buttons.length;i++) {

                        //TODO: rendes child-jai legyenek
                        jQuery("#dialog_tobbgombos #dialog_gomb_link_"+(i+1))[0].href="javascript:;";
                        jQuery("#dialog_tobbgombos #dialog_gomb_link_"+(i+1))[0].onclick=MessageDialogClose;
                        jQuery("#dialog_tobbgombos #dialog_gomb_"+(i+1)+" .newkindbuttoncenter")[0].style.width=(130-24)+'px';
                        jQuery("#dialog_tobbgombos #dialog_gomb_"+(i+1))[0].style.width=130+'px';

                        jQuery(jQuery("#dialog_tobbgombos #dialog_gomb_link_"+(i+1))[0]).text(buttons[i].Caption);
                        if (buttons[i].href) {
                            jQuery("#dialog_tobbgombos #dialog_gomb_link_"+(i+1))[0].href=buttons[i].href;
                            jQuery("#dialog_tobbgombos #dialog_gomb_link_"+(i+1))[0].onclick=null;
                        }
                        if (buttons[i].OnClick) {
                            jQuery("#dialog_tobbgombos #dialog_gomb_link_"+(i+1))[0].onclick=buttons[i].OnClick;
                        }
                        if (buttons[i].Width) {
                            jQuery("#dialog_tobbgombos #dialog_gomb_"+(i+1)+" .newkindbuttoncenter")[0].style.width=(buttons[i].Width-24)+'px';
                            jQuery("#dialog_tobbgombos #dialog_gomb_"+(i+1))[0].style.width=buttons[i].Width+'px';
                        }

                        jQuery("#dialog_tobbgombos #dialog_gomb_"+(i+1))[0].style.display='inline-block';
                    }
                } else {
                    jQuery("#dialog_tobbgombos #dialog_tobbgombos_container_buttons").hide();
                }

                tb_show(title,"#TB_inline?width="+(width?width:500)+"&amp;"+(height?"height="+height+"&amp;":'')+"inlineId=dialog_tobbgombos_container&amp;modal=true");
                if (!denyescape) {
                    jQuery(document).bind("keypress",MessageDialogKeypress);
                }
            }

            /**
             * Végrehajt egy mûveletet, majd kijelzi az eredményt.
             *
             * @param title   Felirat (?)
             * @param url     Meghívandó cím
             * @param data    post adata
             * @param Success Object
             *                .Message - üzenet
             *                .Caption - gomb felirata
             *                .href - url
             *                .OnClick - okézáskor
             *                .Width - szélesség
             */
            function MessageDialogAjaxProcess(title,url,data,Success)
            {
                MessageDialog("Kérlek, várj...",title);
                jQuery.post(url,
                            data,
                            function(responsetext,resp2) {
                                var resp=AjaxCheckResponse(responsetext,"",resp2);

                                if (resp2=="success") {

                                    if (Success.OnSuccess) {
                                        Success.OnSuccess(resp);
                                    }

                                    if (resp.result) {
                                        MessageDialog(Success.Message,title,{Caption:Success.Caption,href:Success.href,OnClick:Success.OnClick,Width:Success.Width},true);
                                    } else {
                                        MessageDialog("Hiba a m?velet során: "+responsetext,title);
                                    }
                                }
                            },
                            'text');
            }



            /**
             * Bezárja az éppen megnyitott MessageDialog-ot.
             */
            function MessageDialogClose() {
                tb_remove();
                jQuery("#dialog_tobbgombos #dialog_tobbgombos_container_inner").empty();
                jQuery(document).unbind("keypress",MessageDialogKeypress);
            }



            function SubmitForm(obj)
            {
                //Event.stop(event);

                var o=obj;
                while (o.tagName!="FORM") {
                    o=o.parentNode;
                }

                var res=true;
                if (o.onsubmit) {
                    res=false;
                    //res=o.parentNode.onsubmit(event); //TODO: IE alatt nincs paramétere
                    res=o.onsubmit();
                }
                if (res) {
                    return o.submit();
                }
            }


            function waitBegin(event,form)
            {
                if (form!=null) {
                    var obj=form.parentNode;
                    var po=jQuery(obj).offset();
                    jQuery("#loading_panel")[0].style.left=po.left+'px';
                    jQuery("#loading_panel")[0].style.top=po.top+'px';
                    var w=jQuery(obj).width();
                    var h=jQuery(obj).height();
                    jQuery("#loading_panel").width(w).height(h).show();

                    var w2=jQuery("#loading").width();
                    var h2=jQuery("#loading").height();
                    jQuery("#loading")[0].style.left=((po.left)+(w/2)-(w2/2))+'px';
                    jQuery("#loading")[0].style.top=((po.top)+(h/2)-(h2/2))+'px';
                } else {
                    jQuery("#loading")[0].style.left='0px';
                    jQuery("#loading")[0].style.top='0px';
                }
                jQuery("#loading").show();
            }

            function waitEnd()
            {
                jQuery("#loading_panel").hide();
                jQuery("#loading").hide();
            }

            function AjaxFormSubmit(event,form,dialogtoclose,disablewaitdialog) {
                if (disablewaitdialog) {
                    MessageDialog("Kérlek, várj...","Feldolgozás","Mégsem");
                }

                waitBegin(event,form);

                var files=jQuery("#"+(form.attributes["id"]?form.attributes["id"].value:"")+" :input:file");

                if ((files.length==0) || (files[0].value=="")) {

                    if (dialogtoclose) {
                        jQuery(dialogtoclose).dialog('close');
                    }

                    var data=jQuery(form).serializeArray();

                    data.push({name:'isajax',value:1});

                    jQuery.post(form.action,data,function(data,statustext) {AjaxFormSubmitCheck(data,statustext,event,form)},'text');

                    return false; //B: mivel mi küldtük el a post-ot, ezért nem kell az eredeti submit
                } else {
                    //MessageDialog("sending file!");
                    return true; //B: kell az eredeti submit, mert van input:file, amit rendesen kell post-olni
                }
            }

            function AjaxCheckResponse(responsetext,errormessage,ajaxresponsestatus)
            {
                waitEnd();
                if (ajaxresponsestatus=="success") {
                    var data=null;
                    try {
                        data=(responsetext.strip()).evalJSON();
                    } catch (e) {
                        MessageDialog((errormessage?errormessage:"Hiba: A szerver nem értelmezhető adatot küldött vissza a böngészőnek. ")+"<br/><br/>"+e+"<br/>"+responsetext,"Kommunikációs hiba");

                        return null;
                    }
                    return data;
                } else {
                    MessageDialog("Nem sikerült a kommunikáció a szerverrel ("+ajaxresponsestatus+").\n\n"+responsetext,"Hiba");

                    return null;
                }
            }

            function AjaxFormSubmitCheck(jsondata,textstatus,event,form) {

                var data=AjaxCheckResponse(jsondata,"",textstatus);

                if ((data==null) || (data=="")) {
                    MessageDialog("Hiba: A szerver nem értelmezhető adatot küldött vissza a böngészőnek.<br/><br/>"+jsondata+"<br/><br/>Kérlek, próbáld újból a műveletet.","Kommunikációs hiba");
                    return false;
                }

                if (data.closedialog) {
                    MessageDialogClose();
                }
                if (data.result) {
                    if ((data.update_id) && ((data.update_content) || (data.update_content_html))) {
                        if (data.update_content_html) {
                            jQuery('#'+data.update_id).html(data.update_content_html);
                        } else {
                            jQuery('#'+data.update_id).load(data.update_content);
                        }
                    }
                    if (data.popupmessage) {
                        if (data.popupmessage_buttonstr) {
                            data.popupmessage_button=eval(data.popupmessage_buttonstr);
                        }
                        MessageDialog(data.popupmessage,data.popupmessage_title,data.popupmessage_button);
                    }

                    if (typeof(data.dialogurl)!="undefined") {
                        MessageDialogClose();
                        MessageConfirm(null,data.dialogtitle,null,data.dialogwidth,data.dialogheight,false,data.dialogurl);

                        return true;
                    }

                    if (typeof(data.forward)!="undefined") {
                        tb_show("Betöltés...");
                        navigateto(data.forward);

                        return true;
                    } else if (typeof(data.callback)!="undefined") {
                        eval(data.callback+"(data,textstatus,event,form)");
                    } else if (typeof(data.eval)!="undefined") {
                        eval(data.eval);
                    } else {
                        if (!data.popupmessage) {
                            if (!data.nothing) {
                                //MessageDialog('TODO: nincs hova továbblépni...');
                            }
                        }
                    }
                } else {
                    if (event!=null) {
                        //Event.stop(event); //TODO: vissza
                    }

                    var msg="";
                    var f="";
                    var obj=null;

                    if (data.errormessage) {
                        msg=msg+data.errormessage+'\n';
                    }

                    $H(data.errormessages).each(function(pair) {

                        if (!pair.value) {
                            msg=msg+pair+'\n';
                        } else {
                            $(pair.value).each(function(pair2,index) {
                                var s=pair2;

                                obj=jQuery("[for="+pair.key+"]");
                                if (obj.length>0) {
                                    if (s.length>1) {
                                        s=s.sub("\%field\%",obj[0].attributes["fieldname"]?obj[0].attributes["fieldname"].value:obj[0].innerHTML);
                                    }
                                }
                                obj=jQuery("#"+pair.key);
                                if (obj.length>0) {
                                    if (s.length>1) {
                                        s=s.sub("\%value\%",obj[0].value);
                                    }
                                }
                                if (s.length>1) {
                                    msg=msg+s+'\n';
                                }
                            });
                        }

                    });

                    MessageDialog(msg);

                    return false;
                }
            }


            function UserLogout()
            {
                MessageConfirm("Biztos, hogy kilépsz?",
                               "Kilépés",
                               new Array({Caption:"Kilépés",href:baseURL+'/felhasznalo/felhasznaloi-tevekenysegek/felhasznalo-kilepes'},
                                         {Caption:"Mégsem",OnClick:MessageDialogClose}),
                               300);
            }


            function UserProfileModify()
            {
                MessageConfirm(null,"Adatok módosítása",null,700,300,false,baseURL+"/felhasznalo/felhasznaloi-adatok/felhasznaloi-adatok-modositasa");
            }


            function UserLoginNeeded(operation)
            {
                MessageConfirm("A műveletet végrehajtásához felhasználói bejelentkezés szükséges. Kérlek jelentkezz át, vagy regisztrálj!",
                               operation,
                               new Array({Caption:"Átjelentkezés",
                                          href:baseURL+'/partner/partner-tevekenysegek/partner-kilepes',
                                          Width:130},
                                         {Caption:"Regisztráció",
                                          href:baseURL+"/felhasznalo/felhasznaloi-adatok/felhasznalo-regisztracio",
                                          Width:130},
                                         {Caption:"Mégsem",
                                          Width:130}
                               ));
            }

            function UserPleaseLogin(operation)
            {
                MessageConfirm("A műveletet csak regisztrált felhasználók használhatják. Kérlek jelentkezz be, vagy regisztrálj!",
                               operation,
                               new Array({Caption:"Bejelentkezés",
                                          OnClick:function() {MessageDialogClose();jQuery("#felhasznalo_input").focus();},
                                          Width:130},
                                         {Caption:"Regisztráció",
                                          href:baseURL+"/felhasznalo/felhasznaloi-adatok/felhasznalo-regisztracio",
                                          Width:130},
                                         {Caption:"Mégsem",
                                          Width:130}
                               ));
            }


            function UgyfelkapuAccess()
            {
                MessageConfirm(null,"Ügyfélkapu",null,400,300,false,baseURL+"/felhasznalo/felhasznaloi-tevekenysegek/felhasznalo-ugyfelkapu-access");
            }


            function FelhasznaloKuponKosarba(coupon_id,skipreturn) {
                jQuery.post(baseURL+"/felhasznalo/kosar/kupon-kosarba",
                            {'id':coupon_id,'isajax':1},
                            function(responsetext,resp2) {

                                var resp=AjaxCheckResponse(responsetext,"",resp2);

                                if (resp2=="success") {

                                    if (resp.result) {
                                        jQuery('#kosargombcontainer').html(resp.html);

                                        jQuery("#kupon_"+coupon_id).animate({opacity:0.4},"slow",null,function() {
                                             jQuery("#kupon_"+coupon_id).animate({opacity:1});
                                        });
                                    } else {
                                        MessageDialog(resp.message,"Gy?jt?");
                                    }
                                } else {
                                    MessageDialog("Nem sikerült a kupont a gy?jt?be rakni."+resp,"Gy?jt?");
                                }
                            },
                            'text');

                if (!skipreturn) {
                    return false;
                }
            }

            function FelhasznaloKuponKosarbol(coupon_id) {
                jQuery.post(baseURL+"/felhasznalo/kosar/kupon-kosarbol",
                            {'id':coupon_id,'isajax':1},
                            function(responsetext,resp2) {

                                var resp=AjaxCheckResponse(responsetext,"",resp2);

                                if (resp2=="success") {
                                    jQuery('#kosargombcontainer').html(resp.html);

                                    jQuery("#kupon_"+coupon_id).hide("slow",function() {
                                        jQuery("#kupon_"+coupon_id).remove();
                                    });
                                    //MessageDialog("A kupont kivettük a gy?jt?b?l.");
                                } else {
                                    MessageDialog("Nem sikerült a kupont kivenni a gy?jt?b?l."+resp,"Gy?jt?");
                                }
                            },
                            'text');

                return false;
            }

            function KuponMegjeloltCimIDk(coupon_id) {

            }

            function FelhasznaloKuponNyomtatasra(coupon_id,skipreturn,useselectedshops) {

                if (UserLevel==1) {
                    var shopids='';
                    if (useselectedshops) {
                        var ids=new Array();
                        jQuery(".shop_address_on_coupon:checkbox[checked]").each(function(i) {
                            ids[i]=jQuery(this).attr("shop_id");
                        });
                        ids[ids.length]=0;

                        shopids=ids.toString();
                    }

                    MessageConfirm("Csak ezt az egy kupont szeretnéd nyomtatni vagy egy lapra több kupont nyomtatsz?\n"+
                                   "\n<b>Felhívjuk figyelmed</b>, hogy tesztjeink alapján egyszerre több kupont <b>csak a Firefox</b> böngésző (minimum 3.0-s verzió) tud kinyomtatni rendesen. Ezért kérjük, ellenőrizd a böngésződ által elkészített nyomtatási előnézet képét!",
                                   "Nyomtatás",
                                   new Array({Caption:"Csak ezt nyomtatom",
                                              OnClick:function () {MessageDialogClose();window.open(baseURL+"/kupon/nyomtatas/kupon-nyomtatas/id/"+coupon_id+"/shop_ids/"+escape(shopids),"_blank");},
                                              Width:180},
                                             {Caption:"Egy lapra többet",
                                              OnClick:function(){
                                                  MessageDialogClose();
                                                  jQuery("#nyomtatogombcontainer").load(baseURL+"/kupon/nyomtatas/nyomtatas-hozzaad",
                                                                                        {'id':coupon_id,'isajax':1,'shop_ids':shopids},
                                                                                        function(resp,resp2) {
                                                                                            if (resp2=="success") {
                                                                                                jQuery("#kupon_"+coupon_id).animate({opacity:0.4},"slow",null,function() {
                                                                                                     jQuery("#kupon_"+coupon_id).animate({opacity:1});
                                                                                                });
                                                                                            } else {
                                                                                                MessageDialog("Nem sikerült a kupont a nyomtatási listához hozzáadni."+resp);
                                                                                            }
                                                                                        });
                                                },
                                              Width:180},
                                             {Caption:"Mégsem",
                                              OnClick:MessageDialogClose
                                             })
                                   );
                } else {
                    window.open(baseURL+"/kupon/nyomtatas/kupon-nyomtatas/id/"+coupon_id,"_blank");
                }

                if (!skipreturn) {
                    return false;
                }
            }


            function CheckSendSMS(coupon_id)
            {
                jQuery.getJSON(baseURL+"/sms/sms/checkavailable/",
                               {coupon_id:coupon_id},
                               function(json) {
                                   if (json.available) {
                                       SendSMS(coupon_id);
                                   } else {
                                       MessageDialog("A kuponhoz rendelt SMS-ek elfogytak. Próbáld újra később.","SMS");
                                   }
                               });
            }

            function SendSMS(coupon_id,retrynum)
            {
                MessageConfirm(null,"Kupon küldése SMS-ben",null,400,300,false,baseURL+"/sms/sms/kupon-kuldes-smsben-form/coupon_id/"+coupon_id+"/retries/"+(retrynum?retrynum:0));
    /*
        jQuery(jQuery("#dialog_sms #dialog_sms_coupon_id")[0]).val(coupon_id);
        tb_show("SMS kÃ¼ldÃ©s","#TB_inline?width=350&amp;height=200&amp;inlineId=dialog_sms_container&amp;modal=true");
        jQuery(document).bind("keypress",MessageDialogKeypress);
    */
            }


            function imageGetURL(imageid,imagesize)
            {
                return baseURL+"/skin/kep/kep/kep_id/"+imageid+"/kep_meret/"+imagesize;
            }

            function barcodeGetURL(barcode)
            {
                return baseURL+"/skin/barcode/barcode/barcode/"+barcode;
            }

            function shopGetURL(shopid)
            {
                return baseURL+"/kupon/uzlet/uzlet-reszletek/id/"+shopid;
            }

            var ontoolbar=false;
            var currkupon=null;

            function KuponMuveletSMS(event)
            {
                //currkupon.attr("kupon_id");
                //TODO: beállítani az aktuális kupon-t és id-jét, hogy mindenki tudhassa
                tb_show("SMS Küldés","#TB_inline?width=330&height=150&inlineId=dialog_sms_container&modal=true");
            }

            jQuery(document).ready(function (event) {

                jQuery("#loading").ajaxComplete(function(request, settings){
                   waitEnd();
                });
                jQuery("#loading").ajaxStop(function(){
                   waitEnd();
                });
                jQuery("#loading").ajaxError(function(event, request, settings){
                   waitEnd();
                });


                jQuery(".kupon-elem-lista").mouseenter(function () {
                    var po=jQuery(this).position();
                    jQuery("#qpontoolbar")[0].style.top=(po.top+24)+'px';
                    jQuery("#qpontoolbar")[0].style.left=((po.left+jQuery(this).width())-jQuery(jQuery("#qpontoolbar")[0]).width())+'px';
        //            jQuery("#qpontoolbar")[0].style.left=(po.left)+'px';
                    jQuery("#qpontoolbar").show();

                    currkupon=jQuery(this);

                    jQuery(".dynamiclink2").each(function(link) {
                        var o2=jQuery(this).attr("onclick2");
                        if (o2) {
                            jQuery(this).attr("href",o2.gsub("coupon_id",currkupon.attr("coupon_id")));
                        }

                        var filt=jQuery(this).attr("filter");
                        if (currkupon.attr("allow"+filt)=="0") {
                            jQuery(this.parentNode).hide();
                        } else {
                            jQuery(this.parentNode).show();
                        }
                    });

                    jQuery(".dynamiclink").each(function(link) {
                        var h2=jQuery(this).attr("href2");
                        if (h2) {
                            jQuery(this).attr("href",h2.gsub("coupon_id",currkupon.attr("coupon_id")));
                        }

                        var filt=jQuery(this).attr("filter");
                        if (currkupon.attr("allow"+filt)=="0") {
                            jQuery(this.parentNode).hide();
                        } else {
                            jQuery(this.parentNode).show();
                        }
                    });

                }).mouseleave(function () {
                    if (ontoolbar) {
                        jQuery("#qpontoolbar").hide();
                    }

                    if (currkupon) {
                        currkupon.removeClass("kupon-elem-lista-selected");
                    }
                });

                jQuery(jQuery("#qpontoolbar")[0]).mouseenter(function () {
                    ontoolbar=true;
                    currkupon.addClass("kupon-elem-lista-selected");
                }).mouseleave(function () {
                    ontoolbar=false;
                    currkupon.removeClass("kupon-elem-lista-selected");
                });

                if (GetURLParam("votestart")==1) {
                    userVote(GetURLParam("votesubject"));
                }

            });


            function nyomtatasInditas()
            {
                MessageConfirm("Sikeresen kinyomtattad a kuponokat? Törölhetjük őket a nyomtatási listáról?",
                               "Nyomtatás",
                               new Array(
                                    {Caption:"Igen, törlés",
                                     OnClick:function() {
                                         MessageDialogClose();
                                         nyomtatoUrites();
                                     }
                                    },
                                    {Caption:"Nem"}
                                   )
                               );
            }


            function nyomtatoUrites()
            {
                MessageDialogAjaxProcess("Nyomtatási lista ürítése",
                                         baseURL+"/kupon/nyomtatas/nyomtatas-urites/",
                                         null,
                                         {Message:"A nyomtatási lista kiürítve.",
                                          Caption:"Rendben",
                                          OnClick:function(){
                                              MessageDialogClose();
                                          },
                                          OnSuccess:function(){
                                              jQuery("#nyomtatogombcontainer").load(baseURL+'/kupon/nyomtatas/nyomtatas-gomb/');
                                          }
                                         });

            }

            function smsKuldesEredmeny(data,textstatus,event,form)
            {
                if (data.code==0) {
                    MessageDialog("Az üzenetet sikeresen elküldtük.");
                } else {
                    MessageDialog("Hiba történt az üzentküldés során: ("+data.code+") "+data.message);
                }
            }

            function CouponShopClicked(input,coupon_id)
            {
                var chks=jQuery("#kupon_"+coupon_id+" .shop_address_on_coupon:checkbox[checked]");
                if (chks.length>MaxShopsOnCoupon) {
                    MessageDialog("Egyszerre csak "+MaxShopsOnCoupon+" üzletet válassz ki, mert lehet, hogy a nyomtatáson csak annyi látszik rendesen!",'Figyelmeztetés',{Caption:"Ok",OnClick:function() {MessageDialogClose();jQuery(input).attr('checked',null).fadeOut().fadeIn().fadeOut().fadeIn();}});
                }

            }

            function userFeedback() {
                MessageConfirm(null,
                               "Visszajelzés",
                               null,
                               500,
                               600,
                               false,
                               baseURL+"/felhasznalo/felhasznaloi-visszajelzes/felhasznaloi-visszajelzes-form");
            }


            function couponDeleteQuestion(coupon_id)
            {
                MessageConfirm(null,
                               "Kupon törlés",
                               null,
                               340,
                               560,
                               false,
                               baseURL+'/kupon/partner/partner-kupon-torles-form/id/'+coupon_id);
            }

            function couponValidityLength(coupon_id)
            {
                MessageConfirm(null,
                               "Kupon megjelenésének és beválthatóságának hosszabbítása",
                               null,
                               420,
                               null,
                               false,
                               baseURL+'/kupon/partner/partner-kupon-hosszabbitas-form/id/'+coupon_id);
            }


            function KuponLogoCsere(coupon_id)
            {
                MessageConfirm(null,
                               "Logó módosítás",
                               null,
                               380,
                               400,
                               false,
                               baseURL+'/kupon/partner/partner-kupon-logo-modositas-form/id/'+coupon_id);
            }

            function KuponLogoCsereOk(coupon_id)
            {

            }

            function KuponSMSVasarlas(coupon_id,id,originalparent,originalparentcontainer)
            {
                MessageDialog("<h4>Hamarosan!</h4>","SMS vásárlás a kuponhoz");
                /*
                MessageDialogURL("SMS vásárlás a kuponhoz",
                                 "",
                                 "<?=$this->url(array('module'=>'kupon','controller'=>'partner','action'=>'partner-kupon-sms-vasarlas'),'default',true)?>/coupon_id/"+coupon_id,
                                 new Array({Caption:"Rendben",OnClick:function(){KuponSMSVasarlasOk(coupon_id,id,originalparent,originalparentcontainer);MessageDialogURLClose(); return false;},Width:130},
                                           {Caption:"Mégsem",OnClick:function(){MessageDialogURLClose(); return false;}}),
                                 400,
                                 320
                                 );
                return false;
                */
            }
            function KuponSMSVasarlasOk(coupon_id,id,originalparent,originalparentcontainer)
            {
                jQuery("#kupon_"+coupon_id+"_info").load("<?=$this->url(array('module'=>'kupon','controller'=>'partner','action'=>'partner-kupon-info','isajax'=>true),'default',true)?>/coupon_id/"+coupon_id);
            }

            function KuponKiemeles(coupon_id)
            {
                MessageConfirm(null,
                               "Kupon kiemelés",
                               null,
                               360,
                               null,
                               false,
                               baseURL+'/kupon/partner/partner-kupon-kiemeles-form/id/'+coupon_id);
            }


            function KuponBoltHozzaadas(coupon_id)
            {
                MessageConfirm(null,
                               "Üzletek hozzárendelése",
                               null,
                               360,
                               null,
                               false,
                               baseURL+'/kupon/kupon-modositas/uzlet-hozzarendeles/'+coupon_id);
            }

            function PasswordForgotUser()
            {
                MessageConfirm(null,
                               "Elfelejtett jelszó",
                               null,
                               400,
                               null,
                               false,
                               baseURL+'/felhasznalo/felhasznaloi-tevekenysegek/felhasznalo-elfelejtett-jelszo-form');
            }


            function highlightElemet(jQueryDefinition,highlightColor,oldBackgroundColor) {
                if (!oldBackgroundColor) {
                    oldBackgroundColor=jQuery(jQueryDefinition).css("background-color");
                }
                jQuery(jQueryDefinition).animate({backgroundColor:  highlightColor}).animate({backgroundColor:oldBackgroundColor},250);
            }

            function highlightElemet2(jQueryDefinition) {
                jQuery(jQueryDefinition).fadeOut().fadeIn();
            }

            function userVote(votesubject) {
                if (!votesubject) {
                    votesubject="";
                }
                MessageConfirm('','Kupon szavazatok',null,600,450,true,baseURL+'/szavazas/kupon-szavazas/szavazas-kupon-szavazas-form/?votesubject='+votesubject);
            }


            function GetURLParam(name)
            {
                /**
                 * credits:
                 * http://www.netlobo.com/url_query_string_javascript.html
                 *                                                            */

                name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
                var regexS = "[\\?&]"+name+"=([^&#]*)";
                var regex = new RegExp( regexS );
                var results = regex.exec( window.location.href );
                if( results == null )
                    return "";
                else
                    return results[1];
            }

            function adminPartnerSettings(partner_id) {
                MessageConfirm('','Partner beállítások',null,600,450,true,baseURL+'/admin/admin-tevekenysegek/admin-partner-tulajdonsagok-form/partner_id/'+partner_id);
            }

            function imageUpload(imageid,onselected,current) {
                MessageConfirm(null,
                               "Kép feltöltés - kiválasztás",
                               null,
                               360,
                               null,
                               false,
                               baseURL+'/kupon/partner/partner-kepfeltoltes-form/imageid/'+imageid+'/onselected/'+escape(onselected)+'/current/'+current);
            }

            function shareInternal(url,coupon_id) {
                shareToolbarToggle(coupon_id);

                if (coupon_id==null) {
                    coupon_id=currkupon.attr("coupon_id");
                    cid=currkupon.attr("cid");
                    coupontitle=currkupon.attr("title");
                    fulltext=jQuery.trim(jQuery("#kupon_"+coupon_id+" .kupon_lista_title").attr("title"));
                } else {
                    c=jQuery("#kupon_"+coupon_id);
                    cid=c.attr("cid");
                    coupontitle=c.attr("title");
                    fulltext=jQuery.trim(jQuery("#kupon_"+coupon_id+" .discount_text").text())+' '+jQuery.trim(jQuery("#kupon_"+coupon_id+" .discount_condition").text());
                }
                img=baseURL2+jQuery("#kupon_"+coupon_id+" .kupon_logo_link_img").attr("src");

                url=url.gsub("%URI%",encodeURI(baseURL2+"/"+cid));
                url=url.gsub("%TITLE%",encodeURIComponent(coupontitle));
                url=url.gsub("%COUPONTEXT%",encodeURIComponent(fulltext));
                url=url.gsub("%IMAGE%",encodeURIComponent("<img src='"+img+"' alt='"+coupontitle+"' />"));
                window.open(url,"_blank");
            }

            function shareFacebook(coupon_id) {
                shareInternal("http://www.facebook.com/share.php?u=%URI%",coupon_id);

            }

            function shareIWIW(coupon_id) {
                shareInternal("http://iwiw.hu/pages/share/share.jsp?u=%URI%",coupon_id);
            }

            function shareTwitter(coupon_id) {
                shareInternal("http://twitter.com/home?status=%URI%%20%COUPONTEXT%",coupon_id);
            }

            function shareStartLap(coupon_id) {
                shareInternal("http://www.startlap.hu/sajat_linkek/addlink.php?url=%URI%&title=%COUPONTEXT%",coupon_id);
            }

            function shareGoogleReader(coupon_id) {
            }

            //B: igazából ez Google Reader
            function shareGoogleBuzz(coupon_id) {
                shareInternal("http://www.google.com/reader/link?url=%URI%&title=%TITLE%&snippet=%IMAGE%%20%COUPONTEXT%"+'&srcTitle='+ApplicationName+'&srcUrl='+encodeURI(baseURL2+"/"),coupon_id);
            }

            function shareToolbarToggle(coupon_id) {
             /*
                tb=jQuery("#kupon_"+coupon_id+" .sharetoolbar");
                if (tb.width()!=120) {
                    jQuery("#kupon_"+coupon_id+" .sharetoolbar .sharetoolbar_togglebutton").hide();
                    tb.animate({width:"120px"});
                } else {
                    tb.animate({width:"70px"});
                    jQuery("#kupon_"+coupon_id+" .sharetoolbar .sharetoolbar_togglebutton").show();
                }
             */
            }
(function(a){a.jgrid={defaults:{recordtext:"View {0} - {1} of {2}",emptyrecords:"No records to view",loadtext:"Loading...",pgtext:"Page {0} of {1}"},search:{caption:"Search...",Find:"Find",Reset:"Reset",odata:["equal","not equal","less","less or equal","greater","greater or equal","begins with","does not begin with","is in","is not in","ends with","does not end with","contains","does not contain"],groupOps:[{op:"AND",text:"all"},{op:"OR",text:"any"}],matchText:" match",rulesText:" rules"},edit:{addCaption:"Add Record",editCaption:"Edit Record",bSubmit:"Submit",bCancel:"Cancel",bClose:"Close",saveData:"Data has been changed! Save changes?",bYes:"Yes",bNo:"No",bExit:"Cancel",msg:{required:"Field is required",number:"Please, enter valid number",minValue:"value must be greater than or equal to ",maxValue:"value must be less than or equal to",email:"is not a valid e-mail",integer:"Please, enter valid integer value",date:"Please, enter valid date value",url:"is not a valid URL. Prefix required ('http://' or 'https://')"}},view:{caption:"View Record",bClose:"Close"},del:{caption:"Delete",msg:"Delete selected record(s)?",bSubmit:"Delete",bCancel:"Cancel"},nav:{edittext:"",edittitle:"Edit selected row",addtext:"",addtitle:"Add new row",deltext:"",deltitle:"Delete selected row",searchtext:"",searchtitle:"Find records",refreshtext:"",refreshtitle:"Reload Grid",alertcap:"Warning",alerttext:"Please, select row",viewtext:"",viewtitle:"View selected row"},col:{caption:"Show/Hide Columns",bSubmit:"Submit",bCancel:"Cancel"},errors:{errcap:"Error",nourl:"No url is set",norecords:"No records to process",model:"Length of colNames <> colModel!"},formatter:{integer:{thousandsSeparator:" ",defaultValue:"0"},number:{decimalSeparator:".",thousandsSeparator:" ",decimalPlaces:2,defaultValue:"0.00"},currency:{decimalSeparator:".",thousandsSeparator:" ",decimalPlaces:2,prefix:"",suffix:"",defaultValue:"0.00"},date:{dayNames:["Sun","Mon","Tue","Wed","Thr","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],AmPm:["am","pm","AM","PM"],S:function(b){return b<11||b>13?["st","nd","rd","th"][Math.min((b-1)%10,3)]:"th"},srcformat:"Y-m-d",newformat:"d/m/Y",masks:{ISO8601Long:"Y-m-d H:i:s",ISO8601Short:"Y-m-d",ShortDate:"n/j/Y",LongDate:"l, F d, Y",FullDateTime:"l, F d, Y g:i:s A",MonthDay:"F d",ShortTime:"g:i A",LongTime:"g:i:s A",SortableDateTime:"Y-m-d\\TH:i:s",UniversalSortableDateTime:"Y-m-d H:i:sO",YearMonth:"F, Y"},reformatAfterEdit:false},baseLinkUrl:"",showAction:"",target:"",checkbox:{disabled:true},idName:"id"}}})(jQuery);/* 
* jqGrid  3.5 - jQuery Grid 
* Copyright (c) 2008, Tony Tomov, tony@trirand.com 
* Dual licensed under the MIT and GPL licenses 
* http://www.opensource.org/licenses/mit-license.php 
* http://www.gnu.org/licenses/gpl.html 
* Date:2009-08-01  
*/
(function($){$.extend($.jgrid,{htmlDecode:function(value){if(value=="&nbsp;"||value=="&#160;"||(value.length==1&&value.charCodeAt(0)==160)){return""}return !value?value:String(value).replace(/&amp;/g,"&").replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"')},htmlEncode:function(value){return !value?value:String(value).replace(/&/g,"&amp;").replace(/>/g,"&gt;").replace(/</g,"&lt;").replace(/"/g,"&quot;")},format:function(format){var args=$.makeArray(arguments).slice(1);return format.replace(/\{(\d+)\}/g,function(m,i){return args[i]})},getAbsoluteIndex:function(t,rInd){var cntnotv=0,cntv=0,cell,i;if($.browser.version>7){return rInd}for(i=0;i<t.cells.length;i++){cell=t.cells(i);if(cell.style.display=="none"){cntnotv++}else{cntv++}if(cntv>rInd){return i}}return i},stripHtml:function(v){var regexp=/<("[^"]*"|'[^']*'|[^'">])*>/gi;if(v){return v.replace(regexp,"")}else{return v}},stringToDoc:function(xmlString){var xmlDoc;if(typeof xmlString!=="string"){return xmlString}try{var parser=new DOMParser();xmlDoc=parser.parseFromString(xmlString,"text/xml")}catch(e){xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async=false;xmlDoc.loadXML(xmlString)}return(xmlDoc&&xmlDoc.documentElement&&xmlDoc.documentElement.tagName!="parsererror")?xmlDoc:null},parse:function(jsonString){var js=jsonString;if(js.substr(0,9)=="while(1);"){js=js.substr(9)}if(js.substr(0,2)=="/*"){js=js.substr(2,js.length-4)}if(!js){js="{}"}with(window){return eval("("+js+")")}}});$.fn.jqGrid=function(p){p=$.extend(true,{url:"",height:150,page:1,rowNum:20,records:0,pager:"",pgbuttons:true,pginput:true,colModel:[],rowList:[],colNames:[],sortorder:"asc",sortname:"",datatype:"xml",mtype:"GET",altRows:false,selarrrow:[],savedRow:[],shrinkToFit:true,xmlReader:{},jsonReader:{},subGrid:false,subGridModel:[],reccount:0,lastpage:0,lastsort:0,selrow:null,beforeSelectRow:null,onSelectRow:null,onSortCol:null,ondblClickRow:null,onRightClickRow:null,onPaging:null,onSelectAll:null,loadComplete:null,gridComplete:null,loadError:null,loadBeforeSend:null,afterInsertRow:null,beforeRequest:null,onHeaderClick:null,viewrecords:false,loadonce:false,multiselect:false,multikey:false,editurl:null,search:false,searchdata:{},caption:"",hidegrid:true,hiddengrid:false,postData:{},userData:{},treeGrid:false,treeGridModel:"nested",treeReader:{},treeANode:-1,ExpandColumn:null,tree_root_level:0,prmNames:{page:"page",rows:"rows",sort:"sidx",order:"sord"},forceFit:false,gridstate:"visible",cellEdit:false,cellsubmit:"remote",nv:0,loadui:"enable",toolbar:[false,""],scroll:false,multiboxonly:false,deselectAfterSort:true,scrollrows:false,autowidth:false,scrollOffset:18,cellLayout:5,subGridWidth:20,multiselectWidth:20,gridview:false,rownumWidth:25,rownumbers:false,pagerpos:"center",recordpos:"right",footerrow:false,userDataOnFooter:false,hoverrows:true,altclass:"ui-priority-secondary",viewsortcols:[false,"vertical",true],resizeclass:""},$.jgrid.defaults,p||{});var grid={headers:[],cols:[],footers:[],dragStart:function(i,x,y){this.resizing={idx:i,startX:x.clientX,sOL:y[0]};this.hDiv.style.cursor="col-resize";this.curGbox=$("#rs_m"+p.id,"#gbox_"+p.id);this.curGbox.css({display:"block",left:y[0],top:y[1],height:y[2]});document.onselectstart=new Function("return false")},dragMove:function(x){if(this.resizing){var diff=x.clientX-this.resizing.startX,h=this.headers[this.resizing.idx],newWidth=h.width+diff,hn,nWn;if(newWidth>33){this.curGbox.css({left:this.resizing.sOL+diff});if(p.forceFit===true){hn=this.headers[this.resizing.idx+p.nv];nWn=hn.width-diff;if(nWn>33){h.newWidth=newWidth;hn.newWidth=nWn;this.newWidth=p.tblwidth}}else{this.newWidth=p.tblwidth+diff;h.newWidth=newWidth}}}},dragEnd:function(){this.hDiv.style.cursor="default";if(this.resizing){var idx=this.resizing.idx,nw=this.headers[idx].newWidth||this.headers[idx].width;this.resizing=false;$("#rs_m"+p.id).css("display","none");p.colModel[idx].width=nw;this.headers[idx].width=nw;this.headers[idx].el.style.width=nw+"px";if(this.cols.length>0){this.cols[idx].style.width=nw+"px"}if(this.footers.length>0){this.footers[idx].style.width=nw+"px"}if(p.forceFit===true){nw=this.headers[idx+p.nv].newWidth||this.headers[idx+p.nv].width;this.headers[idx+p.nv].width=nw;this.headers[idx+p.nv].el.style.width=nw+"px";if(this.cols.length>0){this.cols[idx+p.nv].style.width=nw+"px"}if(this.footers.length>0){this.footers[idx+p.nv].style.width=nw+"px"}p.colModel[idx+p.nv].width=nw}else{p.tblwidth=this.newWidth;$("table:first",this.bDiv).css("width",p.tblwidth+"px");$("table:first",this.hDiv).css("width",p.tblwidth+"px");this.hDiv.scrollLeft=this.bDiv.scrollLeft;if(p.footerrow){$("table:first",this.sDiv).css("width",p.tblwidth+"px");this.sDiv.scrollLeft=this.bDiv.scrollLeft}}}this.curGbox=null;document.onselectstart=new Function("return true")},scrollGrid:function(){if(p.scroll===true){var scrollTop=this.bDiv.scrollTop;if(scrollTop!=this.scrollTop){this.scrollTop=scrollTop;if((this.bDiv.scrollHeight-scrollTop-$(this.bDiv).height())<=0){if(parseInt(p.page,10)+1<=parseInt(p.lastpage,10)){p.page=parseInt(p.page,10)+1;this.populate()}}}}this.hDiv.scrollLeft=this.bDiv.scrollLeft;if(p.footerrow){this.sDiv.scrollLeft=this.bDiv.scrollLeft}}};return this.each(function(){if(this.grid){return}this.p=p;var i;if(this.p.colNames.length===0){for(i=0;i<this.p.colModel.length;i++){this.p.colNames[i]=this.p.colModel[i].label||this.p.colModel[i].name}}if(this.p.colNames.length!==this.p.colModel.length){alert($.jgrid.errors.model);return}var gv=$("<div class='ui-jqgrid-view'</div>"),ii,isMSIE=$.browser.msie?true:false,isSafari=$.browser.safari?true:false;$(gv).insertBefore(this);$(this).appendTo(gv).removeClass("scroll");var eg=$("<div class='ui-jqgrid ui-widget ui-widget-content ui-corner-all'></div>");$(eg).insertBefore(gv).attr("id","gbox_"+this.id);$(gv).appendTo(eg).attr("id","gview_"+this.id);if(isMSIE&&$.browser.version<=6){ii='<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>'}else{ii=""}$("<div class='ui-widget-overlay jqgrid-overlay' id='lui_"+this.id+"'></div>").append(ii).insertBefore(gv);$("<div class='loading ui-state-default ui-state-active' id='load_"+this.id+"'>"+this.p.loadtext+"</div>").insertBefore(gv);$(this).attr({cellSpacing:"0",cellPadding:"0",border:"0",role:"grid","aria-multiselectable":this.p.multiselect,"aria-labelledby":"gbox_"+this.id});var ts=this,bSR=$.isFunction(this.p.beforeSelectRow)?this.p.beforeSelectRow:false,ondblClickRow=$.isFunction(this.p.ondblClickRow)?this.p.ondblClickRow:false,onSortCol=$.isFunction(this.p.onSortCol)?this.p.onSortCol:false,loadComplete=$.isFunction(this.p.loadComplete)?this.p.loadComplete:false,loadError=$.isFunction(this.p.loadError)?this.p.loadError:false,loadBeforeSend=$.isFunction(this.p.loadBeforeSend)?this.p.loadBeforeSend:false,onRightClickRow=$.isFunction(this.p.onRightClickRow)?this.p.onRightClickRow:false,afterInsRow=$.isFunction(this.p.afterInsertRow)?this.p.afterInsertRow:false,onHdCl=$.isFunction(this.p.onHeaderClick)?this.p.onHeaderClick:false,beReq=$.isFunction(this.p.beforeRequest)?this.p.beforeRequest:false,onSC=$.isFunction(this.p.onCellSelect)?this.p.onCellSelect:false,sortkeys=["shiftKey","altKey","ctrlKey"],IntNum=function(val,defval){val=parseInt(val,10);if(isNaN(val)){return defval?defval:0}else{return val}},formatCol=function(pos,rowInd){var ral=ts.p.colModel[pos].align,result='style="';if(ral){result+="text-align:"+ral+";"}if(ts.p.colModel[pos].hidden===true){result+="display:none;"}if(rowInd===0){result+="width: "+grid.headers[pos].width+"px;"}return result+'"'},addCell=function(rowId,cell,pos,irow,srvr){var v,prp;v=formatter(rowId,cell,pos,srvr,"add");prp=formatCol(pos,irow);return'<td role="gridcell" '+prp+' title="'+$.jgrid.stripHtml(v)+'">'+v+"</td>"},formatter=function(rowId,cellval,colpos,rwdat,_act){var cm=ts.p.colModel[colpos],v;if(typeof cm.formatter!=="undefined"){var opts={rowId:rowId,colModel:cm};if($.isFunction(cm.formatter)){v=cm.formatter(cellval,opts,rwdat,_act)}else{if($.fmatter){v=$.fn.fmatter(cm.formatter,cellval,opts,rwdat,_act)}else{v=cellVal(cellval)}}}else{v=cellVal(cellval)}return v},cellVal=function(val){return val===undefined||val===null||val===""?"&#160;":val+""},addMulti=function(rowid,pos,irow){var v='<input type="checkbox" id="jqg_'+rowid+'" class="cbox" name="jqg_'+rowid+'"/>',prp=formatCol(pos,irow);return"<td role='gridcell' "+prp+">"+v+"</td>"},addRowNum=function(pos,irow,pG,rN){var v=(parseInt(pG)-1)*parseInt(rN)+1+irow,prp=formatCol(pos,irow);return'<td role="gridcell" class="ui-state-default jqgrid-rownum" '+prp+">"+v+"</td>"},reader=function(datatype){var field,f=[],j=0,i;for(i=0;i<ts.p.colModel.length;i++){field=ts.p.colModel[i];if(field.name!=="cb"&&field.name!=="subgrid"&&field.name!=="rn"){f[j]=(datatype=="xml")?field.xmlmap||field.name:field.jsonmap||field.name;j++}}return f},addXmlData=function(xml,t,rcnt){ts.p.reccount=0;if($.isXMLDoc(xml)){if(ts.p.treeANode===-1&&ts.p.scroll===false){$("tbody",t).empty();rcnt=0}else{rcnt=rcnt>0?rcnt:0}}else{return}var i,fpos,ir=0,v,row,gi=0,si=0,ni=0,idn,getId,f=[],rd={},rl=ts.rows.length,xmlr,rid,rowData=[],ari=0,cn=(ts.p.altRows===true)?ts.p.altclass:"",cn1;if(!ts.p.xmlReader.repeatitems){f=reader("xml")}if(ts.p.keyIndex===false){idn=ts.p.xmlReader.id;if(idn.indexOf("[")===-1){getId=function(trow,k){return $(idn,trow).text()||k}}else{getId=function(trow,k){return trow.getAttribute(idn.replace(/[\[\]]/g,""))||k}}}else{getId=function(trow){return(f.length-1>=ts.p.keyIndex)?$(f[ts.p.keyIndex],trow).text():$(ts.p.xmlReader.cell+":eq("+ts.p.keyIndex+")",trow).text()}}$(ts.p.xmlReader.page,xml).each(function(){ts.p.page=this.textContent||this.text||1});$(ts.p.xmlReader.total,xml).each(function(){ts.p.lastpage=this.textContent||this.text||1});$(ts.p.xmlReader.records,xml).each(function(){ts.p.records=this.textContent||this.text||0});$(ts.p.xmlReader.userdata,xml).each(function(){ts.p.userData[this.getAttribute("name")]=this.textContent||this.text});var gxml=$(ts.p.xmlReader.root+" "+ts.p.xmlReader.row,xml),gl=gxml.length,j=0;if(gxml&&gl){var rn=ts.p.rowNum;while(j<gl){xmlr=gxml[j];rid=getId(xmlr,j+1);cn1=j%2==1?cn:"";rowData[ari++]='<tr id="'+rid+'" role="row" class ="ui-widget-content jqgrow '+cn1+'">';if(ts.p.rownumbers===true){rowData[ari++]=addRowNum(0,j,ts.p.page,ts.p.rowNum);ni=1}if(ts.p.multiselect===true){rowData[ari++]=addMulti(rid,ni,j);gi=1}if(ts.p.subGrid===true){rowData[ari++]=$(ts).addSubGridCell(gi+ni,j+rcnt);si=1}if(ts.p.xmlReader.repeatitems===true){$(ts.p.xmlReader.cell,xmlr).each(function(k){v=this.textContent||this.text;rd[ts.p.colModel[k+gi+si+ni].name]=v;rowData[ari++]=addCell(rid,v,k+gi+si+ni,j+rcnt,xmlr)})}else{for(i=0;i<f.length;i++){v=$(f[i],xmlr).text();rd[ts.p.colModel[i+gi+si+ni].name]=v;rowData[ari++]=addCell(rid,v,i+gi+si+ni,j+rcnt,xmlr)}}rowData[ari++]="</tr>";if(ts.p.gridview===false){if(ts.p.treeGrid===true){fpos=ts.p.treeANode>=-1?ts.p.treeANode:0;row=$(rowData.join(""))[0];try{$(ts).setTreeNode(rd,row)}catch(e){}rl===0?$("tbody:first",t).append(row):$(ts.rows[j+fpos+rcnt]).after(row)}else{$("tbody:first",t).append(rowData.join(""))}if(ts.p.subGrid===true){try{$(ts).addSubGrid(ts.rows[ts.rows.length-1],gi+ni)}catch(e){}}if(afterInsRow){ts.p.afterInsertRow(rid,rd,xmlr)}rowData=[];ari=0}rd={};ir++;j++;if(ir>=rn){break}}}if(ts.p.gridview===true){$("table:first",t).append(rowData.join(""))}if(ir>0){ts.grid.cols=ts.rows[0].cells;if(ts.p.records===0){ts.p.records=gl}}rowData=null;if(!ts.p.treeGrid&&!ts.p.scroll){ts.grid.bDiv.scrollTop=0;ts.p.reccount=ir}ts.p.treeANode=-1;if(ts.p.userDataOnFooter){$(ts).footerData("set",ts.p.userData,true)}updatepager(false)},addJSONData=function(data,t,rcnt){ts.p.reccount=0;if(data){if(ts.p.treeANode===-1&&ts.p.scroll===false){$("tbody",t).empty();rcnt=0}else{rcnt=rcnt>0?rcnt:0}}else{return}var ir=0,v,i,j,row,f=[],cur,gi=0,si=0,ni=0,len,drows,idn,rd={},fpos,rl=ts.rows.length,idr,rowData=[],ari=0,cn=(ts.p.altRows===true)?ts.p.altclass:"",cn1;ts.p.page=data[ts.p.jsonReader.page]||1;ts.p.lastpage=data[ts.p.jsonReader.total]||1;ts.p.records=data[ts.p.jsonReader.records]||0;ts.p.userData=data[ts.p.jsonReader.userdata]||{};if(!ts.p.jsonReader.repeatitems){f=reader("json")}if(ts.p.keyIndex===false){idn=ts.p.jsonReader.id;if(f.length>0&&!isNaN(idn)){idn=f[idn]}}else{idn=f.length>0?f[ts.p.keyIndex]:ts.p.keyIndex}drows=data[ts.p.jsonReader.root];if(drows){len=drows.length,i=0;var rn=ts.p.rowNum;while(i<len){cur=drows[i];idr=cur[idn];if(idr===undefined){if(f.length===0){if(ts.p.jsonReader.cell){var ccur=cur[ts.p.jsonReader.cell];idr=ccur[idn]||i+1;ccur=null}else{idr=i+1}}else{idr=i+1}}cn1=i%2==1?cn:"";rowData[ari++]='<tr id="'+idr+'" role="row" class= "ui-widget-content jqgrow '+cn1+'">';if(ts.p.rownumbers===true){rowData[ari++]=addRowNum(0,i,ts.p.page,ts.p.rowNum);ni=1}if(ts.p.multiselect){rowData[ari++]=addMulti(idr,ni,i);gi=1}if(ts.p.subGrid){rowData[ari++]=$(ts).addSubGridCell(gi+ni,i+rcnt);si=1}if(ts.p.jsonReader.repeatitems===true){if(ts.p.jsonReader.cell){cur=cur[ts.p.jsonReader.cell]}for(j=0;j<cur.length;j++){rowData[ari++]=addCell(idr,cur[j],j+gi+si+ni,i+rcnt,cur);rd[ts.p.colModel[j+gi+si+ni].name]=cur[j]}}else{for(j=0;j<f.length;j++){v=cur[f[j]];if(v===undefined){try{v=eval("cur."+f[j])}catch(e){}}rowData[ari++]=addCell(idr,v,j+gi+si+ni,i+rcnt,cur);rd[ts.p.colModel[j+gi+si+ni].name]=cur[f[j]]}}rowData[ari++]="</tr>";if(ts.p.gridview===false){if(ts.p.treeGrid===true){fpos=ts.p.treeANode>=-1?ts.p.treeANode:0;row=$(rowData.join(""))[0];try{$(ts).setTreeNode(rd,row)}catch(e){}rl===0?$("tbody:first",t).append(row):$(ts.rows[i+fpos+rcnt]).after(row)}else{$("tbody:first",t).append(rowData.join(""))}if(ts.p.subGrid===true){try{$(ts).addSubGrid(ts.rows[ts.rows.length-1],gi+ni)}catch(e){}}if(afterInsRow){ts.p.afterInsertRow(idr,rd,cur)}rowData=[];ari=0}rd={};ir++;i++;if(ir>rn){break}}if(ts.p.gridview===true){$("table:first",t).append(rowData.join(""))}if(ir>0){ts.grid.cols=ts.rows[0].cells;if(ts.p.records===0){ts.p.records=len}}}if(!ts.p.treeGrid&&!ts.p.scroll){ts.grid.bDiv.scrollTop=0}ts.p.reccount=ir;ts.p.treeANode=-1;if(ts.p.userDataOnFooter){$(ts).footerData("set",ts.p.userData,true)}updatepager(false)},updatepager=function(rn){var cp,last,base,bs,from,to,tot,fmt;base=(parseInt(ts.p.page)-1)*parseInt(ts.p.rowNum);if(ts.p.pager){if(ts.p.loadonce){cp=last=1;ts.p.lastpage=ts.page=1;$(".selbox",ts.p.pager).attr("disabled",true)}else{cp=IntNum(ts.p.page);last=IntNum(ts.p.lastpage);$(".selbox",ts.p.pager).attr("disabled",false)}if(ts.p.pginput===true){$(".ui-pg-input",ts.p.pager).val(ts.p.page);$("#sp_1",ts.p.pager).html(ts.p.lastpage)}if(ts.p.viewrecords){bs=ts.p.scroll===true?0:base;if(ts.p.reccount===0){$(".ui-paging-info",ts.p.pager).html(ts.p.emptyrecords)}else{from=bs+1;to=base+ts.p.reccount;tot=ts.p.records;if($.fmatter){fmt=$.jgrid.formatter.integer||{};from=$.fmatter.util.NumberFormat(from,fmt);to=$.fmatter.util.NumberFormat(to,fmt);tot=$.fmatter.util.NumberFormat(tot,fmt)}$(".ui-paging-info",ts.p.pager).html($.jgrid.format(ts.p.recordtext,from,to,tot))}}if(ts.p.pgbuttons===true){if(cp<=0){cp=last=1}if(cp==1){$("#first, #prev",ts.p.pager).addClass("ui-state-disabled").removeClass("ui-state-hover")}else{$("#first, #prev",ts.p.pager).removeClass("ui-state-disabled")}if(cp==last){$("#next, #last",ts.p.pager).addClass("ui-state-disabled").removeClass("ui-state-hover")}else{$("#next, #last",ts.p.pager).removeClass("ui-state-disabled")}}}if(rn===true&&ts.p.rownumbers===true){$("td.jqgrid-rownum",ts.rows).each(function(i){$(this).html(base+1+i)})}if($.isFunction(ts.p.gridComplete)){ts.p.gridComplete()}},populate=function(){if(!grid.hDiv.loading){var gdata,prm={nd:(new Date().getTime()),_search:ts.p.search},dt,dstr;prm[ts.p.prmNames.rows]=ts.p.rowNum;prm[ts.p.prmNames.page]=ts.p.page;prm[ts.p.prmNames.sort]=ts.p.sortname;prm[ts.p.prmNames.order]=ts.p.sortorder;gdata=$.extend(ts.p.postData,prm);if(ts.p.search){gdata=$.extend(gdata,ts.p.searchdata||{})}var rcnt=ts.p.scroll===false?0:ts.rows.length-1;if($.isFunction(ts.p.datatype)){ts.p.datatype(gdata,"load_"+ts.p.id);return}else{if(beReq){ts.p.beforeRequest()}}dt=ts.p.datatype.toLowerCase();switch(dt){case"json":case"xml":case"script":$.ajax({url:ts.p.url,type:ts.p.mtype,dataType:dt,data:gdata,complete:function(req,st){if(st=="success"||(req.statusText=="OK"&&req.status=="200")){if(dt==="json"||dt==="script"){addJSONData($.jgrid.parse(req.responseText),ts.grid.bDiv,rcnt)}if(dt==="xml"){addXmlData(req.responseXML,ts.grid.bDiv,rcnt)}if(loadComplete){loadComplete(req)}}req=null;endReq()},error:function(xhr,st,err){if(loadError){loadError(xhr,st,err)}endReq();xhr=null},beforeSend:function(xhr){beginReq();if(loadBeforeSend){loadBeforeSend(xhr)}}});if(ts.p.loadonce||ts.p.treeGrid){ts.p.datatype="local"}break;case"xmlstring":beginReq();addXmlData(dstr=$.jgrid.stringToDoc(ts.p.datastr),ts.grid.bDiv);ts.p.datatype="local";if(loadComplete){loadComplete(dstr)}ts.p.datastr=null;endReq();break;case"jsonstring":beginReq();if(typeof ts.p.datastr=="string"){dstr=$.jgrid.parse(ts.p.datastr)}else{dstr=ts.p.datastr}addJSONData(dstr,ts.grid.bDiv);ts.p.datatype="local";if(loadComplete){loadComplete(dstr)}ts.p.datastr=null;endReq();break;case"local":case"clientside":beginReq();ts.p.datatype="local";sortArrayData();endReq();break}}},beginReq=function(){grid.hDiv.loading=true;if(ts.p.hiddengrid){return}switch(ts.p.loadui){case"disable":break;case"enable":$("#load_"+ts.p.id).show();break;case"block":$("#lui_"+ts.p.id).show();$("#load_"+ts.p.id).show();break}},endReq=function(){grid.hDiv.loading=false;switch(ts.p.loadui){case"disable":break;case"enable":$("#load_"+ts.p.id).hide();break;case"block":$("#lui_"+ts.p.id).hide();$("#load_"+ts.p.id).hide();break}},sortArrayData=function(){var stripNum=/[\$,%]/g;var rows=[],col=0,st,sv,findSortKey,newDir=(ts.p.sortorder=="asc")?1:-1;$.each(ts.p.colModel,function(i,v){if(this.index==ts.p.sortname||this.name==ts.p.sortname){col=ts.p.lastsort=i;st=this.sorttype;return false}});if(st=="float"||st=="number"||st=="currency"){findSortKey=function($cell){var key=parseFloat($cell.replace(stripNum,""));return isNaN(key)?0:key}}else{if(st=="int"||st=="integer"){findSortKey=function($cell){return IntNum($cell.replace(stripNum,""))}}else{if(st=="date"){findSortKey=function($cell){var fd=ts.p.colModel[col].datefmt||"Y-m-d";return parseDate(fd,$cell).getTime()}}else{findSortKey=function($cell){return $.trim($cell.toUpperCase())}}}}$.each(ts.rows,function(index,row){try{sv=$.unformat($(row).children("td").eq(col),{colModel:ts.p.colModel[col]},col,true)}catch(_){sv=$(row).children("td").eq(col).text()}row.sortKey=findSortKey(sv);rows[index]=this});if(ts.p.treeGrid){$(ts).SortTree(newDir)}else{rows.sort(function(a,b){if(a.sortKey<b.sortKey){return -newDir}if(a.sortKey>b.sortKey){return newDir}return 0});if(rows[0]){$("td",rows[0]).each(function(k){$(this).css("width",grid.headers[k].width+"px")});grid.cols=rows[0].cells}$.each(rows,function(index,row){$("tbody",ts.grid.bDiv).append(row);row.sortKey=null})}if(ts.p.multiselect){$("tbody tr",ts.grid.bDiv).removeClass("ui-state-highlight");$("[id^=jqg_]",ts.rows).attr("checked",false);$("#cb_jqg",ts.grid.hDiv).attr("checked",false);ts.p.selarrrow=[]}ts.grid.bDiv.scrollTop=0},parseDate=function(format,date){var tsp={m:1,d:1,y:1970,h:0,i:0,s:0},k,hl,dM;date=date.split(/[\\\/:_;.\t\T\s-]/);format=format.split(/[\\\/:_;.\t\T\s-]/);var dfmt=$.jgrid.formatter.date.monthNames;for(k=0,hl=format.length;k<hl;k++){if(format[k]=="M"){dM=$.inArray(date[k],dfmt);if(dM!==-1&&dM<12){date[k]=dM+1}}if(format[k]=="F"){dM=$.inArray(date[k],dfmt);if(dM!==-1&&dM>11){date[k]=dM+1-12}}tsp[format[k].toLowerCase()]=parseInt(date[k],10)}tsp.m=parseInt(tsp.m,10)-1;var ty=tsp.y;if(ty>=70&&ty<=99){tsp.y=1900+tsp.y}else{if(ty>=0&&ty<=69){tsp.y=2000+tsp.y}}return new Date(tsp.y,tsp.m,tsp.d,tsp.h,tsp.i,tsp.s,0)},setPager=function(){var sep="<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>",pgid=$(ts.p.pager).attr("id")||"pager",pginp=(ts.p.pginput===true)?"<td>"+$.jgrid.format(ts.p.pgtext||"","<input class='ui-pg-input' type='text' size='2' maxlength='7' value='0' role='textbox'/>","<span id='sp_1'></span>")+"</td>":"",pgl="<table cellspacing='0' cellpadding='0' border='0' style='table-layout:auto;' class='ui-pg-table'><tbody><tr>",str,pgcnt,lft,cent,rgt,twd,tdw,i,clearVals=function(onpaging){if($.isFunction(ts.p.onPaging)){ts.p.onPaging(onpaging)}ts.p.selrow=null;if(ts.p.multiselect){ts.p.selarrrow=[];$("#cb_jqg",ts.grid.hDiv).attr("checked",false)}ts.p.savedRow=[]};pgcnt="pg_"+pgid;lft=pgid+"_left";cent=pgid+"_center";rgt=pgid+"_right";$(ts.p.pager).addClass("ui-jqgrid-pager corner-bottom").append("<div id='"+pgcnt+"' class='ui-pager-control' role='group'><table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table' style='width:100%;table-layout:fixed;' role='row'><tbody><tr><td id='"+lft+"' align='left'></td><td id='"+cent+"' align='center' style='white-space:nowrap;'></td><td id='"+rgt+"' align='right'></td></tr></tbody></table></div>");if(ts.p.pgbuttons===true){pgl+="<td id='first' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-first'></span></td>";pgl+="<td id='prev' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-prev'></span></td>";pgl+=pginp!=""?sep+pginp+sep:"";pgl+="<td id='next' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-next'></span></td>";pgl+="<td id='last' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-end'></span></td>"}else{if(pginp!=""){pgl+=pginp}}if(ts.p.rowList.length>0){str="<select class='ui-pg-selbox' role='listbox'>";for(i=0;i<ts.p.rowList.length;i++){str+="<option role='option' value="+ts.p.rowList[i]+((ts.p.rowNum==ts.p.rowList[i])?" selected":"")+">"+ts.p.rowList[i]}str+="</select>";pgl+="<td>"+str+"</td>"}pgl+="</tr></tbody></table>";if(ts.p.viewrecords===true){$("td#"+pgid+"_"+ts.p.recordpos,"#"+pgcnt).append("<div class='ui-paging-info'></div>")}$("td#"+pgid+"_"+ts.p.pagerpos,"#"+pgcnt).append(pgl);tdw=$(".ui-jqgrid").css("font-size")||"11px";$("body").append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+tdw+";visibility:hidden;' ></div>");twd=$(pgl).clone(false).appendTo("#testpg").width();$("#testpg").remove();if(twd>0){twd+=25;$("td#"+pgid+"_"+ts.p.pagerpos,"#"+pgcnt).width(twd)}ts.p._nvtd=[];ts.p._nvtd[0]=twd?Math.floor((ts.p.width-twd)/2):Math.floor(ts.p.width/3);ts.p._nvtd[1]=0;pgl=null;$(".ui-pg-selbox","#"+pgcnt).bind("change",function(){ts.p.rowNum=this.value;clearVals("records");populate();return false});if(ts.p.pgbuttons===true){$(".ui-pg-button","#"+pgcnt).hover(function(e){if($(this).hasClass("ui-state-disabled")){this.style.cursor="default"}else{$(this).addClass("ui-state-hover");this.style.cursor="pointer"}},function(e){if($(this).hasClass("ui-state-disabled")){}else{$(this).removeClass("ui-state-hover");this.style.cursor="default"}});$("#first, #prev, #next, #last",ts.p.pager).click(function(e){var cp=IntNum(ts.p.page),last=IntNum(ts.p.lastpage),selclick=false,fp=true,pp=true,np=true,lp=true;if(last===0||last===1){fp=false;pp=false;np=false;lp=false}else{if(last>1&&cp>=1){if(cp===1){fp=false;pp=false}else{if(cp>1&&cp<last){}else{if(cp===last){np=false;lp=false}}}}else{if(last>1&&cp===0){np=false;lp=false;cp=last-1}}}if(this.id==="first"&&fp){ts.p.page=1;selclick=true}if(this.id==="prev"&&pp){ts.p.page=(cp-1);selclick=true}if(this.id==="next"&&np){ts.p.page=(cp+1);selclick=true}if(this.id==="last"&&lp){ts.p.page=last;selclick=true}if(selclick){clearVals(this.id);populate()}return false})}if(ts.p.pginput===true){$("input.ui-pg-input","#"+pgcnt).keypress(function(e){var key=e.charCode?e.charCode:e.keyCode?e.keyCode:0;if(key==13){ts.p.page=($(this).val()>0)?$(this).val():ts.p.page;clearVals("user");populate();return false}return this})}},sortData=function(index,idxcol,reload,sor){if(!ts.p.colModel[idxcol].sortable){return}var imgs,so;if(ts.p.savedRow.length>0){return}if(!reload){if(ts.p.lastsort==idxcol){if(ts.p.sortorder=="asc"){ts.p.sortorder="desc"}else{if(ts.p.sortorder=="desc"){ts.p.sortorder="asc"}}}else{ts.p.sortorder="asc"}ts.p.page=1}if(sor){if(ts.p.lastsort==idxcol&&ts.p.sortorder==sor){return}else{ts.p.sortorder=sor}}var thd=$("thead:first",grid.hDiv).get(0);$("tr th:eq("+ts.p.lastsort+") span.ui-grid-ico-sort",thd).addClass("ui-state-disabled");$("tr th:eq("+ts.p.lastsort+")",thd).attr("aria-selected","false");$("tr th:eq("+idxcol+") span.ui-icon-"+ts.p.sortorder,thd).removeClass("ui-state-disabled");$("tr th:eq("+idxcol+")",thd).attr("aria-selected","true");if(!ts.p.viewsortcols[0]){if(ts.p.lastsort!=idxcol){$("tr th:eq("+ts.p.lastsort+") span.s-ico",thd).hide();$("tr th:eq("+idxcol+") span.s-ico",thd).show()}}ts.p.lastsort=idxcol;index=index.substring(5);ts.p.sortname=ts.p.colModel[idxcol].index||index;so=ts.p.sortorder;if(onSortCol){onSortCol(index,idxcol,so)}if(ts.p.datatype=="local"){if(ts.p.deselectAfterSort){$(ts).resetSelection()}}else{ts.p.selrow=null;if(ts.p.multiselect){$("#cb_jqg",ts.grid.hDiv).attr("checked",false)}ts.p.selarrrow=[];ts.p.savedRow=[]}if(ts.p.scroll===true){$("tbody tr",ts.grid.bDiv).remove()}if(ts.p.subGrid&&ts.p.datatype=="local"){$("td.sgexpanded","#"+ts.p.id).each(function(){$(this).trigger("click")})}populate();if(ts.p.sortname!=index&&idxcol){ts.p.lastsort=idxcol}},setColWidth=function(){var initwidth=0,brd=ts.p.cellLayout,vc=0,lvc,scw=ts.p.scrollOffset,cw,hs=false,aw,tw=0,gw=0,msw=ts.p.multiselectWidth,sgw=ts.p.subGridWidth,rnw=ts.p.rownumWidth,cl=ts.p.cellLayout,cr;$.each(ts.p.colModel,function(i){if(typeof this.hidden==="undefined"){this.hidden=false}if(this.hidden===false){initwidth+=IntNum(this.width);vc++}});if(isNaN(ts.p.width)){ts.p.width=grid.width=initwidth}else{grid.width=ts.p.width}ts.p.tblwidth=initwidth;if(ts.p.shrinkToFit===false&&ts.p.forceFit===true){ts.p.forceFit=false}if(ts.p.shrinkToFit===true){if(isSafari){brd=0;msw+=cl;sgw+=cl;rnw+=cl}if(ts.p.multiselect){tw=msw;gw=msw+brd;vc--}if(ts.p.subGrid){tw+=sgw;gw+=sgw+brd;vc--}if(ts.p.rownumbers){tw+=rnw;gw+=rnw+brd;vc--}aw=grid.width-brd*vc-gw;if(isNaN(ts.p.height)){}else{aw-=scw;hs=true}initwidth=0;$.each(ts.p.colModel,function(i){if(this.hidden===false&&this.name!=="cb"&&this.name!=="subgrid"&&this.name!=="rn"){cw=Math.floor(aw/(ts.p.tblwidth-tw)*this.width);this.width=cw;initwidth+=cw;lvc=i}});cr=0;if(hs&&grid.width-gw-(initwidth+brd*vc)!==scw){cr=grid.width-gw-(initwidth+brd*vc)-scw}else{if(!hs&&Math.abs(grid.width-gw-(initwidth+brd*vc))!==1){cr=grid.width-gw-(initwidth+brd*vc)}}ts.p.colModel[lvc].width+=cr;ts.p.tblwidth=initwidth+tw+cr}},nextVisible=function(iCol){var ret=iCol,j=iCol,i;for(i=iCol+1;i<ts.p.colModel.length;i++){if(ts.p.colModel[i].hidden!==true){j=i;break}}return j-ret},getOffset=function(iCol){var i,ret={},brd1=isSafari?0:ts.p.cellLayout;ret[0]=ret[1]=ret[2]=0;for(i=0;i<=iCol;i++){if(ts.p.colModel[i].hidden===false){ret[0]+=ts.p.colModel[i].width+brd1}}ret[0]=ret[0]-ts.grid.bDiv.scrollLeft;if($(ts.grid.cDiv).is(":visible")){ret[1]+=$(ts.grid.cDiv).height()+parseInt($(ts.grid.cDiv).css("padding-top"))+parseInt($(ts.grid.cDiv).css("padding-bottom"))}if(ts.p.toolbar[0]==true&&(ts.p.toolbar[1]=="top"||ts.p.toolbar[1]=="both")){ret[1]+=$(ts.grid.uDiv).height()+parseInt($(ts.grid.uDiv).css("border-top-width"))+parseInt($(ts.grid.uDiv).css("border-bottom-width"))}ret[2]+=$(ts.grid.bDiv).height()+$(ts.grid.hDiv).height();return ret};this.p.id=this.id;if($.inArray(ts.p.multikey,sortkeys)==-1){ts.p.multikey=false}ts.p.keyIndex=false;for(i=0;i<ts.p.colModel.length;i++){if(ts.p.colModel[i].key===true){ts.p.keyIndex=i;break}}ts.p.sortorder=ts.p.sortorder.toLowerCase();if(this.p.treeGrid===true){try{$(this).setTreeGrid()}catch(_){}}if(this.p.subGrid){try{$(ts).setSubGrid()}catch(_){}}if(this.p.multiselect){this.p.colNames.unshift("<input id='cb_jqg' class='cbox' type='checkbox'/>");this.p.colModel.unshift({name:"cb",width:isSafari?ts.p.multiselectWidth+ts.p.cellLayout:ts.p.multiselectWidth,sortable:false,resizable:false,hidedlg:true,search:false,align:"center"})}if(this.p.rownumbers){this.p.colNames.unshift("");this.p.colModel.unshift({name:"rn",width:ts.p.rownumWidth,sortable:false,resizable:false,hidedlg:true,search:false,align:"center"})}ts.p.xmlReader=$.extend({root:"rows",row:"row",page:"rows>page",total:"rows>total",records:"rows>records",repeatitems:true,cell:"cell",id:"[id]",userdata:"userdata",subgrid:{root:"rows",row:"row",repeatitems:true,cell:"cell"}},ts.p.xmlReader);ts.p.jsonReader=$.extend({root:"rows",page:"page",total:"total",records:"records",repeatitems:true,cell:"cell",id:"id",userdata:"userdata",subgrid:{root:"rows",repeatitems:true,cell:"cell"}},ts.p.jsonReader);if(ts.p.scroll===true){ts.p.pgbuttons=false;ts.p.pginput=false;ts.p.rowList=[]}var thead="<thead><tr class='ui-jqgrid-labels' role='rowheader'>",tdc,idn,w,res,sort,td,ptr,tbody,imgs,iac="",idc="";if(ts.p.shrinkToFit===true&&ts.p.forceFit===true){for(i=ts.p.colModel.length-1;i>=0;i--){if(!ts.p.colModel[i].hidden){ts.p.colModel[i].resizable=false;break}}}if(ts.p.viewsortcols[1]=="horizontal"){iac=" ui-i-asc";idc=" ui-i-desc"}tdc=isMSIE?"class='ui-th-div-ie'":"";imgs="<span class='s-ico' style='display:none'><span sort='asc' class='ui-grid-ico-sort ui-icon-asc"+iac+" ui-state-disabled ui-icon ui-icon-triangle-1-n'></span>";imgs+="<span sort='desc' class='ui-grid-ico-sort ui-icon-desc"+idc+" ui-state-disabled ui-icon ui-icon-triangle-1-s'></span></span>";for(i=0;i<this.p.colNames.length;i++){thead+="<th role='columnheader' class='ui-state-default ui-th-column'>";idn=ts.p.colModel[i].index||ts.p.colModel[i].name;thead+="<div id='jqgh_"+ts.p.colModel[i].name+"' "+tdc+">"+ts.p.colNames[i];if(idn==ts.p.sortname){ts.p.lastsort=i}thead+=imgs+"</div></th>"}thead+="</tr></thead>";$(this).append(thead);$("thead tr:first th",this).hover(function(){$(this).addClass("ui-state-hover")},function(){$(this).removeClass("ui-state-hover")});if(this.p.multiselect){var onSA=true,emp=[],chk;if(typeof ts.p.onSelectAll!=="function"){onSA=false}$("#cb_jqg",this).bind("click",function(){if(this.checked){$("[id^=jqg_]",ts.rows).attr("checked",true);$(ts.rows).each(function(i){if(!$(this).hasClass("subgrid")){$(this).addClass("ui-state-highlight").attr("aria-selected","true");ts.p.selarrrow[i]=ts.p.selrow=this.id}});chk=true;emp=[]}else{$("[id^=jqg_]",ts.rows).attr("checked",false);$(ts.rows).each(function(i){if(!$(this).hasClass("subgrid")){$(this).removeClass("ui-state-highlight").attr("aria-selected","false");emp[i]=this.id}});ts.p.selarrrow=[];ts.p.selrow=null;chk=false}if(onSA){ts.p.onSelectAll(chk?ts.p.selarrrow:emp,chk)}})}$.each(ts.p.colModel,function(i){if(!this.width){this.width=150}});if(ts.p.autowidth===true){var pw=$(eg).innerWidth();ts.p.width=pw>0?pw:"nw"}setColWidth();$(eg).css("width",grid.width+"px").append("<div class='ui-jqgrid-resize-mark' id='rs_m"+ts.p.id+"'>&nbsp;</div>");$(gv).css("width",grid.width+"px");thead=$("thead:first",ts).get(0);var tfoot="<table role='grid' style='width:"+ts.p.tblwidth+"px' class='ui-jqgrid-ftable' cellspacing='0' cellpadding='0' border='0'><tbody><tr role='row' class='ui-widget-content footrow'>";$("tr:first th",thead).each(function(j){var ht=$("div",this)[0];w=ts.p.colModel[j].width;if(typeof ts.p.colModel[j].resizable==="undefined"){ts.p.colModel[j].resizable=true}res=document.createElement("span");$(res).html("&#160;");if(ts.p.colModel[j].resizable){$(this).addClass(ts.p.resizeclass);$(res).mousedown(function(e){if(ts.p.forceFit===true){ts.p.nv=nextVisible(j)}grid.dragStart(j,e,getOffset(j));return false}).addClass("ui-jqgrid-resize")}else{res=""}$(this).css("width",w+"px").prepend(res);if(ts.p.colModel[j].hidden){$(this).css("display","none")}grid.headers[j]={width:w,el:this};sort=ts.p.colModel[j].sortable;if(typeof sort!=="boolean"){ts.p.colModel[j].sortable=true;sort=true}var nm=ts.p.colModel[j].name;if(!(nm=="cb"||nm=="subgrid"||nm=="rn")){if(ts.p.viewsortcols[2]==false){$(".ui-grid-ico-sort",this).click(function(){sortData(ht.id,j,true,$(this).attr("sort"));return false})}else{$("div",this).addClass("ui-jqgrid-sortable").click(function(){sortData(ht.id,j);return false})}}if(sort){if(ts.p.viewsortcols[0]){$("div span.s-ico",this).show();if(j==ts.p.lastsort){$("div span.ui-icon-"+ts.p.sortorder,this).removeClass("ui-state-disabled")}}else{if(j==ts.p.lastsort){$("div span.s-ico",this).show();$("div span.ui-icon-"+ts.p.sortorder,this).removeClass("ui-state-disabled")}}}tfoot+="<td role='gridcell' "+formatCol(j,0)+">&nbsp;</td>"});tfoot+="</tr></tbody></table>";tbody=document.createElement("tbody");this.appendChild(tbody);$(this).addClass("ui-jqgrid-btable");var hTable=$("<table class='ui-jqgrid-htable' style='width:"+ts.p.tblwidth+"px' role='grid' aria-labelledby='gbox_"+this.id+"' cellspacing='0' cellpadding='0' border='0'></table>").append(thead),hg=(ts.p.caption&&ts.p.hiddengrid===true)?true:false,hb=$("<div class='ui-jqgrid-hbox'></div>");grid.hDiv=document.createElement("div");$(grid.hDiv).css({width:grid.width+"px"}).addClass("ui-state-default ui-jqgrid-hdiv").append(hb).bind("selectstart",function(){return false});$(hb).append(hTable);if(hg){$(grid.hDiv).hide();ts.p.gridstate="hidden"}ts.p._height=0;if(ts.p.pager){if(typeof ts.p.pager=="string"){if(ts.p.pager.substr(0,1)!="#"){ts.p.pager="#"+ts.p.pager}}$(ts.p.pager).css({width:grid.width+"px"}).appendTo(eg).addClass("ui-state-default ui-jqgrid-pager");ts.p._height+=parseInt($(ts.p.pager).height(),10);if(hg){$(ts.p.pager).hide()}setPager()}if(ts.p.cellEdit===false&&ts.p.hoverrows===true){$(ts).bind("mouseover",function(e){ptr=$(e.target).parents("tr.jqgrow");if($(ptr).attr("class")!=="subgrid"){$(ptr).addClass("ui-state-hover")}return false}).bind("mouseout",function(e){ptr=$(e.target).parents("tr.jqgrow");$(ptr).removeClass("ui-state-hover");return false})}var ri,ci;$(ts).before(grid.hDiv).click(function(e){td=e.target;var scb=$(td).hasClass("cbox");ptr=$(td,ts.rows).parents("tr.jqgrow");if($(ptr).length===0){return false}var cSel=true;if(bSR){cSel=bSR(ptr[0].id)}if(td.tagName=="A"){return true}if(cSel===true){if(ts.p.cellEdit===true){if(ts.p.multiselect&&scb){$(ts).setSelection(false,true,ptr)}else{ri=ptr[0].rowIndex;ci=!$(td).is("td")?$(td).parents("td:first")[0].cellIndex:td.cellIndex;if(isMSIE){ci=$.jgrid.getAbsoluteIndex(ptr[0],ci)}try{$(ts).editCell(ri,ci,true)}catch(e){}}}else{if(!ts.p.multikey){if(ts.p.multiselect&&ts.p.multiboxonly){if(scb){$(ts).setSelection(false,true,ptr)}else{$(ts.p.selarrrow).each(function(i,n){var ind=ts.rows.namedItem(n);$(ind).removeClass("ui-state-highlight");$("#jqg_"+n.replace(".","\\."),ind).attr("checked",false)});ts.p.selarrrow=[];$("#cb_jqg",ts.grid.hDiv).attr("checked",false);$(ts).setSelection(false,true,ptr)}}else{$(ts).setSelection(false,true,ptr)}}else{if(e[ts.p.multikey]){$(ts).setSelection(false,true,ptr)}else{if(ts.p.multiselect&&scb){scb=$("[id^=jqg_]",ptr).attr("checked");$("[id^=jqg_]",ptr).attr("checked",!scb)}}}}if(onSC){ri=ptr[0].id;ci=!$(td).is("td")?$(td).parents("td:first")[0].cellIndex:td.cellIndex;if(isMSIE){ci=$.jgrid.getAbsoluteIndex(ptr[0],ci)}onSC(ri,ci,$(td).html(),td)}}e.stopPropagation()}).bind("reloadGrid",function(e){if(ts.p.treeGrid===true){ts.p.datatype=ts.p.treedatatype}if(ts.p.datatype=="local"){$(ts).resetSelection()}else{if(!ts.p.treeGrid){ts.p.selrow=null;if(ts.p.multiselect){ts.p.selarrrow=[];$("#cb_jqg",ts.grid.hDiv).attr("checked",false)}if(ts.p.cellEdit){ts.p.savedRow=[]}}}if(ts.p.scroll===true){$("tbody tr",ts.grid.bDiv).remove()}ts.grid.populate();return false});if(ondblClickRow){$(this).dblclick(function(e){td=(e.target);ptr=$(td,ts.rows).parents("tr.jqgrow");if($(ptr).length===0){return false}ri=ptr[0].rowIndex;ci=!$(td).is("td")?$(td).parents("td:first")[0].cellIndex:td.cellIndex;if(isMSIE){ci=$.jgrid.getAbsoluteIndex(ptr[0],ci)}ts.p.ondblClickRow($(ptr).attr("id"),ri,ci);return false})}if(onRightClickRow){$(this).bind("contextmenu",function(e){td=e.target;ptr=$(td,ts.rows).parents("tr.jqgrow");if($(ptr).length===0){return false}if(!ts.p.multiselect){$(ts).setSelection(false,true,ptr)}ri=ptr[0].rowIndex;ci=!$(td).is("td")?$(td).parents("td:first")[0].cellIndex:td.cellIndex;if(isMSIE){ci=$.jgrid.getAbsoluteIndex(ptr[0],ci)}ts.p.onRightClickRow($(ptr).attr("id"),ri,ci);return false})}grid.bDiv=document.createElement("div");$(grid.bDiv).append(this).addClass("ui-jqgrid-bdiv").css({height:ts.p.height+(isNaN(ts.p.height)?"":"px"),width:(grid.width)+"px"}).scroll(function(e){grid.scrollGrid()});$("table:first",grid.bDiv).css({width:ts.p.tblwidth+"px"});if(isMSIE){if($("tbody",this).size()===2){$("tbody:first",this).remove()}if(ts.p.multikey){$(grid.bDiv).bind("selectstart",function(){return false})}}else{if(ts.p.multikey){$(grid.bDiv).bind("mousedown",function(){return false})}}if(hg){$(grid.bDiv).hide()}grid.cDiv=document.createElement("div");var arf=ts.p.hidegrid===true?$("<a role='link' href='javascript:void(0)'/>").addClass("ui-jqgrid-titlebar-close HeaderButton").hover(function(){arf.addClass("ui-state-hover")},function(){arf.removeClass("ui-state-hover")}).append("<span class='ui-icon ui-icon-circle-triangle-n'></span>"):"";$(grid.cDiv).append(arf).append("<span class='ui-jqgrid-title'>"+ts.p.caption+"</span>").addClass("ui-jqgrid-titlebar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix");$(grid.cDiv).insertBefore(grid.hDiv);if(ts.p.toolbar[0]){grid.uDiv=document.createElement("div");if(ts.p.toolbar[1]=="top"){$(grid.uDiv).insertBefore(grid.hDiv)}else{if(ts.p.toolbar[1]=="bottom"){$(grid.uDiv).insertAfter(grid.hDiv)}}if(ts.p.toolbar[1]=="both"){grid.ubDiv=document.createElement("div");$(grid.uDiv).insertBefore(grid.hDiv).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id);$(grid.ubDiv).insertAfter(grid.hDiv).addClass("ui-userdata ui-state-default").attr("id","tb_"+this.id);ts.p._height+=IntNum($(grid.ubDiv).height());if(hg){$(grid.ubDiv).hide()}}else{$(grid.uDiv).width(grid.width).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id)}ts.p._height+=IntNum($(grid.uDiv).height());if(hg){$(grid.uDiv).hide()}}if(ts.p.footerrow){grid.sDiv=document.createElement("div");hb=$("<div class='ui-jqgrid-hbox'></div>");$(grid.sDiv).addClass("ui-jqgrid-sdiv").append(hb).insertAfter(grid.hDiv).width(grid.width);$(hb).append(tfoot);grid.footers=$(".ui-jqgrid-ftable",grid.sDiv)[0].rows[0].cells;if(ts.p.rownumbers){grid.footers[0].className="ui-state-default jqgrid-rownum"}if(hg){$(grid.sDiv).hide()}}if(ts.p.caption){ts.p._height+=parseInt($(grid.cDiv,ts).height(),10);var tdt=ts.p.datatype;if(ts.p.hidegrid===true){$(".ui-jqgrid-titlebar-close",grid.cDiv).toggle(function(){$(".ui-jqgrid-bdiv, .ui-jqgrid-hdiv","#gview_"+ts.p.id).slideUp("fast");if(ts.p.pager){$(ts.p.pager).slideUp("fast")}if(ts.p.toolbar[0]===true){if(ts.p.toolbar[1]=="both"){$(grid.ubDiv).slideUp("fast")}$(grid.uDiv).slideUp("fast")}if(ts.p.footerrow){$(".ui-jqgrid-sdiv","#gbox_"+ts.p.id).slideUp("fast")}$("span",this).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");ts.p.gridstate="hidden";if(onHdCl){if(!hg){ts.p.onHeaderClick(ts.p.gridstate)}}},function(){$(".ui-jqgrid-hdiv, .ui-jqgrid-bdiv","#gview_"+ts.p.id).slideDown("fast");if(ts.p.pager){$(ts.p.pager).slideDown("fast")}if(ts.p.toolbar[0]===true){if(ts.p.toolbar[1]=="both"){$(grid.ubDiv).slideDown("fast")}$(grid.uDiv).slideDown("fast")}if(ts.p.footerrow){$(".ui-jqgrid-sdiv","#gbox_"+ts.p.id).slideDown("fast")}$("span",this).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");if(hg){ts.p.datatype=tdt;populate();hg=false}ts.p.gridstate="visible";if(onHdCl){ts.p.onHeaderClick(ts.p.gridstate)}});if(hg){$(".ui-jqgrid-titlebar-close",grid.cDiv).trigger("click");ts.p.datatype="local"}}}else{$(grid.cDiv).hide()}$(grid.hDiv).after(grid.bDiv).mousemove(function(e){if(grid.resizing){grid.dragMove(e)}return false});ts.p._height+=parseInt($(grid.hDiv).height(),10);$(document).mouseup(function(e){if(grid.resizing){grid.dragEnd();return false}return true});this.updateColumns=function(){var r=this.rows[0],self=this;if(r){$("td",r).each(function(k){$(this).css("width",self.grid.headers[k].width+"px")});this.grid.cols=r.cells}return this};ts.formatCol=function(a,b){return formatCol(a,b)};ts.sortData=function(a,b,c){sortData(a,b,c)};ts.updatepager=function(a){updatepager(a)};ts.formatter=function(rowId,cellval,colpos,rwdat,act){return formatter(rowId,cellval,colpos,rwdat,act)};$.extend(grid,{populate:function(){populate()}});this.grid=grid;ts.addXmlData=function(d){addXmlData(d,ts.grid.bDiv)};ts.addJSONData=function(d){addJSONData(d,ts.grid.bDiv)};populate();ts.p.hiddengrid=false;$(window).unload(function(){$(this).empty();this.grid=null;this.p=null})})};$.fn.extend({getGridParam:function(pName){var $t=this[0];if(!$t.grid){return}if(!pName){return $t.p}else{return $t.p[pName]?$t.p[pName]:null}},setGridParam:function(newParams){return this.each(function(){if(this.grid&&typeof(newParams)==="object"){$.extend(true,this.p,newParams)}})},getDataIDs:function(){var ids=[],i=0,len;this.each(function(){len=this.rows.length;if(len&&len>0){while(i<len){ids[i]=this.rows[i].id;i++}}});return ids},setSelection:function(selection,onsr,sd){return this.each(function(){var $t=this,stat,pt,olr,ner,ia,tpsr;onsr=onsr===false?false:true;if(selection===false){pt=sd}else{pt=$($t.rows.namedItem(selection))}selection=$(pt).attr("id");if(!pt.html()){return}if($t.p.selrow&&$t.p.scrollrows===true){olr=$t.rows.namedItem($t.p.selrow).rowIndex;ner=$t.rows.namedItem(selection).rowIndex;if(ner>=0){if(ner>olr){scrGrid(ner,"d")}else{scrGrid(ner,"u")}}}if(!$t.p.multiselect){if($(pt).attr("class")!=="subgrid"){if($t.p.selrow){$("tr#"+$t.p.selrow.replace(".","\\."),$t.grid.bDiv).removeClass("ui-state-highlight").attr("aria-selected","false")}$t.p.selrow=selection;$(pt).addClass("ui-state-highlight").attr("aria-selected","true");if($t.p.onSelectRow&&onsr){$t.p.onSelectRow($t.p.selrow,true)}}}else{$t.p.selrow=selection;ia=$.inArray($t.p.selrow,$t.p.selarrrow);if(ia===-1){if($(pt).attr("class")!=="subgrid"){$(pt).addClass("ui-state-highlight").attr("aria-selected","true")}stat=true;$("#jqg_"+$t.p.selrow.replace(".","\\."),$t.rows).attr("checked",stat);$t.p.selarrrow.push($t.p.selrow);if($t.p.onSelectRow&&onsr){$t.p.onSelectRow($t.p.selrow,stat)}}else{if($(pt).attr("class")!=="subgrid"){$(pt).removeClass("ui-state-highlight").attr("aria-selected","false")}stat=false;$("#jqg_"+$t.p.selrow.replace(".","\\."),$t.rows).attr("checked",stat);$t.p.selarrrow.splice(ia,1);if($t.p.onSelectRow&&onsr){$t.p.onSelectRow($t.p.selrow,stat)}tpsr=$t.p.selarrrow[0];$t.p.selrow=(tpsr=="undefined")?null:tpsr}}function scrGrid(iR,tp){var ch=$($t.grid.bDiv)[0].clientHeight,st=$($t.grid.bDiv)[0].scrollTop,nROT=$t.rows[iR].offsetTop+$t.rows[iR].clientHeight,pROT=$t.rows[iR].offsetTop;if(tp=="d"){if(nROT>=ch){$($t.grid.bDiv)[0].scrollTop=st+nROT-pROT}}if(tp=="u"){if(pROT<st){$($t.grid.bDiv)[0].scrollTop=st-nROT+pROT}}}})},resetSelection:function(){return this.each(function(){var t=this,ind;if(!t.p.multiselect){if(t.p.selrow){$("tr#"+t.p.selrow.replace(".","\\."),t.grid.bDiv).removeClass("ui-state-highlight");t.p.selrow=null}}else{$(t.p.selarrrow).each(function(i,n){ind=t.rows.namedItem(n);$(ind).removeClass("ui-state-highlight");$("#jqg_"+n.replace(".","\\."),ind).attr("checked",false)});$("#cb_jqg",t.grid.hDiv).attr("checked",false);t.p.selarrrow=[]}t.p.savedRow=[]})},getRowData:function(rowid){var res={};this.each(function(){var $t=this,nm,ind;ind=$t.rows.namedItem(rowid);if(!ind){return res}$("td",ind).each(function(i){nm=$t.p.colModel[i].name;if(nm!=="cb"&&nm!=="subgrid"){if($t.p.treeGrid===true&&nm==$t.p.ExpandColumn){res[nm]=$.jgrid.htmlDecode($("span:first",this).html())}else{res[nm]=$.jgrid.htmlDecode($(this).html())}}})});return res},delRowData:function(rowid){var success=false,rowInd,ia,ri;this.each(function(){var $t=this;rowInd=$t.rows.namedItem(rowid);if(!rowInd){return false}else{ri=rowInd.rowIndex;$(rowInd).remove();$t.p.records--;$t.p.reccount--;$t.updatepager(true);success=true;if(rowid==$t.p.selrow){$t.p.selrow=null}ia=$.inArray(rowid,$t.p.selarrrow);if(ia!=-1){$t.p.selarrrow.splice(ia,1)}}if(ri==0&&success){$t.updateColumns()}if($t.p.altRows===true&&success){var cn=$t.p.altclass;$($t.rows).each(function(i){if(i%2==1){$(this).addClass(cn)}else{$(this).removeClass(cn)}})}});return success},setRowData:function(rowid,data){var nm,success=false;this.each(function(){var t=this,vl,ind;if(!t.grid){return false}var ind=t.rows.namedItem(rowid);if(!ind){return false}if(data){$(this.p.colModel).each(function(i){nm=this.name;if(data[nm]!=undefined){vl=t.formatter(rowid,data[nm],i,data,"edit");if(t.p.treeGrid===true&&nm==t.p.ExpandColumn){$("td:eq("+i+") > span:first",ind).html(vl).attr("title",$.jgrid.stripHtml(vl))}else{$("td:eq("+i+")",ind).html(vl).attr("title",$.jgrid.stripHtml(vl))}success=true}})}});return success},addRowData:function(rowid,data,pos,src){if(!pos){pos="last"}var success=false,nm,row,gi=0,si=0,ni=0,sind,i,v,prp="";if(data){this.each(function(){var t=this;rowid=typeof(rowid)!="undefined"?rowid+"":t.p.records+1;row='<tr id="'+rowid+'" role="row" class="ui-widget-content jqgrow">';if(t.p.rownumbers===true){prp=t.formatCol(ni,1);row+='<td role="gridcell" class="ui-state-default jqgrid-rownum" '+prp+">0</td>";ni=1}if(t.p.multiselect){v='<input type="checkbox" id="jqg_'+rowid+'" class="cbox"/>';prp=t.formatCol(ni,1);row+='<td role="gridcell" '+prp+">"+v+"</td>";gi=1}if(t.p.subGrid===true){row+=$(t).addSubGridCell(gi+ni,1);si=1}for(i=gi+si+ni;i<this.p.colModel.length;i++){nm=this.p.colModel[i].name;v=t.formatter(rowid,data[nm],i,data,"add");prp=t.formatCol(i,1);row+='<td role="gridcell" '+prp+' title="'+$.jgrid.stripHtml(v)+'">'+v+"</td>"}row+="</tr>";if(t.p.subGrid===true){row=$(row)[0];$(t).addSubGrid(row,gi+ni)}if(t.rows.length===0){$("table:first",t.grid.bDiv).append(row)}else{switch(pos){case"last":$(t.rows[t.rows.length-1]).after(row);break;case"first":$(t.rows[0]).before(row);break;case"after":sind=t.rows.namedItem(src);sind!=null?$(t.rows[sind.rowIndex+1]).hasClass("ui-subgrid")?$(t.rows[sind.rowIndex+1]).after(row):$(sind).after(row):"";break;case"before":sind=t.rows.namedItem(src);sind!=null?$(sind).before(row):"";break}}t.p.records++;t.p.reccount++;if(pos==="first"||(pos==="before"&&sind===0)||t.rows.length===1){t.updateColumns()}if(t.p.altRows===true){var cn=t.p.altclass;if(pos=="last"){if(t.rows.length%2==1){$(t.rows[t.rows.length-1]).addClass(cn)}}else{$(t.rows).each(function(i){if(i%2==1){$(this).addClass(cn)}else{$(this).removeClass(cn)}})}}try{t.p.afterInsertRow(rowid,data)}catch(e){}t.updatepager(true);success=true})}return success},footerData:function(action,data,format){var nm,success=false,res={};function isEmpty(obj){for(var i in obj){return false}return true}if(typeof(action)=="undefined"){action="get"}if(typeof(format)!="boolean"){format=true}action=action.toLowerCase();this.each(function(){var t=this,vl,ind;if(!t.grid||!t.p.footerrow){return false}if(action=="set"){if(isEmpty(data)){return false}}success=true;$(this.p.colModel).each(function(i){nm=this.name;if(action=="set"){if(data[nm]!=undefined){vl=format?t.formatter("",data[nm],i,data,"edit"):data[nm];$("tr.footrow td:eq("+i+")",t.grid.sDiv).html(vl).attr("title",$.jgrid.stripHtml(vl));success=true}}else{if(action=="get"){res[nm]=$("tr.footrow td:eq("+i+")",t.grid.sDiv).html()}}})});return action=="get"?res:success},ShowHideCol:function(colname,show){return this.each(function(){var $t=this,fndh=false;if(!$t.grid){return}if(typeof colname==="string"){colname=[colname]}show=show!="none"?"":"none";var sw=show==""?true:false;$(this.p.colModel).each(function(i){if($.inArray(this.name,colname)!==-1&&this.hidden===sw){$("tr",$t.grid.hDiv).each(function(){$("th:eq("+i+")",this).css("display",show)});$($t.rows).each(function(j){$("td:eq("+i+")",$t.rows[j]).css("display",show)});if($t.p.footerrow){$("td:eq("+i+")",$t.grid.sDiv).css("display",show)}if(show=="none"){$t.p.tblwidth-=this.width}else{$t.p.tblwidth+=this.width}this.hidden=!sw;fndh=true}});if(fndh===true){$("table:first",$t.grid.hDiv).width($t.p.tblwidth);$("table:first",$t.grid.bDiv).width($t.p.tblwidth);$t.grid.hDiv.scrollLeft=$t.grid.bDiv.scrollLeft;if($t.p.footerrow){$("table:first",$t.grid.sDiv).width($t.p.tblwidth);$t.grid.sDiv.scrollLeft=$t.grid.bDiv.scrollLeft}}})},hideCol:function(colname){return this.each(function(){$(this).ShowHideCol(colname,"none")})},showCol:function(colname){return this.each(function(){$(this).ShowHideCol(colname,"")})},setGridWidth:function(nwidth,shrink){return this.each(function(){var $t=this,cw,initwidth=0,brd=$t.p.cellLayout,lvc,vc=0,isSafari,hs=false,scw=$t.p.scrollOffset,aw,gw=0,tw=0,msw=$t.p.multiselectWidth,sgw=$t.p.subGridWidth,rnw=$t.p.rownumWidth,cl=$t.p.cellLayout,cr;if(!$t.grid){return}if(typeof shrink!="boolean"){shrink=$t.p.shrinkToFit}if(isNaN(nwidth)){return}if(nwidth==$t.grid.width){return}else{$t.grid.width=$t.p.width=nwidth}$("#gbox_"+$t.p.id).css("width",nwidth+"px");$("#gview_"+$t.p.id).css("width",nwidth+"px");$($t.grid.bDiv).css("width",nwidth+"px");$($t.grid.hDiv).css("width",nwidth+"px");if($t.p.pager){$($t.p.pager).css("width",nwidth+"px")}if($t.p.toolbar[0]===true){$($t.grid.uDiv).css("width",nwidth+"px");if($t.p.toolbar[1]=="both"){$($t.grid.ubDiv).css("width",nwidth+"px")}}if($t.p.footerrow){$($t.grid.sDiv).css("width",nwidth+"px")}if(shrink===false&&$t.p.forceFit==true){$t.p.forceFit=false}if(shrink===true){$.each($t.p.colModel,function(i){if(this.hidden===false){initwidth+=parseInt(this.width,10);vc++}});isSafari=$.browser.safari?true:false;if(isSafari){brd=0;msw+=cl;sgw+=cl;rnw+=cl}if($t.p.multiselect){tw=msw;gw=msw+brd;vc--}if($t.p.subGrid){tw+=sgw;gw+=sgw+brd;vc--}if($t.p.rownumbers){tw+=rnw;gw+=rnw+brd;vc--}$t.p.tblwidth=initwidth;aw=nwidth-brd*vc-gw;if(!isNaN($t.p.height)){if($($t.grid.bDiv)[0].clientHeight<$($t.grid.bDiv)[0].scrollHeight){hs=true;aw-=scw}}initwidth=0;var cl=$t.grid.cols.length>0;$.each($t.p.colModel,function(i){var tn=this.name;if(this.hidden===false&&tn!=="cb"&&tn!=="subgrid"&&tn!=="rn"){cw=Math.floor((aw)/($t.p.tblwidth-tw)*this.width);this.width=cw;initwidth+=cw;$t.grid.headers[i].width=cw;$t.grid.headers[i].el.style.width=cw+"px";if($t.p.footerrow){$t.grid.footers[i].style.width=cw+"px"}if(cl){$t.grid.cols[i].style.width=cw+"px"}lvc=i}});cr=0;if(hs&&nwidth-gw-(initwidth+brd*vc)!==scw){cr=nwidth-gw-(initwidth+brd*vc)-scw}else{if(Math.abs(nwidth-gw-(initwidth+brd*vc))!==1){cr=nwidth-gw-(initwidth+brd*vc)}}$t.p.colModel[lvc].width+=cr;cw=$t.p.colModel[lvc].width;$t.grid.headers[lvc].width=cw;$t.grid.headers[lvc].el.style.width=cw+"px";if(cl>0){$t.grid.cols[lvc].style.width=cw+"px"}$t.p.tblwidth=initwidth+tw+cr;$("table:first",$t.grid.bDiv).css("width",initwidth+tw+cr+"px");$("table:first",$t.grid.hDiv).css("width",initwidth+tw+cr+"px");$t.grid.hDiv.scrollLeft=$t.grid.bDiv.scrollLeft;if($t.p.footerrow){$t.grid.footers[lvc].style.width=cw+"px";$("table:first",$t.grid.sDiv).css("width",initwidth+tw+cr+"px")}}})},setGridHeight:function(nh){return this.each(function(){var $t=this;if(!$t.grid){return}$($t.grid.bDiv).css({height:nh+(isNaN(nh)?"":"px")});$t.p.height=nh})},setCaption:function(newcap){return this.each(function(){this.p.caption=newcap;$("span.ui-jqgrid-title",this.grid.cDiv).html(newcap);$(this.grid.cDiv).show()})},setLabel:function(colname,nData,prop,attrp){return this.each(function(){var $t=this,pos=-1;if(!$t.grid){return}if(isNaN(colname)){$($t.p.colModel).each(function(i){if(this.name==colname){pos=i;return false}})}else{pos=parseInt(colname,10)}if(pos>=0){var thecol=$("tr.ui-jqgrid-labels th:eq("+pos+")",$t.grid.hDiv);if(nData){$("div",thecol).html(nData)}if(prop){if(typeof prop==="string"){$(thecol).addClass(prop)}else{$(thecol).css(prop)}}if(typeof attrp==="object"){$(thecol).attr(attrp)}}})},setCell:function(rowid,colname,nData,cssp,attrp){return this.each(function(){var $t=this,pos=-1,v;if(!$t.grid){return}if(isNaN(colname)){$($t.p.colModel).each(function(i){if(this.name==colname){pos=i;return false}})}else{pos=parseInt(colname,10)}if(pos>=0){var ind=$t.rows.namedItem(rowid);if(ind){var tcell=$("td:eq("+pos+")",ind);if(nData!==""){v=$t.formatter(rowid,nData,pos,ind,"edit");$(tcell).html(v).attr("title",$.jgrid.stripHtml(v))}if(cssp){if(typeof cssp==="string"){$(tcell).addClass(cssp)}else{$(tcell).css(cssp)}}if(typeof attrp==="object"){$(tcell).attr(attrp)}}}})},getCell:function(rowid,col){var ret=false;this.each(function(){var $t=this,pos=-1;if(!$t.grid){return}if(isNaN(col)){$($t.p.colModel).each(function(i){if(this.name===col){pos=i;return false}})}else{pos=parseInt(col,10)}if(pos>=0){var ind=$t.rows.namedItem(rowid);if(ind){ret=$.jgrid.htmlDecode($("td:eq("+pos+")",ind).html())}}});return ret},getCol:function(col){var ret=[];this.each(function(){var $t=this,pos=-1;if(!$t.grid){return}if(isNaN(col)){$($t.p.colModel).each(function(i){if(this.name===col){pos=i;return false}})}else{pos=parseInt(col,10)}if(pos>=0){var ln=$t.rows.length,i=0;if(ln&&ln>0){while(i<ln){ret[i]=$t.rows[i].cells[pos].innerHTML;i++}}}});return ret},clearGridData:function(){return this.each(function(){var $t=this;if(!$t.grid){return}$("tbody:first tr",$t.grid.bDiv).remove();$t.p.selrow=null;$t.p.selarrrow=[];$t.p.savedRow=[];$t.p.records=0;$t.p.page="0";$t.p.lastpage="0";$t.p.reccount=0;$t.updatepager(true)})},getInd:function(rowid,rc){var ret=false,rw;this.each(function(){rw=this.rows.namedItem(rowid);if(rw){ret=rc===true?rw:rw.rowIndex}});return ret}})})(jQuery);(function($){$.fmatter={};$.fn.fmatter=function(formatType,cellval,opts,rwd,act){opts=$.extend({},$.jgrid.formatter,opts);return fireFormatter(formatType,cellval,opts,rwd,act)};$.fmatter.util={NumberFormat:function(nData,opts){if(!isNumber(nData)){nData*=1}if(isNumber(nData)){var bNegative=(nData<0);var sOutput=nData+"";var sDecimalSeparator=(opts.decimalSeparator)?opts.decimalSeparator:".";var nDotIndex;if(isNumber(opts.decimalPlaces)){var nDecimalPlaces=opts.decimalPlaces;var nDecimal=Math.pow(10,nDecimalPlaces);sOutput=Math.round(nData*nDecimal)/nDecimal+"";nDotIndex=sOutput.lastIndexOf(".");if(nDecimalPlaces>0){if(nDotIndex<0){sOutput+=sDecimalSeparator;nDotIndex=sOutput.length-1}else{if(sDecimalSeparator!=="."){sOutput=sOutput.replace(".",sDecimalSeparator)}}while((sOutput.length-1-nDotIndex)<nDecimalPlaces){sOutput+="0"}}}if(opts.thousandsSeparator){var sThousandsSeparator=opts.thousandsSeparator;nDotIndex=sOutput.lastIndexOf(sDecimalSeparator);nDotIndex=(nDotIndex>-1)?nDotIndex:sOutput.length;var sNewOutput=sOutput.substring(nDotIndex);var nCount=-1;for(var i=nDotIndex;i>0;i--){nCount++;if((nCount%3===0)&&(i!==nDotIndex)&&(!bNegative||(i>1))){sNewOutput=sThousandsSeparator+sNewOutput}sNewOutput=sOutput.charAt(i-1)+sNewOutput}sOutput=sNewOutput}sOutput=(opts.prefix)?opts.prefix+sOutput:sOutput;sOutput=(opts.suffix)?sOutput+opts.suffix:sOutput;return sOutput}else{return nData}},DateFormat:function(format,date,newformat,opts){var token=/\\.|[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/g,timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,timezoneClip=/[^-+\dA-Z]/g,pad=function(value,length){value=String(value);length=parseInt(length)||2;while(value.length<length){value="0"+value}return value},ts={m:1,d:1,y:1970,h:0,i:0,s:0},timestamp=0,dM,k,hl,dateFormat=["i18n"];dateFormat.i18n={dayNames:opts.dayNames,monthNames:opts.monthNames};date=date.split(/[\\\/:_;.\t\T\s-]/);format=format.split(/[\\\/:_;.\t\T\s-]/);for(k=0,hl=format.length;k<hl;k++){if(format[k]=="M"){dM=$.inArray(date[k],dateFormat.i18n.monthNames);if(dM!==-1&&dM<12){date[k]=dM+1}}if(format[k]=="F"){dM=$.inArray(date[k],dateFormat.i18n.monthNames);if(dM!==-1&&dM>11){date[k]=dM+1-12}}ts[format[k].toLowerCase()]=parseInt(date[k],10)}ts.m=parseInt(ts.m)-1;var ty=ts.y;if(ty>=70&&ty<=99){ts.y=1900+ts.y}else{if(ty>=0&&ty<=69){ts.y=2000+ts.y}}timestamp=new Date(ts.y,ts.m,ts.d,ts.h,ts.i,ts.s,0);if(opts.masks.newformat){newformat=opts.masks.newformat}else{if(!newformat){newformat="Y-m-d"}}var G=timestamp.getHours(),i=timestamp.getMinutes(),j=timestamp.getDate(),n=timestamp.getMonth()+1,o=timestamp.getTimezoneOffset(),s=timestamp.getSeconds(),u=timestamp.getMilliseconds(),w=timestamp.getDay(),Y=timestamp.getFullYear(),N=(w+6)%7+1,z=(new Date(Y,n-1,j)-new Date(Y,0,1))/86400000,flags={d:pad(j),D:dateFormat.i18n.dayNames[w],j:j,l:dateFormat.i18n.dayNames[w+7],N:N,S:opts.S(j),w:w,z:z,W:N<5?Math.floor((z+N-1)/7)+1:Math.floor((z+N-1)/7)||((new Date(Y-1,0,1).getDay()+6)%7<4?53:52),F:dateFormat.i18n.monthNames[n-1+12],m:pad(n),M:dateFormat.i18n.monthNames[n-1],n:n,t:"?",L:"?",o:"?",Y:Y,y:String(Y).substring(2),a:G<12?opts.AmPm[0]:opts.AmPm[1],A:G<12?opts.AmPm[2]:opts.AmPm[3],B:"?",g:G%12||12,G:G,h:pad(G%12||12),H:pad(G),i:pad(i),s:pad(s),u:u,e:"?",I:"?",O:(o>0?"-":"+")+pad(Math.floor(Math.abs(o)/60)*100+Math.abs(o)%60,4),P:"?",T:(String(timestamp).match(timezone)||[""]).pop().replace(timezoneClip,""),Z:"?",c:"?",r:"?",U:Math.floor(timestamp/1000)};return newformat.replace(token,function($0){return $0 in flags?flags[$0]:$0.substring(1)})}};$.fn.fmatter.defaultFormat=function(cellval,opts){return(isValue(cellval)&&cellval!=="")?cellval:opts.defaultValue?opts.defaultValue:"&#160;"};$.fn.fmatter.email=function(cellval,opts){if(!isEmpty(cellval)){return'<a href="mailto:'+cellval+'">'+cellval+"</a>"}else{return $.fn.fmatter.defaultFormat(cellval,opts)}};$.fn.fmatter.checkbox=function(cval,opts){var op=$.extend({},opts.checkbox),ds;if(!isUndefined(opts.colModel.formatoptions)){op=$.extend({},op,opts.colModel.formatoptions)}if(op.disabled===true){ds="disabled"}else{ds=""}cval=cval+"";cval=cval.toLowerCase();var bchk=cval.search(/(false|0|no|off)/i)<0?" checked='checked' ":"";return'<input type="checkbox" '+bchk+' value="'+cval+'" offval="no" '+ds+"/>"},$.fn.fmatter.link=function(cellval,opts){var op={target:opts.target};var target="";if(!isUndefined(opts.colModel.formatoptions)){op=$.extend({},op,opts.colModel.formatoptions)}if(op.target){target="target="+op.target}if(!isEmpty(cellval)){return"<a "+target+' href="'+cellval+'">'+cellval+"</a>"}else{return $.fn.fmatter.defaultFormat(cellval,opts)}};$.fn.fmatter.showlink=function(cellval,opts){var op={baseLinkUrl:opts.baseLinkUrl,showAction:opts.showAction,addParam:opts.addParam,target:opts.target,idName:opts.idName},target="";if(!isUndefined(opts.colModel.formatoptions)){op=$.extend({},op,opts.colModel.formatoptions)}if(op.target){target="target="+op.target}idUrl=op.baseLinkUrl+op.showAction+"?"+op.idName+"="+opts.rowId+op.addParam;if(isString(cellval)){return"<a "+target+' href="'+idUrl+'">'+cellval+"</a>"}else{return $.fn.fmatter.defaultFormat(cellval,opts)}};$.fn.fmatter.integer=function(cellval,opts){var op=$.extend({},opts.integer);if(!isUndefined(opts.colModel.formatoptions)){op=$.extend({},op,opts.colModel.formatoptions)}if(isEmpty(cellval)){return op.defaultValue}return $.fmatter.util.NumberFormat(cellval,op)};$.fn.fmatter.number=function(cellval,opts){var op=$.extend({},opts.number);if(!isUndefined(opts.colModel.formatoptions)){op=$.extend({},op,opts.colModel.formatoptions)}if(isEmpty(cellval)){return op.defaultValue}return $.fmatter.util.NumberFormat(cellval,op)};$.fn.fmatter.currency=function(cellval,opts){var op=$.extend({},opts.currency);if(!isUndefined(opts.colModel.formatoptions)){op=$.extend({},op,opts.colModel.formatoptions)}if(isEmpty(cellval)){return op.defaultValue}return $.fmatter.util.NumberFormat(cellval,op)};$.fn.fmatter.date=function(cellval,opts,act){var op=$.extend({},opts.date);if(!isUndefined(opts.colModel.formatoptions)){op=$.extend({},op,opts.colModel.formatoptions)}if(!op.reformatAfterEdit&&act=="edit"){return $.fn.fmatter.defaultFormat(cellval,opts)}else{if(!isEmpty(cellval)){return $.fmatter.util.DateFormat(op.srcformat,cellval,op.newformat,op)}else{return $.fn.fmatter.defaultFormat(cellval,opts)}}};$.fn.fmatter.select=function(cellval,opts,act){if(act=="edit"){return $.fn.fmatter.defaultFormat(cellval,opts)}else{if(!isEmpty(cellval)){var oSelect=false;if(!isUndefined(opts.colModel.editoptions)){oSelect=opts.colModel.editoptions.value}if(oSelect){var ret=[],msl=opts.colModel.editoptions.multiple===true?true:false,scell=[],sv;if(msl){scell=cellval.split(",");scell=$.map(scell,function(n){return $.trim(n)})}if(isString(oSelect)){var so=oSelect.split(";"),j=0;for(var i=0;i<so.length;i++){sv=so[i].split(":");if(msl){if(jQuery.inArray(sv[0],scell)>-1){ret[j]=sv[1];j++}}else{if($.trim(sv[0])==$.trim(cellval)){ret[0]=sv[1];break}}}}else{if(isObject(oSelect)){if(msl){ret=jQuery.map(scel,function(n,i){return oSelect[n]})}ret[0]=oSelect[cellval]||""}}return ret.join(", ")}else{return $.fn.fmatter.defaultFormat(cellval,opts)}}}};$.unformat=function(cellval,options,pos,cnt){var ret,formatType=options.colModel.formatter,op=options.colModel.formatoptions||{},unformatFunc=options.colModel.unformat||($.fn.fmatter[formatType]&&$.fn.fmatter[formatType].unformat);if(unformatFunc!=="undefined"&&isFunction(unformatFunc)){ret=unformatFunc(cellval,options)}else{if(formatType!=="undefined"&&isString(formatType)){var opts=$.jgrid.formatter||{},stripTag;switch(formatType){case"integer":op=$.extend({},opts.integer,op);stripTag=eval("/"+op.thousandsSeparator+"/g");ret=$(cellval).text().replace(stripTag,"");break;case"number":op=$.extend({},opts.number,op);stripTag=eval("/"+op.thousandsSeparator+"/g");ret=$(cellval).text().replace(op.decimalSeparator,".").replace(stripTag,"");break;case"currency":op=$.extend({},opts.currency,op);stripTag=eval("/"+op.thousandsSeparator+"/g");ret=$(cellval).text().replace(op.decimalSeparator,".").replace(op.prefix,"").replace(op.suffix,"").replace(stripTag,"");break;case"checkbox":var cbv=(options.colModel.editoptions)?options.colModel.editoptions.value.split(":"):["Yes","No"];ret=$("input",cellval).attr("checked")?cbv[0]:cbv[1];break;default:ret=$(cellval).text();break}}}return ret?ret:cnt===true?$(cellval).text():$.jgrid.htmlDecode($(cellval).html())};function fireFormatter(formatType,cellval,opts,rwd,act){formatType=formatType.toLowerCase();var v=cellval;if($.fn.fmatter[formatType]){v=$.fn.fmatter[formatType](cellval,opts,act)}return v}function debug($obj){if(window.console&&window.console.log){window.console.log($obj)}}isValue=function(o){return(isObject(o)||isString(o)||isNumber(o)||isBoolean(o))};isBoolean=function(o){return typeof o==="boolean"};isNull=function(o){return o===null};isNumber=function(o){return typeof o==="number"&&isFinite(o)};isString=function(o){return typeof o==="string"};isEmpty=function(o){if(!isString(o)&&isValue(o)){return false}else{if(!isValue(o)){return true}}o=$.trim(o).replace(/\&nbsp\;/ig,"").replace(/\&#160\;/ig,"");return o===""};isUndefined=function(o){return typeof o==="undefined"};isObject=function(o){return(o&&(typeof o==="object"||isFunction(o)))||false};isFunction=function(o){return typeof o==="function"}})(jQuery);(function(a){a.fn.extend({getColProp:function(d){var b={},f=this[0];if(!f.grid){return}var e=f.p.colModel;for(var c=0;c<e.length;c++){if(e[c].name==d){b=e[c];break}}return b},setColProp:function(c,b){return this.each(function(){if(this.grid){if(b){var e=this.p.colModel;for(var d=0;d<e.length;d++){if(e[d].name==c){a.extend(this.p.colModel[d],b);break}}}}})},sortGrid:function(c,b){return this.each(function(){var g=this,d=-1;if(!g.grid){return}if(!c){c=g.p.sortname}for(var f=0;f<g.p.colModel.length;f++){if(g.p.colModel[f].index==c||g.p.colModel[f].name==c){d=f;break}}if(d!=-1){var e=g.p.colModel[d].sortable;if(typeof e!=="boolean"){e=true}if(typeof b!=="boolean"){b=false}if(e){g.sortData("jqgh_"+c,d,b)}}})},GridDestroy:function(){return this.each(function(){if(this.grid){if(this.p.pager){a(this.p.pager).remove()}var c=this.id;try{a("#gbox_"+c).remove()}catch(b){}}})},GridUnload:function(){return this.each(function(){if(!this.grid){return}var d={id:a(this).attr("id"),cl:a(this).attr("class")};if(this.p.pager){a(this.p.pager).empty().removeClass("ui-state-default ui-jqgrid-pager corner-bottom")}var b=document.createElement("table");a(b).attr({id:d.id});b.className=d.cl;var c=this.id;a(b).removeClass("ui-jqgrid-btable");if(a(this.p.pager).parents("#gbox_"+c).length===1){a(b).insertBefore("#gbox_"+c).show();a(this.p.pager).insertBefore("#gbox_"+c)}else{a(b).insertBefore("#gbox_"+c).show()}a("#gbox_"+c).remove()})},updateGridRows:function(e,c,d){var b,f=false;this.each(function(){var h=this,j,k,i,g;if(!h.grid){return false}if(!c){c="id"}if(e&&e.length>0){a(e).each(function(m){i=this;k=h.rows.namedItem(i[c]);if(k){g=i[c];if(d===true){if(h.p.jsonReader.repeatitems===true){if(h.p.jsonReader.cell){i=i[h.p.jsonReader.cell]}for(var l=0;l<i.length;l++){j=h.formatter(g,i[l],l,i,"edit");if(h.p.treeGrid===true&&b==h.p.ExpandColumn){a("td:eq("+l+") > span:first",k).html(j).attr("title",a.jgrid.stripHtml(j))}else{a("td:eq("+l+")",k).html(j).attr("title",a.jgrid.stripHtml(j))}}f=true;return true}}a(h.p.colModel).each(function(n){b=d===true?this.jsonmap||this.name:this.name;if(i[b]!=undefined){j=h.formatter(g,i[b],n,i,"edit");if(h.p.treeGrid===true&&b==h.p.ExpandColumn){a("td:eq("+n+") > span:first",k).html(j).attr("title",a.jgrid.stripHtml(j))}else{a("td:eq("+n+")",k).html(j).attr("title",a.jgrid.stripHtml(j))}f=true}})}})}});return f},filterGrid:function(c,b){b=a.extend({gridModel:false,gridNames:false,gridToolbar:false,filterModel:[],formtype:"horizontal",autosearch:true,formclass:"filterform",tableclass:"filtertable",buttonclass:"filterbutton",searchButton:"Search",clearButton:"Clear",enableSearch:false,enableClear:false,beforeSearch:null,afterSearch:null,beforeClear:null,afterClear:null,url:"",marksearched:true},b||{});return this.each(function(){var l=this;this.p=b;if(this.p.filterModel.length==0&&this.p.gridModel===false){alert("No filter is set");return}if(!c){alert("No target grid is set!");return}this.p.gridid=c.indexOf("#")!=-1?c:"#"+c;var d=a(this.p.gridid).getGridParam("colModel");if(d){if(this.p.gridModel===true){var e=a(this.p.gridid)[0];var g;a.each(d,function(o,p){var m=[];this.search=this.search===false?false:true;if(this.editrules&&this.editrules.searchhidden===true){g=true}else{if(this.hidden===true){g=false}else{g=true}}if(this.search===true&&g===true){if(l.p.gridNames===true){m.label=e.p.colNames[o]}else{m.label=""}m.name=this.name;m.index=this.index||this.name;m.stype=this.edittype||"text";if(m.stype!="select"){m.stype="text"}m.defval=this.defval||"";m.surl=this.surl||"";m.sopt=this.editoptions||{};m.width=this.width;l.p.filterModel.push(m)}})}else{a.each(l.p.filterModel,function(o,p){for(var m=0;m<d.length;m++){if(this.name==d[m].name){this.index=d[m].index||this.name;break}}if(!this.index){this.index=this.name}})}}else{alert("Could not get grid colModel");return}var h=function(){var p=0,n;var o=a(l.p.gridid)[0],m;if(a.isFunction(l.p.beforeSearch)){l.p.beforeSearch()}a.each(l.p.filterModel,function(s,u){m=this.index;switch(this.stype){case"select":n=a("select[name="+m+"]",l).val();if(n){o.p.searchdata[m]=n;if(l.p.marksearched){a("#jqgh_"+this.name,o.grid.hDiv).addClass("dirty-cell")}p++}else{if(l.p.marksearched){a("#jqgh_"+this.name,o.grid.hDiv).removeClass("dirty-cell")}try{delete o.p.searchdata[this.index]}catch(t){}}break;default:n=a("input[name="+m+"]",l).val();if(n){o.p.searchdata[m]=n;if(l.p.marksearched){a("#jqgh_"+this.name,o.grid.hDiv).addClass("dirty-cell")}p++}else{if(l.p.marksearched){a("#jqgh_"+this.name,o.grid.hDiv).removeClass("dirty-cell")}try{delete o.p.searchdata[this.index]}catch(t){}}}});var q=p>0?true:false;var r;if(l.p.url){r=a(o).getGridParam("url");a(o).setGridParam({url:l.p.url})}a(o).setGridParam({search:q,page:1}).trigger("reloadGrid");if(r){a(o).setGridParam({url:r})}if(a.isFunction(l.p.afterSearch)){l.p.afterSearch()}};var k=function(){var n,p=0;var o=a(l.p.gridid)[0],m;if(a.isFunction(l.p.beforeClear)){l.p.beforeClear()}a.each(l.p.filterModel,function(s,v){m=this.index;n=(this.defval)?this.defval:"";if(!this.stype){this.stype=="text"}switch(this.stype){case"select":if(n){var u;a("select[name="+m+"] option",l).each(function(){if(a(this).text()==n){this.selected=true;u=a(this).val();return false}});o.p.searchdata[m]=u||"";if(l.p.marksearched){a("#jqgh_"+this.name,o.grid.hDiv).addClass("dirty-cell")}p++}else{if(l.p.marksearched){a("#jqgh_"+this.name,o.grid.hDiv).removeClass("dirty-cell")}try{delete o.p.searchdata[this.index]}catch(t){}}break;case"text":a("input[name="+m+"]",l).val(n);if(n){o.p.searchdata[m]=n;if(l.p.marksearched){a("#jqgh_"+this.name,o.grid.hDiv).addClass("dirty-cell")}p++}else{if(l.p.marksearched){a("#jqgh_"+this.name,o.grid.hDiv).removeClass("dirty-cell")}try{delete o.p.searchdata[this.index]}catch(t){}}}});var q=p>0?true:false;var r;if(l.p.url){r=a(o).getGridParam("url");a(o).setGridParam({url:l.p.url})}a(o).setGridParam({search:q,page:1}).trigger("reloadGrid");if(r){a(o).setGridParam({url:r})}if(a.isFunction(l.p.afterClear)){l.p.afterClear()}};var i=function(){var q=document.createElement("tr");var n,s,m,o,r,p;if(l.p.formtype=="horizontal"){a(f).append(q)}a.each(l.p.filterModel,function(A,v){o=document.createElement("td");a(o).append("<label for='"+this.name+"'>"+this.label+"</label>");r=document.createElement("td");var z=this;if(!this.stype){this.stype="text"}switch(this.stype){case"select":if(this.surl){a(r).load(this.surl,function(){if(z.defval){a("select",this).val(z.defval)}a("select",this).attr({name:z.index||z.name,id:"sg_"+z.name});if(z.sopt){a("select",this).attr(z.sopt)}if(l.p.gridToolbar===true&&z.width){a("select",this).width(z.width)}if(l.p.autosearch===true){a("select",this).change(function(E){h();return false})}})}else{if(z.sopt.value){var t=z.sopt.value;var w=document.createElement("select");a(w).attr({name:z.index||z.name,id:"sg_"+z.name}).attr(z.sopt);if(typeof t==="string"){var u=t.split(";"),D,x;for(var y=0;y<u.length;y++){D=u[y].split(":");x=document.createElement("option");x.value=D[0];x.innerHTML=D[1];if(D[1]==z.defval){x.selected="selected"}w.appendChild(x)}}else{if(typeof t==="object"){for(var C in t){A++;x=document.createElement("option");x.value=C;x.innerHTML=t[C];if(t[C]==z.defval){x.selected="selected"}w.appendChild(x)}}}if(l.p.gridToolbar===true&&z.width){a(w).width(z.width)}a(r).append(w);if(l.p.autosearch===true){a(w).change(function(E){h();return false})}}}break;case"text":var B=this.defval?this.defval:"";a(r).append("<input type='text' name='"+(this.index||this.name)+"' id='sg_"+this.name+"' value='"+B+"'/>");if(z.sopt){a("input",r).attr(z.sopt)}if(l.p.gridToolbar===true&&z.width){if(a.browser.msie){a("input",r).width(z.width-4)}else{a("input",r).width(z.width-2)}}if(l.p.autosearch===true){a("input",r).keypress(function(F){var E=F.charCode?F.charCode:F.keyCode?F.keyCode:0;if(E==13){h();return false}return this})}break}if(l.p.formtype=="horizontal"){if(l.p.gridToolbar===true&&l.p.gridNames===false){a(q).append(r)}else{a(q).append(o).append(r)}a(q).append(r)}else{n=document.createElement("tr");a(n).append(o).append(r);a(f).append(n)}});r=document.createElement("td");if(l.p.enableSearch===true){s="<input type='button' id='sButton' class='"+l.p.buttonclass+"' value='"+l.p.searchButton+"'/>";a(r).append(s);a("input#sButton",r).click(function(){h();return false})}if(l.p.enableClear===true){m="<input type='button' id='cButton' class='"+l.p.buttonclass+"' value='"+l.p.clearButton+"'/>";a(r).append(m);a("input#cButton",r).click(function(){k();return false})}if(l.p.enableClear===true||l.p.enableSearch===true){if(l.p.formtype=="horizontal"){a(q).append(r)}else{n=document.createElement("tr");a(n).append("<td>&nbsp;</td>").append(r);a(f).append(n)}}};var j=a("<form name='SearchForm' style=display:inline;' class='"+this.p.formclass+"'></form>");var f=a("<table class='"+this.p.tableclass+"' cellspacing='0' cellpading='0' border='0'><tbody></tbody></table>");a(j).append(f);i();a(this).append(j);this.triggerSearch=function(){h()};this.clearSearch=function(){k()}})},filterToolbar:function(b){b=a.extend({autosearch:true,beforeSearch:null,afterSearch:null,beforeClear:null,afterClear:null,searchurl:""},b||{});return this.each(function(){var g=this;var c=function(){var n=0,m,l;if(a.isFunction(b.beforeSearch)){b.beforeSearch()}a.each(g.p.colModel,function(q,s){l=this.index||this.name;switch(this.stype){case"select":m=a("select[name="+l+"]",g.grid.hDiv).val();if(m){g.p.searchdata[l]=m;n++}else{try{delete g.p.searchdata[l]}catch(r){}}break;case"text":m=a("input[name="+l+"]",g.grid.hDiv).val();if(m){g.p.searchdata[l]=m;n++}else{try{delete g.p.searchdata[l]}catch(r){}}}});var o=n>0?true:false;var p;if(g.p.searchurl){p=g.p.url;a(g).setGridParam({url:g.p.searchurl})}a(g).setGridParam({search:o,page:1}).trigger("reloadGrid");if(p){a(g).setGridParam({url:p})}if(a.isFunction(b.afterSearch)){b.afterSearch()}};var j=function(){var m,n=0,l;if(a.isFunction(b.beforeClear)){b.beforeClear()}a.each(g.p.colModel,function(q,t){m=(this.defval)?this.defval:"";l=this.index||this.name;switch(this.stype){case"select":if(m){var s;a("select[name="+l+"] option",g.grid.hDiv).each(function(){if(a(this).text()==m){this.selected=true;s=a(this).val();return false}});g.p.searchdata[l]=s||"";n++}else{try{delete g.p.searchdata[l]}catch(r){}}break;case"text":a("input[name="+l+"]",g.grid.hDiv).val(m);if(m){g.p.searchdata[l]=m;n++}else{try{delete g.p.searchdata[l]}catch(r){}}}});var o=n>0?true:false;var p;if(g.p.searchurl){p=g.p.url;a(g).setGridParam({url:g.p.searchurl})}a(g).setGridParam({search:o,page:1}).trigger("reloadGrid");if(p){a(g).setGridParam({url:p})}if(a.isFunction(b.afterClear)){b.afterClear()}};var k=function(){var l=a("tr.ui-search-toolbar",g.grid.hDiv);if(l.css("display")=="none"){l.show()}else{l.hide()}};function f(l,n){var m=a(l);if(m[0]!=null){jQuery.each(n,function(){if(this.data!=null){m.bind(this.type,this.data,this.fn)}else{m.bind(this.type,this.fn)}})}}var h=a("<tr class='ui-search-toolbar' role='rowheader'></tr>"),d,i,e;a.each(g.p.colModel,function(s,o){var u=this;d=a("<th role='columnheader' class='ui-state-default ui-th-column'></th>");i=a("<div style='width:100%;position:relative;'></div>");if(this.hidden===true){a(d).css("display","none")}this.search=this.search===false?false:true;if(typeof this.stype=="undefined"){this.stype="text"}e=a.extend({},this.searchoptions||{});if(this.search){switch(this.stype){case"select":if(this.surl){a(i).load(this.surl,{_nsd:(new Date().getTime())},function(){if(e.defaultValue){a("select",this).val(e.defaultValue)}a("select",this).attr({name:u.index||u.name,id:"gs_"+u.name});if(e.attr){a("select",this).attr(e.attr)}a("select",this).css({width:"100%"});if(e.dataInit!=null){e.dataInit(a("select",this)[0])}if(e.dataEvents!=null){f(a("select",this)[0],e.dataEvents)}if(b.autosearch===true){a("select",this).change(function(n){c();return false})}})}else{if(u.editoptions&&u.editoptions.value){var l=u.editoptions.value,p=document.createElement("select");p.style.width="100%";a(p).attr({name:u.index||u.name,id:"gs_"+u.name});if(typeof l==="string"){var m=l.split(";"),w,q;for(var r=0;r<m.length;r++){w=m[r].split(":");q=document.createElement("option");q.value=w[0];q.innerHTML=w[1];p.appendChild(q)}}else{if(typeof l==="object"){for(var v in l){s++;q=document.createElement("option");q.value=v;q.innerHTML=l[v];p.appendChild(q)}}}if(e.defaultValue){a(p).val(e.defaultValue)}if(e.attr){a(p).attr(e.attr)}if(e.dataInit!=null){e.dataInit(p)}if(e.dataEvents!=null){f(p,e.dataEvents)}a(i).append(p);if(b.autosearch===true){a(p).change(function(n){c();return false})}}}break;case"text":var t=e.defaultValue?e.defaultValue:"";a(i).append("<input type='text' style='width:95%;padding:0px;' name='"+(u.index||u.name)+"' id='gs_"+u.name+"' value='"+t+"'/>");if(e.attr){a("input",i).attr(e.attr)}if(e.dataInit!=null){e.dataInit(a("input",i)[0])}if(e.dataEvents!=null){f(a("input",i)[0],e.dataEvents)}if(b.autosearch===true){a("input",i).keypress(function(x){var n=x.charCode?x.charCode:x.keyCode?x.keyCode:0;if(n==13){c();return false}return this})}break}}a(d).append(i);a(h).append(d)});a("table thead",g.grid.hDiv).append(h);this.triggerToolbar=function(){c()};this.clearToolbar=function(){j()};this.toggleToolbar=function(){k()}})}})})(jQuery);var showModal=function(a){a.w.show()};var closeModal=function(a){a.w.hide().attr("aria-hidden","true");if(a.o){a.o.remove()}};var createModal=function(i,d,a,k,m,l){var h=document.createElement("div");h.className="ui-widget ui-widget-content ui-corner-all ui-jqdialog";h.id=i.themodal;var b=document.createElement("div");b.className="ui-jqdialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix";b.id=i.modalhead;jQuery(b).append("<span class='ui-jqdialog-title'>"+a.caption+"</span>");var j=jQuery("<a href='javascript:void(0)' class='ui-jqdialog-titlebar-close ui-corner-all'></a>").hover(function(){j.addClass("ui-state-hover")},function(){j.removeClass("ui-state-hover")}).append("<span class='ui-icon ui-icon-closethick'></span>");jQuery(b).append(j);var g=document.createElement("div");jQuery(g).addClass("ui-jqdialog-content ui-widget-content").attr("id",i.modalcontent);jQuery(g).append(d);h.appendChild(g);jQuery(h).prepend(b);if(l===true){jQuery("body").append(h)}else{jQuery(h).insertBefore(k)}if(typeof a.jqModal==="undefined"){a.jqModal=true}if(jQuery.fn.jqm&&a.jqModal===true){if(a.left==0&&a.top==0){var f=[];f=findPos(m);a.left=f[0]+4;a.top=f[1]+4}}jQuery("a.ui-jqdialog-titlebar-close",b).click(function(o){var n=jQuery("#"+i.themodal).data("onClose")||a.onClose;var p=jQuery("#"+i.themodal).data("gbox")||a.gbox;hideModal("#"+i.themodal,{gb:p,jqm:a.jqModal,onClose:n});return false});if(a.width==0||!a.width){a.width=300}if(a.height==0||!a.height){a.height=200}if(!a.zIndex){a.zIndex=950}jQuery(h).css({top:a.top+"px",left:a.left+"px",width:isNaN(a.width)?"auto":a.width+"px",height:isNaN(a.height)?"auto":a.height+"px",zIndex:a.zIndex,overflow:"hidden"}).attr({tabIndex:"-1",role:"dialog","aria-labelledby":i.modalhead,"aria-hidden":"true"});if(typeof a.drag=="undefined"){a.drag=true}if(typeof a.resize=="undefined"){a.resize=true}if(a.drag){jQuery(b).css("cursor","move");if(jQuery.fn.jqDrag){jQuery(h).jqDrag(b)}else{try{jQuery(h).draggable({handle:jQuery("#"+b.id)})}catch(c){}}}if(a.resize){if(jQuery.fn.jqResize){jQuery(h).append("<div class='jqResize ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se'></div>");jQuery("#"+i.themodal).jqResize(".jqResize",i.scrollelm?"#"+i.scrollelm:false)}else{try{jQuery(h).resizable({handles:"se",alsoResize:i.scrollelm?"#"+i.scrollelm:false})}catch(c){}}}if(a.closeOnEscape===true){jQuery(h).keydown(function(o){if(o.which==27){var n=jQuery("#"+i.themodal).data("onClose")||a.onClose;hideModal(this,{gb:a.gbox,jqm:a.jqModal,onClose:n})}})}};var viewModal=function(a,c){c=jQuery.extend({toTop:true,overlay:10,modal:false,onShow:showModal,onHide:closeModal,gbox:"",jqm:true,jqM:true},c||{});if(jQuery.fn.jqm&&c.jqm==true){if(c.jqM){jQuery(a).attr("aria-hidden","false").jqm(c).jqmShow()}else{jQuery(a).attr("aria-hidden","false").jqmShow()}}else{if(c.gbox!=""){jQuery(".jqgrid-overlay:first",c.gbox).show();jQuery(a).data("gbox",c.gbox)}jQuery(a).show().attr("aria-hidden","false");try{jQuery(":input:visible",a)[0].focus()}catch(b){}}return false};var hideModal=function(a,d){d=jQuery.extend({jqm:true,gb:""},d||{});if(d.onClose){var b=d.onClose(a);if(typeof b=="boolean"&&!b){return}}if(jQuery.fn.jqm&&d.jqm===true){jQuery(a).attr("aria-hidden","true").jqmHide()}else{if(d.gb!=""){try{jQuery(".jqgrid-overlay:first",d.gb).hide()}catch(c){}}jQuery(a).hide().attr("aria-hidden","true")}};function info_dialog(a,d,b){var c="<div id='info_id'>";c+="<div align='center'><br />"+d+"<br /><br />";c+="<input type='button' size='10' id='closedialog' class='jqmClose EditButton' value='"+b+"' />";c+="</div></div>";createModal({themodal:"info_dialog",modalhead:"info_head",modalcontent:"info_content"},c,{width:290,height:120,drag:false,resize:false,caption:"<b>"+a+"</b>",left:250,top:170,closeOnEscape:true},"","",true);jQuery("#closedialog","#info_id").addClass("ui-state-default ui-corner-all").height(21).css({padding:" .2em .5em",cursor:"pointer"}).hover(function(){jQuery(this).addClass("ui-state-hover")},function(){jQuery(this).removeClass("ui-state-hover")});if(jQuery.fn.jqm){}else{jQuery("#closedialog","#info_id").click(function(f){hideModal("#info_dialog");return false})}viewModal("#info_dialog",{onHide:function(e){e.w.hide().remove();if(e.o){e.o.remove()}},modal:true})}function findPos(a){var b=curtop=0;if(a.offsetParent){do{b+=a.offsetLeft;curtop+=a.offsetTop}while(a=a.offsetParent)}return[b,curtop]}function isArray(a){if(a.constructor.toString().indexOf("Array")==-1){return false}else{return true}}function createEl(h,r,f){var g="";if(r.defaultValue){delete r.defaultValue}function o(i,e){if(jQuery.isFunction(e.dataInit)){i.id=e.id;e.dataInit(i);delete e.id;delete e.dataInit}if(e.dataEvents){jQuery.each(e.dataEvents,function(){if(this.data!=null){jQuery(i).bind(this.type,this.data,this.fn)}else{jQuery(i).bind(this.type,this.fn)}});delete e.dataEvents}return e}switch(h){case"textarea":g=document.createElement("textarea");if(!r.cols){jQuery(g).css("width","98%")}if(f=="&nbsp;"||f=="&#160;"||(f.length==1&&f.charCodeAt(0)==160)){f=""}g.value=f;r=o(g,r);jQuery(g).attr(r);break;case"checkbox":g=document.createElement("input");g.type="checkbox";if(!r.value){var p=f.toLowerCase();if(p.search(/(false|0|no|off|undefined)/i)<0&&p!==""){g.checked=true;g.defaultChecked=true;g.value=f}else{g.value="on"}jQuery(g).attr("offval","off")}else{var a=r.value.split(":");if(f===a[0]){g.checked=true;g.defaultChecked=true}g.value=a[0];jQuery(g).attr("offval",a[1]);try{delete r.value}catch(l){}}r=o(g,r);jQuery(g).attr(r);break;case"select":g=document.createElement("select");var q=r.multiple===true?true:false;if(r.dataUrl!=null){jQuery.get(r.dataUrl,{_nsd:(new Date().getTime())},function(s){try{delete r.dataUrl;delete r.value}catch(t){}var i=jQuery(s).html();jQuery(g).append(i);r=o(g,r);if(typeof r.size==="undefined"){r.size=q?3:1}jQuery(g).attr(r);setTimeout(function(){jQuery("option",g).each(function(e){if(jQuery(this).html()==f){this.selected="selected";return false}})},0)},"html")}else{if(r.value){var j=[],k;if(q){j=f.split(",");j=jQuery.map(j,function(e){return jQuery.trim(e)});if(typeof r.size==="undefined"){r.size=3}}else{r.size=1}if(typeof r.value==="string"){var c=r.value.split(";"),n,d;try{delete r.value}catch(l){}r=o(g,r);jQuery(g).attr(r);for(k=0;k<c.length;k++){n=c[k].split(":");d=document.createElement("option");d.value=n[0];d.innerHTML=n[1];if(!q&&n[1]==f){d.selected="selected"}if(q&&jQuery.inArray(jQuery.trim(n[1]),j)>-1){d.selected="selected"}g.appendChild(d)}}else{if(typeof r.value==="object"){var b=r.value;try{delete r.value}catch(l){}r=o(g,r);jQuery(g).attr(r);k=0;for(var m in b){k++;d=document.createElement("option");d.value=m;d.innerHTML=b[m];if(!q&&b[m]==f){d.selected="selected"}if(q&&jQuery.inArray(jQuery.trim(b[m]),j)>-1){d.selected="selected"}g.appendChild(d)}}}}}break;case"text":case"password":case"button":g=document.createElement("input");g.type=h;g.value=jQuery.jgrid.htmlDecode(f);r=o(g,r);if(!r.size){jQuery(g).css({width:"98%"})}jQuery(g).attr(r);break;case"image":case"file":g=document.createElement("input");g.type=h;r=o(g,r);jQuery(g).attr(r);break}return g}function checkValues(c,l,j){var f,h,m;if(typeof(l)=="string"){for(h=0,len=j.p.colModel.length;h<len;h++){if(j.p.colModel[h].name==l){f=j.p.colModel[h].editrules;l=h;try{m=j.p.colModel[h].formoptions.label}catch(k){}break}}}else{if(l>=0){var f=j.p.colModel[l].editrules}}if(f){if(!m){m=j.p.colNames[l]}if(f.required===true){if(c.match(/^s+$/)||c==""){return[false,m+": "+jQuery.jgrid.edit.msg.required,""]}}var d=f.required===false?false:true;if(f.number===true){if(!(d===false&&isEmpty(c))){if(isNaN(c)){return[false,m+": "+jQuery.jgrid.edit.msg.number,""]}}}if(f.minValue&&!isNaN(f.minValue)){if(parseFloat(c)<parseFloat(f.minValue)){return[false,m+": "+jQuery.jgrid.edit.msg.minValue+" "+f.minValue,""]}}if(f.maxValue&&!isNaN(f.maxValue)){if(parseFloat(c)>parseFloat(f.maxValue)){return[false,m+": "+jQuery.jgrid.edit.msg.maxValue+" "+f.maxValue,""]}}var a;if(f.email===true){if(!(d===false&&isEmpty(c))){a=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;if(!a.test(c)){return[false,m+": "+jQuery.jgrid.edit.msg.email,""]}}}if(f.integer===true){if(!(d===false&&isEmpty(c))){if(isNaN(c)){return[false,m+": "+jQuery.jgrid.edit.msg.integer,""]}if((c%1!=0)||(c.indexOf(".")!=-1)){return[false,m+": "+jQuery.jgrid.edit.msg.integer,""]}}}if(f.date===true){if(!(d===false&&isEmpty(c))){var b=j.p.colModel[l].datefmt||"Y-m-d";if(!checkDate(b,c)){return[false,m+": "+jQuery.jgrid.edit.msg.date+" - "+b,""]}}}if(f.url===true){if(!(d===false&&isEmpty(c))){a=/^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;if(!a.test(c)){return[false,m+": "+jQuery.jgrid.edit.msg.url,""]}}}}return[true,"",""]}function checkDate(l,c){var e={},n;l=l.toLowerCase();if(l.indexOf("/")!=-1){n="/"}else{if(l.indexOf("-")!=-1){n="-"}else{if(l.indexOf(".")!=-1){n="."}else{n="/"}}}l=l.split(n);c=c.split(n);if(c.length!=3){return false}var f=-1,m,g=-1,d=-1;for(var h=0;h<l.length;h++){var b=isNaN(c[h])?0:parseInt(c[h],10);e[l[h]]=b;m=l[h];if(m.indexOf("y")!=-1){f=h}if(m.indexOf("m")!=-1){d=h}if(m.indexOf("d")!=-1){g=h}}if(l[f]=="y"||l[f]=="yyyy"){m=4}else{if(l[f]=="yy"){m=2}else{m=-1}}var a=DaysArray(12);var k;if(f===-1){return false}else{k=e[l[f]].toString();if(m==2&&k.length==1){m=1}if(k.length!=m||e[l[f]]==0){return false}}if(d===-1){return false}else{k=e[l[d]].toString();if(k.length<1||e[l[d]]<1||e[l[d]]>12){return false}}if(g===-1){return false}else{k=e[l[g]].toString();if(k.length<1||e[l[g]]<1||e[l[g]]>31||(e[l[d]]==2&&e[l[g]]>daysInFebruary(e[l[f]]))||e[l[g]]>a[e[l[d]]]){return false}}return true}function daysInFebruary(a){return(((a%4==0)&&((!(a%100==0))||(a%400==0)))?29:28)}function DaysArray(b){for(var a=1;a<=b;a++){this[a]=31;if(a==4||a==6||a==9||a==11){this[a]=30}if(a==2){this[a]=29}}return this}function isEmpty(a){if(a.match(/^s+$/)||a==""){return true}else{return false}};(function(b){var a=null;b.fn.extend({searchGrid:function(c){c=b.extend({recreateFilter:false,drag:true,sField:"searchField",sValue:"searchString",sOper:"searchOper",sFilter:"filters",beforeShowSearch:null,afterShowSearch:null,onInitializeSearch:null,closeAfterSearch:false,closeOnEscape:false,multipleSearch:false,sopt:null,onClose:null},b.jgrid.search,c||{});return this.each(function(){var l=this;if(!l.grid){return}if(b.fn.searchFilter){var g="fbox_"+l.p.id;if(c.recreateFilter===true){b("#"+g).remove()}if(b("#"+g).html()!=null){if(b.isFunction(c.beforeShowSearch)){c.beforeShowSearch(b("#"+g))}f();if(b.isFunction(c.afterShowSearch)){c.afterShowSearch(b("#"+g))}}else{var n=[],u=jQuery("#"+l.p.id).getGridParam("colNames"),r=jQuery("#"+l.p.id).getGridParam("colModel"),t=["eq","ne","lt","le","gt","ge","bw","bn","in","ni","ew","en","cn","nc"],i,q,h;b.each(r,function(x,C){var z=(typeof C.search==="undefined")?true:C.search,y=(C.hidden===true),k=b.extend({},{text:u[x],value:C.index||C.name},this.searchoptions),w=(k.searchhidden===true)||true;if(typeof k.sopt=="undefined"){k.sopt=t}h=0;k.ops=[];for(i=0;i<k.sopt.length;i++){if((q=b.inArray(k.sopt[i],t))!=-1){k.ops[h]={op:k.sopt[i],text:c.odata[q]};h++}}if(typeof(this.stype)==="undefined"){this.stype="text"}if(this.stype=="select"){if(k.dataUrl!=null){}else{if(this.editoptions){var j=this.editoptions.value;if(j){k.dataValues=[];if(typeof(j)==="string"){var e=j.split(";"),B;for(i=0;i<e.length;i++){B=e[i].split(":");k.dataValues[i]={value:B[0],text:B[1]}}}else{if(typeof(j)==="object"){i=0;for(var A in j){k.dataValues[i]={value:A,text:j[A]};i++}}}}}}}if((w&&z)||(z&&!y)){n.push(k)}});if(n.length>0){var p=jQuery.fn.searchFilter.defaults.operators;if(c.sopt!=null){p=[];h=0;for(i=0;c.sopt.length<0;i++){if((q=b.inArray(c.sopt[i],t))!=-1){p[h]={op:c.sopt[i],text:c.odata[q]};h++}}}b("<div id='"+g+"' role='dialog' tabindex='-1'></div>").insertBefore("#gview_"+l.p.id);jQuery("#"+g).searchFilter(n,{groupOps:c.groupOps,operators:p,onClose:d,resetText:c.Reset,searchText:c.Find,windowTitle:c.caption,rulesText:c.rulesText,matchText:c.matchText,onSearch:s,onReset:m,stringResult:c.multipleSearch});b(".ui-widget-overlay","#"+g).remove();if(c.drag===true){b("#"+g+" table thead tr:first td:first").css("cursor","move");if(jQuery.fn.jqDrag){jQuery("#"+g).jqDrag(b("#"+g+" table thead tr:first td:first"))}else{try{b("#"+g).draggable({handle:jQuery("#"+g+" table thead tr:first td:first")})}catch(o){}}}if(c.multipleSearch===false){b(".ui-del, .ui-add, .ui-del, .ui-add-last, .matchText, .rulesText","#"+g).remove();b("select[name='groupOp']","#"+g).hide()}if(b.isFunction(c.onInitializeSearch)){c.onInitializeSearch(b("#"+g))}if(b.isFunction(c.beforeShowSearch)){c.beforeShowSearch(b("#"+g))}f();if(b.isFunction(c.afterShowSearch)){c.afterShowSearch(b("#"+g))}if(c.closeOnEscape===true){jQuery("#"+g).keydown(function(j){if(j.which==27){d(b("#"+g))}})}}}}function s(v){var e=(v!==undefined),k=jQuery("#"+l.p.id),j=[];if(c.multipleSearch===false){j[c.sField]=v.rules[0].field;j[c.sValue]=v.rules[0].data;j[c.sOper]=v.rules[0].op}else{j[c.sFilter]=v}k[0].p.search=e;k[0].p.searchdata=j;k[0].p.page=1;k.trigger("reloadGrid");if(c.closeAfterSearch){d(b("#"+g))}}function m(v){var e=(v!==undefined),k=jQuery("#"+l.p.id),j=[];k[0].p.search=e;if(c.multipleSearch===false){j[c.sField]=j[c.sValue]=j[c.sOper]=""}else{j[c.sFilter]=""}k[0].p.searchdata=j;k[0].p.page=1;k.trigger("reloadGrid")}function d(e){if(c.onClose){var j=c.onClose(e);if(typeof j=="boolean"&&!j){return}}e.hide();b(".jqgrid-overlay","#gbox_"+l.p.id).hide()}function f(){b("#"+g).show();b(".jqgrid-overlay","#gbox_"+l.p.id).show();try{b(":input:visible","#"+g)[0].focus()}catch(e){}}})},editGridRow:function(c,d){d=b.extend({top:0,left:0,width:300,height:"auto",dataheight:"auto",modal:false,drag:true,resize:true,url:null,mtype:"POST",closeAfterAdd:false,closeAfterEdit:false,reloadAfterSubmit:true,onInitializeForm:null,beforeInitData:null,beforeShowForm:null,afterShowForm:null,beforeSubmit:null,afterSubmit:null,onclickSubmit:null,afterComplete:null,onclickPgButtons:null,afterclickPgButtons:null,editData:{},recreateForm:false,jqModal:true,closeOnEscape:false,addedrow:"first",topinfo:"",bottominfo:"",saveicon:[],closeicon:[],savekey:[false,13],navkeys:[false,38,40],checkOnSubmit:false,checkOnUpdate:false,_savedData:{},onClose:null},b.jgrid.edit,d||{});a=d;return this.each(function(){var e=this;if(!e.grid||!c){return}var B=e.p.id,x="FrmGrid_"+B,t="TblGrid_"+B,h={themodal:"editmod"+B,modalhead:"edithd"+B,modalcontent:"editcnt"+B,scrollelm:x},C=b.isFunction(a.beforeShowForm)?a.beforeShowForm:false,N=b.isFunction(a.afterShowForm)?a.afterShowForm:false,M=b.isFunction(a.beforeInitData)?a.beforeInitData:false,n=b.isFunction(a.onInitializeForm)?a.onInitializeForm:false,H=null,I=1,p=0,u,D,E,Q,G,A;if(c=="new"){c="_empty";d.caption=d.addCaption}else{d.caption=d.editCaption}if(d.recreateForm===true&&b("#"+h.themodal).html()!=null){b("#"+h.themodal).remove()}var j=true;if(d.checkOnUpdate&&d.jqModal&&!d.modal){j=false}if(b("#"+h.themodal).html()!=null){b(".ui-jqdialog-title","#"+h.modalhead).html(d.caption);b("#FormError","#"+t).hide();if(M){M(b("#"+x))}m(c,e,x);if(c=="_empty"){b("#pData, #nData","#"+t+"_2").hide()}else{b("#pData, #nData","#"+t+"_2").show()}if(d.processing===true){d.processing=false;b("#sData","#"+t).removeClass("ui-state-active")}if(b("#"+x).data("disabled")===true){b(".confirm","#"+h.themodal).hide();b("#"+x).data("disabled",false)}if(C){C(b("#"+x))}b("#"+h.themodal).data("onClose",a.onClose);viewModal("#"+h.themodal,{gbox:"#gbox_"+B,jqm:d.jqModal,jqM:false,closeoverlay:j,modal:d.modal});if(!j){b(".jqmOverlay").click(function(){if(!f()){return false}hideModal("#"+h.themodal,{gb:"#gbox_"+B,jqm:d.jqModal,onClose:a.onClose});return false})}if(N){N(b("#"+x))}}else{b(e.p.colModel).each(function(V){var W=this.formoptions;I=Math.max(I,W?W.colpos||0:0);p=Math.max(p,W?W.rowpos||0:0)});var q=isNaN(d.dataheight)?d.dataheight:d.dataheight+"px";var L,S=b("<form name='FormPost' id='"+x+"' class='FormGrid' style='width:100%;overflow:auto;position:relative;height:"+q+";'></form>").data("disabled",false),z=b("<table id='"+t+"' class='EditTable' cellspacing='0' cellpading='0' border='0'><tbody></tbody></table>");b(S).append(z);L=b("<tr id='FormError' style='display:none'><td class='ui-state-error' colspan='"+(I*2)+"'></td></tr>");L[0].rp=0;b(z).append(L);if(a.topinfo){L=b("<tr><td class='topinfo' colspan='"+(I*2)+"'>"+a.topinfo+"</td></tr>");L[0].rp=0;b(z).append(L)}if(M){M(b("#"+x))}var y=r(c,e,z,I),k="<a href='javascript:void(0)' id='pData' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></div>",l="<a href='javascript:void(0)' id='nData' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></div>",g="<a href='javascript:void(0)' id='sData' class='fm-button ui-state-default ui-corner-all'>"+d.bSubmit+"</a>",s="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+d.bCancel+"</a>";var P="<table border='0' class='EditTable' id='"+t+"_2'><tbody><tr id='Act_Buttons'><td class='navButton ui-widget-content'>"+k+l+"</td><td class='EditButton ui-widget-content'>"+g+"&nbsp;"+s+"</td></tr>";if(a.bottominfo){P+="<tr><td class='bottominfo' colspan='2'>"+a.bottominfo+"</td></tr>"}P+="</tbody></table>";if(p>0){var w=[];b.each(b(z)[0].rows,function(V,W){w[V]=W});w.sort(function(W,V){if(W.rp>V.rp){return 1}if(W.rp<V.rp){return -1}return 0});b.each(w,function(V,W){b("tbody",z).append(W)})}d.gbox="#gbox_"+B;var o=false;if(d.closeOnEscape===true){d.closeOnEscape=false;o=true}var O=b("<span></span>").append(S).append(P);createModal(h,O,d,"#gview_"+e.p.id,b("#gview_"+e.p.id)[0]);O=null;P=null;jQuery("#"+h.themodal).keydown(function(V){if(b("#"+x).data("disabled")===true){return false}if(a.savekey[0]===true&&V.which==a.savekey[1]){b("#sData","#"+t+"_2").trigger("click");return false}if(V.which===27){if(!f()){return false}if(o){hideModal(this,{gb:d.gbox,jqm:d.jqModal,onClose:a.onClose})}return false}if(a.navkeys[0]===true){if(b("#id_g","#"+t).val()=="_empty"){return true}if(V.which==a.navkeys[1]){b("#pData","#"+t+"_2").trigger("click");return false}if(V.which==a.navkeys[2]){b("#nData","#"+t+"_2").trigger("click");return false}}});if(d.checkOnUpdate){b("a.ui-jqdialog-titlebar-close span","#"+h.themodal).removeClass("jqmClose");b("a.ui-jqdialog-titlebar-close","#"+h.themodal).unbind("click").click(function(){if(!f()){return false}hideModal("#"+h.themodal,{gb:"#gbox_"+B,jqm:d.jqModal,onClose:a.onClose});return false})}d.saveicon=b.extend([true,"left","ui-icon-disk"],d.saveicon);d.closeicon=b.extend([true,"left","ui-icon-close"],d.closeicon);if(d.saveicon[0]==true){b("#sData","#"+t+"_2").addClass(d.saveicon[1]=="right"?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+d.saveicon[2]+"'></span>")}if(d.closeicon[0]==true){b("#cData","#"+t+"_2").addClass(d.closeicon[1]=="right"?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+d.closeicon[2]+"'></span>")}if(a.checkOnSubmit||a.checkOnUpdate){g="<a href='javascript:void(0)' id='sNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+d.bYes+"</a>";l="<a href='javascript:void(0)' id='nNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+d.bNo+"</a>";s="<a href='javascript:void(0)' id='cNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+d.bExit+"</a>";var F,v=d.zIndex||999;v++;if(b.browser.msie&&b.browser.version==6){F='<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>'}else{F=""}b("<div class='ui-widget-overlay jqgrid-overlay confirm' style='z-index:"+v+";display:none;'>&nbsp;"+F+"</div><div class='confirm ui-widget-content ui-jqconfirm' style='z-index:"+(v+1)+"'>"+d.saveData+"<br/><br/>"+g+l+s+"</div>").insertAfter("#"+x);b("#sNew","#"+h.themodal).click(function(){i([true,"",""]);b("#"+x).data("disabled",false);b(".confirm","#"+h.themodal).hide();return false});b("#nNew","#"+h.themodal).click(function(){b(".confirm","#"+h.themodal).hide();b("#"+x).data("disabled",false);setTimeout(function(){b(":input","#"+x)[0].focus()},0);return false});b("#cNew","#"+h.themodal).click(function(){b(".confirm","#"+h.themodal).hide();b("#"+x).data("disabled",false);hideModal("#"+h.themodal,{gb:"#gbox_"+B,jqm:d.jqModal,onClose:a.onClose});return false})}if(n){n(b("#"+x))}if(c=="_empty"){b("#pData,#nData","#"+t+"_2").hide()}else{b("#pData,#nData","#"+t+"_2").show()}if(C){C(b("#"+x))}b("#"+h.themodal).data("onClose",a.onClose);viewModal("#"+h.themodal,{gbox:"#gbox_"+B,jqm:d.jqModal,closeoverlay:j,modal:d.modal});if(!j){b(".jqmOverlay").click(function(){if(!f()){return false}hideModal("#"+h.themodal,{gb:"#gbox_"+B,jqm:d.jqModal,onClose:a.onClose});return false})}if(N){N(b("#"+x))}b(".fm-button","#"+h.themodal).hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});b("#sData","#"+t+"_2").click(function(V){D={};Q={};b("#FormError","#"+t).hide();T();if(D.id=="_empty"){i()}else{if(d.checkOnSubmit===true){G=b.extend({},D,Q);A=J(G,a._savedData);if(A){b("#"+x).data("disabled",true);b(".confirm","#"+h.themodal).show()}else{i()}}else{i()}}return false});b("#cData","#"+t+"_2").click(function(V){if(!f()){return false}hideModal("#"+h.themodal,{gb:"#gbox_"+B,jqm:d.jqModal,onClose:a.onClose});return false});b("#nData","#"+t+"_2").click(function(V){if(!f()){return false}b("#FormError","#"+t).hide();var W=U();W[0]=parseInt(W[0]);if(W[0]!=-1&&W[1][W[0]+1]){if(b.isFunction(d.onclickPgButtons)){d.onclickPgButtons("next",b("#"+x),W[1][W[0]])}m(W[1][W[0]+1],e,x);b(e).setSelection(W[1][W[0]+1]);if(b.isFunction(d.afterclickPgButtons)){d.afterclickPgButtons("next",b("#"+x),W[1][W[0]+1])}K(W[0]+1,W[1].length-1)}return false});b("#pData","#"+t+"_2").click(function(W){if(!f()){return false}b("#FormError","#"+t).hide();var V=U();if(V[0]!=-1&&V[1][V[0]-1]){if(b.isFunction(d.onclickPgButtons)){d.onclickPgButtons("prev",b("#"+x),V[1][V[0]])}m(V[1][V[0]-1],e,x);b(e).setSelection(V[1][V[0]-1]);if(b.isFunction(d.afterclickPgButtons)){d.afterclickPgButtons("prev",b("#"+x),V[1][V[0]-1])}K(V[0]-1,V[1].length-1)}return false})}var R=U();K(R[0],R[1].length-1);function K(W,X,V){if(W==0){b("#pData","#"+t+"_2").addClass("ui-state-disabled")}else{b("#pData","#"+t+"_2").removeClass("ui-state-disabled")}if(W==X){b("#nData","#"+t+"_2").addClass("ui-state-disabled")}else{b("#nData","#"+t+"_2").removeClass("ui-state-disabled")}}function U(){var W=b(e).getDataIDs(),V=b("#id_g","#"+t).val(),X=b.inArray(V,W);return[X,W]}function f(){var V=true;b("#FormError","#"+t).hide();if(a.checkOnUpdate){D={};Q={};T();G=b.extend({},D,Q);A=J(G,a._savedData);if(A){b("#"+x).data("disabled",true);b(".confirm","#"+h.themodal).show();V=false}}return V}function T(){b(".FormElement","#"+t).each(function(W){switch(b(this).get(0).type){case"checkbox":if(b(this).attr("checked")){D[this.name]=b(this).val()}else{var V=b(this).attr("offval");D[this.name]=V;Q[this.name]=V}break;case"select-one":D[this.name]=b("option:selected",this).val();Q[this.name]=b("option:selected",this).text();break;case"select-multiple":D[this.name]=b(this).val();if(D[this.name]){D[this.name]=D[this.name].join(",")}else{D[this.name]=""}var X=[];b("option:selected",this).each(function(Y,Z){X[Y]=b(Z).text()});Q[this.name]=X.join(",");break;case"password":case"text":case"textarea":case"button":D[this.name]=b(this).val();D[this.name]=!e.p.autoencode?D[this.name]:b.jgrid.htmlEncode(D[this.name]);break}});return true}function r(Y,ae,ab,aj){var V,W,ag,ah=0,al,am,af,ak=[],ac=false,ad,X,Z="<td class='CaptionTD ui-widget-content'>&nbsp;</td><td class='DataTD ui-widget-content' style='white-space:pre'>&nbsp;</td>",aa="";for(var ai=1;ai<=aj;ai++){aa+=Z}if(Y!="_empty"){ac=b(ae).getInd(Y)}b(ae.p.colModel).each(function(aq){V=this.name;if(this.editrules&&this.editrules.edithidden==true){W=false}else{W=this.hidden===true?true:false}am=W?"style='display:none'":"";if(V!=="cb"&&V!=="subgrid"&&this.editable===true&&V!=="rn"){if(ac===false){al=""}else{if(V==ae.p.ExpandColumn&&ae.p.treeGrid===true){al=b("td:eq("+aq+")",ae.rows[ac]).text()}else{try{al=b.unformat(b("td:eq("+aq+")",ae.rows[ac]),{colModel:this},aq)}catch(ao){al=b("td:eq("+aq+")",ae.rows[ac]).html()}}}var ap=b.extend({},this.editoptions||{},{id:V,name:V});frmopt=b.extend({},{elmprefix:"",elmsuffix:"",rowabove:false,rowcontent:""},this.formoptions||{}),ad=parseInt(frmopt.rowpos)||ah+1,X=parseInt((parseInt(frmopt.colpos)||1)*2);if(Y=="_empty"&&ap.defaultValue){al=b.isFunction(ap.defaultValue)?ap.defaultValue():ap.defaultValue}if(!this.edittype){this.edittype="text"}af=createEl(this.edittype,ap,al);if(al==""&&this.edittype=="checkbox"){al=b(af).attr("offval")}if(a.checkOnSubmit||a.checkOnUpdate){a._savedData[V]=al}b(af).addClass("FormElement");ag=b(ab).find("tr[rowpos="+ad+"]");if(frmopt.rowabove){var ar=b("<tr><td class='contentinfo' colspan='"+(aj*2)+"'>"+frmopt.rowcontent+"</td></tr>");b(ab).append(ar);ar[0].rp=ad}if(ag.length==0){ag=b("<tr "+am+" rowpos='"+ad+"'></tr>").addClass("FormData").attr("id","tr_"+V);b(ag).append(aa);b(ab).append(ag);ag[0].rp=ad}b("td:eq("+(X-2)+")",ag[0]).html(typeof frmopt.label==="undefined"?ae.p.colNames[aq]:frmopt.label);b("td:eq("+(X-1)+")",ag[0]).append(frmopt.elmprefix).append(af).append(frmopt.elmsuffix);ak[ah]=aq;ah++}});if(ah>0){var an=b("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+(aj*2-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='"+Y+"'/></td></tr>");an[0].rp=ah+999;b(ab).append(an);if(a.checkOnSubmit||a.checkOnUpdate){a._savedData.id=Y}}return ak}function m(W,ab,X){var af,ad,Y=0,ac,aa,V,Z,ae;if(a.checkOnSubmit||a.checkOnUpdate){a._savedData={};a._savedData.id=W}if(W=="_empty"){b(ab.p.colModel).each(function(ag){af=this.name.replace(".","\\.");V=b.extend({},this.editoptions||{});aa=b("#"+af,"#"+X);if(aa[0]!=null){Z="";if(V.defaultValue){Z=b.isFunction(V.defaultValue)?V.defaultValue():V.defaultValue;if(aa[0].type=="checkbox"){ae=Z.toLowerCase();if(ae.search(/(false|0|no|off|undefined)/i)<0&&ae!==""){aa[0].checked=true;aa[0].defaultChecked=true;aa[0].value=Z}else{aa.attr({checked:"",defaultChecked:""})}}else{aa.val(Z)}}else{if(aa[0].type=="checkbox"){aa[0].checked=false;aa[0].defaultChecked=false;Z=b(aa).attr("offval")}else{aa.val(Z)}}if(a.checkOnSubmit===true||a.checkOnUpdate){a._savedData[af]=Z}}});b("#id_g","#"+X).val("_empty");return}b("table:first tr#"+W+" td",ab.grid.bDiv).each(function(ah){af=ab.p.colModel[ah].name.replace(".","\\.");if(ab.p.colModel[ah].editrules&&ab.p.colModel[ah].editrules.edithidden===true){ad=false}else{ad=ab.p.colModel[ah].hidden===true?true:false}if(af!=="cb"&&af!=="subgrid"&&ab.p.colModel[ah].editable===true){if(af==ab.p.ExpandColumn&&ab.p.treeGrid===true){ac=b(this).text()}else{try{ac=b.unformat(this,{colModel:ab.p.colModel[ah]},ah)}catch(ag){ac=b(this).html()}}if(a.checkOnSubmit===true||a.checkOnUpdate){a._savedData[af]=ac}switch(ab.p.colModel[ah].edittype){case"password":case"text":case"button":case"image":ac=b.jgrid.htmlDecode(ac);b("#"+af,"#"+X).val(ac);break;case"textarea":if(ac=="&nbsp;"||ac=="&#160;"||(ac.length==1&&ac.charCodeAt(0)==160)){ac=""}b("#"+af,"#"+X).val(ac);break;case"select":ac=b.jgrid.htmlDecode(ac);b("#"+af+" option","#"+X).each(function(ai){if(!ab.p.colModel[ah].editoptions.multiple&&ac==b(this).text()){this.selected=true}else{if(ab.p.colModel[ah].editoptions.multiple){if(b.inArray(b(this).text(),ac.split(","))>-1){this.selected=true}else{this.selected=false}}else{this.selected=false}}});break;case"checkbox":ac=ac.toLowerCase();if(ac.search(/(false|0|no|off|undefined)/i)<0&&ac!==""){b("#"+af,"#"+X).attr("checked",true);b("#"+af,"#"+X).attr("defaultChecked",true)}else{b("#"+af,"#"+X).attr("checked",false);b("#"+af,"#"+X).attr("defaultChecked","")}break}Y++}});if(Y>0){b("#id_g","#"+t).val(W)}return Y}function i(){var Y,W=[true,"",""],V={};for(var X in D){W=checkValues(D[X],X,e);if(W[0]==false){break}}if(W[0]){if(b.isFunction(a.onclickSubmit)){V=a.onclickSubmit(a)||{}}if(b.isFunction(a.beforeSubmit)){W=a.beforeSubmit(D,b("#"+x))}}u=a.url?a.url:e.p.editurl;if(W[0]){if(!u){W[0]=false;W[1]+=" "+b.jgrid.errors.nourl}}if(W[0]===false){b("#FormError>td","#"+t).html(W[1]);b("#FormError","#"+t).show();return}if(!d.processing){d.processing=true;b("#sData","#"+t+"_2").addClass("ui-state-active");D.oper=D.id=="_empty"?"add":"edit";D=b.extend(D,a.editData,V);b.ajax({url:u,type:a.mtype,data:D,complete:function(aa,Z){if(Z!="success"){W[0]=false;W[1]=Z+" Status: "+aa.statusText+" Error code: "+aa.status}else{if(b.isFunction(a.afterSubmit)){W=a.afterSubmit(aa,D)}}if(W[0]===false){b("#FormError>td","#"+t).html(W[1]);b("#FormError","#"+t).show()}else{D=b.extend(D,Q);if(D.id=="_empty"){if(!W[2]){W[2]=parseInt(e.p.records)+1}D.id=W[2];if(a.closeAfterAdd){if(a.reloadAfterSubmit){b(e).trigger("reloadGrid")}else{b(e).addRowData(W[2],D,d.addedrow);b(e).setSelection(W[2])}hideModal("#"+h.themodal,{gb:"#gbox_"+B,jqm:d.jqModal,onClose:a.onClose})}else{if(a.clearAfterAdd){if(a.reloadAfterSubmit){b(e).trigger("reloadGrid")}else{b(e).addRowData(W[2],D,d.addedrow)}m("_empty",e,x)}else{if(a.reloadAfterSubmit){b(e).trigger("reloadGrid")}else{b(e).addRowData(W[2],D,d.addedrow)}}}}else{if(a.reloadAfterSubmit){b(e).trigger("reloadGrid");if(!a.closeAfterEdit){b(e).setSelection(D.id)}}else{if(e.p.treeGrid===true){b(e).setTreeRow(D.id,D)}else{b(e).setRowData(D.id,D)}}if(a.closeAfterEdit){hideModal("#"+h.themodal,{gb:"#gbox_"+B,jqm:d.jqModal,onClose:a.onClose})}}if(b.isFunction(a.afterComplete)){Y=aa;setTimeout(function(){a.afterComplete(Y,D,b("#"+x));Y=null},500)}}d.processing=false;if(a.checkOnSubmit||a.checkOnUpdate){b("#"+x).data("disabled",false);if(a._savedData.id!="_empty"){a._savedData=D}}b("#sData","#"+t+"_2").removeClass("ui-state-active");try{b(":input:visible","#"+x)[0].focus()}catch(ab){}},error:function(ab,Z,aa){b("#FormError>td","#"+t).html(Z+" : "+aa);b("#FormError","#"+t).show();d.processing=false;b("#"+x).data("disabled",false);b("#sData","#"+t+"_2").removeClass("ui-state-active")}})}}function J(Y,V){var W=false,X;for(X in Y){if(Y[X]!=V[X]){W=true;break}}return W}})},viewGridRow:function(c,d){d=b.extend({top:0,left:0,width:0,height:"auto",dataheight:"auto",modal:false,drag:true,resize:true,jqModal:true,closeOnEscape:false,labelswidth:"30%",closeicon:[],navkeys:[false,38,40],onClose:null},b.jgrid.view,d||{});return this.each(function(){var w=this;if(!w.grid||!c){return}if(!d.imgpath){d.imgpath=w.p.imgpath}var q=w.p.id,y="ViewGrid_"+q,r="ViewTbl_"+q,i={themodal:"viewmod"+q,modalhead:"viewhd"+q,modalcontent:"viewcnt"+q,scrollelm:y},g=1,e=0;if(b("#"+i.themodal).html()!=null){b(".ui-jqdialog-title","#"+i.modalhead).html(d.caption);b("#FormError","#"+r).hide();l(c,w);viewModal("#"+i.themodal,{gbox:"#gbox_"+q,jqm:d.jqModal,jqM:false,modal:d.modal});j()}else{b(w.p.colModel).each(function(C){var D=this.formoptions;g=Math.max(g,D?D.colpos||0:0);e=Math.max(e,D?D.rowpos||0:0)});var x=isNaN(d.dataheight)?d.dataheight:d.dataheight+"px";var v,A=b("<form name='FormPost' id='"+y+"' class='FormGrid' style='width:100%;overflow:auto;position:relative;height:"+x+";'></form>"),k=b("<table id='"+r+"' class='EditTable' cellspacing='1' cellpading='2' border='0' style='table-layout:fixed'><tbody></tbody></table>");b(A).append(k);var u=m(c,w,k,g),s="<a href='javascript:void(0)' id='pData' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></div>",t="<a href='javascript:void(0)' id='nData' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></div>",B="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+d.bClose+"</a>";if(e>0){var f=[];b.each(b(k)[0].rows,function(C,D){f[C]=D});f.sort(function(D,C){if(D.rp>C.rp){return 1}if(D.rp<C.rp){return -1}return 0});b.each(f,function(C,D){b("tbody",k).append(D)})}d.gbox="#gbox_"+q;var p=false;if(d.closeOnEscape===true){d.closeOnEscape=false;p=true}var z=b("<span></span>").append(A).append("<table border='0' class='EditTable' id='"+r+"_2'><tbody><tr id='Act_Buttons'><td class='navButton ui-widget-content' width='"+d.labelswidth+"'>"+s+t+"</td><td class='EditButton ui-widget-content'>"+B+"</td></tr></tbody></table>");createModal(i,z,d,"#gview_"+w.p.id,b("#gview_"+w.p.id)[0]);z=null;jQuery("#"+i.themodal).keydown(function(C){if(C.which===27){if(p){hideModal(this,{gb:d.gbox,jqm:d.jqModal,onClose:d.onClose})}return false}if(d.navkeys[0]===true){if(C.which===d.navkeys[1]){b("#pData","#"+r+"_2").trigger("click");return false}if(C.which===d.navkeys[2]){b("#nData","#"+r+"_2").trigger("click");return false}}});d.closeicon=b.extend([true,"left","ui-icon-close"],d.closeicon);if(d.closeicon[0]==true){b("#cData","#"+r+"_2").addClass(d.closeicon[1]=="right"?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+d.closeicon[2]+"'></span>")}viewModal("#"+i.themodal,{gbox:"#gbox_"+q,jqm:d.jqModal,modal:d.modal});b(".fm-button:not(.ui-state-disabled)","#"+r+"_2").hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});j();b("#cData","#"+r+"_2").click(function(C){hideModal("#"+i.themodal,{gb:"#gbox_"+q,jqm:d.jqModal,onClose:d.onClose});return false});b("#nData","#"+r+"_2").click(function(C){b("#FormError","#"+r).hide();var D=h();D[0]=parseInt(D[0]);if(D[0]!=-1&&D[1][D[0]+1]){if(b.isFunction(d.onclickPgButtons)){d.onclickPgButtons("next",b("#"+y),D[1][D[0]])}l(D[1][D[0]+1],w);b(w).setSelection(D[1][D[0]+1]);if(b.isFunction(d.afterclickPgButtons)){d.afterclickPgButtons("next",b("#"+y),D[1][D[0]+1])}n(D[0]+1,D[1].length-1)}j();return false});b("#pData","#"+r+"_2").click(function(D){b("#FormError","#"+r).hide();var C=h();if(C[0]!=-1&&C[1][C[0]-1]){if(b.isFunction(d.onclickPgButtons)){d.onclickPgButtons("prev",b("#"+y),C[1][C[0]])}l(C[1][C[0]-1],w);b(w).setSelection(C[1][C[0]-1]);if(b.isFunction(d.afterclickPgButtons)){d.afterclickPgButtons("prev",b("#"+y),C[1][C[0]-1])}n(C[0]-1,C[1].length-1)}j();return false})}function j(){if(d.closeOnEscape===true||d.navkeys[0]===true){setTimeout(function(){b(".ui-jqdialog-titlebar-close","#"+i.modalhead).focus()},0)}}var o=h();n(o[0],o[1].length-1);function n(D,E,C){if(D==0){b("#pData","#"+r+"_2").addClass("ui-state-disabled")}else{b("#pData","#"+r+"_2").removeClass("ui-state-disabled")}if(D==E){b("#nData","#"+r+"_2").addClass("ui-state-disabled")}else{b("#nData","#"+r+"_2").removeClass("ui-state-disabled")}}function h(){var D=b(w).getDataIDs(),C=b("#id_g","#"+r).val(),E=b.inArray(C,D);return[E,D]}function m(I,O,M,U){var E,H,P,X,C,S=0,W,Y,V=[],N=false,K="<td class='CaptionTD ui-widget-content' width='"+d.labelswidth+"'>&nbsp;</td><td class='DataTD ui-helper-reset ui-widget-content' style='white-space:pre;'>&nbsp;</td>",L="",F="<td class='CaptionTD ui-widget-content'>&nbsp;</td><td class='DataTD ui-widget-content' style='white-space:pre;'>&nbsp;</td>",J=["integer","number","currency"],R=0,Q=0,G,D;for(var T=1;T<=U;T++){L+=T==1?K:F}b(O.p.colModel).each(function(aa){if(this.editrules&&this.editrules.edithidden===true){H=false}else{H=this.hidden===true?true:false}if(!H&&this.align==="right"){if(this.formatter&&b.inArray(this.formatter,J)!==-1){R=Math.max(R,parseInt(this.width,10))}else{Q=Math.max(Q,parseInt(this.width,10))}}});G=R!==0?R:Q!==0?Q:0;N=b(O).getInd(I);b(O.p.colModel).each(function(ab){E=this.name;D=false;if(this.editrules&&this.editrules.edithidden===true){H=false}else{H=this.hidden===true?true:false}Y=H?"style='display:none'":"";if(E!=="cb"&&E!=="subgrid"&&this.editable===true){if(N===false){W=""}else{if(E==O.p.ExpandColumn&&O.p.treeGrid===true){W=b("td:eq("+ab+")",O.rows[N]).text()}else{W=b("td:eq("+ab+")",O.rows[N]).html()}}D=this.align==="right"&&G!==0?true:false;var aa=b.extend({},this.editoptions||{},{id:E,name:E}),af=b.extend({},{rowabove:false,rowcontent:""},this.formoptions||{}),ac=parseInt(af.rowpos)||S+1,ae=parseInt((parseInt(af.colpos)||1)*2);if(af.rowabove){var ad=b("<tr><td class='contentinfo' colspan='"+(U*2)+"'>"+af.rowcontent+"</td></tr>");b(M).append(ad);ad[0].rp=ac}P=b(M).find("tr[rowpos="+ac+"]");if(P.length==0){P=b("<tr "+Y+" rowpos='"+ac+"'></tr>").addClass("FormData").attr("id","trv_"+E);b(P).append(L);b(M).append(P);P[0].rp=ac}b("td:eq("+(ae-2)+")",P[0]).html("<b>"+(typeof af.label==="undefined"?O.p.colNames[ab]:af.label)+"</b>");b("td:eq("+(ae-1)+")",P[0]).append("<span>"+W+"</span>").attr("id","v_"+E);if(D){b("td:eq("+(ae-1)+") span",P[0]).css({"text-align":"right",width:G+"px"})}V[S]=ab;S++}});if(S>0){var Z=b("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+(U*2-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='"+I+"'/></td></tr>");Z[0].rp=S+99;b(M).append(Z)}return V}function l(G,H){var C,I,F=0,E,D;b("#"+G+" td",H.grid.bDiv).each(function(J){C=H.p.colModel[J].name.replace(".","\\.");if(H.p.colModel[J].editrules&&H.p.colModel[J].editrules.edithidden===true){I=false}else{I=H.p.colModel[J].hidden===true?true:false}if(C!=="cb"&&C!=="subgrid"&&H.p.colModel[J].editable===true){if(C==H.p.ExpandColumn&&H.p.treeGrid===true){E=b(this).text()}else{E=b(this).html()}D=b.extend({},H.p.colModel[J].editoptions||{});C="v_"+C;b("#"+C+" span","#"+r).html(E);if(I){b("#"+C,"#"+r).parents("tr:first").hide()}F++}});if(F>0){b("#id_g","#"+r).val(G)}return F}})},delGridRow:function(c,d){d=b.extend({top:0,left:0,width:240,height:"auto",dataheight:"auto",modal:false,drag:true,resize:true,url:"",mtype:"POST",reloadAfterSubmit:true,beforeShowForm:null,afterShowForm:null,beforeSubmit:null,onclickSubmit:null,afterSubmit:null,jqModal:true,closeOnEscape:false,delData:{},delicon:[],cancelicon:[],onClose:null},b.jgrid.del,d||{});a=d;return this.each(function(){var l=this;if(!l.grid){return}if(!c){return}var m=typeof d.beforeShowForm==="function"?true:false,g=typeof d.afterShowForm==="function"?true:false,e=l.p.id,f={},j="DelTbl_"+e,h={themodal:"delmod"+e,modalhead:"delhd"+e,modalcontent:"delcnt"+e,scrollelm:j};if(isArray(c)){c=c.join()}if(b("#"+h.themodal).html()!=null){b("#DelData>td","#"+j).text(c);b("#DelError","#"+j).hide();if(d.processing===true){d.processing=false;b("#dData","#"+j).removeClass("ui-state-active")}if(m){d.beforeShowForm(b("#"+j))}viewModal("#"+h.themodal,{gbox:"#gbox_"+e,jqm:d.jqModal,jqM:false,modal:d.modal});if(g){d.afterShowForm(b("#"+j))}}else{var n=isNaN(d.dataheight)?d.dataheight:d.dataheight+"px";var k="<div id='"+j+"' class='formdata' style='width:100%;overflow:auto;position:relative;height:"+n+";'>";k+="<table class='DelTable'><tbody>";k+="<tr id='DelError' style='display:none'><td ></td></tr>";k+="<tr id='DelData' style='display:none'><td >"+c+"</td></tr>";k+='<tr><td class="delmsg" style="white-space:pre;">'+d.msg+"</td></tr><tr><td >&nbsp;</td></tr>";k+="</tbody></table></div>";var i="<a href='javascript:void(0)' id='dData' class='fm-button ui-state-default ui-corner-all'>"+d.bSubmit+"</a>",o="<a href='javascript:void(0)' id='eData' class='fm-button ui-state-default ui-corner-all'>"+d.bCancel+"</a>";k+="<table cellspacing='0' cellpadding='0' border='0' class='EditTable' id='"+j+"_2'><tbody><tr><td class='DataTD ui-widget-content'></td></tr><tr style='display:block;height:3px;'><td></td></tr><tr><td class='DelButton EditButton'>"+i+"&nbsp;"+o+"</td></tr></tbody></table>";d.gbox="#gbox_"+e;createModal(h,k,d,"#gview_"+l.p.id,b("#gview_"+l.p.id)[0]);b(".fm-button","#"+j+"_2").hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});d.delicon=b.extend([true,"left","ui-icon-scissors"],d.delicon);d.cancelicon=b.extend([true,"left","ui-icon-cancel"],d.cancelicon);if(d.delicon[0]==true){b("#dData","#"+j+"_2").addClass(d.delicon[1]=="right"?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+d.delicon[2]+"'></span>")}if(d.cancelicon[0]==true){b("#eData","#"+j+"_2").addClass(d.cancelicon[1]=="right"?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+d.cancelicon[2]+"'></span>")}b("#dData","#"+j+"_2").click(function(s){var q=[true,""];f={};var r=b("#DelData>td","#"+j).text();if(typeof d.onclickSubmit==="function"){f=d.onclickSubmit(a)||{}}if(typeof d.beforeSubmit==="function"){q=d.beforeSubmit(r)}var p=a.url?a.url:l.p.editurl;if(!p){q[0]=false;q[1]+=" "+b.jgrid.errors.nourl}if(q[0]===false){b("#DelError>td","#"+j).html(q[1]);b("#DelError","#"+j).show()}else{if(!d.processing){d.processing=true;b(this).addClass("ui-state-active");var t=b.extend({oper:"del",id:r},d.delData,f);b.ajax({url:p,type:d.mtype,data:t,complete:function(x,v){if(v!="success"){q[0]=false;q[1]=v+" Status: "+x.statusText+" Error code: "+x.status}else{if(typeof a.afterSubmit==="function"){q=a.afterSubmit(x,r)}}if(q[0]===false){b("#DelError>td","#"+j).html(q[1]);b("#DelError","#"+j).show()}else{if(a.reloadAfterSubmit){if(l.p.treeGrid){b(l).setGridParam({treeANode:0,datatype:l.p.treedatatype})}b(l).trigger("reloadGrid")}else{var u=[];u=r.split(",");if(l.p.treeGrid===true){try{b(l).delTreeNode(u[0])}catch(y){}}else{for(var w=0;w<u.length;w++){b(l).delRowData(u[w])}}l.p.selrow=null;l.p.selarrrow=[]}if(b.isFunction(a.afterComplete)){setTimeout(function(){a.afterComplete(x,r)},500)}}d.processing=false;b("#dData","#"+j+"_2").removeClass("ui-state-active");if(q[0]){hideModal("#"+h.themodal,{gb:"#gbox_"+e,jqm:d.jqModal,onClose:a.onClose})}},error:function(w,u,v){b("#DelError>td","#"+j).html(u+" : "+v);b("#DelError","#"+j).show();d.processing=false;b("#dData","#"+j+"_2").removeClass("ui-state-active")}})}}return false});b("#eData","#"+j+"_2").click(function(p){hideModal("#"+h.themodal,{gb:"#gbox_"+e,jqm:d.jqModal,onClose:a.onClose});return false});if(m){d.beforeShowForm(b("#"+j))}viewModal("#"+h.themodal,{gbox:"#gbox_"+e,jqm:d.jqModal,modal:d.modal});if(g){d.afterShowForm(b("#"+j))}}if(d.closeOnEscape===true){setTimeout(function(){b(".ui-jqdialog-titlebar-close","#"+h.modalhead).focus()},0)}})},navGrid:function(f,h,e,g,d,c,i){h=b.extend({edit:true,editicon:"ui-icon-pencil",add:true,addicon:"ui-icon-plus",del:true,delicon:"ui-icon-trash",search:true,searchicon:"ui-icon-search",refresh:true,refreshicon:"ui-icon-refresh",refreshstate:"firstpage",view:false,viewicon:"ui-icon-document",position:"left",closeOnEscape:true},b.jgrid.nav,h||{});return this.each(function(){var j={themodal:"alertmod",modalhead:"alerthd",modalcontent:"alertcnt"},n=this,m,s,o,k;if(!n.grid){return}if(b("#"+j.themodal).html()==null){if(typeof window.innerWidth!="undefined"){m=window.innerWidth,s=window.innerHeight}else{if(typeof document.documentElement!="undefined"&&typeof document.documentElement.clientWidth!="undefined"&&document.documentElement.clientWidth!=0){m=document.documentElement.clientWidth,s=document.documentElement.clientHeight}else{m=1024;s=768}}createModal(j,"<div>"+h.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",{gbox:"#gbox_"+n.p.id,jqModal:true,drag:true,resize:true,caption:h.alertcap,top:s/2-25,left:m/2-100,width:200,height:"auto",closeOnEscape:h.closeOnEscape},"","",true)}var p,q=b("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:left;table-layout:auto;'><tbody><tr></tr></tbody></table>"),r="<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>",l=b(n.p.pager).attr("id")||"pager";if(h.add){g=g||{};p=b("<td class='ui-pg-button ui-corner-all'></td>");b(p).append("<div class='ui-pg-div'><span class='ui-icon "+h.addicon+"'></span>"+h.addtext+"</div>");b("tr",q).append(p);b(p,q).attr({title:h.addtitle||"",id:g.id||"add_"+n.p.id}).click(function(){if(typeof h.addfunc=="function"){h.addfunc()}else{b(n).editGridRow("new",g)}return false}).hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});p=null}if(h.edit){p=b("<td class='ui-pg-button ui-corner-all'></td>");e=e||{};b(p).append("<div class='ui-pg-div'><span class='ui-icon "+h.editicon+"'></span>"+h.edittext+"</div>");b("tr",q).append(p);b(p,q).attr({title:h.edittitle||"",id:e.id||"edit_"+n.p.id}).click(function(){var t=n.p.selrow;if(t){if(typeof h.editfunc=="function"){h.editfunc(t)}else{b(n).editGridRow(t,e)}}else{viewModal("#"+j.themodal,{gbox:"#gbox_"+n.p.id,jqm:true});b("#jqg_alrt").focus()}return false}).hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});p=null}if(h.view){p=b("<td class='ui-pg-button ui-corner-all'></td>");i=i||{};b(p).append("<div class='ui-pg-div'><span class='ui-icon "+h.viewicon+"'></span>"+h.viewtext+"</div>");b("tr",q).append(p);b(p,q).attr({title:h.viewtitle||"",id:i.id||"view_"+n.p.id}).click(function(){var t=n.p.selrow;if(t){b(n).viewGridRow(t,i)}else{viewModal("#"+j.themodal,{gbox:"#gbox_"+n.p.id,jqm:true});b("#jqg_alrt").focus()}return false}).hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});p=null}if(h.del){p=b("<td class='ui-pg-button ui-corner-all'></td>");d=d||{};b(p).append("<div class='ui-pg-div'><span class='ui-icon "+h.delicon+"'></span>"+h.deltext+"</div>");b("tr",q).append(p);b(p,q).attr({title:h.deltitle||"",id:d.id||"del_"+n.p.id}).click(function(){var t;if(n.p.multiselect){t=n.p.selarrrow;if(t.length==0){t=null}}else{t=n.p.selrow}if(t){b(n).delGridRow(t,d)}else{viewModal("#"+j.themodal,{gbox:"#gbox_"+n.p.id,jqm:true});b("#jqg_alrt").focus()}return false}).hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});p=null}if(h.add||h.edit||h.del||h.view){b("tr",q).append(r)}if(h.search){p=b("<td class='ui-pg-button ui-corner-all'></td>");c=c||{};b(p).append("<div class='ui-pg-div'><span class='ui-icon "+h.searchicon+"'></span>"+h.searchtext+"</div>");b("tr",q).append(p);b(p,q).attr({title:h.searchtitle||"",id:c.id||"search_"+n.p.id}).click(function(){b(n).searchGrid(c);return false}).hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});p=null}if(h.refresh){p=b("<td class='ui-pg-button ui-corner-all'></td>");b(p).append("<div class='ui-pg-div'><span class='ui-icon "+h.refreshicon+"'></span>"+h.refreshtext+"</div>");b("tr",q).append(p);b(p,q).attr({title:h.refreshtitle||"",id:"refresh_"+n.p.id}).click(function(){n.p.search=false;switch(h.refreshstate){case"firstpage":n.p.page=1;b(n).trigger("reloadGrid");break;case"current":var t=n.p.multiselect===true?n.p.selarrrow:n.p.selrow;b(n).trigger("reloadGrid");setTimeout(function(){if(n.p.multiselect===true){if(t.length>0){for(var v=0;v<t.length;v++){b(n).setSelection(t[v],false)}}}else{if(t){b(n).setSelection(t,false)}}},1000);break}if(h.search){var u=n.p.id;b("#fbox_"+u).searchFilter().reset()}return false}).hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});p=null}k=b(".ui-jqgrid").css("font-size")||"11px";b("body").append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+k+";visibility:hidden;' ></div>");o=b(q).clone(false).appendTo("#testpg").width();b("#testpg").remove();b("#"+l+"_"+h.position,"#"+l).append(q);if(n.p._nvtd){if(o>n.p._nvtd[0]){b("#"+l+"_"+h.position,"#"+l).width(o);n.p._nvtd[0]=o}n.p._nvtd[1]=o}})},navButtonAdd:function(c,d){d=b.extend({caption:"newButton",title:"",buttonicon:"ui-icon-newwin",onClickButton:null,position:"last"},d||{});return this.each(function(){if(!this.grid){return}if(c.indexOf("#")!=0){c="#"+c}var e=b(".navtable",c)[0];if(e){var f=b("<td></td>");b(f).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'><span class='ui-icon "+d.buttonicon+"'></span>"+d.caption+"</div>");if(d.id){b(f).attr("id",d.id)}if(d.position=="first"){if(e.rows[0].cells.length===0){b("tr",e).append(f)}else{b("tr td:eq(0)",e).before(f)}}else{b("tr",e).append(f)}b(f,e).attr("title",d.title||"").click(function(g){if(b.isFunction(d.onClickButton)){d.onClickButton()}return false}).hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")})}})},navSeparatorAdd:function(c,d){d=b.extend({sepclass:"ui-separator",sepcontent:""},d||{});return this.each(function(){if(!this.grid){return}if(c.indexOf("#")!=0){c="#"+c}var f=b(".navtable",c)[0];if(f){var e="<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='"+d.sepclass+"'></span>"+d.sepcontent+"</td>";b("tr",f).append(e)}})},GridToForm:function(c,d){return this.each(function(){var g=this;if(!g.grid){return}var f=b(g).getRowData(c);if(f){for(var e in f){if(b("[name="+e+"]",d).is("input:radio")){b("[name="+e+"]",d).each(function(){if(b(this).val()==f[e]){b(this).attr("checked","checked")}else{b(this).attr("checked","")}})}else{b("[name="+e+"]",d).val(f[e])}}}})},FormToGrid:function(c,d){return this.each(function(){var g=this;if(!g.grid){return}var e=b(d).serializeArray();var f={};b.each(e,function(h,j){f[j.name]=j.value});b(g).setRowData(c,f)})}})})(jQuery);jQuery.fn.searchFilter=function(a,c){function b(j,p,g){this.$=j;this.add=function(z){if(z==null){j.find(".ui-add-last").click()}else{j.find(".sf:eq("+z+") .ui-add").click()}return this};this.del=function(z){if(z==null){j.find(".sf:last .ui-del").click()}else{j.find(".sf:eq("+z+") .ui-del").click()}return this};this.search=function(z){j.find(".ui-search").click();return this};this.reset=function(z){j.find(".ui-reset").click();return this};this.close=function(){j.find(".ui-closer").click();return this};if(p!=null){function v(){jQuery(this).toggleClass("ui-state-hover");return false}function i(z){jQuery(this).toggleClass("ui-state-active",(z.type=="mousedown"));return false}function e(z,A){return"<option value='"+z+"'>"+A+"</option>"}function s(B,z,A){return"<select class='"+B+"'"+(A?" style='display:none;'":"")+">"+z+"</select>"}function w(z,B){var A=j.find("tr.sf td.data "+z);if(A[0]!=null){B(A)}}function q(z,B){var A=j.find("tr.sf td.data "+z);if(A[0]!=null){jQuery.each(B,function(){if(this.data!=null){A.bind(this.type,this.data,this.fn)}else{A.bind(this.type,this.fn)}})}}var n=jQuery.extend({},jQuery.fn.searchFilter.defaults,g);var y=-1;var x="";jQuery.each(n.groupOps,function(){x+=e(this.op,this.text)});x="<select name='groupOp'>"+x+"</select>";j.html("").addClass("ui-searchFilter").append("<div class='ui-widget-overlay' style='z-index: -1'>&nbsp;</div><table class='ui-widget-content ui-corner-all'><thead><tr><td colspan='5' class='ui-widget-header ui-corner-all' style='line-height: 18px;'><div class='ui-closer ui-state-default ui-corner-all ui-helper-clearfix' style='float: right;'><span class='ui-icon ui-icon-close'></span></div>"+n.windowTitle+"</td></tr></thead><tbody><tr class='sf'><td class='fields'></td><td class='ops'></td><td class='data'></td><td><div class='ui-del ui-state-default ui-corner-all'><span class='ui-icon ui-icon-minus'></span></div></td><td><div class='ui-add ui-state-default ui-corner-all'><span class='ui-icon ui-icon-plus'></span></div></td></tr><tr><td colspan='5' class='divider'><div>&nbsp;</div></td></tr></tbody><tfoot><tr><td colspan='3'><span class='ui-reset ui-state-default ui-corner-all' style='display: inline-block; float: left;'><span class='ui-icon ui-icon-arrowreturnthick-1-w' style='float: left;'></span><span style='line-height: 18px; padding: 0 7px 0 3px;'>"+n.resetText+"</span></span><span class='ui-search ui-state-default ui-corner-all' style='display: inline-block; float: right;'><span class='ui-icon ui-icon-search' style='float: left;'></span><span style='line-height: 18px; padding: 0 7px 0 3px;'>"+n.searchText+"</span></span><span class='matchText'>"+n.matchText+"</span> "+x+" <span class='rulesText'>"+n.rulesText+"</span></td><td>&nbsp;</td><td><div class='ui-add-last ui-state-default ui-corner-all'><span class='ui-icon ui-icon-plusthick'></span></div></td></tr></tfoot></table>");var k=j.find("tr.sf");var h=k.find("td.fields");var f=k.find("td.ops");var o=k.find("td.data");var r="";jQuery.each(n.operators,function(){r+=e(this.op,this.text)});r=s("default",r,true);f.append(r);var l="<input type='text' class='default' style='display:none;' />";o.append(l);var u="";var t=false;var d=false;jQuery.each(p,function(B){var A=B;u+=e(this.value,this.text);if(this.ops!=null){t=true;var z="";jQuery.each(this.ops,function(){z+=e(this.op,this.text)});z=s("field"+A,z,true);f.append(z)}if(this.dataUrl!=null){if(B>y){y=B}d=true;var E=this.dataEvents;var C=this.dataInit;jQuery.get(this.dataUrl,function(G){var F=jQuery("<div />").append(G);F.find("select").addClass("field"+A).hide();o.append(F.html());if(C){w(".field"+B,C)}if(E){q(".field"+B,E)}if(B==y){j.find("tr.sf td.fields select[name='field']").change()}})}else{if(this.dataValues!=null){d=true;var D="";jQuery.each(this.dataValues,function(){D+=e(this.value,this.text)});D=s("field"+A,D,true);o.append(D)}else{if(this.dataEvents!=null||this.dataInit!=null){d=true;var D="<input type='text' class='field"+A+"' />";o.append(D)}}}if(this.dataInit!=null&&B!=y){w(".field"+B,this.dataInit)}if(this.dataEvents!=null&&B!=y){q(".field"+B,this.dataEvents)}});u="<select name='field'>"+u+"</select>";h.append(u);var m=h.find("select[name='field']");if(t){m.change(function(B){var A=B.target.selectedIndex;var C=jQuery(B.target).parents("tr.sf").find("td.ops");C.find("select").removeAttr("name").hide();var z=C.find(".field"+A);if(z[0]==null){z=C.find(".default")}z.attr("name","op").show()})}else{f.find(".default").attr("name","op").show()}if(d){m.change(function(B){var A=B.target.selectedIndex;var C=jQuery(B.target).parents("tr.sf").find("td.data");C.find("select,input").removeAttr("name").hide();var z=C.find(".field"+A);if(z[0]==null){z=C.find(".default")}z.attr("name","data").show()})}else{o.find(".default").attr("name","data").show()}if(t||d){m.change()}j.find(".ui-state-default").hover(v,v).mousedown(i).mouseup(i);j.find(".ui-closer").click(function(z){n.onClose(jQuery(j.selector));return false});j.find(".ui-del").click(function(z){var A=jQuery(z.target).parents(".sf");if(A.siblings(".sf").length>0){if(n.datepickerFix===true&&jQuery.fn.datepicker!==undefined){A.find(".hasDatepicker").datepicker("destroy")}A.remove()}else{A.find("select[name='field']")[0].selectedIndex=0;A.find("select[name='op']")[0].selectedIndex=0;A.find(".data input").val("");A.find(".data select").each(function(){this.selectedIndex=0});A.find("select[name='field']").change()}return false});j.find(".ui-add").click(function(C){var D=jQuery(C.target).parents(".sf");var B=D.clone(true).insertAfter(D);B.find(".ui-state-default").removeClass("ui-state-hover ui-state-active");if(n.clone){B.find("select[name='field']")[0].selectedIndex=D.find("select[name='field']")[0].selectedIndex;var A=(B.find("select[name='op']")[0]==null);if(!A){B.find("select[name='op']").focus()[0].selectedIndex=D.find("select[name='op']")[0].selectedIndex}var z=B.find("select[name='data']");if(z[0]!=null){z[0].selectedIndex=D.find("select[name='data']")[0].selectedIndex}}else{B.find(".data input").val("");B.find("select[name='field']").focus()}if(n.datepickerFix===true&&jQuery.fn.datepicker!==undefined){D.find(".hasDatepicker").each(function(){var E=jQuery.data(this,"datepicker").settings;B.find("#"+this.id).unbind().removeAttr("id").removeClass("hasDatepicker").datepicker(E)})}B.find("select[name='field']").change();return false});j.find(".ui-search").click(function(C){var B=jQuery(j.selector);var z;var A=B.find("select[name='groupOp'] :selected").val();if(!n.stringResult){z={groupOp:A,rules:[]}}else{z='{"groupOp":"'+A+'","rules":['}B.find(".sf").each(function(D){var G=jQuery(this).find("select[name='field'] :selected").val();var F=jQuery(this).find("select[name='op'] :selected").val();var E=jQuery(this).find("input[name='data'],select[name='data'] :selected").val();if(!n.stringResult){z.rules.push({field:G,op:F,data:E})}else{if(D>0){z+=","}z+='{"field":"'+G+'",';z+='"op":"'+F+'",';z+='"data":"'+E+'"}'}});if(n.stringResult){z+="]}"}n.onSearch(z);return false});j.find(".ui-reset").click(function(A){var z=jQuery(j.selector);z.find(".ui-del").click();z.find("select[name='groupOp']")[0].selectedIndex=0;n.onReset();return false});j.find(".ui-add-last").click(function(){var A=jQuery(j.selector+" .sf:last");var z=A.clone(true).insertAfter(A);z.find(".ui-state-default").removeClass("ui-state-hover ui-state-active");z.find(".data input").val("");z.find("select[name='field']").focus();if(n.datepickerFix===true&&jQuery.fn.datepicker!==undefined){A.find(".hasDatepicker").each(function(){var B=jQuery.data(this,"datepicker").settings;z.find("#"+this.id).unbind().removeAttr("id").removeClass("hasDatepicker").datepicker(B)})}z.find("select[name='field']").change();return false})}}return new b(this,a,c)};jQuery.fn.searchFilter.version="1.2.9";jQuery.fn.searchFilter.defaults={clone:true,datepickerFix:true,onReset:function(a){alert("Reset Clicked. Data Returned: "+a)},onSearch:function(a){alert("Search Clicked. Data Returned: "+a)},onClose:function(a){a.hide()},groupOps:[{op:"AND",text:"all"},{op:"OR",text:"any"}],operators:[{op:"eq",text:"is equal to"},{op:"ne",text:"is not equal to"},{op:"lt",text:"is less than"},{op:"le",text:"is less or equal to"},{op:"gt",text:"is greater than"},{op:"ge",text:"is greater or equal to"},{op:"in",text:"is in"},{op:"ni",text:"is not in"},{op:"bw",text:"begins with"},{op:"bn",text:"does not begin with"},{op:"ew",text:"ends with"},{op:"en",text:"does not end with"},{op:"cn",text:"contains"},{op:"nc",text:"does not contain"}],matchText:"match",rulesText:"rules",resetText:"Reset",searchText:"Search",stringResult:true,windowTitle:"Search Rules"};(function(a){a.fn.extend({editRow:function(c,i,h,j,b,e,d,f,g){return this.each(function(){var n=this,t,o,l,m=0,s=null,r=[],k,q;if(!n.grid){return}var p;k=a(n).getInd(c,true);if(k==false){return}l=a(k).attr("editable")||"0";if(l=="0"){q=n.p.colModel;a("td",k).each(function(x){t=q[x].name;p=q[x].hidden===true?true:false;var w=n.p.treeGrid===true&&t==n.p.ExpandColumn;if(w){o=a("span:first",this).html()}else{try{o=a.unformat(this,{colModel:q[x]},x)}catch(u){o=a(this).html()}}if(t!="cb"&&t!="subgrid"&&t!="rn"){r[t]=o;if(q[x].editable===true&&!p){if(s===null){s=x}if(w){a("span:first",this).html("")}else{a(this).html("")}var v=a.extend({},q[x].editoptions||{},{id:c+"_"+t,name:t});if(!q[x].edittype){q[x].edittype="text"}var y=createEl(q[x].edittype,v,o,a(this));a(y).addClass("editable");if(w){a("span:first",this).append(y)}else{a(this).append(y)}if(q[x].edittype=="select"&&q[x].editoptions.multiple===true&&a.browser.msie){a(y).width(a(y).width())}m++}}});if(m>0){r.id=c;n.p.savedRow.push(r);a(k).attr("editable","1");a("td:eq("+s+") input",k).focus();if(i===true){a(k).bind("keydown",function(u){if(u.keyCode===27){a(n).restoreRow(c,g)}if(u.keyCode===13){a(n).saveRow(c,j,b,e,d,f,g);return false}u.stopPropagation()})}if(a.isFunction(h)){h(c)}}}})},saveRow:function(h,g,e,f,d,c,b){return this.each(function(){var o=this,t,p={},l={},j,r,q,i;if(!o.grid){return}i=a(o).getInd(h,true);if(i==false){return}j=a(i).attr("editable");e=e?e:o.p.editurl;if(j==="1"&&e){a("td",i).each(function(u){t=o.p.colModel[u].name;if(t!="cb"&&t!="subgrid"&&o.p.colModel[u].editable===true&&t!="rn"){if(o.p.colModel[u].hidden===true){p[t]=a(this).html()}else{switch(o.p.colModel[u].edittype){case"checkbox":var k=["Yes","No"];if(o.p.colModel[u].editoptions){k=o.p.colModel[u].editoptions.value.split(":")}p[t]=a("input",this).attr("checked")?k[0]:k[1];break;case"text":case"password":case"textarea":case"button":p[t]=!o.p.autoencode?a("input, textarea",this).val():a.jgrid.htmlEncode(a("input, textarea",this).val());break;case"select":if(!o.p.colModel[u].editoptions.multiple){p[t]=a("select>option:selected",this).val();l[t]=a("select>option:selected",this).text()}else{var v=a("select",this),w=[];p[t]=a(v).val();if(p[t]){p[t]=p[t].join(",")}else{p[t]=""}a("select > option:selected",this).each(function(x,y){w[x]=a(y).text()});l[t]=w.join(",")}break}q=checkValues(p[t],u,o);if(q[0]===false){q[1]=p[t]+" "+q[1];return false}}}});if(q[0]===false){try{info_dialog(a.jgrid.errors.errcap,q[1],a.jgrid.edit.bClose)}catch(s){alert(q[1])}return}if(p){p.id=h;if(f){p=a.extend({},p,f)}}if(!o.grid.hDiv.loading){o.grid.hDiv.loading=true;a("div.loading",o.grid.hDiv).fadeIn("fast");if(e=="clientArray"){p=a.extend({},p,l);var n=a(o).setRowData(h,p);a(i).attr("editable","0");for(var m=0;m<o.p.savedRow.length;m++){if(o.p.savedRow[m].id===h){r=m;break}}if(r>=0){o.p.savedRow.splice(r,1)}if(a.isFunction(d)){d(h,n)}}else{a.ajax({url:e,data:p,type:"POST",complete:function(w,x){if(x==="success"){var v;if(a.isFunction(g)){v=g(w)}else{v=true}if(v===true){p=a.extend({},p,l);a(o).setRowData(h,p);a(i).attr("editable","0");for(var u=0;u<o.p.savedRow.length;u++){if(o.p.savedRow[u].id===h){r=u;break}}if(r>=0){o.p.savedRow.splice(r,1)}if(a.isFunction(d)){d(h,w.responseText)}}else{a(o).restoreRow(h,b)}}},error:function(k,u){if(a.isFunction(c)){c(h,k,u)}else{alert("Error Row: "+h+" Result: "+k.status+":"+k.statusText+" Status: "+u)}}})}o.grid.hDiv.loading=false;a("div.loading",o.grid.hDiv).fadeOut("fast");a(i).unbind("keydown")}}})},restoreRow:function(c,b){return this.each(function(){var g=this,d,f;if(!g.grid){return}f=a(g).getInd(c,true);if(f==false){return}for(var e=0;e<g.p.savedRow.length;e++){if(g.p.savedRow[e].id===c){d=e;break}}if(d>=0){a(g).setRowData(c,g.p.savedRow[d]);a(f).attr("editable","0");g.p.savedRow.splice(d,1)}if(a.isFunction(b)){b(c)}})}})})(jQuery);(function(a){a.fn.extend({editCell:function(d,c,b){return this.each(function(){var j=this,m,k,g;if(!j.grid||j.p.cellEdit!==true){return}c=parseInt(c,10);j.p.selrow=j.rows[d].id;if(!j.p.knv){a(j).GridNav()}if(j.p.savedRow.length>0){if(b===true){if(d==j.p.iRow&&c==j.p.iCol){return}}var h=a("td:eq("+j.p.savedRow[0].ic+")>#"+j.p.savedRow[0].id+"_"+j.p.savedRow[0].name.replace(".","\\."),j.rows[j.p.savedRow[0].id]).val();if(j.p.savedRow[0].v!=h){a(j).saveCell(j.p.savedRow[0].id,j.p.savedRow[0].ic)}else{a(j).restoreCell(j.p.savedRow[0].id,j.p.savedRow[0].ic)}}else{window.setTimeout(function(){a("#"+j.p.knv).attr("tabindex","-1").focus()},0)}m=j.p.colModel[c].name;if(m=="subgrid"||m=="cb"||m=="rn"){return}if(j.p.colModel[c].editable===true&&b===true){g=a("td:eq("+c+")",j.rows[d]);if(parseInt(j.p.iCol)>=0&&parseInt(j.p.iRow)>=0){a("td:eq("+j.p.iCol+")",j.rows[j.p.iRow]).removeClass("edit-cell ui-state-highlight");a(j.rows[j.p.iRow]).removeClass("selected-row ui-state-hover")}a(g).addClass("edit-cell ui-state-highlight");a(j.rows[d]).addClass("selected-row ui-state-hover");try{k=a.unformat(g,{colModel:j.p.colModel[c]},c)}catch(l){k=a.jgrid.htmlDecode(a(g).html())}var f=a.extend({},j.p.colModel[c].editoptions||{},{id:d+"_"+m,name:m});if(!j.p.colModel[c].edittype){j.p.colModel[c].edittype="text"}j.p.savedRow.push({id:d,ic:c,name:m,v:k});if(a.isFunction(j.p.formatCell)){var i=j.p.formatCell(j.rows[d].id,m,k,d,c);if(i){k=i}}var e=createEl(j.p.colModel[c].edittype,f,k,g);if(a.isFunction(j.p.beforeEditCell)){j.p.beforeEditCell(j.rows[d].id,m,k,d,c)}a(g).html("").append(e).attr("tabindex","0");window.setTimeout(function(){a(e).focus()},0);a("input, select, textarea",g).bind("keydown",function(n){if(n.keyCode===27){a(j).restoreCell(d,c)}if(n.keyCode===13){a(j).saveCell(d,c)}if(n.keyCode==9){if(n.shiftKey){a(j).prevCell(d,c)}else{a(j).nextCell(d,c)}}n.stopPropagation()});if(a.isFunction(j.p.afterEditCell)){j.p.afterEditCell(j.rows[d].id,m,k,d,c)}}else{if(parseInt(j.p.iCol)>=0&&parseInt(j.p.iRow)>=0){a("td:eq("+j.p.iCol+")",j.rows[j.p.iRow]).removeClass("edit-cell ui-state-highlight");a(j.rows[j.p.iRow]).removeClass("selected-row ui-state-hover")}a("td:eq("+c+")",j.rows[d]).addClass("edit-cell ui-state-highlight");a(j.rows[d]).addClass("selected-row ui-state-hover");if(a.isFunction(j.p.onSelectCell)){k=a("td:eq("+c+")",j.rows[d]).html().replace(/\&nbsp\;/ig,"");j.p.onSelectCell(j.rows[d].id,m,k,d,c)}}j.p.iCol=c;j.p.iRow=d})},saveCell:function(c,b){return this.each(function(){var j=this,l;if(!j.grid||j.p.cellEdit!==true){return}if(j.p.savedRow.length>=1){l=0}else{l=null}if(l!=null){var g=a("td:eq("+b+")",j.rows[c]),q,o,r=j.p.colModel[b].name.replace(".","\\.");switch(j.p.colModel[b].edittype){case"select":if(!j.p.colModel[b].editoptions.multiple){q=a("#"+c+"_"+r.replace(".","\\.")+">option:selected",j.rows[c]).val();o=a("#"+c+"_"+r.replace(".","\\.")+">option:selected",j.rows[c]).text()}else{var d=a("#"+c+"_"+r.replace(".","\\."),j.rows[c]),f=[];q=a(d).val();if(q){q.join(",")}else{q=""}a("option:selected",d).each(function(e,s){f[e]=a(s).text()});o=f.join(",")}break;case"checkbox":var h=["Yes","No"];if(j.p.colModel[b].editoptions){h=j.p.colModel[b].editoptions.value.split(":")}q=a("#"+c+"_"+r.replace(".","\\."),j.rows[c]).attr("checked")?h[0]:h[1];o=q;break;case"password":case"text":case"textarea":case"button":q=!j.p.autoencode?a("#"+c+"_"+r.replace(".","\\."),j.rows[c]).val():a.jgrid.htmlEncode(a("#"+c+"_"+r.replace(".","\\."),j.rows[c]).val());o=q;break}if(o!=j.p.savedRow[l].v){if(a.isFunction(j.p.beforeSaveCell)){var p=j.p.beforeSaveCell(j.rows[c].id,r,q,c,b);if(p){q=p}}var i=checkValues(q,b,j);if(i[0]===true){var k={};if(a.isFunction(j.p.beforeSubmitCell)){k=j.p.beforeSubmitCell(j.rows[c].id,r,q,c,b);if(!k){k={}}}if(j.p.cellsubmit=="remote"){if(j.p.cellurl){var n={};n[r]=q;n.id=j.rows[c].id;n=a.extend(k,n);a.ajax({url:j.p.cellurl,data:n,type:"POST",complete:function(e,t){if(t=="success"){if(a.isFunction(j.p.afterSubmitCell)){var s=j.p.afterSubmitCell(e,n.id,r,q,c,b);if(s[0]===true){a(g).empty();a(j).setCell(j.rows[c].id,b,o);a(g).addClass("dirty-cell");a(j.rows[c]).addClass("edited");if(a.isFunction(j.p.afterSaveCell)){j.p.afterSaveCell(j.rows[c].id,r,q,c,b)}j.p.savedRow.splice(0,1)}else{info_dialog(a.jgrid.errors.errcap,s[1],a.jgrid.edit.bClose);a(j).restoreCell(c,b)}}else{a(g).empty();a(j).setCell(j.rows[c].id,b,o);a(g).addClass("dirty-cell");a(j.rows[c]).addClass("edited");if(a.isFunction(j.p.afterSaveCell)){j.p.afterSaveCell(j.rows[c].id,r,q,c,b)}j.p.savedRow.splice(0,1)}}},error:function(e,s){if(a.isFunction(j.p.errorCell)){j.p.errorCell(e,s);a(j).restoreCell(c,b)}else{info_dialog(a.jgrid.errors.errcap,e.status+" : "+e.statusText+"<br/>"+s,a.jgrid.edit.bClose);a(j).restoreCell(c,b)}}})}else{try{info_dialog(a.jgrid.errors.errcap,a.jgrid.errors.nourl,a.jgrid.edit.bClose);a(j).restoreCell(c,b)}catch(m){}}}if(j.p.cellsubmit=="clientArray"){a(g).empty();a(j).setCell(j.rows[c].id,b,o);a(g).addClass("dirty-cell");a(j.rows[c]).addClass("edited");if(a.isFunction(j.p.afterSaveCell)){j.p.afterSaveCell(j.rows[c].id,r,q,c,b)}j.p.savedRow.splice(0,1)}}else{try{window.setTimeout(function(){info_dialog(a.jgrid.errors.errcap,q+" "+i[1],a.jgrid.edit.bClose)},100);a(j).restoreCell(c,b)}catch(m){}}}else{a(j).restoreCell(c,b)}}if(a.browser.opera){a("#"+j.p.knv).attr("tabindex","-1").focus()}else{window.setTimeout(function(){a("#"+j.p.knv).attr("tabindex","-1").focus()},0)}})},restoreCell:function(c,b){return this.each(function(){var h=this,d;if(!h.grid||h.p.cellEdit!==true){return}if(h.p.savedRow.length>=1){d=0}else{d=null}if(d!=null){var g=a("td:eq("+b+")",h.rows[c]);if(a.isFunction(a.fn.datepicker)){try{a.datepicker("hide")}catch(f){try{a.datepicker.hideDatepicker()}catch(f){}}}a(g).empty().attr("tabindex","-1");a(h).setCell(h.rows[c].id,b,h.p.savedRow[d].v);h.p.savedRow.splice(0,1)}window.setTimeout(function(){a("#"+h.p.knv).attr("tabindex","-1").focus()},0)})},nextCell:function(c,b){return this.each(function(){var f=this,e=false;if(!f.grid||f.p.cellEdit!==true){return}for(var d=b+1;d<f.p.colModel.length;d++){if(f.p.colModel[d].editable===true){e=d;break}}if(e!==false){a(f).editCell(c,e,true)}else{if(f.p.savedRow.length>0){a(f).saveCell(c,b)}}})},prevCell:function(c,b){return this.each(function(){var f=this,e=false;if(!f.grid||f.p.cellEdit!==true){return}for(var d=b-1;d>=0;d--){if(f.p.colModel[d].editable===true){e=d;break}}if(e!==false){a(f).editCell(c,e,true)}else{if(f.p.savedRow.length>0){a(f).saveCell(c,b)}}})},GridNav:function(){return this.each(function(){var f=this;if(!f.grid||f.p.cellEdit!==true){return}f.p.knv=a("table:first",f.grid.bDiv).attr("id")+"_kn";var e=a("<span style='width:0px;height:0px;background-color:black;' tabindex='0'><span tabindex='-1' style='width:0px;height:0px;background-color:grey' id='"+f.p.knv+"'></span></span>"),c;a(e).insertBefore(f.grid.cDiv);a("#"+f.p.knv).focus();a("#"+f.p.knv).keydown(function(g){switch(g.keyCode){case 38:if(f.p.iRow-1>=0){d(f.p.iRow-1,f.p.iCol,"vu");a(f).editCell(f.p.iRow-1,f.p.iCol,false)}break;case 40:if(f.p.iRow+1<=f.rows.length-1){d(f.p.iRow+1,f.p.iCol,"vd");a(f).editCell(f.p.iRow+1,f.p.iCol,false)}break;case 37:if(f.p.iCol-1>=0){c=b(f.p.iCol-1,"lft");d(f.p.iRow,c,"h");a(f).editCell(f.p.iRow,c,false)}break;case 39:if(f.p.iCol+1<=f.p.colModel.length-1){c=b(f.p.iCol+1,"rgt");d(f.p.iRow,c,"h");a(f).editCell(f.p.iRow,c,false)}break;case 13:if(parseInt(f.p.iCol,10)>=0&&parseInt(f.p.iRow,10)>=0){a(f).editCell(f.p.iRow,f.p.iCol,true)}break}return false});function d(o,m,n){if(n.substr(0,1)=="v"){var g=a(f.grid.bDiv)[0].clientHeight,p=a(f.grid.bDiv)[0].scrollTop,q=f.rows[o].offsetTop+f.rows[o].clientHeight,k=f.rows[o].offsetTop;if(n=="vd"){if(q>=g){a(f.grid.bDiv)[0].scrollTop=a(f.grid.bDiv)[0].scrollTop+f.rows[o].clientHeight}}if(n=="vu"){if(k<p){a(f.grid.bDiv)[0].scrollTop=a(f.grid.bDiv)[0].scrollTop-f.rows[o].clientHeight}}}if(n=="h"){var j=a(f.grid.bDiv)[0].clientWidth,i=a(f.grid.bDiv)[0].scrollLeft,h=f.rows[o].cells[m].offsetLeft+f.rows[o].cells[m].clientWidth,l=f.rows[o].cells[m].offsetLeft;if(h>=j+parseInt(i)){a(f.grid.bDiv)[0].scrollLeft=a(f.grid.bDiv)[0].scrollLeft+f.rows[o].cells[m].clientWidth}else{if(l<i){a(f.grid.bDiv)[0].scrollLeft=a(f.grid.bDiv)[0].scrollLeft-f.rows[o].cells[m].clientWidth}}}}function b(k,g){var j,h;if(g=="lft"){j=k+1;for(h=k;h>=0;h--){if(f.p.colModel[h].hidden!==true){j=h;break}}}if(g=="rgt"){j=k-1;for(h=k;h<f.p.colModel.length;h++){if(f.p.colModel[h].hidden!==true){j=h;break}}}return j}})},getChangedCells:function(c){var b=[];if(!c){c="all"}this.each(function(){var e=this,d;if(!e.grid||e.p.cellEdit!==true){return}a(e.rows).each(function(f){var g={};if(a(this).hasClass("edited")){a("td",this).each(function(h){d=e.p.colModel[h].name;if(d!=="cb"&&d!=="subgrid"){if(c=="dirty"){if(a(this).hasClass("dirty-cell")){g[d]=a.jgrid.htmlDecode(a(this).html())}}else{g[d]=a.jgrid.htmlDecode(a(this).html())}}});g.id=this.id;b.push(g)}})});return b}})})(jQuery);(function(d){d.fn.jqm=function(f){var e={overlay:50,closeoverlay:true,overlayClass:"jqmOverlay",closeClass:"jqmClose",trigger:".jqModal",ajax:o,ajaxText:"",target:o,modal:o,toTop:o,onShow:o,onHide:o,onLoad:o};return this.each(function(){if(this._jqm){return n[this._jqm].c=d.extend({},n[this._jqm].c,f)}p++;this._jqm=p;n[p]={c:d.extend(e,d.jqm.params,f),a:o,w:d(this).addClass("jqmID"+p),s:p};if(e.trigger){d(this).jqmAddTrigger(e.trigger)}})};d.fn.jqmAddClose=function(f){return l(this,f,"jqmHide")};d.fn.jqmAddTrigger=function(f){return l(this,f,"jqmShow")};d.fn.jqmShow=function(e){return this.each(function(){d.jqm.open(this._jqm,e)})};d.fn.jqmHide=function(e){return this.each(function(){d.jqm.close(this._jqm,e)})};d.jqm={hash:{},open:function(B,A){var m=n[B],q=m.c,i="."+q.closeClass,v=(parseInt(m.w.css("z-index"))),v=(v>0)?v:3000,f=d("<div></div>").css({height:"100%",width:"100%",position:"fixed",left:0,top:0,"z-index":v-1,opacity:q.overlay/100});if(m.a){return o}m.t=A;m.a=true;m.w.css("z-index",v);if(q.modal){if(!a[0]){k("bind")}a.push(B)}else{if(q.overlay>0){if(q.closeoverlay){m.w.jqmAddClose(f)}}else{f=o}}m.o=(f)?f.addClass(q.overlayClass).prependTo("body"):o;if(c){d("html,body").css({height:"100%",width:"100%"});if(f){f=f.css({position:"absolute"})[0];for(var w in {Top:1,Left:1}){f.style.setExpression(w.toLowerCase(),"(_=(document.documentElement.scroll"+w+" || document.body.scroll"+w+"))+'px'")}}}if(q.ajax){var e=q.target||m.w,x=q.ajax,e=(typeof e=="string")?d(e,m.w):d(e),x=(x.substr(0,1)=="@")?d(A).attr(x.substring(1)):x;e.html(q.ajaxText).load(x,function(){if(q.onLoad){q.onLoad.call(this,m)}if(i){m.w.jqmAddClose(d(i,m.w))}j(m)})}else{if(i){m.w.jqmAddClose(d(i,m.w))}}if(q.toTop&&m.o){m.w.before('<span id="jqmP'+m.w[0]._jqm+'"></span>').insertAfter(m.o)}(q.onShow)?q.onShow(m):m.w.show();j(m);return o},close:function(f){var e=n[f];if(!e.a){return o}e.a=o;if(a[0]){a.pop();if(!a[0]){k("unbind")}}if(e.c.toTop&&e.o){d("#jqmP"+e.w[0]._jqm).after(e.w).remove()}if(e.c.onHide){e.c.onHide(e)}else{e.w.hide();if(e.o){e.o.remove()}}return o},params:{}};var p=0,n=d.jqm.hash,a=[],c=d.browser.msie&&(d.browser.version=="6.0"),o=false,g=d('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),j=function(e){if(c){if(e.o){e.o.html('<p style="width:100%;height:100%"/>').prepend(g)}else{if(!d("iframe.jqm",e.w)[0]){e.w.prepend(g)}}}h(e)},h=function(f){try{d(":input:visible",f.w)[0].focus()}catch(e){}},k=function(e){d()[e]("keypress",b)[e]("keydown",b)[e]("mousedown",b)},b=function(m){var f=n[a[a.length-1]],i=(!d(m.target).parents(".jqmID"+f.s)[0]);if(i){h(f)}return !i},l=function(e,f,i){return e.each(function(){var m=this._jqm;d(f).each(function(){if(!this[i]){this[i]=[];d(this).click(function(){for(var q in {jqmShow:1,jqmHide:1}){for(var r in this[q]){if(n[this[q][r]]){n[this[q][r]].w[q](this)}}}return o})}this[i].push(m)})})}})(jQuery);(function(g){g.fn.jqDrag=function(f){return c(this,f,"d")};g.fn.jqResize=function(i,f){return c(this,i,"r",f)};g.jqDnR={dnr:{},e:0,drag:function(f){if(h.k=="d"){e.css({left:h.X+f.pageX-h.pX,top:h.Y+f.pageY-h.pY})}else{e.css({width:Math.max(f.pageX-h.pX+h.W,0),height:Math.max(f.pageY-h.pY+h.H,0)});if(M1){a.css({width:Math.max(f.pageX-M1.pX+M1.W,0),height:Math.max(f.pageY-M1.pY+M1.H,0)})}}return false},stop:function(){g().unbind("mousemove",b.drag).unbind("mouseup",b.stop)}};var b=g.jqDnR,h=b.dnr,e=b.e,a,c=function(l,j,i,f){return l.each(function(){j=(j)?g(j,l):l;j.bind("mousedown",{e:l,k:i},function(k){var o=k.data,n={};e=o.e;a=f?g(f):false;if(e.css("position")!="relative"){try{e.position(n)}catch(m){}}h={X:n.left||d("left")||0,Y:n.top||d("top")||0,W:d("width")||e[0].scrollWidth||0,H:d("height")||e[0].scrollHeight||0,pX:k.pageX,pY:k.pageY,k:o.k};if(a&&o.k!="d"){M1={X:n.left||f1("left")||0,Y:n.top||f1("top")||0,W:a[0].offsetWidth||f1("width")||0,H:a[0].offsetHeight||f1("height")||0,pX:k.pageX,pY:k.pageY,k:o.k}}else{M1=false}g().mousemove(g.jqDnR.drag).mouseup(g.jqDnR.stop);return false})})},d=function(f){return parseInt(e.css(f))||false};f1=function(f){return parseInt(a.css(f))||false}})(jQuery);function tableToGrid(a,b){$(a).each(function(){if(this.grid){return}$(this).width("99%");var n=$(this).width();var p=$("input[type=checkbox]:first",$(this));var h=$("input[type=radio]:first",$(this));var d=p.length>0;var g=!d&&h.length>0;var j=d||g;var i=p.attr("name")||h.attr("name");var l=[];var o=[];$("th",$(this)).each(function(){if(l.length==0&&j){l.push({name:"__selection__",index:"__selection__",width:0,hidden:true});o.push("__selection__")}else{l.push({name:$(this).attr("id")||$(this).html(),index:$(this).attr("id")||$(this).html(),width:$(this).width()||150});o.push($(this).html())}});var f=[];var e=[];var m=[];$("tbody > tr",$(this)).each(function(){var r={};var q=0;f.push(r);$("td",$(this)).each(function(){if(q==0&&j){var s=$("input",$(this));var t=s.attr("value");e.push(t||f.length);if(s.attr("checked")){m.push(t)}r[l[q].name]=s.attr("value")}else{r[l[q].name]=$(this).html()}q++})});$(this).empty();$(this).addClass("scroll");$(this).jqGrid($.extend({datatype:"local",width:n,colNames:o,colModel:l,multiselect:d},b||{}));for(var k=0;k<f.length;k++){var c=null;if(e.length>0){c=e[k];if(c&&c.replace){c=encodeURIComponent(c).replace(/[.\-%]/g,"_")}}if(c==null){c=k+1}$(this).addRowData(c,f[k])}for(var k=0;k<m.length;k++){$(this).setSelection(m[k])}})};
