/*!
 * jQuery JavaScript Library v1.7.2
 * http://jquery.com/
 *
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2011, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Wed Mar 21 12:46:34 2012 -0700
 */
 
 // Peter:
 // This file date: November 13, 2013.
 
(function(window, undefined) {
  var document = window.document, navigator = window.navigator, location = window.location;
  var jQuery = (function() {
    var jQuery = function(selector, context) {
      return new jQuery.fn.init(selector, context, rootjQuery);
    }, _jQuery = window.jQuery, _$ = window.$, rootjQuery, quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, rnotwhite = /\S/, trimLeft = /^\s+/, trimRight = /\s+$/, rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, fcamelCase = function(all, letter) {
      return (letter + "").toUpperCase();
    }, userAgent = navigator.userAgent, browserMatch, readyList, DOMContentLoaded, toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, class2type = {};
    jQuery.fn = jQuery.prototype = {
      constructor : jQuery,
      init : function(selector, context, rootjQuery) {
        var match, elem, ret, doc;
        if (!selector) {
          return this;
        }
        if (selector.nodeType) {
          this.context = this[0] = selector;
          this.length = 1;
          return this;
        }
        if (selector === "body" && !context && document.body) {
          this.context = document;
          this[0] = document.body;
          this.selector = selector;
          this.length = 1;
          return this;
        }
        if ( typeof selector === "string") {
          if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) {
            match = [null, selector, null];
          } else {
            match = quickExpr.exec(selector);
          }
          if (match && (match[1] || !context)) {
            if (match[1]) {
              context = context instanceof jQuery ? context[0] : context;
              doc = ( context ? context.ownerDocument || context : document);
              ret = rsingleTag.exec(selector);
              if (ret) {
                if (jQuery.isPlainObject(context)) {
                  selector = [document.createElement(ret[1])];
                  jQuery.fn.attr.call(selector, context, true);
                } else {
                  selector = [doc.createElement(ret[1])];
                }
              } else {
                ret = jQuery.buildFragment([match[1]], [doc]);
                selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
              }
              return jQuery.merge(this, selector);
            } else {
              elem = document.getElementById(match[2]);
              if (elem && elem.parentNode) {
                if (elem.id !== match[2]) {
                  return rootjQuery.find(selector);
                }
                this.length = 1;
                this[0] = elem;
              }
              this.context = document;
              this.selector = selector;
              return this;
            }
          } else {
            if (!context || context.jquery) {
              return (context || rootjQuery).find(selector);
            } else {
              return this.constructor(context).find(selector);
            }
          }
        } else {
          if (jQuery.isFunction(selector)) {
            return rootjQuery.ready(selector);
          }
        }
        if (selector.selector !== undefined) {
          this.selector = selector.selector;
          this.context = selector.context;
        }
        return jQuery.makeArray(selector, this);
      },
      selector : "",
      jquery : "1.7.2",
      length : 0,
      size : function() {
        return this.length;
      },
      toArray : function() {
        return slice.call(this, 0);
      },
      get : function(num) {
        return num == null ? this.toArray() : (num < 0 ? this[this.length + num] : this[num]);
      },
      pushStack : function(elems, name, selector) {
        var ret = this.constructor();
        if (jQuery.isArray(elems)) {
          push.apply(ret, elems);
        } else {
          jQuery.merge(ret, elems);
        }
        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 ret;
      },
      each : function(callback, args) {
        return jQuery.each(this, callback, args);
      },
      ready : function(fn) {
        jQuery.bindReady();
        readyList.add(fn);
        return this;
      },
      eq : function(i) {
        i = +i;
        return i === -1 ? this.slice(i) : this.slice(i, i + 1);
      },
      first : function() {
        return this.eq(0);
      },
      last : function() {
        return this.eq(-1);
      },
      slice : function() {
        return this.pushStack(slice.apply(this, arguments), "slice", slice.call(arguments).join(","));
      },
      map : function(callback) {
        return this.pushStack(jQuery.map(this, function(elem, i) {
          return callback.call(elem, i, elem);
        }));
      },
      end : function() {
        return this.prevObject || this.constructor(null);
      },
      push : push,
      sort : [].sort,
      splice : [].splice
    };
    jQuery.fn.init.prototype = jQuery.fn;
    jQuery.extend = jQuery.fn.extend = function() {
      var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false;
      if ( typeof target === "boolean") {
        deep = target;
        target = arguments[1] || {};
        i = 2;
      }
      if ( typeof target !== "object" && !jQuery.isFunction(target)) {
        target = {};
      }
      if (length === i) {
        target = this;
        --i;
      }
      for (; i < length; i++) {
        if (( options = arguments[i]) != null) {
          for (name in options) {
            src = target[name];
            copy = options[name];
            if (target === copy) {
              continue;
            }
            if (deep && copy && (jQuery.isPlainObject(copy) || ( copyIsArray = jQuery.isArray(copy)))) {
              if (copyIsArray) {
                copyIsArray = false;
                clone = src && jQuery.isArray(src) ? src : [];
              } else {
                clone = src && jQuery.isPlainObject(src) ? src : {};
              }
              target[name] = jQuery.extend(deep, clone, copy);
            } else {
              if (copy !== undefined) {
                target[name] = copy;
              }
            }
          }
        }
      }
      return target;
    };
    jQuery.extend({
      noConflict : function(deep) {
        if (window.$ === jQuery) {
          window.$ = _$;
        }
        if (deep && window.jQuery === jQuery) {
          window.jQuery = _jQuery;
        }
        return jQuery;
      },
      isReady : false,
      readyWait : 1,
      holdReady : function(hold) {
        if (hold) {
          jQuery.readyWait++;
        } else {
          jQuery.ready(true);
        }
      },
      ready : function(wait) {
        if ((wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady)) {
          if (!document.body) {
            return setTimeout(jQuery.ready, 1);
          }
          jQuery.isReady = true;
          if (wait !== true && --jQuery.readyWait > 0) {
            return;
          }
          readyList.fireWith(document, [jQuery]);
          if (jQuery.fn.trigger) {
            jQuery(document).trigger("ready").off("ready");
          }
        }
      },
      bindReady : function() {
        if (readyList) {
          return;
        }
        readyList = jQuery.Callbacks("once memory");
        if (document.readyState === "complete") {
          return setTimeout(jQuery.ready, 1);
        }
        if (document.addEventListener) {
          document.addEventListener("DOMContentLoaded", DOMContentLoaded, false);
          window.addEventListener("load", jQuery.ready, false);
        } else {
          if (document.attachEvent) {
            document.attachEvent("onreadystatechange", DOMContentLoaded);
            window.attachEvent("onload", jQuery.ready);
            var toplevel = false;
            try {
              toplevel = window.frameElement == null;
            } catch(e) {
            }
            if (document.documentElement.doScroll && toplevel) {
              doScrollCheck();
            }
          }
        }
      },
      isFunction : function(obj) {
        return jQuery.type(obj) === "function";
      },
      isArray : Array.isArray ||
      function(obj) {
        return jQuery.type(obj) === "array";
      },
      isWindow : function(obj) {
        return obj != null && obj == obj.window;
      },
      isNumeric : function(obj) {
        return !isNaN(parseFloat(obj)) && isFinite(obj);
      },
      type : function(obj) {
        return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";
      },
      isPlainObject : function(obj) {
        if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) {
          return false;
        }
        try {
          if (obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
            return false;
          }
        } catch(e) {
          return false;
        }
        var key;
        for (key in obj) {
        }
        return key === undefined || hasOwn.call(obj, key);
      },
      isEmptyObject : function(obj) {
        for (var name in obj) {
          return false;
        }
        return true;
      },
      error : function(msg) {
        throw new Error(msg);
      },
      parseJSON : function(data) {
        if ( typeof data !== "string" || !data) {
          return null;
        }
        data = jQuery.trim(data);
        if (window.JSON && window.JSON.parse) {
          return window.JSON.parse(data);
        }
        if (rvalidchars.test(data.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, ""))) {
          return (new Function("return " + data))();
        }
        jQuery.error("Invalid JSON: " + data);
      },
      parseXML : function(data) {
        if ( typeof data !== "string" || !data) {
          return null;
        }
        var xml, tmp;
        try {
          if (window.DOMParser) {
            tmp = new DOMParser();
            xml = tmp.parseFromString(data, "text/xml");
          } else {
            xml = new ActiveXObject("Microsoft.XMLDOM");
            xml.async = "false";
            xml.loadXML(data);
          }
        } catch(e) {
          xml = undefined;
        }
        if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
          jQuery.error("Invalid XML: " + data);
        }
        return xml;
      },
      noop : function() {
      },
      globalEval : function(data) {
        if (data && rnotwhite.test(data)) {
          (window.execScript ||
          function(data) {
            window["eval"].call(window, data);
          })(data);
        }
      },
      camelCase : function(string) {
        return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
      },
      nodeName : function(elem, name) {
        return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
      },
      each : function(object, callback, args) {
        var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object);
        if (args) {
          if (isObj) {
            for (name in object) {
              if (callback.apply(object[name], args) === false) {
                break;
              }
            }
          } else {
            for (; i < length; ) {
              if (callback.apply(object[i++], args) === false) {
                break;
              }
            }
          }
        } else {
          if (isObj) {
            for (name in object) {
              if (callback.call(object[name], name, object[name]) === false) {
                break;
              }
            }
          } else {
            for (; i < length; ) {
              if (callback.call(object[i], i, object[i++]) === false) {
                break;
              }
            }
          }
        }
        return object;
      },
      trim : trim ? function(text) {
        return text == null ? "" : trim.call(text);
      } : function(text) {
        return text == null ? "" : text.toString().replace(trimLeft, "").replace(trimRight, "");
      },
      makeArray : function(array, results) {
        var ret = results || [];
        if (array != null) {
          var type = jQuery.type(array);
          if (array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow(array)) {
            push.call(ret, array);
          } else {
            jQuery.merge(ret, array);
          }
        }
        return ret;
      },
      inArray : function(elem, array, i) {
        var len;
        if (array) {
          if (indexOf) {
            return indexOf.call(array, elem, i);
          }
          len = array.length;
          i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
          for (; i < len; i++) {
            if ( i in array && array[i] === elem) {
              return i;
            }
          }
        }
        return -1;
      },
      merge : function(first, second) {
        var i = first.length, j = 0;
        if ( typeof second.length === "number") {
          for (var l = second.length; j < l; j++) {
            first[i++] = second[j];
          }
        } else {
          while (second[j] !== undefined) {
            first[i++] = second[j++];
          }
        }
        first.length = i;
        return first;
      },
      grep : function(elems, callback, inv) {
        var ret = [], retVal;
        inv = !!inv;
        for (var i = 0, length = elems.length; i < length; i++) {
          retVal = !!callback(elems[i], i);
          if (inv !== retVal) {
            ret.push(elems[i]);
          }
        }
        return ret;
      },
      map : function(elems, callback, arg) {
        var value, key, ret = [], i = 0, length = elems.length, isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ((length > 0 && elems[0] && elems[length - 1]) || length === 0 || jQuery.isArray(elems));
        if (isArray) {
          for (; i < length; i++) {
            value = callback(elems[i], i, arg);
            if (value != null) {
              ret[ret.length] = value;
            }
          }
        } else {
          for (key in elems) {
            value = callback(elems[key], key, arg);
            if (value != null) {
              ret[ret.length] = value;
            }
          }
        }
        return ret.concat.apply([], ret);
      },
      guid : 1,
      proxy : function(fn, context) {
        if ( typeof context === "string") {
          var tmp = fn[context];
          context = fn;
          fn = tmp;
        }
        if (!jQuery.isFunction(fn)) {
          return undefined;
        }
        var args = slice.call(arguments, 2), proxy = function() {
          return fn.apply(context, args.concat(slice.call(arguments)));
        };
        proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
        return proxy;
      },
      access : function(elems, fn, key, value, chainable, emptyGet, pass) {
        var exec, bulk = key == null, i = 0, length = elems.length;
        if (key && typeof key === "object") {
          for (i in key) {
            jQuery.access(elems, fn, i, key[i], 1, emptyGet, value);
          }
          chainable = 1;
        } else {
          if (value !== undefined) {
            exec = pass === undefined && jQuery.isFunction(value);
            if (bulk) {
              if (exec) {
                exec = fn;
                fn = function(elem, key, value) {
                  return exec.call(jQuery(elem), value);
                };
              } else {
                fn.call(elems, value);
                fn = null;
              }
            }
            if (fn) {
              for (; i < length; i++) {
                fn(elems[i], key, exec ? value.call(elems[i], i, fn(elems[i], key)) : value, pass);
              }
            }
            chainable = 1;
          }
        }
        return chainable ? elems : bulk ? fn.call(elems) : length ? fn(elems[0], key) : emptyGet;
      },
      now : function() {
        return (new Date()).getTime();
      },
      uaMatch : function(ua) {
        ua = ua.toLowerCase();
        var match = rwebkit.exec(ua) || ropera.exec(ua) || rmsie.exec(ua) || ua.indexOf("compatible") < 0 && rmozilla.exec(ua) || [];
        return {
          browser : match[1] || "",
          version : match[2] || "0"
        };
      },
      sub : function() {
        function jQuerySub(selector, context) {
          return new jQuerySub.fn.init(selector, context);
        }
        jQuery.extend(true, jQuerySub, this);
        jQuerySub.superclass = this;
        jQuerySub.fn = jQuerySub.prototype = this();
        jQuerySub.fn.constructor = jQuerySub;
        jQuerySub.sub = this.sub;
        jQuerySub.fn.init = function init(selector, context) {
          if (context && context instanceof jQuery && !( context instanceof jQuerySub)) {
            context = jQuerySub(context);
          }
          return jQuery.fn.init.call(this, selector, context, rootjQuerySub);
        };
        jQuerySub.fn.init.prototype = jQuerySub.fn;
        var rootjQuerySub = jQuerySub(document);
        return jQuerySub;
      },
      browser : {}
    });
    jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
      class2type["[object " + name + "]"] = name.toLowerCase();
    });
    browserMatch = jQuery.uaMatch(userAgent);
    if (browserMatch.browser) {
      jQuery.browser[browserMatch.browser] = true;
      jQuery.browser.version = browserMatch.version;
    }
    if (jQuery.browser.webkit) {
      jQuery.browser.safari = true;
    }
    if (rnotwhite.test("\xA0")) {
      trimLeft = /^[\s\xA0]+/;
      trimRight = /[\s\xA0]+$/;
    }
    rootjQuery = jQuery(document);
    if (document.addEventListener) {
      DOMContentLoaded = function() {
        document.removeEventListener("DOMContentLoaded", DOMContentLoaded, false);
        jQuery.ready();
      };
    } else {
      if (document.attachEvent) {
        DOMContentLoaded = function() {
          if (document.readyState === "complete") {
            document.detachEvent("onreadystatechange", DOMContentLoaded);
            jQuery.ready();
          }
        };
      }
    }
    function doScrollCheck() {
      if (jQuery.isReady) {
        return;
      }
      try {
        document.documentElement.doScroll("left");
      } catch(e) {
        setTimeout(doScrollCheck, 1);
        return;
      }
      jQuery.ready();
    }
    return jQuery;
  })();
  var flagsCache = {};
  function createFlags(flags) {
    var object = flagsCache[flags] = {}, i, length;
    flags = flags.split(/\s+/);
    for ( i = 0, length = flags.length; i < length; i++) {
      object[flags[i]] = true;
    }
    return object;
  }
  jQuery.Callbacks = function(flags) {
    flags = flags ? (flagsCache[flags] || createFlags(flags)) : {};
    var list = [], stack = [], memory, fired, firing, firingStart, firingLength, firingIndex, add = function(args) {
      var i, length, elem, type, actual;
      for ( i = 0, length = args.length; i < length; i++) {
        elem = args[i];
        type = jQuery.type(elem);
        if (type === "array") {
          add(elem);
        } else {
          if (type === "function") {
            if (!flags.unique || !self.has(elem)) {
              list.push(elem);
            }
          }
        }
      }
    }, fire = function(context, args) {
      args = args || [];
      memory = !flags.memory || [context, args];
      fired = true;
      firing = true;
      firingIndex = firingStart || 0;
      firingStart = 0;
      firingLength = list.length;
      for (; list && firingIndex < firingLength; firingIndex++) {
        if (list[firingIndex].apply(context, args) === false && flags.stopOnFalse) {
          memory = true;
          break;
        }
      }
      firing = false;
      if (list) {
        if (!flags.once) {
          if (stack && stack.length) {
            memory = stack.shift();
            self.fireWith(memory[0], memory[1]);
          }
        } else {
          if (memory === true) {
            self.disable();
          } else {
            list = [];
          }
        }
      }
    }, self = {
      add : function() {
        if (list) {
          var length = list.length;
          add(arguments);
          if (firing) {
            firingLength = list.length;
          } else {
            if (memory && memory !== true) {
              firingStart = length;
              fire(memory[0], memory[1]);
            }
          }
        }
        return this;
      },
      remove : function() {
        if (list) {
          var args = arguments, argIndex = 0, argLength = args.length;
          for (; argIndex < argLength; argIndex++) {
            for (var i = 0; i < list.length; i++) {
              if (args[argIndex] === list[i]) {
                if (firing) {
                  if (i <= firingLength) {
                    firingLength--;
                    if (i <= firingIndex) {
                      firingIndex--;
                    }
                  }
                }
                list.splice(i--, 1);
                if (flags.unique) {
                  break;
                }
              }
            }
          }
        }
        return this;
      },
      has : function(fn) {
        if (list) {
          var i = 0, length = list.length;
          for (; i < length; i++) {
            if (fn === list[i]) {
              return true;
            }
          }
        }
        return false;
      },
      empty : function() {
        list = [];
        return this;
      },
      disable : function() {
        list = stack = memory = undefined;
        return this;
      },
      disabled : function() {
        return !list;
      },
      lock : function() {
        stack = undefined;
        if (!memory || memory === true) {
          self.disable();
        }
        return this;
      },
      locked : function() {
        return !stack;
      },
      fireWith : function(context, args) {
        if (stack) {
          if (firing) {
            if (!flags.once) {
              stack.push([context, args]);
            }
          } else {
            if (!(flags.once && memory)) {
              fire(context, args);
            }
          }
        }
        return this;
      },
      fire : function() {
        self.fireWith(this, arguments);
        return this;
      },
      fired : function() {
        return !!fired;
      }
    };
    return self;
  };
  var sliceDeferred = [].slice;
  jQuery.extend({
    Deferred : function(func) {
      var doneList = jQuery.Callbacks("once memory"), failList = jQuery.Callbacks("once memory"), progressList = jQuery.Callbacks("memory"), state = "pending", lists = {
        resolve : doneList,
        reject : failList,
        notify : progressList
      }, promise = {
        done : doneList.add,
        fail : failList.add,
        progress : progressList.add,
        state : function() {
          return state;
        },
        isResolved : doneList.fired,
        isRejected : failList.fired,
        then : function(doneCallbacks, failCallbacks, progressCallbacks) {
          deferred.done(doneCallbacks).fail(failCallbacks).progress(progressCallbacks);
          return this;
        },
        always : function() {
          deferred.done.apply(deferred, arguments).fail.apply(deferred, arguments);
          return this;
        },
        pipe : function(fnDone, fnFail, fnProgress) {
          return jQuery.Deferred(function(newDefer) {
            jQuery.each({
              done : [fnDone, "resolve"],
              fail : [fnFail, "reject"],
              progress : [fnProgress, "notify"]
            }, function(handler, data) {
              var fn = data[0], action = data[1], returned;
              if (jQuery.isFunction(fn)) {
                deferred[handler](function() {
                  returned = fn.apply(this, arguments);
                  if (returned && jQuery.isFunction(returned.promise)) {
                    returned.promise().then(newDefer.resolve, newDefer.reject, newDefer.notify);
                  } else {
                    newDefer[action+"With"](this === deferred ? newDefer : this, [returned]);
                  }
                });
              } else {
                deferred[handler](newDefer[action]);
              }
            });
          }).promise();
        },
        promise : function(obj) {
          if (obj == null) {
            obj = promise;
          } else {
            for (var key in promise) {
              obj[key] = promise[key];
            }
          }
          return obj;
        }
      }, deferred = promise.promise({}), key;
      for (key in lists) {
        deferred[key] = lists[key].fire;
        deferred[key + "With"] = lists[key].fireWith;
      }
      deferred.done(function() {
        state = "resolved";
      }, failList.disable, progressList.lock).fail(function() {
        state = "rejected";
      }, doneList.disable, progressList.lock);
      if (func) {
        func.call(deferred, deferred);
      }
      return deferred;
    },
    when : function(firstParam) {
      var args = sliceDeferred.call(arguments, 0), i = 0, length = args.length, pValues = new Array(length), count = length, pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction(firstParam.promise) ? firstParam : jQuery.Deferred(), promise = deferred.promise();
      function resolveFunc(i) {
        return function(value) {
          args[i] = arguments.length > 1 ? sliceDeferred.call(arguments, 0) : value;
          if (!(--count)) {
            deferred.resolveWith(deferred, args);
          }
        };
      }

      function progressFunc(i) {
        return function(value) {
          pValues[i] = arguments.length > 1 ? sliceDeferred.call(arguments, 0) : value;
          deferred.notifyWith(promise, pValues);
        };
      }

      if (length > 1) {
        for (; i < length; i++) {
          if (args[i] && args[i].promise && jQuery.isFunction(args[i].promise)) {
            args[i].promise().then(resolveFunc(i), deferred.reject, progressFunc(i));
          } else {--count;
          }
        }
        if (!count) {
          deferred.resolveWith(deferred, args);
        }
      } else {
        if (deferred !== firstParam) {
          deferred.resolveWith(deferred, length ? [firstParam] : []);
        }
      }
      return promise;
    }
  });
  jQuery.support = (function() {
    var support, all, a, select, opt, input, fragment, tds, events, eventName, i, isSupported, div = document.createElement("div"), documentElement = document.documentElement;
    div.setAttribute("className", "t");
    div.innerHTML = "   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
    all = div.getElementsByTagName("*");
    a = div.getElementsByTagName("a")[0];
    if (!all || !all.length || !a) {
      return {};
    }
    select = document.createElement("select");
    opt = select.appendChild(document.createElement("option"));
    input = div.getElementsByTagName("input")[0];
    support = {
      leadingWhitespace : (div.firstChild.nodeType === 3),
      tbody : !div.getElementsByTagName("tbody").length,
      htmlSerialize : !!div.getElementsByTagName("link").length,
      style : /top/.test(a.getAttribute("style")),
      hrefNormalized : (a.getAttribute("href") === "/a"),
      opacity : /^0.55/.test(a.style.opacity),
      cssFloat : !!a.style.cssFloat,
      checkOn : (input.value === "on"),
      optSelected : opt.selected,
      getSetAttribute : div.className !== "t",
      enctype : !!document.createElement("form").enctype,
      html5Clone : document.createElement("nav").cloneNode(true).outerHTML !== "<:nav></:nav>",
      submitBubbles : true,
      changeBubbles : true,
      focusinBubbles : false,
      deleteExpando : true,
      noCloneEvent : true,
      inlineBlockNeedsLayout : false,
      shrinkWrapBlocks : false,
      reliableMarginRight : true,
      pixelMargin : true
    };
    jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat");
    input.checked = true;
    support.noCloneChecked = input.cloneNode(true).checked;
    select.disabled = true;
    support.optDisabled = !opt.disabled;
    try {
      delete div.test;
    } catch(e) {
      support.deleteExpando = false;
    }
    if (!div.addEventListener && div.attachEvent && div.fireEvent) {
      div.attachEvent("onclick", function() {
        support.noCloneEvent = false;
      });
      div.cloneNode(true).fireEvent("onclick");
    }
    input = document.createElement("input");
    input.value = "t";
    input.setAttribute("type", "radio");
    support.radioValue = input.value === "t";
    input.setAttribute("checked", "checked");
    input.setAttribute("name", "t");
    div.appendChild(input);
    fragment = document.createDocumentFragment();
    fragment.appendChild(div.lastChild);
    support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
    support.appendChecked = input.checked;
    fragment.removeChild(input);
    fragment.appendChild(div);
    if (div.attachEvent) {
      for (i in {
        submit : 1,
        change : 1,
        focusin : 1
      }) {
        eventName = "on" + i;
        isSupported = ( eventName in div);
        if (!isSupported) {
          div.setAttribute(eventName, "return;");
          isSupported = ( typeof div[eventName] === "function");
        }
        support[i + "Bubbles"] = isSupported;
      }
    }
    fragment.removeChild(div);
    fragment = select = opt = div = input = null;
    jQuery(function() {
      var container, outer, inner, table, td, offsetSupport, marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, paddingMarginBorderVisibility, paddingMarginBorder, body = document.getElementsByTagName("body")[0];
      if (!body) {
        return;
      }
      conMarginTop = 1;
      paddingMarginBorder = "padding:0;margin:0;border:";
      positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;";
      paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;";
      style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;";
      html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div><table " + style + "' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
      container = document.createElement("div");
      container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
      body.insertBefore(container, body.firstChild);
      div = document.createElement("div");
      container.appendChild(div);
      div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>";
      tds = div.getElementsByTagName("td");
      isSupported = (tds[0].offsetHeight === 0);
      tds[0].style.display = "";
      tds[1].style.display = "none";
      support.reliableHiddenOffsets = isSupported && (tds[0].offsetHeight === 0);
      if (window.getComputedStyle) {
        div.innerHTML = "";
        marginDiv = document.createElement("div");
        marginDiv.style.width = "0";
        marginDiv.style.marginRight = "0";
        div.style.width = "2px";
        div.appendChild(marginDiv);
        support.reliableMarginRight = (parseInt((window.getComputedStyle(marginDiv, null) || {
          marginRight : 0
        }).marginRight, 10) || 0) === 0;
      }
      if ( typeof div.style.zoom !== "undefined") {
        div.innerHTML = "";
        div.style.width = div.style.padding = "1px";
        div.style.border = 0;
        div.style.overflow = "hidden";
        div.style.display = "inline";
        div.style.zoom = 1;
        support.inlineBlockNeedsLayout = (div.offsetWidth === 3);
        div.style.display = "block";
        div.style.overflow = "visible";
        div.innerHTML = "<div style='width:5px;'></div>";
        support.shrinkWrapBlocks = (div.offsetWidth !== 3);
      }
      div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility;
      div.innerHTML = html;
      outer = div.firstChild;
      inner = outer.firstChild;
      td = outer.nextSibling.firstChild.firstChild;
      offsetSupport = {
        doesNotAddBorder : (inner.offsetTop !== 5),
        doesAddBorderForTableAndCells : (td.offsetTop === 5)
      };
      inner.style.position = "fixed";
      inner.style.top = "20px";
      offsetSupport.fixedPosition = (inner.offsetTop === 20 || inner.offsetTop === 15);
      inner.style.position = inner.style.top = "";
      outer.style.overflow = "hidden";
      outer.style.position = "relative";
      offsetSupport.subtractsBorderForOverflowNotVisible = (inner.offsetTop === -5);
      offsetSupport.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== conMarginTop);
      if (window.getComputedStyle) {
        div.style.marginTop = "1%";
        support.pixelMargin = (window.getComputedStyle(div, null) || {
          marginTop : 0
        }).marginTop !== "1%";
      }
      if ( typeof container.style.zoom !== "undefined") {
        container.style.zoom = 1;
      }
      body.removeChild(container);
      marginDiv = div = container = null;
      jQuery.extend(support, offsetSupport);
    });
    return support;
  })();
  var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g;
  jQuery.extend({
    cache : {},
    uuid : 0,
    expando : "jQuery" + (jQuery.fn.jquery + Math.random()).replace(/\D/g, ""),
    noData : {
      embed : true,
      object : "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
      applet : true
    },
    hasData : function(elem) {
      elem = elem.nodeType ? jQuery.cache[elem[jQuery.expando]] : elem[jQuery.expando];
      return !!elem && !isEmptyDataObject(elem);
    },
    data : function(elem, name, data, pvt) {
      if (!jQuery.acceptData(elem)) {
        return;
      }
      var privateCache, thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", isNode = elem.nodeType, cache = isNode ? jQuery.cache : elem, id = isNode ? elem[internalKey] : elem[internalKey] && internalKey, isEvents = name === "events";
      if ((!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined) {
        return;
      }
      if (!id) {
        if (isNode) {
          elem[internalKey] = id = ++jQuery.uuid;
        } else {
          id = internalKey;
        }
      }
      if (!cache[id]) {
        cache[id] = {};
        if (!isNode) {
          cache[id].toJSON = jQuery.noop;
        }
      }
      if ( typeof name === "object" || typeof name === "function") {
        if (pvt) {
          cache[id] = jQuery.extend(cache[id], name);
        } else {
          cache[id].data = jQuery.extend(cache[id].data, name);
        }
      }
      privateCache = thisCache = cache[id];
      if (!pvt) {
        if (!thisCache.data) {
          thisCache.data = {};
        }
        thisCache = thisCache.data;
      }
      if (data !== undefined) {
        thisCache[jQuery.camelCase(name)] = data;
      }
      if (isEvents && !thisCache[name]) {
        return privateCache.events;
      }
      if (getByName) {
        ret = thisCache[name];
        if (ret == null) {
          ret = thisCache[jQuery.camelCase(name)];
        }
      } else {
        ret = thisCache;
      }
      return ret;
    },
    removeData : function(elem, name, pvt) {
      if (!jQuery.acceptData(elem)) {
        return;
      }
      var thisCache, i, l, internalKey = jQuery.expando, isNode = elem.nodeType, cache = isNode ? jQuery.cache : elem, id = isNode ? elem[internalKey] : internalKey;
      if (!cache[id]) {
        return;
      }
      if (name) {
        thisCache = pvt ? cache[id] : cache[id].data;
        if (thisCache) {
          if (!jQuery.isArray(name)) {
            if ( name in thisCache) {
              name = [name];
            } else {
              name = jQuery.camelCase(name);
              if ( name in thisCache) {
                name = [name];
              } else {
                name = name.split(" ");
              }
            }
          }
          for ( i = 0, l = name.length; i < l; i++) {
            delete thisCache[name[i]];
          }
          if (!( pvt ? isEmptyDataObject : jQuery.isEmptyObject)(thisCache)) {
            return;
          }
        }
      }
      if (!pvt) {
        delete cache[id].data;
        if (!isEmptyDataObject(cache[id])) {
          return;
        }
      }
      if (jQuery.support.deleteExpando || !cache.setInterval) {
        delete cache[id];
      } else {
        cache[id] = null;
      }
      if (isNode) {
        if (jQuery.support.deleteExpando) {
          delete elem[internalKey];
        } else {
          if (elem.removeAttribute) {
            elem.removeAttribute(internalKey);
          } else {
            elem[internalKey] = null;
          }
        }
      }
    },
    _data : function(elem, name, data) {
      return jQuery.data(elem, name, data, true);
    },
    acceptData : function(elem) {
      if (elem.nodeName) {
        var match = jQuery.noData[elem.nodeName.toLowerCase()];
        if (match) {
          return !(match === true || elem.getAttribute("classid") !== match);
        }
      }
      return true;
    }
  });
  jQuery.fn.extend({
    data : function(key, value) {
      var parts, part, attr, name, l, elem = this[0], i = 0, data = null;
      if (key === undefined) {
        if (this.length) {
          data = jQuery.data(elem);
          if (elem.nodeType === 1 && !jQuery._data(elem, "parsedAttrs")) {
            attr = elem.attributes;
            for ( l = attr.length; i < l; i++) {
              name = attr[i].name;
              if (name.indexOf("data-") === 0) {
                name = jQuery.camelCase(name.substring(5));
                dataAttr(elem, name, data[name]);
              }
            }
            jQuery._data(elem, "parsedAttrs", true);
          }
        }
        return data;
      }
      if ( typeof key === "object") {
        return this.each(function() {
          jQuery.data(this, key);
        });
      }
      parts = key.split(".", 2);
      parts[1] = parts[1] ? "." + parts[1] : "";
      part = parts[1] + "!";
      return jQuery.access(this, function(value) {
        if (value === undefined) {
          data = this.triggerHandler("getData" + part, [parts[0]]);
          if (data === undefined && elem) {
            data = jQuery.data(elem, key);
            data = dataAttr(elem, key, data);
          }
          return data === undefined && parts[1] ? this.data(parts[0]) : data;
        }
        parts[1] = value;
        this.each(function() {
          var self = jQuery(this);
          self.triggerHandler("setData" + part, parts);
          jQuery.data(this, key, value);
          self.triggerHandler("changeData" + part, parts);
        });
      }, null, value, arguments.length > 1, null, false);
    },
    removeData : function(key) {
      return this.each(function() {
        jQuery.removeData(this, key);
      });
    }
  });
  function dataAttr(elem, key, data) {
    if (data === undefined && elem.nodeType === 1) {
      var name = "data-" + key.replace(rmultiDash, "-$1").toLowerCase();
      data = elem.getAttribute(name);
      if ( typeof data === "string") {
        try {
          data = data === "true" ? true : data === "false" ? false : data === "null" ? null : jQuery.isNumeric(data) ? +data : rbrace.test(data) ? jQuery.parseJSON(data) : data;
        } catch(e) {
        }
        jQuery.data(elem, key, data);
      } else {
        data = undefined;
      }
    }
    return data;
  }

  function isEmptyDataObject(obj) {
    for (var name in obj) {
      if (name === "data" && jQuery.isEmptyObject(obj[name])) {
        continue;
      }
      if (name !== "toJSON") {
        return false;
      }
    }
    return true;
  }

  function handleQueueMarkDefer(elem, type, src) {
    var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery._data(elem, deferDataKey);
    if (defer && (src === "queue" || !jQuery._data(elem, queueDataKey)) && (src === "mark" || !jQuery._data(elem, markDataKey))) {
      setTimeout(function() {
        if (!jQuery._data(elem, queueDataKey) && !jQuery._data(elem, markDataKey)) {
          jQuery.removeData(elem, deferDataKey, true);
          defer.fire();
        }
      }, 0);
    }
  }
  jQuery.extend({
    _mark : function(elem, type) {
      if (elem) {
        type = (type || "fx") + "mark";
        jQuery._data(elem, type, (jQuery._data(elem, type) || 0) + 1);
      }
    },
    _unmark : function(force, elem, type) {
      if (force !== true) {
        type = elem;
        elem = force;
        force = false;
      }
      if (elem) {
        type = type || "fx";
        var key = type + "mark", count = force ? 0 : ((jQuery._data(elem, key) || 1) - 1);
        if (count) {
          jQuery._data(elem, key, count);
        } else {
          jQuery.removeData(elem, key, true);
          handleQueueMarkDefer(elem, type, "mark");
        }
      }
    },
    queue : function(elem, type, data) {
      var q;
      if (elem) {
        type = (type || "fx") + "queue";
        q = jQuery._data(elem, type);
        if (data) {
          if (!q || jQuery.isArray(data)) {
            q = jQuery._data(elem, type, jQuery.makeArray(data));
          } else {
            q.push(data);
          }
        }
        return q || [];
      }
    },
    dequeue : function(elem, type) {
      type = type || "fx";
      var queue = jQuery.queue(elem, type), fn = queue.shift(), hooks = {};
      if (fn === "inprogress") {
        fn = queue.shift();
      }
      if (fn) {
        if (type === "fx") {
          queue.unshift("inprogress");
        }
        jQuery._data(elem, type + ".run", hooks);
        fn.call(elem, function() {
          jQuery.dequeue(elem, type);
        }, hooks);
      }
      if (!queue.length) {
        jQuery.removeData(elem, type + "queue " + type + ".run", true);
        handleQueueMarkDefer(elem, type, "queue");
      }
    }
  });
  jQuery.fn.extend({
    queue : function(type, data) {
      var setter = 2;
      if ( typeof type !== "string") {
        data = type;
        type = "fx";
        setter--;
      }
      if (arguments.length < setter) {
        return jQuery.queue(this[0], type);
      }
      return data === undefined ? this : this.each(function() {
        var queue = jQuery.queue(this, type, data);
        if (type === "fx" && queue[0] !== "inprogress") {
          jQuery.dequeue(this, type);
        }
      });
    },
    dequeue : function(type) {
      return this.each(function() {
        jQuery.dequeue(this, type);
      });
    },
    delay : function(time, type) {
      time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
      type = type || "fx";
      return this.queue(type, function(next, hooks) {
        var timeout = setTimeout(next, time);
        hooks.stop = function() {
          clearTimeout(timeout);
        };
      });
    },
    clearQueue : function(type) {
      return this.queue(type || "fx", []);
    },
    promise : function(type, object) {
      if ( typeof type !== "string") {
        object = type;
        type = undefined;
      }
      type = type || "fx";
      var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp;
      function resolve() {
        if (!(--count)) {
          defer.resolveWith(elements, [elements]);
        }
      }

      while (i--) {
        if (( tmp = jQuery.data(elements[i], deferDataKey, undefined, true) || (jQuery.data(elements[i], queueDataKey, undefined, true) || jQuery.data(elements[i], markDataKey, undefined, true)) && jQuery.data(elements[i], deferDataKey, jQuery.Callbacks("once memory"), true))) {
          count++;
          tmp.add(resolve);
        }
      }
      resolve();
      return defer.promise(object);
    }
  });
  var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, nodeHook, boolHook, fixSpecified;
  jQuery.fn.extend({
    attr : function(name, value) {
      return jQuery.access(this, jQuery.attr, name, value, arguments.length > 1);
    },
    removeAttr : function(name) {
      return this.each(function() {
        jQuery.removeAttr(this, name);
      });
    },
    prop : function(name, value) {
      return jQuery.access(this, jQuery.prop, name, value, arguments.length > 1);
    },
    removeProp : function(name) {
      name = jQuery.propFix[name] || name;
      return this.each(function() {
        try {
          this[name] = undefined;
          delete this[name];
        } catch(e) {
        }
      });
    },
    addClass : function(value) {
      var classNames, i, l, elem, setClass, c, cl;
      if (jQuery.isFunction(value)) {
        return this.each(function(j) {
          jQuery(this).addClass(value.call(this, j, this.className));
        });
      }
      if (value && typeof value === "string") {
        classNames = value.split(rspace);
        for ( i = 0, l = this.length; i < l; i++) {
          elem = this[i];
          if (elem.nodeType === 1) {
            if (!elem.className && classNames.length === 1) {
              elem.className = value;
            } else {
              setClass = " " + elem.className + " ";
              for ( c = 0, cl = classNames.length; c < cl; c++) {
                if (!~setClass.indexOf(" " + classNames[c] + " ")) {
                  setClass += classNames[c] + " ";
                }
              }
              elem.className = jQuery.trim(setClass);
            }
          }
        }
      }
      return this;
    },
    removeClass : function(value) {
      var classNames, i, l, elem, className, c, cl;
      if (jQuery.isFunction(value)) {
        return this.each(function(j) {
          jQuery(this).removeClass(value.call(this, j, this.className));
        });
      }
      if ((value && typeof value === "string") || value === undefined) {
        classNames = (value || "").split(rspace);
        for ( i = 0, l = this.length; i < l; i++) {
          elem = this[i];
          if (elem.nodeType === 1 && elem.className) {
            if (value) {
              className = (" " + elem.className + " ").replace(rclass, " ");
              for ( c = 0, cl = classNames.length; c < cl; c++) {
                className = className.replace(" " + classNames[c] + " ", " ");
              }
              elem.className = jQuery.trim(className);
            } else {
              elem.className = "";
            }
          }
        }
      }
      return this;
    },
    toggleClass : function(value, stateVal) {
      var type = typeof value, isBool = typeof stateVal === "boolean";
      if (jQuery.isFunction(value)) {
        return this.each(function(i) {
          jQuery(this).toggleClass(value.call(this, i, this.className, stateVal), stateVal);
        });
      }
      return this.each(function() {
        if (type === "string") {
          var className, i = 0, self = jQuery(this), state = stateVal, classNames = value.split(rspace);
          while (( className = classNames[i++])) {
            state = isBool ? state : !self.hasClass(className);
            self[state?"addClass":"removeClass"](className);
          }
        } else {
          if (type === "undefined" || type === "boolean") {
            if (this.className) {
              jQuery._data(this, "__className__", this.className);
            }
            this.className = this.className || value === false ? "" : jQuery._data(this, "__className__") || "";
          }
        }
      });
    },
    hasClass : function(selector) {
      var className = " " + selector + " ", i = 0, l = this.length;
      for (; i < l; i++) {
        if (this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf(className) > -1) {
          return true;
        }
      }
      return false;
    },
    val : function(value) {
      var hooks, ret, isFunction, elem = this[0];
      if (!arguments.length) {
        if (elem) {
          hooks = jQuery.valHooks[elem.type] || jQuery.valHooks[elem.nodeName.toLowerCase()];
          if (hooks && "get" in hooks && ( ret = hooks.get(elem, "value")) !== undefined) {
            return ret;
          }
          ret = elem.value;
          return typeof ret === "string" ? ret.replace(rreturn, "") : ret == null ? "" : ret;
        }
        return;
      }
      isFunction = jQuery.isFunction(value);
      return this.each(function(i) {
        var self = jQuery(this), val;
        if (this.nodeType !== 1) {
          return;
        }
        if (isFunction) {
          val = value.call(this, i, self.val());
        } else {
          val = value;
        }
        if (val == null) {
          val = "";
        } else {
          if ( typeof val === "number") {
            val += "";
          } else {
            if (jQuery.isArray(val)) {
              val = jQuery.map(val, function(value) {
                return value == null ? "" : value + "";
              });
            }
          }
        }
        hooks = jQuery.valHooks[this.type] || jQuery.valHooks[this.nodeName.toLowerCase()];
        if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) {
          this.value = val;
        }
      });
    }
  });
  jQuery.extend({
    valHooks : {
      option : {
        get : function(elem) {
          var val = elem.attributes.value;
          return !val || val.specified ? elem.value : elem.text;
        }
      },
      select : {
        get : function(elem) {
          var value, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one";
          if (index < 0) {
            return null;
          }
          i = one ? index : 0;
          max = one ? index + 1 : options.length;
          for (; i < max; i++) {
            option = options[i];
            if (option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup"))) {
              value = jQuery(option).val();
              if (one) {
                return value;
              }
              values.push(value);
            }
          }
          if (one && !values.length && options.length) {
            return jQuery(options[index]).val();
          }
          return values;
        },
        set : function(elem, value) {
          var values = jQuery.makeArray(value);
          jQuery(elem).find("option").each(function() {
            this.selected = jQuery.inArray(jQuery(this).val(), values) >= 0;
          });
          if (!values.length) {
            elem.selectedIndex = -1;
          }
          return values;
        }
      }
    },
    attrFn : {
      val : true,
      css : true,
      html : true,
      text : true,
      data : true,
      width : true,
      height : true,
      offset : true
    },
    attr : function(elem, name, value, pass) {
      var ret, hooks, notxml, nType = elem.nodeType;
      if (!elem || nType === 3 || nType === 8 || nType === 2) {
        return;
      }
      if (pass && name in jQuery.attrFn) {
        return jQuery(elem)[name](value);
      }
      if ( typeof elem.getAttribute === "undefined") {
        return jQuery.prop(elem, name, value);
      }
      notxml = nType !== 1 || !jQuery.isXMLDoc(elem);
      if (notxml) {
        name = name.toLowerCase();
        hooks = jQuery.attrHooks[name] || (rboolean.test(name) ? boolHook : nodeHook);
      }
      if (value !== undefined) {
        if (value === null) {
          jQuery.removeAttr(elem, name);
          return;
        } else {
          if (hooks && "set" in hooks && notxml && ( ret = hooks.set(elem, value, name)) !== undefined) {
            return ret;
          } else {
            elem.setAttribute(name, "" + value);
            return value;
          }
        }
      } else {
        if (hooks && "get" in hooks && notxml && ( ret = hooks.get(elem, name)) !== null) {
          return ret;
        } else {
          ret = elem.getAttribute(name);
          return ret === null ? undefined : ret;
        }
      }
    },
    removeAttr : function(elem, value) {
      var propName, attrNames, name, l, isBool, i = 0;
      if (value && elem.nodeType === 1) {
        attrNames = value.toLowerCase().split(rspace);
        l = attrNames.length;
        for (; i < l; i++) {
          name = attrNames[i];
          if (name) {
            propName = jQuery.propFix[name] || name;
            isBool = rboolean.test(name);
            if (!isBool) {
              jQuery.attr(elem, name, "");
            }
            elem.removeAttribute( getSetAttribute ? name : propName);
            if (isBool && propName in elem) {
              elem[propName] = false;
            }
          }
        }
      }
    },
    attrHooks : {
      type : {
        set : function(elem, value) {
          if (rtype.test(elem.nodeName) && elem.parentNode) {
            jQuery.error("type property can't be changed");
          } else {
            if (!jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input")) {
              var val = elem.value;
              elem.setAttribute("type", value);
              if (val) {
                elem.value = val;
              }
              return value;
            }
          }
        }
      },
      value : {
        get : function(elem, name) {
          if (nodeHook && jQuery.nodeName(elem, "button")) {
            return nodeHook.get(elem, name);
          }
          return name in elem ? elem.value : null;
        },
        set : function(elem, value, name) {
          if (nodeHook && jQuery.nodeName(elem, "button")) {
            return nodeHook.set(elem, value, name);
          }
          elem.value = value;
        }
      }
    },
    propFix : {
      tabindex : "tabIndex",
      readonly : "readOnly",
      "for" : "htmlFor",
      "class" : "className",
      maxlength : "maxLength",
      cellspacing : "cellSpacing",
      cellpadding : "cellPadding",
      rowspan : "rowSpan",
      colspan : "colSpan",
      usemap : "useMap",
      frameborder : "frameBorder",
      contenteditable : "contentEditable"
    },
    prop : function(elem, name, value) {
      var ret, hooks, notxml, nType = elem.nodeType;
      if (!elem || nType === 3 || nType === 8 || nType === 2) {
        return;
      }
      notxml = nType !== 1 || !jQuery.isXMLDoc(elem);
      if (notxml) {
        name = jQuery.propFix[name] || name;
        hooks = jQuery.propHooks[name];
      }
      if (value !== undefined) {
        if (hooks && "set" in hooks && ( ret = hooks.set(elem, value, name)) !== undefined) {
          return ret;
        } else {
          return (elem[name] = value);
        }
      } else {
        if (hooks && "get" in hooks && ( ret = hooks.get(elem, name)) !== null) {
          return ret;
        } else {
          return elem[name];
        }
      }
    },
    propHooks : {
      tabIndex : {
        get : function(elem) {
          var attributeNode = elem.getAttributeNode("tabindex");
          return attributeNode && attributeNode.specified ? parseInt(attributeNode.value, 10) : rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href ? 0 : undefined;
        }
      }
    }
  });
  jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
  boolHook = {
    get : function(elem, name) {
      var attrNode, property = jQuery.prop(elem, name);
      return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name)) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined;
    },
    set : function(elem, value, name) {
      var propName;
      if (value === false) {
        jQuery.removeAttr(elem, name);
      } else {
        propName = jQuery.propFix[name] || name;
        if ( propName in elem) {
          elem[propName] = true;
        }
        elem.setAttribute(name, name.toLowerCase());
      }
      return name;
    }
  };
  if (!getSetAttribute) {
    fixSpecified = {
      name : true,
      id : true,
      coords : true
    };
    nodeHook = jQuery.valHooks.button = {
      get : function(elem, name) {
        var ret;
        ret = elem.getAttributeNode(name);
        return ret && (fixSpecified[name] ? ret.nodeValue !== "" : ret.specified) ? ret.nodeValue : undefined;
      },
      set : function(elem, value, name) {
        var ret = elem.getAttributeNode(name);
        if (!ret) {
          ret = document.createAttribute(name);
          elem.setAttributeNode(ret);
        }
        return (ret.nodeValue = value + "");
      }
    };
    jQuery.attrHooks.tabindex.set = nodeHook.set;
    jQuery.each(["width", "height"], function(i, name) {
      jQuery.attrHooks[name] = jQuery.extend(jQuery.attrHooks[name], {
        set : function(elem, value) {
          if (value === "") {
            elem.setAttribute(name, "auto");
            return value;
          }
        }
      });
    });
    jQuery.attrHooks.contenteditable = {
      get : nodeHook.get,
      set : function(elem, value, name) {
        if (value === "") {
          value = "false";
        }
        nodeHook.set(elem, value, name);
      }
    };
  }
  if (!jQuery.support.hrefNormalized) {
    jQuery.each(["href", "src", "width", "height"], function(i, name) {
      jQuery.attrHooks[name] = jQuery.extend(jQuery.attrHooks[name], {
        get : function(elem) {
          var ret = elem.getAttribute(name, 2);
          return ret === null ? undefined : ret;
        }
      });
    });
  }
  if (!jQuery.support.style) {
    jQuery.attrHooks.style = {
      get : function(elem) {
        return elem.style.cssText.toLowerCase() || undefined;
      },
      set : function(elem, value) {
        return (elem.style.cssText = "" + value);
      }
    };
  }
  if (!jQuery.support.optSelected) {
    jQuery.propHooks.selected = jQuery.extend(jQuery.propHooks.selected, {
      get : function(elem) {
        var parent = elem.parentNode;
        if (parent) {
          parent.selectedIndex
          if (parent.parentNode) {
            parent.parentNode.selectedIndex
          }
        }
        return null;
      }
    });
  }
  if (!jQuery.support.enctype) {
    jQuery.propFix.enctype = "encoding";
  }
  if (!jQuery.support.checkOn) {
    jQuery.each(["radio", "checkbox"], function() {
      jQuery.valHooks[this] = {
        get : function(elem) {
          return elem.getAttribute("value") === null ? "on" : elem.value;
        }
      };
    });
  }
  jQuery.each(["radio", "checkbox"], function() {
    jQuery.valHooks[this] = jQuery.extend(jQuery.valHooks[this], {
      set : function(elem, value) {
        if (jQuery.isArray(value)) {
          return (elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0);
        }
      }
    });
  });
  var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, rhoverHack = /(?:^|\s)hover(\.\S+)?\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, quickParse = function(selector) {
    var quick = rquickIs.exec(selector);
    if (quick) {
      quick[1] = (quick[1] || "").toLowerCase();
      quick[3] = quick[3] && new RegExp("(?:^|\\s)" + quick[3] + "(?:\\s|$)");
    }
    return quick;
  }, quickIs = function(elem, m) {
    var attrs = elem.attributes || {};
    return ((!m[1] || elem.nodeName.toLowerCase() === m[1]) && (!m[2] || (attrs.id || {}).value === m[2]) && (!m[3] || m[3].test((attrs["class"] || {}).value)));
  }, hoverHack = function(events) {
    return jQuery.event.special.hover ? events : events.replace(rhoverHack, "mouseenter$1 mouseleave$1");
  };
  jQuery.event = {
    add : function(elem, types, handler, data, selector) {
      var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, quick, handlers, special;
      if (elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !( elemData = jQuery._data(elem))) {
        return;
      }
      if (handler.handler) {
        handleObjIn = handler;
        handler = handleObjIn.handler;
        selector = handleObjIn.selector;
      }
      if (!handler.guid) {
        handler.guid = jQuery.guid++;
      }
      events = elemData.events;
      if (!events) {
        elemData.events = events = {};
      }
      eventHandle = elemData.handle;
      if (!eventHandle) {
        elemData.handle = eventHandle = function(e) {
          return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply(eventHandle.elem, arguments) : undefined;
        };
        eventHandle.elem = elem;
      }
      types = jQuery.trim(hoverHack(types)).split(" ");
      for ( t = 0; t < types.length; t++) {
        tns = rtypenamespace.exec(types[t]) || [];
        type = tns[1];
        namespaces = (tns[2] || "").split(".").sort();
        special = jQuery.event.special[type] || {};
        type = ( selector ? special.delegateType : special.bindType) || type;
        special = jQuery.event.special[type] || {};
        handleObj = jQuery.extend({
          type : type,
          origType : tns[1],
          data : data,
          handler : handler,
          guid : handler.guid,
          selector : selector,
          quick : selector && quickParse(selector),
          namespace : namespaces.join(".")
        }, handleObjIn);
        handlers = events[type];
        if (!handlers) {
          handlers = events[type] = [];
          handlers.delegateCount = 0;
          if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
            if (elem.addEventListener) {
              elem.addEventListener(type, eventHandle, false);
            } else {
              if (elem.attachEvent) {
                elem.attachEvent("on" + type, eventHandle);
              }
            }
          }
        }
        if (special.add) {
          special.add.call(elem, handleObj);
          if (!handleObj.handler.guid) {
            handleObj.handler.guid = handler.guid;
          }
        }
        if (selector) {
          handlers.splice(handlers.delegateCount++, 0, handleObj);
        } else {
          handlers.push(handleObj);
        }
        jQuery.event.global[type] = true;
      }
      elem = null;
    },
    global : {},
    remove : function(elem, types, handler, selector, mappedTypes) {
      var elemData = jQuery.hasData(elem) && jQuery._data(elem), t, tns, type, origType, namespaces, origCount, j, events, special, handle, eventType, handleObj;
      if (!elemData || !( events = elemData.events)) {
        return;
      }
      types = jQuery.trim(hoverHack(types || "")).split(" ");
      for ( t = 0; t < types.length; t++) {
        tns = rtypenamespace.exec(types[t]) || [];
        type = origType = tns[1];
        namespaces = tns[2];
        if (!type) {
          for (type in events) {
            jQuery.event.remove(elem, type + types[t], handler, selector, true);
          }
          continue;
        }
        special = jQuery.event.special[type] || {};
        type = ( selector ? special.delegateType : special.bindType) || type;
        eventType = events[type] || [];
        origCount = eventType.length;
        namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
        for ( j = 0; j < eventType.length; j++) {
          handleObj = eventType[j];
          if ((mappedTypes || origType === handleObj.origType) && (!handler || handler.guid === handleObj.guid) && (!namespaces || namespaces.test(handleObj.namespace)) && (!selector || selector === handleObj.selector || selector === "**" && handleObj.selector)) {
            eventType.splice(j--, 1);
            if (handleObj.selector) {
              eventType.delegateCount--;
            }
            if (special.remove) {
              special.remove.call(elem, handleObj);
            }
          }
        }
        if (eventType.length === 0 && origCount !== eventType.length) {
          if (!special.teardown || special.teardown.call(elem, namespaces) === false) {
            jQuery.removeEvent(elem, type, elemData.handle);
          }
          delete events[type];
        }
      }
      if (jQuery.isEmptyObject(events)) {
        handle = elemData.handle;
        if (handle) {
          handle.elem = null;
        }
        jQuery.removeData(elem, ["events", "handle"], true);
      }
    },
    customEvent : {
      getData : true,
      setData : true,
      changeData : true
    },
    trigger : function(event, data, elem, onlyHandlers) {
      if (elem && (elem.nodeType === 3 || elem.nodeType === 8)) {
        return;
      }
      var type = event.type || event, namespaces = [], cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
      if (rfocusMorph.test(type + jQuery.event.triggered)) {
        return;
      }
      if (type.indexOf("!") >= 0) {
        type = type.slice(0, -1);
        exclusive = true;
      }
      if (type.indexOf(".") >= 0) {
        namespaces = type.split(".");
        type = namespaces.shift();
        namespaces.sort();
      }
      if ((!elem || jQuery.event.customEvent[type]) && !jQuery.event.global[type]) {
        return;
      }
      event = typeof event === "object" ? event[jQuery.expando] ? event : new jQuery.Event(type, event) : new jQuery.Event(type);
      event.type = type;
      event.isTrigger = true;
      event.exclusive = exclusive;
      event.namespace = namespaces.join(".");
      event.namespace_re = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
      ontype = type.indexOf(":") < 0 ? "on" + type : "";
      if (!elem) {
        cache = jQuery.cache;
        for (i in cache) {
          if (cache[i].events && cache[i].events[type]) {
            jQuery.event.trigger(event, data, cache[i].handle.elem, true);
          }
        }
        return;
      }
      event.result = undefined;
      if (!event.target) {
        event.target = elem;
      }
      data = data != null ? jQuery.makeArray(data) : [];
      data.unshift(event);
      special = jQuery.event.special[type] || {};
      if (special.trigger && special.trigger.apply(elem, data) === false) {
        return;
      }
      eventPath = [[elem, special.bindType || type]];
      if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) {
        bubbleType = special.delegateType || type;
        cur = rfocusMorph.test(bubbleType + type) ? elem : elem.parentNode;
        old = null;
        for (; cur; cur = cur.parentNode) {
          eventPath.push([cur, bubbleType]);
          old = cur;
        }
        if (old && old === elem.ownerDocument) {
          eventPath.push([old.defaultView || old.parentWindow || window, bubbleType]);
        }
      }
      for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++) {
        cur = eventPath[i][0];
        event.type = eventPath[i][1];
        handle = (jQuery._data(cur,"events")||{})[event.type] && jQuery._data(cur, "handle");
        if (handle) {
          handle.apply(cur, data);
        }
        handle = ontype && cur[ontype];
        if (handle && jQuery.acceptData(cur) && handle.apply(cur, data) === false) {
          event.preventDefault();
        }
      }
      event.type = type;
      if (!onlyHandlers && !event.isDefaultPrevented()) {
        if ((!special._default || special._default.apply(elem.ownerDocument, data) === false) && !(type === "click" && jQuery.nodeName(elem, "a")) && jQuery.acceptData(elem)) {
          if (ontype && elem[type] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow(elem)) {
            old = elem[ontype];
            if (old) {
              elem[ontype] = null;
            }
            jQuery.event.triggered = type;
            elem[type]();
            jQuery.event.triggered = undefined;
            if (old) {
              elem[ontype] = old;
            }
          }
        }
      }
      return event.result;
    },
    dispatch : function(event) {
      event = jQuery.event.fix(event || window.event);
      var handlers = ((jQuery._data(this,"events")||{})[event.type] || []), delegateCount = handlers.delegateCount, args = [].slice.call(arguments, 0), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[event.type] || {}, handlerQueue = [], i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
      args[0] = event;
      event.delegateTarget = this;
      if (special.preDispatch && special.preDispatch.call(this, event) === false) {
        return;
      }
      if (delegateCount && !(event.button && event.type === "click")) {
        jqcur = jQuery(this);
        jqcur.context = this.ownerDocument || this;
        for ( cur = event.target; cur != this; cur = cur.parentNode || this) {
          if (cur.disabled !== true) {
            selMatch = {};
            matches = [];
            jqcur[0] = cur;
            for ( i = 0; i < delegateCount; i++) {
              handleObj = handlers[i];
              sel = handleObj.selector;
              if (selMatch[sel] === undefined) {
                selMatch[sel] = (handleObj.quick ? quickIs(cur, handleObj.quick) : jqcur.is(sel));
              }
              if (selMatch[sel]) {
                matches.push(handleObj);
              }
            }
            if (matches.length) {
              handlerQueue.push({
                elem : cur,
                matches : matches
              });
            }
          }
        }
      }
      if (handlers.length > delegateCount) {
        handlerQueue.push({
          elem : this,
          matches : handlers.slice(delegateCount)
        });
      }
      for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++) {
        matched = handlerQueue[i];
        event.currentTarget = matched.elem;
        for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++) {
          handleObj = matched.matches[j];
          if (run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test(handleObj.namespace)) {
            event.data = handleObj.data;
            event.handleObj = handleObj;
            ret = ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler).apply(matched.elem, args);
            if (ret !== undefined) {
              event.result = ret;
              if (ret === false) {
                event.preventDefault();
                event.stopPropagation();
              }
            }
          }
        }
      }
      if (special.postDispatch) {
        special.postDispatch.call(this, event);
      }
      return event.result;
    },
    props : "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
    fixHooks : {},
    keyHooks : {
      props : "char charCode key keyCode".split(" "),
      filter : function(event, original) {
        if (event.which == null) {
          event.which = original.charCode != null ? original.charCode : original.keyCode;
        }
        return event;
      }
    },
    mouseHooks : {
      props : "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
      filter : function(event, original) {
        var eventDoc, doc, body, button = original.button, fromElement = original.fromElement;
        if (event.pageX == null && original.clientX != null) {
          eventDoc = event.target.ownerDocument || document;
          doc = eventDoc.documentElement;
          body = eventDoc.body;
          event.pageX = original.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
          event.pageY = original.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
        }
        if (!event.relatedTarget && fromElement) {
          event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
        }
        if (!event.which && button !== undefined) {
          event.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
        }
        return event;
      }
    },
    fix : function(event) {
      if (event[jQuery.expando]) {
        return event;
      }
      var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[event.type] || {}, copy = fixHook.props ? this.props.concat(fixHook.props) : this.props;
      event = jQuery.Event(originalEvent);
      for ( i = copy.length; i; ) {
        prop = copy[--i];
        event[prop] = originalEvent[prop];
      }
      if (!event.target) {
        event.target = originalEvent.srcElement || document;
      }
      if (event.target.nodeType === 3) {
        event.target = event.target.parentNode;
      }
      if (event.metaKey === undefined) {
        event.metaKey = event.ctrlKey;
      }
      return fixHook.filter ? fixHook.filter(event, originalEvent) : event;
    },
    special : {
      ready : {
        setup : jQuery.bindReady
      },
      load : {
        noBubble : true
      },
      focus : {
        delegateType : "focusin"
      },
      blur : {
        delegateType : "focusout"
      },
      beforeunload : {
        setup : function(data, namespaces, eventHandle) {
          if (jQuery.isWindow(this)) {
            this.onbeforeunload = eventHandle;
          }
        },
        teardown : function(namespaces, eventHandle) {
          if (this.onbeforeunload === eventHandle) {
            this.onbeforeunload = null;
          }
        }
      }
    },
    simulate : function(type, elem, event, bubble) {
      var e = jQuery.extend(new jQuery.Event(), event, {
        type : type,
        isSimulated : true,
        originalEvent : {}
      });
      if (bubble) {
        jQuery.event.trigger(e, null, elem);
      } else {
        jQuery.event.dispatch.call(elem, e);
      }
      if (e.isDefaultPrevented()) {
        event.preventDefault();
      }
    }
  };
  jQuery.event.handle = jQuery.event.dispatch;
  jQuery.removeEvent = document.removeEventListener ? function(elem, type, handle) {
    if (elem.removeEventListener) {
      elem.removeEventListener(type, handle, false);
    }
  } : function(elem, type, handle) {
    if (elem.detachEvent) {
      elem.detachEvent("on" + type, handle);
    }
  };
  jQuery.Event = function(src, props) {
    if (!(this instanceof jQuery.Event)) {
      return new jQuery.Event(src, props);
    }
    if (src && src.type) {
      this.originalEvent = src;
      this.type = src.type;
      this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
    } else {
      this.type = src;
    }
    if (props) {
      jQuery.extend(this, props);
    }
    this.timeStamp = src && src.timeStamp || jQuery.now();
    this[jQuery.expando] = true;
  };
  function returnFalse() {
    return false;
  }

  function returnTrue() {
    return true;
  }
  jQuery.Event.prototype = {
    preventDefault : function() {
      this.isDefaultPrevented = returnTrue;
      var e = this.originalEvent;
      if (!e) {
        return;
      }
      if (e.preventDefault) {
        e.preventDefault();
      } else {
        e.returnValue = false;
      }
    },
    stopPropagation : function() {
      this.isPropagationStopped = returnTrue;
      var e = this.originalEvent;
      if (!e) {
        return;
      }
      if (e.stopPropagation) {
        e.stopPropagation();
      }
      e.cancelBubble = true;
    },
    stopImmediatePropagation : function() {
      this.isImmediatePropagationStopped = returnTrue;
      this.stopPropagation();
    },
    isDefaultPrevented : returnFalse,
    isPropagationStopped : returnFalse,
    isImmediatePropagationStopped : returnFalse
  };
  jQuery.each({
    mouseenter : "mouseover",
    mouseleave : "mouseout"
  }, function(orig, fix) {
    jQuery.event.special[orig] = {
      delegateType : fix,
      bindType : fix,
      handle : function(event) {
        var target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector, ret;
        if (!related || (related !== target && !jQuery.contains(target, related))) {
          event.type = handleObj.origType;
          ret = handleObj.handler.apply(this, arguments);
          event.type = fix;
        }
        return ret;
      }
    };
  });
  if (!jQuery.support.submitBubbles) {
    jQuery.event.special.submit = {
      setup : function() {
        if (jQuery.nodeName(this, "form")) {
          return false;
        }
        jQuery.event.add(this, "click._submit keypress._submit", function(e) {
          var elem = e.target, form = jQuery.nodeName(elem, "input") || jQuery.nodeName(elem, "button") ? elem.form : undefined;
          if (form && !form._submit_attached) {
            jQuery.event.add(form, "submit._submit", function(event) {
              event._submit_bubble = true;
            });
            form._submit_attached = true;
          }
        });
      },
      postDispatch : function(event) {
        if (event._submit_bubble) {
          delete event._submit_bubble;
          if (this.parentNode && !event.isTrigger) {
            jQuery.event.simulate("submit", this.parentNode, event, true);
          }
        }
      },
      teardown : function() {
        if (jQuery.nodeName(this, "form")) {
          return false;
        }
        jQuery.event.remove(this, "._submit");
      }
    };
  }
  if (!jQuery.support.changeBubbles) {
    jQuery.event.special.change = {
      setup : function() {
        if (rformElems.test(this.nodeName)) {
          if (this.type === "checkbox" || this.type === "radio") {
            jQuery.event.add(this, "propertychange._change", function(event) {
              if (event.originalEvent.propertyName === "checked") {
                this._just_changed = true;
              }
            });
            jQuery.event.add(this, "click._change", function(event) {
              if (this._just_changed && !event.isTrigger) {
                this._just_changed = false;
                jQuery.event.simulate("change", this, event, true);
              }
            });
          }
          return false;
        }
        jQuery.event.add(this, "beforeactivate._change", function(e) {
          var elem = e.target;
          if (rformElems.test(elem.nodeName) && !elem._change_attached) {
            jQuery.event.add(elem, "change._change", function(event) {
              if (this.parentNode && !event.isSimulated && !event.isTrigger) {
                jQuery.event.simulate("change", this.parentNode, event, true);
              }
            });
            elem._change_attached = true;
          }
        });
      },
      handle : function(event) {
        var elem = event.target;
        if (this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox")) {
          return event.handleObj.handler.apply(this, arguments);
        }
      },
      teardown : function() {
        jQuery.event.remove(this, "._change");
        return rformElems.test(this.nodeName);
      }
    };
  }
  if (!jQuery.support.focusinBubbles) {
    jQuery.each({
      focus : "focusin",
      blur : "focusout"
    }, function(orig, fix) {
      var attaches = 0, handler = function(event) {
        jQuery.event.simulate(fix, event.target, jQuery.event.fix(event), true);
      };
      jQuery.event.special[fix] = {
        setup : function() {
          if (attaches++ === 0) {
            document.addEventListener(orig, handler, true);
          }
        },
        teardown : function() {
          if (--attaches === 0) {
            document.removeEventListener(orig, handler, true);
          }
        }
      };
    });
  }
  jQuery.fn.extend({
    on : function(types, selector, data, fn, one) {
      var origFn, type;
      if ( typeof types === "object") {
        if ( typeof selector !== "string") {
          data = data || selector;
          selector = undefined;
        }
        for (type in types) {
          this.on(type, selector, data, types[type], one);
        }
        return this;
      }
      if (data == null && fn == null) {
        fn = selector;
        data = selector = undefined;
      } else {
        if (fn == null) {
          if ( typeof selector === "string") {
            fn = data;
            data = undefined;
          } else {
            fn = data;
            data = selector;
            selector = undefined;
          }
        }
      }
      if (fn === false) {
        fn = returnFalse;
      } else {
        if (!fn) {
          return this;
        }
      }
      if (one === 1) {
        origFn = fn;
        fn = function(event) {
          jQuery().off(event);
          return origFn.apply(this, arguments);
        };
        fn.guid = origFn.guid || (origFn.guid = jQuery.guid++);
      }
      return this.each(function() {
        jQuery.event.add(this, types, fn, data, selector);
      });
    },
    one : function(types, selector, data, fn) {
      return this.on(types, selector, data, fn, 1);
    },
    off : function(types, selector, fn) {
      if (types && types.preventDefault && types.handleObj) {
        var handleObj = types.handleObj;
        jQuery(types.delegateTarget).off(handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler);
        return this;
      }
      if ( typeof types === "object") {
        for (var type in types) {
          this.off(type, selector, types[type]);
        }
        return this;
      }
      if (selector === false || typeof selector === "function") {
        fn = selector;
        selector = undefined;
      }
      if (fn === false) {
        fn = returnFalse;
      }
      return this.each(function() {
        jQuery.event.remove(this, types, fn, selector);
      });
    },
    bind : function(types, data, fn) {
      return this.on(types, null, data, fn);
    },
    unbind : function(types, fn) {
      return this.off(types, null, fn);
    },
    live : function(types, data, fn) {
      jQuery(this.context).on(types, this.selector, data, fn);
      return this;
    },
    die : function(types, fn) {
      jQuery(this.context).off(types, this.selector || "**", fn);
      return this;
    },
    delegate : function(selector, types, data, fn) {
      return this.on(types, selector, data, fn);
    },
    undelegate : function(selector, types, fn) {
      return arguments.length == 1 ? this.off(selector, "**") : this.off(types, selector, fn);
    },
    trigger : function(type, data) {
      return this.each(function() {
        jQuery.event.trigger(type, data, this);
      });
    },
    triggerHandler : function(type, data) {
      if (this[0]) {
        return jQuery.event.trigger(type, data, this[0], true);
      }
    },
    toggle : function(fn) {
      var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function(event) {
        var lastToggle = (jQuery._data(this, "lastToggle" + fn.guid) || 0) % i;
        jQuery._data(this, "lastToggle" + fn.guid, lastToggle + 1);
        event.preventDefault();
        return args[lastToggle].apply(this, arguments) || false;
      };
      toggler.guid = guid;
      while (i < args.length) {
        args[i++].guid = guid;
      }
      return this.click(toggler);
    },
    hover : function(fnOver, fnOut) {
      return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
    }
  });
  jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu").split(" "), function(i, name) {
    jQuery.fn[name] = function(data, fn) {
      if (fn == null) {
        fn = data;
        data = null;
      }
      return arguments.length > 0 ? this.on(name, null, data, fn) : this.trigger(name);
    };
    if (jQuery.attrFn) {
      jQuery.attrFn[name] = true;
    }
    if (rkeyEvent.test(name)) {
      jQuery.event.fixHooks[name] = jQuery.event.keyHooks;
    }
    if (rmouseEvent.test(name)) {
      jQuery.event.fixHooks[name] = jQuery.event.mouseHooks;
    }
  });
  /*!
   * Sizzle CSS Selector Engine
   *  Copyright 2011, The Dojo Foundation
   *  Released under the MIT, BSD, and GPL Licenses.
   *  More information: http://sizzlejs.com/
   */
  (function() {
    var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache" + (Math.random() + "").replace(".", ""), done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/;
    [0, 0].sort(function() {
      baseHasDuplicate = false;
      return 0;
    });
    var Sizzle = function(selector, context, results, seed) {
      results = results || [];
      context = context || document;
      var origContext = context;
      if (context.nodeType !== 1 && context.nodeType !== 9) {
        return [];
      }
      if (!selector || typeof selector !== "string") {
        return results;
      }
      var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML(context), parts = [], soFar = selector;
      do {
        chunker.exec("");
        m = chunker.exec(soFar);
        if (m) {
          soFar = m[3];
          parts.push(m[1]);
          if (m[2]) {
            extra = m[3];
            break;
          }
        }
      } while(m);
      if (parts.length > 1 && origPOS.exec(selector)) {
        if (parts.length === 2 && Expr.relative[parts[0]]) {
          set = posProcess(parts[0] + parts[1], context, seed);
        } 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, seed);
          }
        }
      } else {
        if (!seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1])) {
          ret = Sizzle.find(parts.shift(), context, contextXML);
          context = ret.expr ? Sizzle.filter(ret.expr,ret.set)[0] : ret.set[0];
        }
        if (context) {
          ret = seed ? {
            expr : parts.pop(),
            set : makeArray(seed)
          } : Sizzle.find(parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML);
          set = ret.expr ? Sizzle.filter(ret.expr, ret.set) : ret.set;
          if (parts.length > 0) {
            checkSet = makeArray(set);
          } else {
            prune = false;
          }
          while (parts.length) {
            cur = parts.pop();
            pop = cur;
            if (!Expr.relative[cur]) {
              cur = "";
            } else {
              pop = parts.pop();
            }
            if (pop == null) {
              pop = context;
            }
            Expr.relative[cur](checkSet, pop, contextXML);
          }
        } else {
          checkSet = parts = [];
        }
      }
      if (!checkSet) {
        checkSet = set;
      }
      if (!checkSet) {
        Sizzle.error(cur || selector);
      }
      if (toString.call(checkSet) === "[object Array]") {
        if (!prune) {
          results.push.apply(results, checkSet);
        } else {
          if (context && context.nodeType === 1) {
            for ( i = 0; checkSet[i] != null; i++) {
              if (checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i]))) {
                results.push(set[i]);
              }
            }
          } else {
            for ( 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, origContext, results, seed);
        Sizzle.uniqueSort(results);
      }
      return results;
    };
    Sizzle.uniqueSort = function(results) {
      if (sortOrder) {
        hasDuplicate = baseHasDuplicate;
        results.sort(sortOrder);
        if (hasDuplicate) {
          for (var i = 1; i < results.length; i++) {
            if (results[i] === results[i - 1]) {
              results.splice(i--, 1);
            }
          }
        }
      }
      return results;
    };
    Sizzle.matches = function(expr, set) {
      return Sizzle(expr, null, null, set);
    };
    Sizzle.matchesSelector = function(node, expr) {
      return Sizzle(expr, null, null, [node]).length > 0;
    };
    Sizzle.find = function(expr, context, isXML) {
      var set, i, len, match, type, left;
      if (!expr) {
        return [];
      }
      for ( i = 0, len = Expr.order.length; i < len; i++) {
        type = Expr.order[i];
        if (( match = Expr.leftMatch[type].exec(expr))) {
          left = match[1];
          match.splice(1, 1);
          if (left.substr(left.length - 1) !== "\\") {
            match[1] = (match[1] || "").replace(rBackslash, "");
            set = Expr.find[type](match, context, isXML);
            if (set != null) {
              expr = expr.replace(Expr.match[type], "");
              break;
            }
          }
        }
      }
      if (!set) {
        set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName("*") : [];
      }
      return {
        set : set,
        expr : expr
      };
    };
    Sizzle.filter = function(expr, set, inplace, not) {
      var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);
      while (expr && set.length) {
        for (type in Expr.filter) {
          if (( match = Expr.leftMatch[type].exec(expr)) != null && match[2]) {
            filter = Expr.filter[type];
            left = match[1];
            anyFound = false;
            match.splice(1, 1);
            if (left.substr(left.length - 1) === "\\") {
              continue;
            }
            if (curLoop === result) {
              result = [];
            }
            if (Expr.preFilter[type]) {
              match = Expr.preFilter[type](match, curLoop, inplace, result, not, isXMLFilter);
              if (!match) {
                anyFound = found = true;
              } else {
                if (match === true) {
                  continue;
                }
              }
            }
            if (match) {
              for ( i = 0; ( item = curLoop[i]) != null; i++) {
                if (item) {
                  found = filter(item, match, i, curLoop);
                  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;
            }
          }
        }
        if (expr === old) {
          if (anyFound == null) {
            Sizzle.error(expr);
          } else {
            break;
          }
        }
        old = expr;
      }
      return curLoop;
    };
    Sizzle.error = function(msg) {
      throw new Error("Syntax error, unrecognized expression: " + msg);
    };
    var getText = Sizzle.getText = function(elem) {
      var i, node, nodeType = elem.nodeType, ret = "";
      if (nodeType) {
        if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
          if ( typeof elem.textContent === "string") {
            return elem.textContent;
          } else {
            if ( typeof elem.innerText === "string") {
              return elem.innerText.replace(rReturn, "");
            } else {
              for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
                ret += getText(elem);
              }
            }
          }
        } else {
          if (nodeType === 3 || nodeType === 4) {
            return elem.nodeValue;
          }
        }
      } else {
        for ( i = 0; ( node = elem[i]); i++) {
          if (node.nodeType !== 8) {
            ret += getText(node);
          }
        }
      }
      return ret;
    };
    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|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
        TAG : /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
        CHILD : /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
        POS : /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
        PSEUDO : /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
      },
      leftMatch : {},
      attrMap : {
        "class" : "className",
        "for" : "htmlFor"
      },
      attrHandle : {
        href : function(elem) {
          return elem.getAttribute("href");
        },
        type : function(elem) {
          return elem.getAttribute("type");
        }
      },
      relative : {
        "+" : function(checkSet, part) {
          var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test(part), isPartStrNotTag = isPartStr && !isTag;
          if (isTag) {
            part = part.toLowerCase();
          }
          for (var i = 0, l = checkSet.length, elem; i < l; i++) {
            if (( elem = checkSet[i])) {
              while (( elem = elem.previousSibling) && elem.nodeType !== 1) {
              }
              checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part;
            }
          }
          if (isPartStrNotTag) {
            Sizzle.filter(part, checkSet, true);
          }
        },
        ">" : function(checkSet, part) {
          var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length;
          if (isPartStr && !rNonWord.test(part)) {
            part = part.toLowerCase();
            for (; i < l; i++) {
              elem = checkSet[i];
              if (elem) {
                var parent = elem.parentNode;
                checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
              }
            }
          } else {
            for (; i < l; i++) {
              elem = checkSet[i];
              if (elem) {
                checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part;
              }
            }
            if (isPartStr) {
              Sizzle.filter(part, checkSet, true);
            }
          }
        },
        "" : function(checkSet, part, isXML) {
          var nodeCheck, doneName = done++, checkFn = dirCheck;
          if ( typeof part === "string" && !rNonWord.test(part)) {
            part = part.toLowerCase();
            nodeCheck = part;
            checkFn = dirNodeCheck;
          }
          checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
        },
        "~" : function(checkSet, part, isXML) {
          var nodeCheck, doneName = done++, checkFn = dirCheck;
          if ( typeof part === "string" && !rNonWord.test(part)) {
            part = part.toLowerCase();
            nodeCheck = part;
            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.parentNode ? [m] : [];
          }
        },
        NAME : function(match, context) {
          if ( typeof context.getElementsByName !== "undefined") {
            var ret = [], results = context.getElementsByName(match[1]);
            for (var i = 0, l = results.length; i < l; i++) {
              if (results[i].getAttribute("name") === match[1]) {
                ret.push(results[i]);
              }
            }
            return ret.length === 0 ? null : ret;
          }
        },
        TAG : function(match, context) {
          if ( typeof context.getElementsByTagName !== "undefined") {
            return context.getElementsByTagName(match[1]);
          }
        }
      },
      preFilter : {
        CLASS : function(match, curLoop, inplace, result, not, isXML) {
          match = " " + match[1].replace(rBackslash, "") + " ";
          if (isXML) {
            return match;
          }
          for (var i = 0, elem; ( elem = curLoop[i]) != null; i++) {
            if (elem) {
              if (not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0)) {
                if (!inplace) {
                  result.push(elem);
                }
              } else {
                if (inplace) {
                  curLoop[i] = false;
                }
              }
            }
          }
          return false;
        },
        ID : function(match) {
          return match[1].replace(rBackslash, "");
        },
        TAG : function(match, curLoop) {
          return match[1].replace(rBackslash, "").toLowerCase();
        },
        CHILD : function(match) {
          if (match[1] === "nth") {
            if (!match[2]) {
              Sizzle.error(match[0]);
            }
            match[2] = match[2].replace(/^\+|\s*/g, "");
            var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test(match[2]) && "0n+" + match[2] || match[2]);
            match[2] = (test[1] + (test[2] || 1)) - 0;
            match[3] = test[3] - 0;
          } else {
            if (match[2]) {
              Sizzle.error(match[0]);
            }
          }
          match[0] = done++;
          return match;
        },
        ATTR : function(match, curLoop, inplace, result, not, isXML) {
          var name = match[1] = match[1].replace(rBackslash, "");
          if (!isXML && Expr.attrMap[name]) {
            match[1] = Expr.attrMap[name];
          }
          match[4] = (match[4] || match[5] || "").replace(rBackslash, "");
          if (match[2] === "~=") {
            match[4] = " " + match[4] + " ";
          }
          return match;
        },
        PSEUDO : function(match, curLoop, inplace, result, not) {
          if (match[1] === "not") {
            if ((chunker.exec(match[3]) || "").length > 1 || /^\w/.test(match[3])) {
              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]) || Expr.match.CHILD.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) {
          if (elem.parentNode) {
            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) {
          var attr = elem.getAttribute("type"), type = elem.type;
          return elem.nodeName.toLowerCase() === "input" && "text" === type && (attr === type || attr === null);
        },
        radio : function(elem) {
          return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
        },
        checkbox : function(elem) {
          return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
        },
        file : function(elem) {
          return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
        },
        password : function(elem) {
          return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
        },
        submit : function(elem) {
          var name = elem.nodeName.toLowerCase();
          return (name === "input" || name === "button") && "submit" === elem.type;
        },
        image : function(elem) {
          return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
        },
        reset : function(elem) {
          var name = elem.nodeName.toLowerCase();
          return (name === "input" || name === "button") && "reset" === elem.type;
        },
        button : function(elem) {
          var name = elem.nodeName.toLowerCase();
          return name === "input" && "button" === elem.type || name === "button";
        },
        input : function(elem) {
          return (/input|select|textarea|button/i).test(elem.nodeName);
        },
        focus : function(elem) {
          return elem === elem.ownerDocument.activeElement;
        }
      },
      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 : {
        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 || getText([elem]) || "").indexOf(match[3]) >= 0;
            } else {
              if (name === "not") {
                var not = match[3];
                for (var j = 0, l = not.length; j < l; j++) {
                  if (not[j] === elem) {
                    return false;
                  }
                }
                return true;
              } else {
                Sizzle.error(name);
              }
            }
          }
        },
        CHILD : function(elem, match) {
          var first, last, doneName, parent, cache, count, diff, type = match[1], node = elem;
          switch(type) {
            case"only":
            case"first":
              while (( node = node.previousSibling)) {
                if (node.nodeType === 1) {
                  return false;
                }
              }
              if (type === "first") {
                return true;
              }
              node = elem;
            case"last":
              while (( node = node.nextSibling)) {
                if (node.nodeType === 1) {
                  return false;
                }
              }
              return true;
            case"nth":
              first = match[2];
              last = match[3];
              if (first === 1 && last === 0) {
                return true;
              }
              doneName = match[0];
              parent = elem.parentNode;
              if (parent && (parent[expando] !== doneName || !elem.nodeIndex)) {
                count = 0;
                for ( node = parent.firstChild; node; node = node.nextSibling) {
                  if (node.nodeType === 1) {
                    node.nodeIndex = ++count;
                  }
                }
                parent[expando] = doneName;
              }
              diff = elem.nodeIndex - last;
              if (first === 0) {
                return diff === 0;
              } else {
                return (diff % first === 0 && diff / first >= 0);
              }
          }
        },
        ID : function(elem, match) {
          return elem.nodeType === 1 && elem.getAttribute("id") === match;
        },
        TAG : function(elem, match) {
          return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
        },
        CLASS : function(elem, match) {
          return (" " + (elem.className || elem.getAttribute("class")) + " ").indexOf(match) > -1;
        },
        ATTR : function(elem, match) {
          var name = match[1], result = Sizzle.attr ? Sizzle.attr(elem, name) : Expr.attrHandle[name] ? Expr.attrHandle[name](elem) : elem[name] != null ? elem[name] : elem.getAttribute(name), value = result + "", type = match[2], check = match[4];
          return result == null ? type === "!=" : !type && Sizzle.attr ? result != null : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : 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, fescape = function(all, num) {
      return "\\" + (num - 0 + 1);
    };
    for (var type in Expr.match) {
      Expr.match[type] = new RegExp(Expr.match[type].source + (/(?![^\[]*\])(?![^\(]*\))/.source));
      Expr.leftMatch[type] = new RegExp(/(^(?:.|\r|\n)*?)/.source + Expr.match[type].source.replace(/\\(\d+)/g, fescape));
    }
    Expr.match.globalPOS = origPOS;
    var makeArray = function(array, results) {
      array = Array.prototype.slice.call(array, 0);
      if (results) {
        results.push.apply(results, array);
        return results;
      }
      return array;
    };
    try {
      Array.prototype.slice.call(document.documentElement.childNodes,0)[0].nodeType
    } catch(e) {
      makeArray = function(array, results) {
        var i = 0, ret = results || [];
        if (toString.call(array) === "[object Array]") {
          Array.prototype.push.apply(ret, array);
        } else {
          if ( typeof array.length === "number") {
            for (var l = array.length; i < l; i++) {
              ret.push(array[i]);
            }
          } else {
            for (; array[i]; i++) {
              ret.push(array[i]);
            }
          }
        }
        return ret;
      };
    }
    var sortOrder, siblingCheck;
    if (document.documentElement.compareDocumentPosition) {
      sortOrder = function(a, b) {
        if (a === b) {
          hasDuplicate = true;
          return 0;
        }
        if (!a.compareDocumentPosition || !b.compareDocumentPosition) {
          return a.compareDocumentPosition ? -1 : 1;
        }
        return a.compareDocumentPosition(b) & 4 ? -1 : 1;
      };
    } else {
      sortOrder = function(a, b) {
        if (a === b) {
          hasDuplicate = true;
          return 0;
        } else {
          if (a.sourceIndex && b.sourceIndex) {
            return a.sourceIndex - b.sourceIndex;
          }
        }
        var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup;
        if (aup === bup) {
          return siblingCheck(a, b);
        } else {
          if (!aup) {
            return -1;
          } else {
            if (!bup) {
              return 1;
            }
          }
        }
        while (cur) {
          ap.unshift(cur);
          cur = cur.parentNode;
        }
        cur = bup;
        while (cur) {
          bp.unshift(cur);
          cur = cur.parentNode;
        }
        al = ap.length;
        bl = bp.length;
        for (var i = 0; i < al && i < bl; i++) {
          if (ap[i] !== bp[i]) {
            return siblingCheck(ap[i], bp[i]);
          }
        }
        return i === al ? siblingCheck(a, bp[i], -1) : siblingCheck(ap[i], b, 1);
      };
      siblingCheck = function(a, b, ret) {
        if (a === b) {
          return ret;
        }
        var cur = a.nextSibling;
        while (cur) {
          if (cur === b) {
            return -1;
          }
          cur = cur.nextSibling;
        }
        return 1;
      };
    }
    (function() {
      var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement;
      form.innerHTML = "<a name='" + id + "'/>";
      root.insertBefore(form, root.firstChild);
      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);
      root = form = null;
    })();
    (function() {
      var div = document.createElement("div");
      div.appendChild(document.createComment(""));
      if (div.getElementsByTagName("*").length > 0) {
        Expr.find.TAG = function(match, context) {
          var results = context.getElementsByTagName(match[1]);
          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;
        };
      }
      div.innerHTML = "<a href='#'></a>";
      if (div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#") {
        Expr.attrHandle.href = function(elem) {
          return elem.getAttribute("href", 2);
        };
      }
      div = null;
    })();
    if (document.querySelectorAll) {
      (function() {
        var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__";
        div.innerHTML = "<p class='TEST'></p>";
        if (div.querySelectorAll && div.querySelectorAll(".TEST").length === 0) {
          return;
        }
        Sizzle = function(query, context, extra, seed) {
          context = context || document;
          if (!seed && !Sizzle.isXML(context)) {
            var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(query);
            if (match && (context.nodeType === 1 || context.nodeType === 9)) {
              if (match[1]) {
                return makeArray(context.getElementsByTagName(query), extra);
              } else {
                if (match[2] && Expr.find.CLASS && context.getElementsByClassName) {
                  return makeArray(context.getElementsByClassName(match[2]), extra);
                }
              }
            }
            if (context.nodeType === 9) {
              if (query === "body" && context.body) {
                return makeArray([context.body], extra);
              } else {
                if (match && match[3]) {
                  var elem = context.getElementById(match[3]);
                  if (elem && elem.parentNode) {
                    if (elem.id === match[3]) {
                      return makeArray([elem], extra);
                    }
                  } else {
                    return makeArray([], extra);
                  }
                }
              }
              try {
                return makeArray(context.querySelectorAll(query), extra);
              } catch(qsaError) {
              }
            } else {
              if (context.nodeType === 1 && context.nodeName.toLowerCase() !== "object") {
                var oldContext = context, old = context.getAttribute("id"), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test(query);
                if (!old) {
                  context.setAttribute("id", nid);
                } else {
                  nid = nid.replace(/'/g, "\\$&");
                }
                if (relativeHierarchySelector && hasParent) {
                  context = context.parentNode;
                }
                try {
                  if (!relativeHierarchySelector || hasParent) {
                    return makeArray(context.querySelectorAll("[id='" + nid + "'] " + query), extra);
                  }
                } catch(pseudoError) {
                } finally {
                  if (!old) {
                    oldContext.removeAttribute("id");
                  }
                }
              }
            }
          }
          return oldSizzle(query, context, extra, seed);
        };
        for (var prop in oldSizzle) {
          Sizzle[prop] = oldSizzle[prop];
        }
        div = null;
      })();
    }
    (function() {
      var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
      if (matches) {
        var disconnectedMatch = !matches.call(document.createElement("div"), "div"), pseudoWorks = false;
        try {
          matches.call(document.documentElement, "[test!='']:sizzle");
        } catch(pseudoError) {
          pseudoWorks = true;
        }
        Sizzle.matchesSelector = function(node, expr) {
          expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
          if (!Sizzle.isXML(node)) {
            try {
              if (pseudoWorks || !Expr.match.PSEUDO.test(expr) && !/!=/.test(expr)) {
                var ret = matches.call(node, expr);
                if (ret || !disconnectedMatch || node.document && node.document.nodeType !== 11) {
                  return ret;
                }
              }
            } catch(e) {
            }
          }
          return Sizzle(expr, null, null, [node]).length > 0;
        };
      }
    })();
    (function() {
      var div = document.createElement("div");
      div.innerHTML = "<div class='test e'></div><div class='test'></div>";
      if (!div.getElementsByClassName || div.getElementsByClassName("e").length === 0) {
        return;
      }
      div.lastChild.className = "e";
      if (div.getElementsByClassName("e").length === 1) {
        return;
      }
      Expr.order.splice(1, 0, "CLASS");
      Expr.find.CLASS = function(match, context, isXML) {
        if ( typeof context.getElementsByClassName !== "undefined" && !isXML) {
          return context.getElementsByClassName(match[1]);
        }
      };
      div = null;
    })();
    function dirNodeCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) {
      for (var i = 0, l = checkSet.length; i < l; i++) {
        var elem = checkSet[i];
        if (elem) {
          var match = false;
          elem = elem[dir];
          while (elem) {
            if (elem[expando] === doneName) {
              match = checkSet[elem.sizset];
              break;
            }
            if (elem.nodeType === 1 && !isXML) {
              elem[expando] = doneName;
              elem.sizset = i;
            }
            if (elem.nodeName.toLowerCase() === 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) {
          var match = false;
          elem = elem[dir];
          while (elem) {
            if (elem[expando] === doneName) {
              match = checkSet[elem.sizset];
              break;
            }
            if (elem.nodeType === 1) {
              if (!isXML) {
                elem[expando] = doneName;
                elem.sizset = 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;
        }
      }
    }

    if (document.documentElement.contains) {
      Sizzle.contains = function(a, b) {
        return a !== b && (a.contains ? a.contains(b) : true);
      };
    } else {
      if (document.documentElement.compareDocumentPosition) {
        Sizzle.contains = function(a, b) {
          return !!(a.compareDocumentPosition(b) & 16);
        };
      } else {
        Sizzle.contains = function() {
          return false;
        };
      }
    }
    Sizzle.isXML = function(elem) {
      var documentElement = ( elem ? elem.ownerDocument || elem : 0).documentElement;
      return documentElement ? documentElement.nodeName !== "HTML" : false;
    };
    var posProcess = function(selector, context, seed) {
      var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context;
      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, seed);
      }
      return Sizzle.filter(later, tmpSet);
    };
    Sizzle.attr = jQuery.attr;
    Sizzle.selectors.attrMap = {};
    jQuery.find = Sizzle;
    jQuery.expr = Sizzle.selectors;
    jQuery.expr[":"] = jQuery.expr.filters;
    jQuery.unique = Sizzle.uniqueSort;
    jQuery.text = Sizzle.getText;
    jQuery.isXMLDoc = Sizzle.isXML;
    jQuery.contains = Sizzle.contains;
  })();
  var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.globalPOS, guaranteedUnique = {
    children : true,
    contents : true,
    next : true,
    prev : true
  };
  jQuery.fn.extend({
    find : function(selector) {
      var self = this, i, l;
      if ( typeof selector !== "string") {
        return jQuery(selector).filter(function() {
          for ( i = 0, l = self.length; i < l; i++) {
            if (jQuery.contains(self[i], this)) {
              return true;
            }
          }
        });
      }
      var ret = this.pushStack("", "find", selector), length, n, r;
      for ( i = 0, l = this.length; i < l; i++) {
        length = ret.length;
        jQuery.find(selector, this[i], ret);
        if (i > 0) {
          for ( n = length; n < ret.length; n++) {
            for ( r = 0; r < length; r++) {
              if (ret[r] === ret[n]) {
                ret.splice(n--, 1);
                break;
              }
            }
          }
        }
      }
      return ret;
    },
    has : function(target) {
      var targets = jQuery(target);
      return this.filter(function() {
        for (var i = 0, l = targets.length; i < l; i++) {
          if (jQuery.contains(this, targets[i])) {
            return true;
          }
        }
      });
    },
    not : function(selector) {
      return this.pushStack(winnow(this, selector, false), "not", selector);
    },
    filter : function(selector) {
      return this.pushStack(winnow(this, selector, true), "filter", selector);
    },
    is : function(selector) {
      return !!selector && ( typeof selector === "string" ? POS.test(selector) ? jQuery(selector, this.context).index(this[0]) >= 0 : jQuery.filter(selector, this).length > 0 : this.filter(selector).length > 0);
    },
    closest : function(selectors, context) {
      var ret = [], i, l, cur = this[0];
      if (jQuery.isArray(selectors)) {
        var level = 1;
        while (cur && cur.ownerDocument && cur !== context) {
          for ( i = 0; i < selectors.length; i++) {
            if (jQuery(cur).is(selectors[i])) {
              ret.push({
                selector : selectors[i],
                elem : cur,
                level : level
              });
            }
          }
          cur = cur.parentNode;
          level++;
        }
        return ret;
      }
      var pos = POS.test(selectors) || typeof selectors !== "string" ? jQuery(selectors, context || this.context) : 0;
      for ( i = 0, l = this.length; i < l; i++) {
        cur = this[i];
        while (cur) {
          if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors)) {
            ret.push(cur);
            break;
          } else {
            cur = cur.parentNode;
            if (!cur || !cur.ownerDocument || cur === context || cur.nodeType === 11) {
              break;
            }
          }
        }
      }
      ret = ret.length > 1 ? jQuery.unique(ret) : ret;
      return this.pushStack(ret, "closest", selectors);
    },
    index : function(elem) {
      if (!elem) {
        return (this[0] && this[0].parentNode) ? this.prevAll().length : -1;
      }
      if ( typeof elem === "string") {
        return jQuery.inArray(this[0], jQuery(elem));
      }
      return jQuery.inArray(elem.jquery ? elem[0] : elem, this);
    },
    add : function(selector, context) {
      var set = typeof selector === "string" ? jQuery(selector, context) : jQuery.makeArray(selector && selector.nodeType ? [selector] : selector), all = jQuery.merge(this.get(), set);
      return this.pushStack(isDisconnected(set[0]) || isDisconnected(all[0]) ? all : jQuery.unique(all));
    },
    andSelf : function() {
      return this.add(this.prevObject);
    }
  });
  function isDisconnected(node) {
    return !node || !node.parentNode || node.parentNode.nodeType === 11;
  }
  jQuery.each({
    parent : function(elem) {
      var parent = elem.parentNode;
      return parent && parent.nodeType !== 11 ? parent : null;
    },
    parents : function(elem) {
      return jQuery.dir(elem, "parentNode");
    },
    parentsUntil : function(elem, i, until) {
      return jQuery.dir(elem, "parentNode", until);
    },
    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");
    },
    nextUntil : function(elem, i, until) {
      return jQuery.dir(elem, "nextSibling", until);
    },
    prevUntil : function(elem, i, until) {
      return jQuery.dir(elem, "previousSibling", until);
    },
    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(until, selector) {
      var ret = jQuery.map(this, fn, until);
      if (!runtil.test(name)) {
        selector = until;
      }
      if (selector && typeof selector === "string") {
        ret = jQuery.filter(selector, ret);
      }
      ret = this.length > 1 && !guaranteedUnique[name] ? jQuery.unique(ret) : ret;
      if ((this.length > 1 || rmultiselector.test(selector)) && rparentsprev.test(name)) {
        ret = ret.reverse();
      }
      return this.pushStack(ret, name, slice.call(arguments).join(","));
    };
  });
  jQuery.extend({
    filter : function(expr, elems, not) {
      if (not) {
        expr = ":not(" + expr + ")";
      }
      return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [] : jQuery.find.matches(expr, elems);
    },
    dir : function(elem, dir, until) {
      var matched = [], cur = elem[dir];
      while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery(cur).is(until))) {
        if (cur.nodeType === 1) {
          matched.push(cur);
        }
        cur = cur[dir];
      }
      return matched;
    },
    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;
    },
    sibling : function(n, elem) {
      var r = [];
      for (; n; n = n.nextSibling) {
        if (n.nodeType === 1 && n !== elem) {
          r.push(n);
        }
      }
      return r;
    }
  });
  function winnow(elements, qualifier, keep) {
    qualifier = qualifier || 0;
    if (jQuery.isFunction(qualifier)) {
      return jQuery.grep(elements, function(elem, i) {
        var retVal = !!qualifier.call(elem, i, elem);
        return retVal === keep;
      });
    } else {
      if (qualifier.nodeType) {
        return jQuery.grep(elements, function(elem, i) {
          return (elem === qualifier) === keep;
        });
      } else {
        if ( typeof qualifier === "string") {
          var filtered = jQuery.grep(elements, function(elem) {
            return elem.nodeType === 1;
          });
          if (isSimple.test(qualifier)) {
            return jQuery.filter(qualifier, filtered, !keep);
          } else {
            qualifier = jQuery.filter(qualifier, filtered);
          }
        }
      }
    }
    return jQuery.grep(elements, function(elem, i) {
      return (jQuery.inArray(elem, qualifier) >= 0) === keep;
    });
  }

  function createSafeFragment(document) {
    var list = nodeNames.split("|"), safeFrag = document.createDocumentFragment();
    if (safeFrag.createElement) {
      while (list.length) {
        safeFrag.createElement(list.pop());
      }
    }
    return safeFrag;
  }

  var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = {
    option : [1, "<select multiple='multiple'>", "</select>"],
    legend : [1, "<fieldset>", "</fieldset>"],
    thead : [1, "<table>", "</table>"],
    tr : [2, "<table><tbody>", "</tbody></table>"],
    td : [3, "<table><tbody><tr>", "</tr></tbody></table>"],
    col : [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"],
    area : [1, "<map>", "</map>"],
    _default : [0, "", ""]
  }, safeFragment = createSafeFragment(document);
  wrapMap.optgroup = wrapMap.option;
  wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  wrapMap.th = wrapMap.td;
  if (!jQuery.support.htmlSerialize) {
    wrapMap._default = [1, "div<div>", "</div>"];
  }
  jQuery.fn.extend({
    text : function(value) {
      return jQuery.access(this, function(value) {
        return value === undefined ? jQuery.text(this) : this.empty().append((this[0] && this[0].ownerDocument || document).createTextNode(value));
      }, null, value, arguments.length);
    },
    wrapAll : function(html) {
      if (jQuery.isFunction(html)) {
        return this.each(function(i) {
          jQuery(this).wrapAll(html.call(this, i));
        });
      }
      if (this[0]) {
        var wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true);
        if (this[0].parentNode) {
          wrap.insertBefore(this[0]);
        }
        wrap.map(function() {
          var elem = this;
          while (elem.firstChild && elem.firstChild.nodeType === 1) {
            elem = elem.firstChild;
          }
          return elem;
        }).append(this);
      }
      return this;
    },
    wrapInner : function(html) {
      if (jQuery.isFunction(html)) {
        return this.each(function(i) {
          jQuery(this).wrapInner(html.call(this, i));
        });
      }
      return this.each(function() {
        var self = jQuery(this), contents = self.contents();
        if (contents.length) {
          contents.wrapAll(html);
        } else {
          self.append(html);
        }
      });
    },
    wrap : function(html) {
      var isFunction = jQuery.isFunction(html);
      return this.each(function(i) {
        jQuery(this).wrapAll( isFunction ? html.call(this, i) : html);
      });
    },
    unwrap : function() {
      return this.parent().each(function() {
        if (!jQuery.nodeName(this, "body")) {
          jQuery(this).replaceWith(this.childNodes);
        }
      }).end();
    },
    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() {
      if (this[0] && this[0].parentNode) {
        return this.domManip(arguments, false, function(elem) {
          this.parentNode.insertBefore(elem, this);
        });
      } else {
        if (arguments.length) {
          var set = jQuery.clean(arguments);
          set.push.apply(set, this.toArray());
          return this.pushStack(set, "before", arguments);
        }
      }
    },
    after : function() {
      if (this[0] && this[0].parentNode) {
        return this.domManip(arguments, false, function(elem) {
          this.parentNode.insertBefore(elem, this.nextSibling);
        });
      } else {
        if (arguments.length) {
          var set = this.pushStack(this, "after", arguments);
          set.push.apply(set, jQuery.clean(arguments));
          return set;
        }
      }
    },
    remove : function(selector, keepData) {
      for (var i = 0, elem; ( elem = this[i]) != null; i++) {
        if (!selector || jQuery.filter(selector, [elem]).length) {
          if (!keepData && elem.nodeType === 1) {
            jQuery.cleanData(elem.getElementsByTagName("*"));
            jQuery.cleanData([elem]);
          }
          if (elem.parentNode) {
            elem.parentNode.removeChild(elem);
          }
        }
      }
      return this;
    },
    empty : function() {
      for (var i = 0, elem; ( elem = this[i]) != null; i++) {
        if (elem.nodeType === 1) {
          jQuery.cleanData(elem.getElementsByTagName("*"));
        }
        while (elem.firstChild) {
          elem.removeChild(elem.firstChild);
        }
      }
      return this;
    },
    clone : function(dataAndEvents, deepDataAndEvents) {
      dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
      deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
      return this.map(function() {
        return jQuery.clone(this, dataAndEvents, deepDataAndEvents);
      });
    },
    html : function(value) {
      return jQuery.access(this, function(value) {
        var elem = this[0] || {}, i = 0, l = this.length;
        if (value === undefined) {
          return elem.nodeType === 1 ? elem.innerHTML.replace(rinlinejQuery, "") : null;
        }
        if ( typeof value === "string" && !rnoInnerhtml.test(value) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test(value)) && !wrapMap[(rtagName.exec(value)||["",""])[1].toLowerCase()]) {
          value = value.replace(rxhtmlTag, "<$1></$2>");
          try {
            for (; i < l; i++) {
              elem = this[i] || {};
              if (elem.nodeType === 1) {
                jQuery.cleanData(elem.getElementsByTagName("*"));
                elem.innerHTML = value;
              }
            }
            elem = 0;
          } catch(e) {
          }
        }
        if (elem) {
          this.empty().append(value);
        }
      }, null, value, arguments.length);
    },
    replaceWith : function(value) {
      if (this[0] && this[0].parentNode) {
        if (jQuery.isFunction(value)) {
          return this.each(function(i) {
            var self = jQuery(this), old = self.html();
            self.replaceWith(value.call(this, i, old));
          });
        }
        if ( typeof value !== "string") {
          value = jQuery(value).detach();
        }
        return this.each(function() {
          var next = this.nextSibling, parent = this.parentNode;
          jQuery(this).remove();
          if (next) {
            jQuery(next).before(value);
          } else {
            jQuery(parent).append(value);
          }
        });
      } else {
        return this.length ? this.pushStack(jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value) : this;
      }
    },
    detach : function(selector) {
      return this.remove(selector, true);
    },
    domManip : function(args, table, callback) {
      var results, first, fragment, parent, value = args[0], scripts = [];
      if (!jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test(value)) {
        return this.each(function() {
          jQuery(this).domManip(args, table, callback, true);
        });
      }
      if (jQuery.isFunction(value)) {
        return this.each(function(i) {
          var self = jQuery(this);
          args[0] = value.call(this, i, table ? self.html() : undefined);
          self.domManip(args, table, callback);
        });
      }
      if (this[0]) {
        parent = value && value.parentNode;
        if (jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length) {
          results = {
            fragment : parent
          };
        } else {
          results = jQuery.buildFragment(args, this, scripts);
        }
        fragment = results.fragment;
        if (fragment.childNodes.length === 1) {
          first = fragment = fragment.firstChild;
        } else {
          first = fragment.firstChild;
        }
        if (first) {
          table = table && jQuery.nodeName(first, "tr");
          for (var i = 0, l = this.length, lastIndex = l - 1; i < l; i++) {
            callback.call( table ? root(this[i], first) : this[i], results.cacheable || (l > 1 && i < lastIndex) ? jQuery.clone(fragment, true, true) : fragment);
          }
        }
        if (scripts.length) {
          jQuery.each(scripts, function(i, elem) {
            if (elem.src) {
              jQuery.ajax({
                type : "GET",
                global : false,
                url : elem.src,
                async : false,
                dataType : "script"
              });
            } else {
              jQuery.globalEval((elem.text || elem.textContent || elem.innerHTML || "").replace(rcleanScript, "/*$0*/"));
            }
            if (elem.parentNode) {
              elem.parentNode.removeChild(elem);
            }
          });
        }
      }
      return this;
    }
  });
  function root(elem, cur) {
    return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem;
  }

  function cloneCopyEvent(src, dest) {
    if (dest.nodeType !== 1 || !jQuery.hasData(src)) {
      return;
    }
    var type, i, l, oldData = jQuery._data(src), curData = jQuery._data(dest, oldData), events = oldData.events;
    if (events) {
      delete curData.handle;
      curData.events = {};
      for (type in events) {
        for ( i = 0, l = events[type].length; i < l; i++) {
          jQuery.event.add(dest, type, events[type][i]);
        }
      }
    }
    if (curData.data) {
      curData.data = jQuery.extend({}, curData.data);
    }
  }

  function cloneFixAttributes(src, dest) {
    var nodeName;
    if (dest.nodeType !== 1) {
      return;
    }
    if (dest.clearAttributes) {
      dest.clearAttributes();
    }
    if (dest.mergeAttributes) {
      dest.mergeAttributes(src);
    }
    nodeName = dest.nodeName.toLowerCase();
    if (nodeName === "object") {
      dest.outerHTML = src.outerHTML;
    } else {
      if (nodeName === "input" && (src.type === "checkbox" || src.type === "radio")) {
        if (src.checked) {
          dest.defaultChecked = dest.checked = src.checked;
        }
        if (dest.value !== src.value) {
          dest.value = src.value;
        }
      } else {
        if (nodeName === "option") {
          dest.selected = src.defaultSelected;
        } else {
          if (nodeName === "input" || nodeName === "textarea") {
            dest.defaultValue = src.defaultValue;
          } else {
            if (nodeName === "script" && dest.text !== src.text) {
              dest.text = src.text;
            }
          }
        }
      }
    }
    dest.removeAttribute(jQuery.expando);
    dest.removeAttribute("_submit_attached");
    dest.removeAttribute("_change_attached");
  }
  jQuery.buildFragment = function(args, nodes, scripts) {
    var fragment, cacheable, cacheresults, doc, first = args[0];
    if (nodes && nodes[0]) {
      doc = nodes[0].ownerDocument || nodes[0];
    }
    if (!doc.createDocumentFragment) {
      doc = document;
    }
    if (args.length === 1 && typeof first === "string" && first.length < 512 && doc === document && first.charAt(0) === "<" && !rnocache.test(first) && (jQuery.support.checkClone || !rchecked.test(first)) && (jQuery.support.html5Clone || !rnoshimcache.test(first))) {
      cacheable = true;
      cacheresults = jQuery.fragments[first];
      if (cacheresults && cacheresults !== 1) {
        fragment = cacheresults;
      }
    }
    if (!fragment) {
      fragment = doc.createDocumentFragment();
      jQuery.clean(args, doc, fragment, scripts);
    }
    if (cacheable) {
      jQuery.fragments[first] = cacheresults ? fragment : 1;
    }
    return {
      fragment : fragment,
      cacheable : cacheable
    };
  };
  jQuery.fragments = {};
  jQuery.each({
    appendTo : "append",
    prependTo : "prepend",
    insertBefore : "before",
    insertAfter : "after",
    replaceAll : "replaceWith"
  }, function(name, original) {
    jQuery.fn[name] = function(selector) {
      var ret = [], insert = jQuery(selector), parent = this.length === 1 && this[0].parentNode;
      if (parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1) {
        insert[original](this[0]);
        return this;
      } else {
        for (var i = 0, l = insert.length; i < l; i++) {
          var elems = (i > 0 ? this.clone(true) : this).get();
          jQuery(insert[i])[original](elems);
          ret = ret.concat(elems);
        }
        return this.pushStack(ret, name, insert.selector);
      }
    };
  });
  function getAll(elem) {
    if ( typeof elem.getElementsByTagName !== "undefined") {
      return elem.getElementsByTagName("*");
    } else {
      if ( typeof elem.querySelectorAll !== "undefined") {
        return elem.querySelectorAll("*");
      } else {
        return [];
      }
    }
  }

  function fixDefaultChecked(elem) {
    if (elem.type === "checkbox" || elem.type === "radio") {
      elem.defaultChecked = elem.checked;
    }
  }

  function findInputs(elem) {
    var nodeName = (elem.nodeName || "").toLowerCase();
    if (nodeName === "input") {
      fixDefaultChecked(elem);
    } else {
      if (nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined") {
        jQuery.grep(elem.getElementsByTagName("input"), fixDefaultChecked);
      }
    }
  }

  function shimCloneNode(elem) {
    var div = document.createElement("div");
    safeFragment.appendChild(div);
    div.innerHTML = elem.outerHTML;
    return div.firstChild;
  }
  jQuery.extend({
    clone : function(elem, dataAndEvents, deepDataAndEvents) {
      var srcElements, destElements, i, clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test("<" + elem.nodeName + ">") ? elem.cloneNode(true) : shimCloneNode(elem);
      if ((!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) {
        cloneFixAttributes(elem, clone);
        srcElements = getAll(elem);
        destElements = getAll(clone);
        for ( i = 0; srcElements[i]; ++i) {
          if (destElements[i]) {
            cloneFixAttributes(srcElements[i], destElements[i]);
          }
        }
      }
      if (dataAndEvents) {
        cloneCopyEvent(elem, clone);
        if (deepDataAndEvents) {
          srcElements = getAll(elem);
          destElements = getAll(clone);
          for ( i = 0; srcElements[i]; ++i) {
            cloneCopyEvent(srcElements[i], destElements[i]);
          }
        }
      }
      srcElements = destElements = null;
      return clone;
    },
    clean : function(elems, context, fragment, scripts) {
      var checkScriptType, script, j, ret = [];
      context = context || document;
      if ( typeof context.createElement === "undefined") {
        context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
      }
      for (var i = 0, elem; ( elem = elems[i]) != null; i++) {
        if ( typeof elem === "number") {
          elem += "";
        }
        if (!elem) {
          continue;
        }
        if ( typeof elem === "string") {
          if (!rhtml.test(elem)) {
            elem = context.createTextNode(elem);
          } else {
            elem = elem.replace(rxhtmlTag, "<$1></$2>");
            var tag = (rtagName.exec(elem)||["",""])[1].toLowerCase(), wrap = wrapMap[tag] || wrapMap._default, depth = wrap[0], div = context.createElement("div"), safeChildNodes = safeFragment.childNodes, remove;
            if (context === document) {
              safeFragment.appendChild(div);
            } else {
              createSafeFragment(context).appendChild(div);
            }
            div.innerHTML = wrap[1] + elem + wrap[2];
            while (depth--) {
              div = div.lastChild;
            }
            if (!jQuery.support.tbody) {
              var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : wrap[1] === "<table>" && !hasBody ? div.childNodes : [];
              for ( j = tbody.length - 1; j >= 0; --j) {
                if (jQuery.nodeName(tbody[j], "tbody") && !tbody[j].childNodes.length) {
                  tbody[j].parentNode.removeChild(tbody[j]);
                }
              }
            }
            if (!jQuery.support.leadingWhitespace && rleadingWhitespace.test(elem)) {
              div.insertBefore(context.createTextNode(rleadingWhitespace.exec(elem)[0]), div.firstChild);
            }
            elem = div.childNodes;
            if (div) {
              div.parentNode.removeChild(div);
              if (safeChildNodes.length > 0) {
                remove = safeChildNodes[safeChildNodes.length - 1];
                if (remove && remove.parentNode) {
                  remove.parentNode.removeChild(remove);
                }
              }
            }
          }
        }
        var len;
        if (!jQuery.support.appendChecked) {
          if (elem[0] && typeof ( len = elem.length) === "number") {
            for ( j = 0; j < len; j++) {
              findInputs(elem[j]);
            }
          } else {
            findInputs(elem);
          }
        }
        if (elem.nodeType) {
          ret.push(elem);
        } else {
          ret = jQuery.merge(ret, elem);
        }
      }
      if (fragment) {
        checkScriptType = function(elem) {
          return !elem.type || rscriptType.test(elem.type);
        };
        for ( i = 0; ret[i]; i++) {
          script = ret[i];
          if (scripts && jQuery.nodeName(script, "script") && (!script.type || rscriptType.test(script.type))) {
            scripts.push(script.parentNode ? script.parentNode.removeChild(script) : script);
          } else {
            if (script.nodeType === 1) {
              var jsTags = jQuery.grep(script.getElementsByTagName("script"), checkScriptType);
              ret.splice.apply(ret, [i + 1, 0].concat(jsTags));
            }
            fragment.appendChild(script);
          }
        }
      }
      return ret;
    },
    cleanData : function(elems) {
      var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando;
      for (var i = 0, elem; ( elem = elems[i]) != null; i++) {
        if (elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) {
          continue;
        }
        id = elem[jQuery.expando];
        if (id) {
          data = cache[id];
          if (data && data.events) {
            for (var type in data.events) {
              if (special[type]) {
                jQuery.event.remove(elem, type);
              } else {
                jQuery.removeEvent(elem, type, data.handle);
              }
            }
            if (data.handle) {
              data.handle.elem = null;
            }
          }
          if (deleteExpando) {
            delete elem[jQuery.expando];
          } else {
            if (elem.removeAttribute) {
              elem.removeAttribute(jQuery.expando);
            }
          }
          delete cache[id];
        }
      }
    }
  });
  var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rupper = /([A-Z]|^ms)/g, rnum = /^[\-+]?(?:\d*\.)?\d+$/i, rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i, rrelNum = /^([\-+])=([\-+.\de]+)/, rmargin = /^margin/, cssShow = {
    position : "absolute",
    visibility : "hidden",
    display : "block"
  }, cssExpand = ["Top", "Right", "Bottom", "Left"], curCSS, getComputedStyle, currentStyle;
  jQuery.fn.css = function(name, value) {
    return jQuery.access(this, function(elem, name, value) {
      return value !== undefined ? jQuery.style(elem, name, value) : jQuery.css(elem, name);
    }, name, value, arguments.length > 1);
  };
  jQuery.extend({
    cssHooks : {
      opacity : {
        get : function(elem, computed) {
          if (computed) {
            var ret = curCSS(elem, "opacity");
            return ret === "" ? "1" : ret;
          } else {
            return elem.style.opacity;
          }
        }
      }
    },
    cssNumber : {
      fillOpacity : true,
      fontWeight : true,
      lineHeight : true,
      opacity : true,
      orphans : true,
      widows : true,
      zIndex : true,
      zoom : true
    },
    cssProps : {
      "float" : jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
    },
    style : function(elem, name, value, extra) {
      if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) {
        return;
      }
      var ret, type, origName = jQuery.camelCase(name), style = elem.style, hooks = jQuery.cssHooks[origName];
      name = jQuery.cssProps[origName] || origName;
      if (value !== undefined) {
        type = typeof value;
        if (type === "string" && ( ret = rrelNum.exec(value))) {
          value = (+(ret[1] + 1) * +ret[2]) + parseFloat(jQuery.css(elem, name));
          type = "number";
        }
        if (value == null || type === "number" && isNaN(value)) {
          return;
        }
        if (type === "number" && !jQuery.cssNumber[origName]) {
          value += "px";
        }
        if (!hooks || !("set" in hooks) || ( value = hooks.set(elem, value)) !== undefined) {
          try {
            style[name] = value;
          } catch(e) {
          }
        }
      } else {
        if (hooks && "get" in hooks && ( ret = hooks.get(elem, false, extra)) !== undefined) {
          return ret;
        }
        return style[name];
      }
    },
    css : function(elem, name, extra) {
      var ret, hooks;
      name = jQuery.camelCase(name);
      hooks = jQuery.cssHooks[name];
      name = jQuery.cssProps[name] || name;
      if (name === "cssFloat") {
        name = "float";
      }
      if (hooks && "get" in hooks && ( ret = hooks.get(elem, true, extra)) !== undefined) {
        return ret;
      } else {
        if (curCSS) {
          return curCSS(elem, name);
        }
      }
    },
    swap : function(elem, options, callback) {
      var old = {}, ret, name;
      for (name in options) {
        old[name] = elem.style[name];
        elem.style[name] = options[name];
      }
      ret = callback.call(elem);
      for (name in options) {
        elem.style[name] = old[name];
      }
      return ret;
    }
  });
  jQuery.curCSS = jQuery.css;
  if (document.defaultView && document.defaultView.getComputedStyle) {
    getComputedStyle = function(elem, name) {
      var ret, defaultView, computedStyle, width, style = elem.style;
      name = name.replace(rupper, "-$1").toLowerCase();
      if (( defaultView = elem.ownerDocument.defaultView) && ( computedStyle = defaultView.getComputedStyle(elem, null))) {
        ret = computedStyle.getPropertyValue(name);
        if (ret === "" && !jQuery.contains(elem.ownerDocument.documentElement, elem)) {
          ret = jQuery.style(elem, name);
        }
      }
      if (!jQuery.support.pixelMargin && computedStyle && rmargin.test(name) && rnumnonpx.test(ret)) {
        width = style.width;
        style.width = ret;
        ret = computedStyle.width;
        style.width = width;
      }
      return ret;
    };
  }
  if (document.documentElement.currentStyle) {
    currentStyle = function(elem, name) {
      var left, rsLeft, uncomputed, ret = elem.currentStyle && elem.currentStyle[name], style = elem.style;
      if (ret == null && style && ( uncomputed = style[name])) {
        ret = uncomputed;
      }
      if (rnumnonpx.test(ret)) {
        left = style.left;
        rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
        if (rsLeft) {
          elem.runtimeStyle.left = elem.currentStyle.left;
        }
        style.left = name === "fontSize" ? "1em" : ret;
        ret = style.pixelLeft + "px";
        style.left = left;
        if (rsLeft) {
          elem.runtimeStyle.left = rsLeft;
        }
      }
      return ret === "" ? "auto" : ret;
    };
  }
  curCSS = getComputedStyle || currentStyle;
  function getWidthOrHeight(elem, name, extra) {
    var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, i = name === "width" ? 1 : 0, len = 4;
    if (val > 0) {
      if (extra !== "border") {
        for (; i < len; i += 2) {
          if (!extra) {
            val -= parseFloat(jQuery.css(elem, "padding" + cssExpand[i])) || 0;
          }
          if (extra === "margin") {
            val += parseFloat(jQuery.css(elem, extra + cssExpand[i])) || 0;
          } else {
            val -= parseFloat(jQuery.css(elem, "border" + cssExpand[i] + "Width")) || 0;
          }
        }
      }
      return val + "px";
    }
    val = curCSS(elem, name);
    if (val < 0 || val == null) {
      val = elem.style[name];
    }
    if (rnumnonpx.test(val)) {
      return val;
    }
    val = parseFloat(val) || 0;
    if (extra) {
      for (; i < len; i += 2) {
        val += parseFloat(jQuery.css(elem, "padding" + cssExpand[i])) || 0;
        if (extra !== "padding") {
          val += parseFloat(jQuery.css(elem, "border" + cssExpand[i] + "Width")) || 0;
        }
        if (extra === "margin") {
          val += parseFloat(jQuery.css(elem, extra + cssExpand[i])) || 0;
        }
      }
    }
    return val + "px";
  }
  jQuery.each(["height", "width"], function(i, name) {
    jQuery.cssHooks[name] = {
      get : function(elem, computed, extra) {
        if (computed) {
          if (elem.offsetWidth !== 0) {
            return getWidthOrHeight(elem, name, extra);
          } else {
            return jQuery.swap(elem, cssShow, function() {
              return getWidthOrHeight(elem, name, extra);
            });
          }
        }
      },
      set : function(elem, value) {
        return rnum.test(value) ? value + "px" : value;
      }
    };
  });
  if (!jQuery.support.opacity) {
    jQuery.cssHooks.opacity = {
      get : function(elem, computed) {
        return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ? (parseFloat(RegExp.$1) / 100) + "" : computed ? "1" : "";
      },
      set : function(elem, value) {
        var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric(value) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || "";
        style.zoom = 1;
        if (value >= 1 && jQuery.trim(filter.replace(ralpha, "")) === "") {
          style.removeAttribute("filter");
          if (currentStyle && !currentStyle.filter) {
            return;
          }
        }
        style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : filter + " " + opacity;
      }
    };
  }
  jQuery(function() {
    if (!jQuery.support.reliableMarginRight) {
      jQuery.cssHooks.marginRight = {
        get : function(elem, computed) {
          return jQuery.swap(elem, {
            display : "inline-block"
          }, function() {
            if (computed) {
              return curCSS(elem, "margin-right");
            } else {
              return elem.style.marginRight;
            }
          });
        }
      };
    }
  });
  if (jQuery.expr && jQuery.expr.filters) {
    jQuery.expr.filters.hidden = function(elem) {
      var width = elem.offsetWidth, height = elem.offsetHeight;
      return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css(elem, "display")) === "none");
    };
    jQuery.expr.filters.visible = function(elem) {
      return !jQuery.expr.filters.hidden(elem);
    };
  }
  jQuery.each({
    margin : "",
    padding : "",
    border : "Width"
  }, function(prefix, suffix) {
    jQuery.cssHooks[prefix + suffix] = {
      expand : function(value) {
        var i, parts = typeof value === "string" ? value.split(" ") : [value], expanded = {};
        for ( i = 0; i < 4; i++) {
          expanded[prefix + cssExpand[i] + suffix] = parts[i] || parts[i - 2] || parts[0];
        }
        return expanded;
      }
    };
  });
  var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, _load = jQuery.fn.load, prefilters = {}, transports = {}, ajaxLocation, ajaxLocParts, allTypes = ["*/"] + ["*"];
  try {
    ajaxLocation = location.href;
  } catch(e) {
    ajaxLocation = document.createElement("a");
    ajaxLocation.href = "";
    ajaxLocation = ajaxLocation.href;
  }
  ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || [];
  function addToPrefiltersOrTransports(structure) {
    return function(dataTypeExpression, func) {
      if ( typeof dataTypeExpression !== "string") {
        func = dataTypeExpression;
        dataTypeExpression = "*";
      }
      if (jQuery.isFunction(func)) {
        var dataTypes = dataTypeExpression.toLowerCase().split(rspacesAjax), i = 0, length = dataTypes.length, dataType, list, placeBefore;
        for (; i < length; i++) {
          dataType = dataTypes[i];
          placeBefore = /^\+/.test(dataType);
          if (placeBefore) {
            dataType = dataType.substr(1) || "*";
          }
          list = structure[dataType] = structure[dataType] || [];
          list[placeBefore?"unshift":"push"](func);
        }
      }
    };
  }

  function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR, dataType, inspected) {
    dataType = dataType || options.dataTypes[0];
    inspected = inspected || {};
    inspected[dataType] = true;
    var list = structure[dataType], i = 0, length = list ? list.length : 0, executeOnly = (structure === prefilters), selection;
    for (; i < length && (executeOnly || !selection); i++) {
      selection = list[i](options, originalOptions, jqXHR);
      if ( typeof selection === "string") {
        if (!executeOnly || inspected[selection]) {
          selection = undefined;
        } else {
          options.dataTypes.unshift(selection);
          selection = inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR, selection, inspected);
        }
      }
    }
    if ((executeOnly || !selection) && !inspected["*"]) {
      selection = inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR, "*", inspected);
    }
    return selection;
  }

  function ajaxExtend(target, src) {
    var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {};
    for (key in src) {
      if (src[key] !== undefined) {
        (flatOptions[key]?target:(deep||(deep={})))[key] = src[key];
      }
    }
    if (deep) {
      jQuery.extend(true, target, deep);
    }
  }
  jQuery.fn.extend({
    load : function(url, params, callback) {
      if ( typeof url !== "string" && _load) {
        return _load.apply(this, arguments);
      } else {
        if (!this.length) {
          return this;
        }
      }
      var off = url.indexOf(" ");
      if (off >= 0) {
        var selector = url.slice(off, url.length);
        url = url.slice(0, off);
      }
      var type = "GET";
      if (params) {
        if (jQuery.isFunction(params)) {
          callback = params;
          params = undefined;
        } else {
          if ( typeof params === "object") {
            params = jQuery.param(params, jQuery.ajaxSettings.traditional);
            type = "POST";
          }
        }
      }
      var self = this;
      jQuery.ajax({
        url : url,
        type : type,
        dataType : "html",
        data : params,
        complete : function(jqXHR, status, responseText) {
          responseText = jqXHR.responseText;
          if (jqXHR.isResolved()) {
            jqXHR.done(function(r) {
              responseText = r;
            });
            self.html( selector ? jQuery("<div>").append(responseText.replace(rscript, "")).find(selector) : responseText);
          }
          if (callback) {
            self.each(callback, [responseText, status, jqXHR]);
          }
        }
      });
      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 || rselectTextarea.test(this.nodeName) || rinput.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.replace(rCRLF, "\r\n")
          };
        }) : {
          name : elem.name,
          value : val.replace(rCRLF, "\r\n")
        };
      }).get();
    }
  });
  jQuery.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(i, o) {
    jQuery.fn[o] = function(f) {
      return this.on(o, f);
    };
  });
  jQuery.each(["get", "post"], function(i, method) {
    jQuery[method] = function(url, data, callback, type) {
      if (jQuery.isFunction(data)) {
        type = type || callback;
        callback = data;
        data = undefined;
      }
      return jQuery.ajax({
        type : method,
        url : url,
        data : data,
        success : callback,
        dataType : type
      });
    };
  });
  jQuery.extend({
    getScript : function(url, callback) {
      return jQuery.get(url, undefined, callback, "script");
    },
    getJSON : function(url, data, callback) {
      return jQuery.get(url, data, callback, "json");
    },
    ajaxSetup : function(target, settings) {
      if (settings) {
        ajaxExtend(target, jQuery.ajaxSettings);
      } else {
        settings = target;
        target = jQuery.ajaxSettings;
      }
      ajaxExtend(target, settings);
      return target;
    },
    ajaxSettings : {
      url : ajaxLocation,
      isLocal : rlocalProtocol.test(ajaxLocParts[1]),
      global : true,
      type : "GET",
      contentType : "application/x-www-form-urlencoded; charset=UTF-8",
      processData : true,
      async : true,
      accepts : {
        xml : "application/xml, text/xml",
        html : "text/html",
        text : "text/plain",
        json : "application/json, text/javascript",
        "*" : allTypes
      },
      contents : {
        xml : /xml/,
        html : /html/,
        json : /json/
      },
      responseFields : {
        xml : "responseXML",
        text : "responseText"
      },
      converters : {
        "* text" : window.String,
        "text html" : true,
        "text json" : jQuery.parseJSON,
        "text xml" : jQuery.parseXML
      },
      flatOptions : {
        context : true,
        url : true
      }
    },
    ajaxPrefilter : addToPrefiltersOrTransports(prefilters),
    ajaxTransport : addToPrefiltersOrTransports(transports),
    ajax : function(url, options) {
      if ( typeof url === "object") {
        options = url;
        url = undefined;
      }
      options = options || {};
      var s = jQuery.ajaxSetup({}, options), callbackContext = s.context || s, globalEventContext = callbackContext !== s && (callbackContext.nodeType || callbackContext instanceof jQuery) ? jQuery(callbackContext) : jQuery.event, deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), statusCode = s.statusCode || {}, ifModifiedKey, requestHeaders = {}, requestHeadersNames = {}, responseHeadersString, responseHeaders, transport, timeoutTimer, parts, state = 0, fireGlobals, i, jqXHR = {
        readyState : 0,
        setRequestHeader : function(name, value) {
          if (!state) {
            var lname = name.toLowerCase();
            name = requestHeadersNames[lname] = requestHeadersNames[lname] || name;
            requestHeaders[name] = value;
          }
          return this;
        },
        getAllResponseHeaders : function() {
          return state === 2 ? responseHeadersString : null;
        },
        getResponseHeader : function(key) {
          var match;
          if (state === 2) {
            if (!responseHeaders) {
              responseHeaders = {};
              while (( match = rheaders.exec(responseHeadersString))) {
                responseHeaders[match[1].toLowerCase()] = match[2];
              }
            }
            match = responseHeaders[key.toLowerCase()];
          }
          return match === undefined ? null : match;
        },
        overrideMimeType : function(type) {
          if (!state) {
            s.mimeType = type;
          }
          return this;
        },
        abort : function(statusText) {
          statusText = statusText || "abort";
          if (transport) {
            transport.abort(statusText);
          }
          done(0, statusText);
          return this;
        }
      };
      function done(status, nativeStatusText, responses, headers) {
        if (state === 2) {
          return;
        }
        state = 2;
        if (timeoutTimer) {
          clearTimeout(timeoutTimer);
        }
        transport = undefined;
        responseHeadersString = headers || "";
        jqXHR.readyState = status > 0 ? 4 : 0;
        var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses(s, jqXHR, responses) : undefined, lastModified, etag;
        if (status >= 200 && status < 300 || status === 304) {
          if (s.ifModified) {
            if (( lastModified = jqXHR.getResponseHeader("Last-Modified"))) {
              jQuery.lastModified[ifModifiedKey] = lastModified;
            }
            if (( etag = jqXHR.getResponseHeader("Etag"))) {
              jQuery.etag[ifModifiedKey] = etag;
            }
          }
          if (status === 304) {
            statusText = "notmodified";
            isSuccess = true;
          } else {
            try {
              success = ajaxConvert(s, response);
              statusText = "success";
              isSuccess = true;
            } catch(e) {
              statusText = "parsererror";
              error = e;
            }
          }
        } else {
          error = statusText;
          if (!statusText || status) {
            statusText = "error";
            if (status < 0) {
              status = 0;
            }
          }
        }
        jqXHR.status = status;
        jqXHR.statusText = "" + (nativeStatusText || statusText);
        if (isSuccess) {
          deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
        } else {
          deferred.rejectWith(callbackContext, [jqXHR, statusText, error]);
        }
        jqXHR.statusCode(statusCode);
        statusCode = undefined;
        if (fireGlobals) {
          globalEventContext.trigger("ajax" + ( isSuccess ? "Success" : "Error"), [jqXHR, s, isSuccess ? success : error]);
        }
        completeDeferred.fireWith(callbackContext, [jqXHR, statusText]);
        if (fireGlobals) {
          globalEventContext.trigger("ajaxComplete", [jqXHR, s]);
          if (!(--jQuery.active)) {
            jQuery.event.trigger("ajaxStop");
          }
        }
      }
      deferred.promise(jqXHR);
      jqXHR.success = jqXHR.done;
      jqXHR.error = jqXHR.fail;
      jqXHR.complete = completeDeferred.add;
      jqXHR.statusCode = function(map) {
        if (map) {
          var tmp;
          if (state < 2) {
            for (tmp in map) {
              statusCode[tmp] = [statusCode[tmp], map[tmp]];
            }
          } else {
            tmp = map[jqXHR.status];
            jqXHR.then(tmp, tmp);
          }
        }
        return this;
      };
      s.url = ((url || s.url) + "").replace(rhash, "").replace(rprotocol, ajaxLocParts[1] + "//");
      s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().split(rspacesAjax);
      if (s.crossDomain == null) {
        parts = rurl.exec(s.url.toLowerCase());
        s.crossDomain = !!(parts && (parts[1] != ajaxLocParts[1] || parts[2] != ajaxLocParts[2] || (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443))));
      }
      if (s.data && s.processData && typeof s.data !== "string") {
        s.data = jQuery.param(s.data, s.traditional);
      }
      inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);
      if (state === 2) {
        return false;
      }
      fireGlobals = s.global;
      s.type = s.type.toUpperCase();
      s.hasContent = !rnoContent.test(s.type);
      if (fireGlobals && jQuery.active++ === 0) {
        jQuery.event.trigger("ajaxStart");
      }
      if (!s.hasContent) {
        if (s.data) {
          s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
          delete s.data;
        }
        ifModifiedKey = s.url;
        if (s.cache === false) {
          var ts = jQuery.now(), ret = s.url.replace(rts, "$1_=" + ts);
          s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
        }
      }
      if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
        jqXHR.setRequestHeader("Content-Type", s.contentType);
      }
      if (s.ifModified) {
        ifModifiedKey = ifModifiedKey || s.url;
        if (jQuery.lastModified[ifModifiedKey]) {
          jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[ifModifiedKey]);
        }
        if (jQuery.etag[ifModifiedKey]) {
          jqXHR.setRequestHeader("If-None-Match", jQuery.etag[ifModifiedKey]);
        }
      }
      jqXHR.setRequestHeader("Accept", s.dataTypes[0] && s.accepts[s.dataTypes[0]] ? s.accepts[s.dataTypes[0]] + (s.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "") : s.accepts["*"]);
      for (i in s.headers) {
        jqXHR.setRequestHeader(i, s.headers[i]);
      }
      if (s.beforeSend && (s.beforeSend.call(callbackContext, jqXHR, s) === false || state === 2)) {
        jqXHR.abort();
        return false;
      }
      for (i in {
        success : 1,
        error : 1,
        complete : 1
      }) {
        jqXHR[i](s[i]);
      }
      transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR);
      if (!transport) {
        done(-1, "No Transport");
      } else {
        jqXHR.readyState = 1;
        if (fireGlobals) {
          globalEventContext.trigger("ajaxSend", [jqXHR, s]);
        }
        if (s.async && s.timeout > 0) {
          timeoutTimer = setTimeout(function() {
            jqXHR.abort("timeout");
          }, s.timeout);
        }
        try {
          state = 1;
          transport.send(requestHeaders, done);
        } catch(e) {
          if (state < 2) {
            done(-1, e);
          } else {
            throw e;
          }
        }
      }
      return jqXHR;
    },
    param : function(a, traditional) {
      var s = [], add = function(key, value) {
        value = jQuery.isFunction(value) ? value() : value;
        s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
      };
      if (traditional === undefined) {
        traditional = jQuery.ajaxSettings.traditional;
      }
      if (jQuery.isArray(a) || (a.jquery && !jQuery.isPlainObject(a))) {
        jQuery.each(a, function() {
          add(this.name, this.value);
        });
      } else {
        for (var prefix in a) {
          buildParams(prefix, a[prefix], traditional, add);
        }
      }
      return s.join("&").replace(r20, "+");
    }
  });
  function buildParams(prefix, obj, traditional, add) {
    if (jQuery.isArray(obj)) {
      jQuery.each(obj, function(i, v) {
        if (traditional || rbracket.test(prefix)) {
          add(prefix, v);
        } else {
          buildParams(prefix + "[" + ( typeof v === "object" ? i : "") + "]", v, traditional, add);
        }
      });
    } else {
      if (!traditional && jQuery.type(obj) === "object") {
        for (var name in obj) {
          buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
        }
      } else {
        add(prefix, obj);
      }
    }
  }
  jQuery.extend({
    active : 0,
    lastModified : {},
    etag : {}
  });
  function ajaxHandleResponses(s, jqXHR, responses) {
    var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType;
    for (type in responseFields) {
      if ( type in responses) {
        jqXHR[responseFields[type]] = responses[type];
      }
    }
    while (dataTypes[0] === "*") {
      dataTypes.shift();
      if (ct === undefined) {
        ct = s.mimeType || jqXHR.getResponseHeader("content-type");
      }
    }
    if (ct) {
      for (type in contents) {
        if (contents[type] && contents[type].test(ct)) {
          dataTypes.unshift(type);
          break;
        }
      }
    }
    if (dataTypes[0] in responses) {
      finalDataType = dataTypes[0];
    } else {
      for (type in responses) {
        if (!dataTypes[0] || s.converters[type + " " + dataTypes[0]]) {
          finalDataType = type;
          break;
        }
        if (!firstDataType) {
          firstDataType = type;
        }
      }
      finalDataType = finalDataType || firstDataType;
    }
    if (finalDataType) {
      if (finalDataType !== dataTypes[0]) {
        dataTypes.unshift(finalDataType);
      }
      return responses[finalDataType];
    }
  }

  function ajaxConvert(s, response) {
    if (s.dataFilter) {
      response = s.dataFilter(response, s.dataType);
    }
    var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, current = dataTypes[0], prev, conversion, conv, conv1, conv2;
    for ( i = 1; i < length; i++) {
      if (i === 1) {
        for (key in s.converters) {
          if ( typeof key === "string") {
            converters[key.toLowerCase()] = s.converters[key];
          }
        }
      }
      prev = current;
      current = dataTypes[i];
      if (current === "*") {
        current = prev;
      } else {
        if (prev !== "*" && prev !== current) {
          conversion = prev + " " + current;
          conv = converters[conversion] || converters["* " + current];
          if (!conv) {
            conv2 = undefined;
            for (conv1 in converters) {
              tmp = conv1.split(" ");
              if (tmp[0] === prev || tmp[0] === "*") {
                conv2 = converters[tmp[1] + " " + current];
                if (conv2) {
                  conv1 = converters[conv1];
                  if (conv1 === true) {
                    conv = conv2;
                  } else {
                    if (conv2 === true) {
                      conv = conv1;
                    }
                  }
                  break;
                }
              }
            }
          }
          if (!(conv || conv2)) {
            jQuery.error("No conversion from " + conversion.replace(" ", " to "));
          }
          if (conv !== true) {
            response = conv ? conv(response) : conv2(conv1(response));
          }
        }
      }
    }
    return response;
  }

  var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i;
  jQuery.ajaxSetup({
    jsonp : "callback",
    jsonpCallback : function() {
      return jQuery.expando + "_" + (jsc++);
    }
  });
  jQuery.ajaxPrefilter("json jsonp", function(s, originalSettings, jqXHR) {
    var inspectData = ( typeof s.data === "string") && /^application\/x\-www\-form\-urlencoded/.test(s.contentType);
    if (s.dataTypes[0] === "jsonp" || s.jsonp !== false && (jsre.test(s.url) || inspectData && jsre.test(s.data))) {
      var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction(s.jsonpCallback) ? s.jsonpCallback() : s.jsonpCallback, previous = window[jsonpCallback], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2";
      if (s.jsonp !== false) {
        url = url.replace(jsre, replace);
        if (s.url === url) {
          if (inspectData) {
            data = data.replace(jsre, replace);
          }
          if (s.data === data) {
            url += (/\?/.test(url) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
          }
        }
      }
      s.url = url;
      s.data = data;
      window[jsonpCallback] = function(response) {
        responseContainer = [response];
      };
      jqXHR.always(function() {
        window[jsonpCallback] = previous;
        if (responseContainer && jQuery.isFunction(previous)) {
          window[jsonpCallback](responseContainer[0]);
        }
      });
      s.converters["script json"] = function() {
        if (!responseContainer) {
          jQuery.error(jsonpCallback + " was not called");
        }
        return responseContainer[0];
      };
      s.dataTypes[0] = "json";
      return "script";
    }
  });
  jQuery.ajaxSetup({
    accepts : {
      script : "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
    },
    contents : {
      script : /javascript|ecmascript/
    },
    converters : {
      "text script" : function(text) {
        jQuery.globalEval(text);
        return text;
      }
    }
  });
  jQuery.ajaxPrefilter("script", function(s) {
    if (s.cache === undefined) {
      s.cache = false;
    }
    if (s.crossDomain) {
      s.type = "GET";
      s.global = false;
    }
  });
  jQuery.ajaxTransport("script", function(s) {
    if (s.crossDomain) {
      var script, head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
      return {
        send : function(_, callback) {
          script = document.createElement("script");
          script.async = "async";
          if (s.scriptCharset) {
            script.charset = s.scriptCharset;
          }
          script.src = s.url;
          script.onload = script.onreadystatechange = function(_, isAbort) {
            if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {
              script.onload = script.onreadystatechange = null;
              if (head && script.parentNode) {
                head.removeChild(script);
              }
              script = undefined;
              if (!isAbort) {
                callback(200, "success");
              }
            }
          };
          head.insertBefore(script, head.firstChild);
        },
        abort : function() {
          if (script) {
            script.onload(0, 1);
          }
        }
      };
    }
  });
  var xhrOnUnloadAbort = window.ActiveXObject ? function() {
    for (var key in xhrCallbacks) {
      xhrCallbacks[key](0, 1);
    }
  } : false, xhrId = 0, xhrCallbacks;
  function createStandardXHR() {
    try {
      return new window.XMLHttpRequest();
    } catch(e) {
    }
  }

  function createActiveXHR() {
    try {
      return new window.ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
    }
  }
  jQuery.ajaxSettings.xhr = window.ActiveXObject ? function() {
    return !this.isLocal && createStandardXHR() || createActiveXHR();
  } : createStandardXHR;
  (function(xhr) {
    jQuery.extend(jQuery.support, {
      ajax : !!xhr,
      cors : !!xhr && ("withCredentials" in xhr)
    });
  })(jQuery.ajaxSettings.xhr());
  if (jQuery.support.ajax) {
    jQuery.ajaxTransport(function(s) {
      if (!s.crossDomain || jQuery.support.cors) {
        var callback;
        return {
          send : function(headers, complete) {
            var xhr = s.xhr(), handle, i;
            if (s.username) {
              xhr.open(s.type, s.url, s.async, s.username, s.password);
            } else {
              xhr.open(s.type, s.url, s.async);
            }
            if (s.xhrFields) {
              for (i in s.xhrFields) {
                xhr[i] = s.xhrFields[i];
              }
            }
            if (s.mimeType && xhr.overrideMimeType) {
              xhr.overrideMimeType(s.mimeType);
            }
            if (!s.crossDomain && !headers["X-Requested-With"]) {
              headers["X-Requested-With"] = "XMLHttpRequest";
            }
            try {
              for (i in headers) {
                xhr.setRequestHeader(i, headers[i]);
              }
            } catch(_) {
            }
            xhr.send((s.hasContent && s.data) || null);
            callback = function(_, isAbort) {
              var status, statusText, responseHeaders, responses, xml;
              try {
                if (callback && (isAbort || xhr.readyState === 4)) {
                  callback = undefined;
                  if (handle) {
                    xhr.onreadystatechange = jQuery.noop;
                    if (xhrOnUnloadAbort) {
                      delete xhrCallbacks[handle];
                    }
                  }
                  if (isAbort) {
                    if (xhr.readyState !== 4) {
                      xhr.abort();
                    }
                  } else {
                    status = xhr.status;
                    responseHeaders = xhr.getAllResponseHeaders();
                    responses = {};
                    xml = xhr.responseXML;
                    if (xml && xml.documentElement) {
                      responses.xml = xml;
                    }
                    try {
                      responses.text = xhr.responseText;
                    } catch(_) {
                    }
                    try {
                      statusText = xhr.statusText;
                    } catch(e) {
                      statusText = "";
                    }
                    if (!status && s.isLocal && !s.crossDomain) {
                      status = responses.text ? 200 : 404;
                    } else {
                      if (status === 1223) {
                        status = 204;
                      }
                    }
                  }
                }
              } catch(firefoxAccessException) {
                if (!isAbort) {
                  complete(-1, firefoxAccessException);
                }
              }
              if (responses) {
                complete(status, statusText, responses, responseHeaders);
              }
            };
            if (!s.async || xhr.readyState === 4) {
              callback();
            } else {
              handle = ++xhrId;
              if (xhrOnUnloadAbort) {
                if (!xhrCallbacks) {
                  xhrCallbacks = {};
                  jQuery(window).unload(xhrOnUnloadAbort);
                }
                xhrCallbacks[handle] = callback;
              }
              xhr.onreadystatechange = callback;
            }
          },
          abort : function() {
            if (callback) {
              callback(0, 1);
            }
          }
        };
      }
    });
  }
  var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [["height", "marginTop", "marginBottom", "paddingTop", "paddingBottom"], ["width", "marginLeft", "marginRight", "paddingLeft", "paddingRight"], ["opacity"]], fxNow;
  jQuery.fn.extend({
    show : function(speed, easing, callback) {
      var elem, display;
      if (speed || speed === 0) {
        return this.animate(genFx("show", 3), speed, easing, callback);
      } else {
        for (var i = 0, j = this.length; i < j; i++) {
          elem = this[i];
          if (elem.style) {
            display = elem.style.display;
            if (!jQuery._data(elem, "olddisplay") && display === "none") {
              display = elem.style.display = "";
            }
            if ((display === "" && jQuery.css(elem, "display") === "none") || !jQuery.contains(elem.ownerDocument.documentElement, elem)) {
              jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
            }
          }
        }
        for ( i = 0; i < j; i++) {
          elem = this[i];
          if (elem.style) {
            display = elem.style.display;
            if (display === "" || display === "none") {
              elem.style.display = jQuery._data(elem, "olddisplay") || "";
            }
          }
        }
        return this;
      }
    },
    hide : function(speed, easing, callback) {
      if (speed || speed === 0) {
        return this.animate(genFx("hide", 3), speed, easing, callback);
      } else {
        var elem, display, i = 0, j = this.length;
        for (; i < j; i++) {
          elem = this[i];
          if (elem.style) {
            display = jQuery.css(elem, "display");
            if (display !== "none" && !jQuery._data(elem, "olddisplay")) {
              jQuery._data(elem, "olddisplay", display);
            }
          }
        }
        for ( i = 0; i < j; i++) {
          if (this[i].style) {
            this[i].style.display = "none";
          }
        }
        return this;
      }
    },
    _toggle : jQuery.fn.toggle,
    toggle : function(fn, fn2, callback) {
      var bool = typeof fn === "boolean";
      if (jQuery.isFunction(fn) && jQuery.isFunction(fn2)) {
        this._toggle.apply(this, arguments);
      } else {
        if (fn == null || bool) {
          this.each(function() {
            var state = bool ? fn : jQuery(this).is(":hidden");
            jQuery(this)[state?"show":"hide"]();
          });
        } else {
          this.animate(genFx("toggle", 3), fn, fn2, callback);
        }
      }
      return this;
    },
    fadeTo : function(speed, to, easing, callback) {
      return this.filter(":hidden").css("opacity", 0).show().end().animate({
        opacity : to
      }, speed, easing, callback);
    },
    animate : function(prop, speed, easing, callback) {
      var optall = jQuery.speed(speed, easing, callback);
      if (jQuery.isEmptyObject(prop)) {
        return this.each(optall.complete, [false]);
      }
      prop = jQuery.extend({}, prop);
      function doAnimation() {
        if (optall.queue === false) {
          jQuery._mark(this);
        }
        var opt = jQuery.extend({}, optall), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, e, hooks, replace, parts, start, end, unit, method;
        opt.animatedProperties = {};
        for (p in prop) {
          name = jQuery.camelCase(p);
          if (p !== name) {
            prop[name] = prop[p];
            delete prop[p];
          }
          if (( hooks = jQuery.cssHooks[name]) && "expand" in hooks) {
            replace = hooks.expand(prop[name]);
            delete prop[name];
            for (p in replace) {
              if (!( p in prop)) {
                prop[p] = replace[p];
              }
            }
          }
        }
        for (name in prop) {
          val = prop[name];
          if (jQuery.isArray(val)) {
            opt.animatedProperties[name] = val[1];
            val = prop[name] = val[0];
          } else {
            opt.animatedProperties[name] = opt.specialEasing && opt.specialEasing[name] || opt.easing || "swing";
          }
          if (val === "hide" && hidden || val === "show" && !hidden) {
            return opt.complete.call(this);
          }
          if (isElement && (name === "height" || name === "width")) {
            opt.overflow = [this.style.overflow, this.style.overflowX, this.style.overflowY];
            if (jQuery.css(this, "display") === "inline" && jQuery.css(this, "float") === "none") {
              if (!jQuery.support.inlineBlockNeedsLayout || defaultDisplay(this.nodeName) === "inline") {
                this.style.display = "inline-block";
              } else {
                this.style.zoom = 1;
              }
            }
          }
        }
        if (opt.overflow != null) {
          this.style.overflow = "hidden";
        }
        for (p in prop) {
          e = new jQuery.fx(this, opt, p);
          val = prop[p];
          if (rfxtypes.test(val)) {
            method = jQuery._data(this, "toggle" + p) || (val === "toggle" ? hidden ? "show" : "hide" : 0);
            if (method) {
              jQuery._data(this, "toggle" + p, method === "show" ? "hide" : "show");
              e[method]();
            } else {
              e[val]();
            }
          } else {
            parts = rfxnum.exec(val);
            start = e.cur();
            if (parts) {
              end = parseFloat(parts[2]);
              unit = parts[3] || (jQuery.cssNumber[p] ? "" : "px");
              if (unit !== "px") {
                jQuery.style(this, p, (end || 1) + unit);
                start = ((end || 1) / e.cur()) * start;
                jQuery.style(this, p, start + unit);
              }
              if (parts[1]) {
                end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
              }
              e.custom(start, end, unit);
            } else {
              e.custom(start, val, "");
            }
          }
        }
        return true;
      }
      return optall.queue === false ? this.each(doAnimation) : this.queue(optall.queue, doAnimation);
    },
    stop : function(type, clearQueue, gotoEnd) {
      if ( typeof type !== "string") {
        gotoEnd = clearQueue;
        clearQueue = type;
        type = undefined;
      }
      if (clearQueue && type !== false) {
        this.queue(type || "fx", []);
      }
      return this.each(function() {
        var index, hadTimers = false, timers = jQuery.timers, data = jQuery._data(this);
        if (!gotoEnd) {
          jQuery._unmark(true, this);
        }
        function stopQueue(elem, data, index) {
          var hooks = data[index];
          jQuery.removeData(elem, index, true);
          hooks.stop(gotoEnd);
        }

        if (type == null) {
          for (index in data) {
            if (data[index] && data[index].stop && index.indexOf(".run") === index.length - 4) {
              stopQueue(this, data, index);
            }
          }
        } else {
          if (data[ index = type + ".run"] && data[index].stop) {
            stopQueue(this, data, index);
          }
        }
        for ( index = timers.length; index--; ) {
          if (timers[index].elem === this && (type == null || timers[index].queue === type)) {
            if (gotoEnd) {
              timers[index](true);
            } else {
              timers[index].saveState();
            }
            hadTimers = true;
            timers.splice(index, 1);
          }
        }
        if (!(gotoEnd && hadTimers)) {
          jQuery.dequeue(this, type);
        }
      });
    }
  });
  function createFxNow() {
    setTimeout(clearFxNow, 0);
    return ( fxNow = jQuery.now());
  }

  function clearFxNow() {
    fxNow = undefined;
  }

  function genFx(type, num) {
    var obj = {};
    jQuery.each(fxAttrs.concat.apply([], fxAttrs.slice(0, num)), function() {
      obj[this] = type;
    });
    return obj;
  }
  jQuery.each({
    slideDown : genFx("show", 1),
    slideUp : genFx("hide", 1),
    slideToggle : genFx("toggle", 1),
    fadeIn : {
      opacity : "show"
    },
    fadeOut : {
      opacity : "hide"
    },
    fadeToggle : {
      opacity : "toggle"
    }
  }, function(name, props) {
    jQuery.fn[name] = function(speed, easing, callback) {
      return this.animate(props, speed, easing, callback);
    };
  });
  jQuery.extend({
    speed : function(speed, easing, fn) {
      var opt = speed && typeof speed === "object" ? jQuery.extend({}, 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 : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
      if (opt.queue == null || opt.queue === true) {
        opt.queue = "fx";
      }
      opt.old = opt.complete;
      opt.complete = function(noUnmark) {
        if (jQuery.isFunction(opt.old)) {
          opt.old.call(this);
        }
        if (opt.queue) {
          jQuery.dequeue(this, opt.queue);
        } else {
          if (noUnmark !== false) {
            jQuery._unmark(this);
          }
        }
      };
      return opt;
    },
    easing : {
      linear : function(p) {
        return p;
      },
      swing : function(p) {
        return (-Math.cos(p * Math.PI) / 2) + 0.5;
      }
    },
    timers : [],
    fx : function(elem, options, prop) {
      this.options = options;
      this.elem = elem;
      this.prop = prop;
      options.orig = options.orig || {};
    }
  });
  jQuery.fx.prototype = {
    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);
    },
    cur : function() {
      if (this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null)) {
        return this.elem[this.prop];
      }
      var parsed, r = jQuery.css(this.elem, this.prop);
      return isNaN( parsed = parseFloat(r)) ? !r || r === "auto" ? 0 : r : parsed;
    },
    custom : function(from, to, unit) {
      var self = this, fx = jQuery.fx;
      this.startTime = fxNow || createFxNow();
      this.end = to;
      this.now = this.start = from;
      this.pos = this.state = 0;
      this.unit = unit || this.unit || (jQuery.cssNumber[this.prop] ? "" : "px");
      function t(gotoEnd) {
        return self.step(gotoEnd);
      }
      t.queue = this.options.queue;
      t.elem = this.elem;
      t.saveState = function() {
        if (jQuery._data(self.elem, "fxshow" + self.prop) === undefined) {
          if (self.options.hide) {
            jQuery._data(self.elem, "fxshow" + self.prop, self.start);
          } else {
            if (self.options.show) {
              jQuery._data(self.elem, "fxshow" + self.prop, self.end);
            }
          }
        }
      };
      if (t() && jQuery.timers.push(t) && !timerId) {
        timerId = setInterval(fx.tick, fx.interval);
      }
    },
    show : function() {
      var dataShow = jQuery._data(this.elem, "fxshow" + this.prop);
      this.options.orig[this.prop] = dataShow || jQuery.style(this.elem, this.prop);
      this.options.show = true;
      if (dataShow !== undefined) {
        this.custom(this.cur(), dataShow);
      } else {
        this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
      }
      jQuery(this.elem).show();
    },
    hide : function() {
      this.options.orig[this.prop] = jQuery._data(this.elem, "fxshow" + this.prop) || jQuery.style(this.elem, this.prop);
      this.options.hide = true;
      this.custom(this.cur(), 0);
    },
    step : function(gotoEnd) {
      var p, n, complete, t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options;
      if (gotoEnd || t >= options.duration + this.startTime) {
        this.now = this.end;
        this.pos = this.state = 1;
        this.update();
        options.animatedProperties[this.prop] = true;
        for (p in options.animatedProperties) {
          if (options.animatedProperties[p] !== true) {
            done = false;
          }
        }
        if (done) {
          if (options.overflow != null && !jQuery.support.shrinkWrapBlocks) {
            jQuery.each(["", "X", "Y"], function(index, value) {
              elem.style["overflow" + value] = options.overflow[index];
            });
          }
          if (options.hide) {
            jQuery(elem).hide();
          }
          if (options.hide || options.show) {
            for (p in options.animatedProperties) {
              jQuery.style(elem, p, options.orig[p]);
              jQuery.removeData(elem, "fxshow" + p, true);
              jQuery.removeData(elem, "toggle" + p, true);
            }
          }
          complete = options.complete;
          if (complete) {
            options.complete = false;
            complete.call(elem);
          }
        }
        return false;
      } else {
        if (options.duration == Infinity) {
          this.now = t;
        } else {
          n = t - this.startTime;
          this.state = n / options.duration;
          this.pos = jQuery.easing[options.animatedProperties[this.prop]](this.state, n, 0, 1, options.duration);
          this.now = this.start + ((this.end - this.start) * this.pos);
        }
        this.update();
      }
      return true;
    }
  };
  jQuery.extend(jQuery.fx, {
    tick : function() {
      var timer, timers = jQuery.timers, i = 0;
      for (; i < timers.length; i++) {
        timer = timers[i];
        if (!timer() && timers[i] === timer) {
          timers.splice(i--, 1);
        }
      }
      if (!timers.length) {
        jQuery.fx.stop();
      }
    },
    interval : 13,
    stop : function() {
      clearInterval(timerId);
      timerId = null;
    },
    speeds : {
      slow : 600,
      fast : 200,
      _default : 400
    },
    step : {
      opacity : function(fx) {
        jQuery.style(fx.elem, "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;
        }
      }
    }
  });
  jQuery.each(fxAttrs.concat.apply([], fxAttrs), function(i, prop) {
    if (prop.indexOf("margin")) {
      jQuery.fx.step[prop] = function(fx) {
        jQuery.style(fx.elem, prop, Math.max(0, fx.now) + fx.unit);
      };
    }
  });
  if (jQuery.expr && jQuery.expr.filters) {
    jQuery.expr.filters.animated = function(elem) {
      return jQuery.grep(jQuery.timers, function(fn) {
        return elem === fn.elem;
      }).length;
    };
  }
  function defaultDisplay(nodeName) {
    if (!elemdisplay[nodeName]) {
      var body = document.body, elem = jQuery("<" + nodeName + ">").appendTo(body), display = elem.css("display");
      elem.remove();
      if (display === "none" || display === "") {
        if (!iframe) {
          iframe = document.createElement("iframe");
          iframe.frameBorder = iframe.width = iframe.height = 0;
        }
        body.appendChild(iframe);
        if (!iframeDoc || !iframe.createElement) {
          iframeDoc = (iframe.contentWindow || iframe.contentDocument).document;
          iframeDoc.write((jQuery.support.boxModel ? "<!doctype html>" : "") + "<html><body>");
          iframeDoc.close();
        }
        elem = iframeDoc.createElement(nodeName);
        iframeDoc.body.appendChild(elem);
        display = jQuery.css(elem, "display");
        body.removeChild(iframe);
      }
      elemdisplay[nodeName] = display;
    }
    return elemdisplay[nodeName];
  }

  var getOffset, rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i;
  if ("getBoundingClientRect" in document.documentElement) {
    getOffset = function(elem, doc, docElem, box) {
      try {
        box = elem.getBoundingClientRect();
      } catch(e) {
      }
      if (!box || !jQuery.contains(docElem, elem)) {
        return box ? {
          top : box.top,
          left : box.left
        } : {
          top : 0,
          left : 0
        };
      }
      var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft;
      return {
        top : top,
        left : left
      };
    };
  } else {
    getOffset = function(elem, doc, docElem) {
      var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft;
      while (( elem = elem.parentNode) && elem !== body && elem !== docElem) {
        if (jQuery.support.fixedPosition && prevComputedStyle.position === "fixed") {
          break;
        }
        computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
        top -= elem.scrollTop;
        left -= elem.scrollLeft;
        if (elem === offsetParent) {
          top += elem.offsetTop;
          left += elem.offsetLeft;
          if (jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName))) {
            top += parseFloat(computedStyle.borderTopWidth) || 0;
            left += parseFloat(computedStyle.borderLeftWidth) || 0;
          }
          prevOffsetParent = offsetParent;
          offsetParent = elem.offsetParent;
        }
        if (jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible") {
          top += parseFloat(computedStyle.borderTopWidth) || 0;
          left += parseFloat(computedStyle.borderLeftWidth) || 0;
        }
        prevComputedStyle = computedStyle;
      }
      if (prevComputedStyle.position === "relative" || prevComputedStyle.position === "static") {
        top += body.offsetTop;
        left += body.offsetLeft;
      }
      if (jQuery.support.fixedPosition && prevComputedStyle.position === "fixed") {
        top += Math.max(docElem.scrollTop, body.scrollTop);
        left += Math.max(docElem.scrollLeft, body.scrollLeft);
      }
      return {
        top : top,
        left : left
      };
    };
  }
  jQuery.fn.offset = function(options) {
    if (arguments.length) {
      return options === undefined ? this : this.each(function(i) {
        jQuery.offset.setOffset(this, options, i);
      });
    }
    var elem = this[0], doc = elem && elem.ownerDocument;
    if (!doc) {
      return null;
    }
    if (elem === doc.body) {
      return jQuery.offset.bodyOffset(elem);
    }
    return getOffset(elem, doc, doc.documentElement);
  };
  jQuery.offset = {
    bodyOffset : function(body) {
      var top = body.offsetTop, left = body.offsetLeft;
      if (jQuery.support.doesNotIncludeMarginInBodyOffset) {
        top += parseFloat(jQuery.css(body, "marginTop")) || 0;
        left += parseFloat(jQuery.css(body, "marginLeft")) || 0;
      }
      return {
        top : top,
        left : left
      };
    },
    setOffset : function(elem, options, i) {
      var position = jQuery.css(elem, "position");
      if (position === "static") {
        elem.style.position = "relative";
      }
      var curElem = jQuery(elem), curOffset = curElem.offset(), curCSSTop = jQuery.css(elem, "top"), curCSSLeft = jQuery.css(elem, "left"), calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft;
      if (calculatePosition) {
        curPosition = curElem.position();
        curTop = curPosition.top;
        curLeft = curPosition.left;
      } else {
        curTop = parseFloat(curCSSTop) || 0;
        curLeft = parseFloat(curCSSLeft) || 0;
      }
      if (jQuery.isFunction(options)) {
        options = options.call(elem, i, curOffset);
      }
      if (options.top != null) {
        props.top = (options.top - curOffset.top) + curTop;
      }
      if (options.left != null) {
        props.left = (options.left - curOffset.left) + curLeft;
      }
      if ("using" in options) {
        options.using.call(elem, props);
      } else {
        curElem.css(props);
      }
    }
  };
  jQuery.fn.extend({
    position : function() {
      if (!this[0]) {
        return null;
      }
      var elem = this[0], offsetParent = this.offsetParent(), offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? {
        top : 0,
        left : 0
      } : offsetParent.offset();
      offset.top -= parseFloat(jQuery.css(elem, "marginTop")) || 0;
      offset.left -= parseFloat(jQuery.css(elem, "marginLeft")) || 0;
      parentOffset.top += parseFloat(jQuery.css(offsetParent[0], "borderTopWidth")) || 0;
      parentOffset.left += parseFloat(jQuery.css(offsetParent[0], "borderLeftWidth")) || 0;
      return {
        top : offset.top - parentOffset.top,
        left : offset.left - parentOffset.left
      };
    },
    offsetParent : function() {
      return this.map(function() {
        var offsetParent = this.offsetParent || document.body;
        while (offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static")) {
          offsetParent = offsetParent.offsetParent;
        }
        return offsetParent;
      });
    }
  });
  jQuery.each({
    scrollLeft : "pageXOffset",
    scrollTop : "pageYOffset"
  }, function(method, prop) {
    var top = /Y/.test(prop);
    jQuery.fn[method] = function(val) {
      return jQuery.access(this, function(elem, method, val) {
        var win = getWindow(elem);
        if (val === undefined) {
          return win ? ( prop in win) ? win[prop] : jQuery.support.boxModel && win.document.documentElement[method] || win.document.body[method] : elem[method];
        }
        if (win) {
          win.scrollTo(!top ? val : jQuery(win).scrollLeft(), top ? val : jQuery(win).scrollTop());
        } else {
          elem[method] = val;
        }
      }, method, val, arguments.length, null);
    };
  });
  function getWindow(elem) {
    return jQuery.isWindow(elem) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false;
  }
  jQuery.each({
    Height : "height",
    Width : "width"
  }, function(name, type) {
    var clientProp = "client" + name, scrollProp = "scroll" + name, offsetProp = "offset" + name;
    jQuery.fn["inner" + name] = function() {
      var elem = this[0];
      return elem ? elem.style ? parseFloat(jQuery.css(elem, type, "padding")) : this[type]() : null;
    };
    jQuery.fn["outer" + name] = function(margin) {
      var elem = this[0];
      return elem ? elem.style ? parseFloat(jQuery.css(elem, type, margin ? "margin" : "border")) : this[type]() : null;
    };
    jQuery.fn[type] = function(value) {
      return jQuery.access(this, function(elem, type, value) {
        var doc, docElemProp, orig, ret;
        if (jQuery.isWindow(elem)) {
          doc = elem.document;
          docElemProp = doc.documentElement[clientProp];
          return jQuery.support.boxModel && docElemProp || doc.body && doc.body[clientProp] || docElemProp;
        }
        if (elem.nodeType === 9) {
          doc = elem.documentElement;
          if (doc[clientProp] >= doc[scrollProp]) {
            return doc[clientProp];
          }
          return Math.max(elem.body[scrollProp], doc[scrollProp], elem.body[offsetProp], doc[offsetProp]);
        }
        if (value === undefined) {
          orig = jQuery.css(elem, type);
          ret = parseFloat(orig);
          return jQuery.isNumeric(ret) ? ret : orig;
        }
        jQuery(elem).css(type, value);
      }, type, value, arguments.length, null);
    };
  });
  window.jQuery = window.$ = jQuery;
  if ( typeof define === "function" && define.amd && define.amd.jQuery) {
    define("jquery", [], function() {
      return jQuery;
    });
  }
})(window);
(function(f, g, j, b) {
  var h = /progid:DXImageTransform\.Microsoft\.Matrix\(.*?\)/, c = /^([\+\-]=)?([\d+.\-]+)(.*)$/, q = /%/;
  var d = j.createElement("modernizr"), e = d.style;
  function n(s) {
    return parseFloat(s);
  }

  function l() {
    var s = {
      transformProperty : "",
      MozTransform : "-moz-",
      WebkitTransform : "-webkit-",
      OTransform : "-o-",
      msTransform : "-ms-"
    };
    for (var t in s) {
      if ( typeof e[t] != "undefined") {
        return s[t];
      }
    }
    return null;
  }

  function r() {
    if ( typeof (g.Modernizr) !== "undefined") {
      return Modernizr.csstransforms;
    }
    var t = ["transformProperty", "WebkitTransform", "MozTransform", "OTransform", "msTransform"];
    for (var s in t) {
      if (e[t[s]] !== b) {
        return true;
      }
    }
  }

  var a = l(), i = a !== null ? a + "transform" : false, k = a !== null ? a + "transform-origin" : false;
  f.support.csstransforms = r();
  if (a == "-ms-") {
    i = "msTransform";
    k = "msTransformOrigin";
  }
  f.extend({
    transform : function(s) {
      s.transform = this;
      this.$elem = f(s);
      this.applyingMatrix = false;
      this.matrix = null;
      this.height = null;
      this.width = null;
      this.outerHeight = null;
      this.outerWidth = null;
      this.boxSizingValue = null;
      this.boxSizingProperty = null;
      this.attr = null;
      this.transformProperty = i;
      this.transformOriginProperty = k;
    }
  });
  f.extend(f.transform, {
    funcs : ["matrix", "origin", "reflect", "reflectX", "reflectXY", "reflectY", "rotate", "scale", "scaleX", "scaleY", "skew", "skewX", "skewY", "translate", "translateX", "translateY"]
  });
  f.fn.transform = function(s, t) {
    return this.each(function() {
      var u = this.transform || new f.transform(this);
      if (s) {
        u.exec(s, t);
      }
    });
  };
  f.transform.prototype = {
    exec : function(s, t) {
      t = f.extend(true, {
        forceMatrix : false,
        preserve : false
      }, t);
      this.attr = null;
      if (t.preserve) {
        s = f.extend(true, this.getAttrs(true, true), s);
      } else {
        s = f.extend(true, {}, s);
      }
      this.setAttrs(s);
      if (f.support.csstransforms && !t.forceMatrix) {
        return this.execFuncs(s);
      } else {
        if (f.browser.msie || (f.support.csstransforms && t.forceMatrix)) {
          return this.execMatrix(s);
        }
      }
      return false;
    },
    execFuncs : function(t) {
      var s = [];
      for (var u in t) {
        if (u == "origin") {
          this[u].apply(this, f.isArray(t[u]) ? t[u] : [t[u]]);
        } else {
          if (f.inArray(u, f.transform.funcs) !== -1) {
            s.push(this.createTransformFunc(u, t[u]));
          }
        }
      }
      this.$elem.css(i, s.join(" "));
      return true;
    },
    execMatrix : function(z) {
      var C, x, t;
      var F = this.$elem[0], B = this;
      function A(N, M) {
        if (q.test(N)) {
          return parseFloat(N) / 100 * B["safeOuter"+(M?"Height":"Width")]();
        }
        return o(F, N);
      }

      var s = /translate[X|Y]?/, u = [];
      for (var v in z) {
        switch(f.type(z[v])) {
          case"array":
            t = z[v];
            break;
          case"string":
            t = f.map(z[v].split(","), f.trim);
            break;
          default:
            t = [z[v]];
        }
        if (f.matrix[v]) {
          if (f.cssAngle[v]) {
            t = f.map(t, f.angle.toDegree);
          } else {
            if (!f.cssNumber[v]) {
              t = f.map(t, A);
            } else {
              t = f.map(t, n);
            }
          }
          x = f.matrix[v].apply(this, t);
          if (s.test(v)) {
            u.push(x);
          } else {
            C = C ? C.x(x) : x;
          }
        } else {
          if (v == "origin") {
            this[v].apply(this, t);
          }
        }
      }
      C = C || f.matrix.identity();
      f.each(u, function(M, N) {
        C = C.x(N);
      });
      var K = parseFloat(C.e(1, 1).toFixed(6)), I = parseFloat(C.e(2, 1).toFixed(6)), H = parseFloat(C.e(1, 2).toFixed(6)), G = parseFloat(C.e(2, 2).toFixed(6)), L = C.rows === 3 ? parseFloat(C.e(1, 3).toFixed(6)) : 0, J = C.rows === 3 ? parseFloat(C.e(2, 3).toFixed(6)) : 0;
      if (f.support.csstransforms && a === "-moz-") {
        this.$elem.css(i, "matrix(" + K + ", " + I + ", " + H + ", " + G + ", " + L + "px, " + J + "px)");
      } else {
        if (f.support.csstransforms) {
          this.$elem.css(i, "matrix(" + K + ", " + I + ", " + H + ", " + G + ", " + L + ", " + J + ")");
        } else {
          if (f.browser.msie) {
            var w = ", FilterType='nearest neighbor'";
            var D = this.$elem[0].style;
            var E = "progid:DXImageTransform.Microsoft.Matrix(M11=" + K + ", M12=" + H + ", M21=" + I + ", M22=" + G + ", sizingMethod='auto expand'" + w + ")";
            var y = D.filter || f.curCSS(this.$elem[0], "filter") || "";
            D.filter = h.test(y) ? y.replace(h, E) : y ? y + " " + E : E;
            this.applyingMatrix = true;
            this.matrix = C;
            this.fixPosition(C, L, J);
            this.applyingMatrix = false;
            this.matrix = null;
          }
        }
      }
      return true;
    },
    origin : function(s, t) {
      if (f.support.csstransforms) {
        if ( typeof t === "undefined") {
          this.$elem.css(k, s);
        } else {
          this.$elem.css(k, s + " " + t);
        }
        return true;
      }
      switch(s) {
        case"left":
          s = "0";
          break;
        case"right":
          s = "100%";
          break;
        case"center":
        case b:
          s = "50%";
      }
      switch(t) {
        case"top":
          t = "0";
          break;
        case"bottom":
          t = "100%";
          break;
        case"center":
        case b:
          t = "50%";
      }
      this.setAttr("origin", [q.test(s) ? s : o(this.$elem[0], s) + "px", q.test(t) ? t : o(this.$elem[0], t) + "px"]);
      return true;
    },
    createTransformFunc : function(t, u) {
      if (t.substr(0, 7) === "reflect") {
        var s = u ? f.matrix[t]() : f.matrix.identity();
        return "matrix(" + s.e(1, 1) + ", " + s.e(2, 1) + ", " + s.e(1, 2) + ", " + s.e(2, 2) + ", 0, 0)";
      }
      if (t == "matrix") {
        if (a === "-moz-") {
          u[4] = u[4] ? u[4] + "px" : 0;
          u[5] = u[5] ? u[5] + "px" : 0;
        }
      }
      return t + "(" + (f.isArray(u) ? u.join(", ") : u) + ")";
    },
    fixPosition : function(B, y, x, D, s) {
      var w = new f.matrix.calc(B, this.safeOuterHeight(), this.safeOuterWidth()), C = this.getAttr("origin");
      var v = w.originOffset(new f.matrix.V2(q.test(C[0]) ? parseFloat(C[0]) / 100 * w.outerWidth : parseFloat(C[0]), q.test(C[1]) ? parseFloat(C[1]) / 100 * w.outerHeight : parseFloat(C[1])));
      var t = w.sides();
      var u = this.$elem.css("position");
      if (u == "static") {
        u = "relative";
      }
      var A = {
        top : 0,
        left : 0
      };
      var z = {
        position : u,
        top : (v.top + x + t.top + A.top) + "px",
        left : (v.left + y + t.left + A.left) + "px",
        zoom : 1
      };
      this.$elem.css(z);
    }
  };
  function o(s, u) {
    var t = c.exec(f.trim(u));
    if (t[3] && t[3] !== "px") {
      var w = "paddingBottom", v = f.style(s, w);
      f.style(s, w, u);
      u = p(s, w);
      f.style(s, w, v);
      return u;
    }
    return parseFloat(u);
  }

  function p(t, u) {
    if (t[u] != null && (!t.style || t.style[u] == null)) {
      return t[u];
    }
    var s = parseFloat(f.css(t, u));
    return s && s > -10000 ? s : 0;
  }

})(jQuery, this, this.document);
(function(d, c, a, f) {
  d.extend(d.transform.prototype, {
    safeOuterHeight : function() {
      return this.safeOuterLength("height");
    },
    safeOuterWidth : function() {
      return this.safeOuterLength("width");
    },
    safeOuterLength : function(l) {
      var p = "outer" + (l == "width" ? "Width" : "Height");
      if (!d.support.csstransforms && d.browser.msie) {
        l = l == "width" ? "width" : "height";
        if (this.applyingMatrix && !this[p] && this.matrix) {
          var k = new d.matrix.calc(this.matrix, 1, 1), n = k.offset(), g = this.$elem[p]() / n[l];
          this[p] = g;
          return g;
        } else {
          if (this.applyingMatrix && this[p]) {
            return this[p];
          }
        }
        var o = {
          height : ["top", "bottom"],
          width : ["left", "right"]
        };
        var h = this.$elem[0], j = parseFloat(d.curCSS(h, l, true)), q = this.boxSizingProperty, i = this.boxSizingValue;
        if (!this.boxSizingProperty) {
          q = this.boxSizingProperty = e() || "box-sizing";
          i = this.boxSizingValue = this.$elem.css(q) || "content-box";
        }
        if (this[p] && this[l] == j) {
          return this[p];
        } else {
          this[l] = j;
        }
        if (q && (i == "padding-box" || i == "content-box")) {
          j += parseFloat(d.curCSS(h, "padding-" + o[l][0], true)) || 0 + parseFloat(d.curCSS(h, "padding-" + o[l][1], true)) || 0;
        }
        if (q && i == "content-box") {
          j += parseFloat(d.curCSS(h, "border-" + o[l][0] + "-width", true)) || 0 + parseFloat(d.curCSS(h, "border-" + o[l][1] + "-width", true)) || 0;
        }
        this[p] = j;
        return j;
      }
      return this.$elem[p]();
    }
  });
  var b = null;
  function e() {
    if (b) {
      return b;
    }
    var h = {
      boxSizing : "box-sizing",
      MozBoxSizing : "-moz-box-sizing",
      WebkitBoxSizing : "-webkit-box-sizing",
      OBoxSizing : "-o-box-sizing"
    }, g = a.body;
    for (var i in h) {
      if ( typeof g.style[i] != "undefined") {
        b = h[i];
        return b;
      }
    }
    return null;
  }

})(jQuery, this, this.document);
(function(g, f, b, h) {
  var d = /([\w\-]*?)\((.*?)\)/g, a = "data-transform", e = /\s/, c = /,\s?/;
  g.extend(g.transform.prototype, {
    setAttrs : function(i) {
      var j = "", l;
      for (var k in i) {
        l = i[k];
        if (g.isArray(l)) {
          l = l.join(", ");
        }
        j += " " + k + "(" + l + ")";
      }
      this.attr = g.trim(j);
      this.$elem.attr(a, this.attr);
    },
    setAttr : function(k, l) {
      if (g.isArray(l)) {
        l = l.join(", ");
      }
      var j = this.attr || this.$elem.attr(a);
      if (!j || j.indexOf(k) == -1) {
        this.attr = g.trim(j + " " + k + "(" + l + ")");
        this.$elem.attr(a, this.attr);
      } else {
        var i = [], n;
        d.lastIndex = 0;
        while ( n = d.exec(j)) {
          if (k == n[1]) {
            i.push(k + "(" + l + ")");
          } else {
            i.push(n[0]);
          }
        }
        this.attr = i.join(" ");
        this.$elem.attr(a, this.attr);
      }
    },
    getAttrs : function() {
      var j = this.attr || this.$elem.attr(a);
      if (!j) {
        return {};
      }
      var i = {}, l, k;
      d.lastIndex = 0;
      while (( l = d.exec(j)) !== null) {
        if (l) {
          k = l[2].split(c);
          i[l[1]] = k.length == 1 ? k[0] : k;
        }
      }
      return i;
    },
    getAttr : function(j) {
      var i = this.getAttrs();
      if ( typeof i[j] !== "undefined") {
        return i[j];
      }
      if (j === "origin" && g.support.csstransforms) {
        return this.$elem.css(this.transformOriginProperty).split(e);
      } else {
        if (j === "origin") {
          return ["50%", "50%"];
        }
      }
      return g.cssDefault[j] || 0;
    }
  });
  if ( typeof (g.cssAngle) == "undefined") {
    g.cssAngle = {};
  }
  g.extend(g.cssAngle, {
    rotate : true,
    skew : true,
    skewX : true,
    skewY : true
  });
  if ( typeof (g.cssDefault) == "undefined") {
    g.cssDefault = {};
  }
  g.extend(g.cssDefault, {
    scale : [1, 1],
    scaleX : 1,
    scaleY : 1,
    matrix : [1, 0, 0, 1, 0, 0],
    origin : ["50%", "50%"],
    reflect : [1, 0, 0, 1, 0, 0],
    reflectX : [1, 0, 0, 1, 0, 0],
    reflectXY : [1, 0, 0, 1, 0, 0],
    reflectY : [1, 0, 0, 1, 0, 0]
  });
  if ( typeof (g.cssMultipleValues) == "undefined") {
    g.cssMultipleValues = {};
  }
  g.extend(g.cssMultipleValues, {
    matrix : 6,
    origin : {
      length : 2,
      duplicate : true
    },
    reflect : 6,
    reflectX : 6,
    reflectXY : 6,
    reflectY : 6,
    scale : {
      length : 2,
      duplicate : true
    },
    skew : 2,
    translate : 2
  });
  g.extend(g.cssNumber, {
    matrix : true,
    reflect : true,
    reflectX : true,
    reflectXY : true,
    reflectY : true,
    scale : true,
    scaleX : true,
    scaleY : true
  });
  g.each(g.transform.funcs, function(j, k) {
    g.cssHooks[k] = {
      set : function(n, o) {
        var l = n.transform || new g.transform(n), i = {};
        i[k] = o;
        l.exec(i, {
          preserve : true
        });
      },
      get : function(n, l) {
        var i = n.transform || new g.transform(n);
        return i.getAttr(k);
      }
    };
  });
  g.each(["reflect", "reflectX", "reflectXY", "reflectY"], function(j, k) {
    g.cssHooks[k].get = function(n, l) {
      var i = n.transform || new g.transform(n);
      return i.getAttr("matrix") || g.cssDefault[k];
    };
  });
})(jQuery, this, this.document);
(function(e, g, h, c) {
  var d = /^([+\-]=)?([\d+.\-]+)(.*)$/;
  var a = e.fn.animate;
  e.fn.animate = function(p, l, o, n) {
    var k = e.speed(l, o, n), j = e.cssMultipleValues;
    k.complete = k.old;
    if (!e.isEmptyObject(p)) {
      if ( typeof k.original === "undefined") {
        k.original = {};
      }
      e.each(p, function(s, u) {
        if (j[s] || e.cssAngle[s] || (!e.cssNumber[s] && e.inArray(s, e.transform.funcs) !== -1)) {
          var t = null;
          if (jQuery.isArray(p[s])) {
            var r = 1, q = u.length;
            if (j[s]) {
              r = ( typeof j[s].length === "undefined" ? j[s] : j[s].length);
            }
            if (q > r || (q < r && q == 2) || (q == 2 && r == 2 && isNaN(parseFloat(u[q - 1])))) {
              t = u[q - 1];
              u.splice(q - 1, 1);
            }
          }
          k.original[s] = u.toString();
          p[s] = parseFloat(u);
        }
      });
    }
    return a.apply(this, [arguments[0], k]);
  };
  var b = "paddingBottom";
  function i(k, l) {
    if (k[l] != null && (!k.style || k.style[l] == null)) {
    }
    var j = parseFloat(e.css(k, l));
    return j && j > -10000 ? j : 0;
  }

  var f = e.fx.prototype.custom;
  e.fx.prototype.custom = function(u, v, w) {
    var y = e.cssMultipleValues[this.prop], p = e.cssAngle[this.prop];
    if (y || (!e.cssNumber[this.prop] && e.inArray(this.prop, e.transform.funcs) !== -1)) {
      this.values = [];
      if (!y) {
        y = 1;
      }
      var x = this.options.original[this.prop], t = e(this.elem).css(this.prop), j = e.cssDefault[this.prop] || 0;
      if (!e.isArray(t)) {
        t = [t];
      }
      if (!e.isArray(x)) {
        if (e.type(x) === "string") {
          x = x.split(",");
        } else {
          x = [x];
        }
      }
      var l = y.length || y, s = 0;
      while (x.length < l) {
        x.push(y.duplicate ? x[0] : j[s] || 0);
        s++;
      }
      var k, r, q, o = this, n = o.elem.transform;
      orig = e.style(o.elem, b);
      e.each(x, function(z, A) {
        if (t[z]) {
          k = t[z];
        } else {
          if (j[z] && !y.duplicate) {
            k = j[z];
          } else {
            if (y.duplicate) {
              k = t[0];
            } else {
              k = 0;
            }
          }
        }
        if (p) {
          k = e.angle.toDegree(k);
        } else {
          if (!e.cssNumber[o.prop]) {
            r = d.exec(e.trim(k));
            if (r[3] && r[3] !== "px") {
              if (r[3] === "%") {
                k = parseFloat(r[2]) / 100 * n["safeOuter"+(z?"Height":"Width")]();
              } else {
                e.style(o.elem, b, k);
                k = i(o.elem, b);
                e.style(o.elem, b, orig);
              }
            }
          }
        }
        k = parseFloat(k);
        r = d.exec(e.trim(A));
        if (r) {
          q = parseFloat(r[2]);
          w = r[3] || "px";
          if (p) {
            q = e.angle.toDegree(q + w);
            w = "deg";
          } else {
            if (!e.cssNumber[o.prop] && w === "%") {
              k = (k / n["safeOuter"+(z?"Height":"Width")]()) * 100;
            } else {
              if (!e.cssNumber[o.prop] && w !== "px") {
                e.style(o.elem, b, (q || 1) + w);
                k = ((q || 1) / i(o.elem, b)) * k;
                e.style(o.elem, b, orig);
              }
            }
          }
          if (r[1]) {
            q = ((r[1] === "-=" ? -1 : 1) * q) + k;
          }
        } else {
          q = A;
          w = "";
        }
        o.values.push({
          start : k,
          end : q,
          unit : w
        });
      });
    }
    return f.apply(this, arguments);
  };
  e.fx.multipleValueStep = {
    _default : function(j) {
      e.each(j.values, function(k, l) {
        j.values[k].now = l.start + ((l.end - l.start) * j.pos);
      });
    }
  };
  e.each(["matrix", "reflect", "reflectX", "reflectXY", "reflectY"], function(j, k) {
    e.fx.multipleValueStep[k] = function(n) {
      var p = n.decomposed, l = e.matrix;
      m = l.identity();
      p.now = {};
      e.each(p.start, function(q) {
        p.now[q] = parseFloat(p.start[q]) + ((parseFloat(p.end[q]) - parseFloat(p.start[q])) * n.pos);
        if (((q === "scaleX" || q === "scaleY") && p.now[q] === 1) || (q !== "scaleX" && q !== "scaleY" && p.now[q] === 0)) {
          return true;
        }
        m = m.x(l[q](p.now[q]));
      });
      var o;
      e.each(n.values, function(q) {
        switch(q) {
          case 0:
            o = parseFloat(m.e(1, 1).toFixed(6));
            break;
          case 1:
            o = parseFloat(m.e(2, 1).toFixed(6));
            break;
          case 2:
            o = parseFloat(m.e(1, 2).toFixed(6));
            break;
          case 3:
            o = parseFloat(m.e(2, 2).toFixed(6));
            break;
          case 4:
            o = parseFloat(m.e(1, 3).toFixed(6));
            break;
          case 5:
            o = parseFloat(m.e(2, 3).toFixed(6));
            break;
        }
        n.values[q].now = o;
      });
    };
  });
  e.each(e.transform.funcs, function(j, k) {
    e.fx.step[k] = function(o) {
      var n = o.elem.transform || new e.transform(o.elem), l = {};
      if (e.cssMultipleValues[k] || (!e.cssNumber[k] && e.inArray(k, e.transform.funcs) !== -1)) {
        (e.fx.multipleValueStep[o.prop] || e.fx.multipleValueStep._default)(o);
        l[o.prop] = [];
        e.each(o.values, function(p, q) {
          l[o.prop].push(q.now + (e.cssNumber[o.prop] ? "" : q.unit));
        });
      } else {
        l[o.prop] = o.now + (e.cssNumber[o.prop] ? "" : o.unit);
      }
      n.exec(l, {
        preserve : true
      });
    };
  });
  e.each(["matrix", "reflect", "reflectX", "reflectXY", "reflectY"], function(j, k) {
    e.fx.step[k] = function(q) {
      var p = q.elem.transform || new e.transform(q.elem), o = {};
      if (!q.initialized) {
        q.initialized = true;
        if (k !== "matrix") {
          var n = e.matrix[k]().elements;
          var r;
          e.each(q.values, function(s) {
            switch(s) {
              case 0:
                r = n[0];
                break;
              case 1:
                r = n[2];
                break;
              case 2:
                r = n[1];
                break;
              case 3:
                r = n[3];
                break;
              default:
                r = 0;
            }
            q.values[s].end = r;
          });
        }
        q.decomposed = {};
        var l = q.values;
        q.decomposed.start = e.matrix.matrix(l[0].start, l[1].start, l[2].start, l[3].start, l[4].start, l[5].start).decompose();
        q.decomposed.end = e.matrix.matrix(l[0].end, l[1].end, l[2].end, l[3].end, l[4].end, l[5].end).decompose();
      }
      (e.fx.multipleValueStep[q.prop] || e.fx.multipleValueStep._default)(q);
      o.matrix = [];
      e.each(q.values, function(s, t) {
        o.matrix.push(t.now);
      });
      p.exec(o, {
        preserve : true
      });
    };
  });
})(jQuery, this, this.document);
(function(g, h, j, c) {
  var d = 180 / Math.PI;
  var k = 200 / Math.PI;
  var f = Math.PI / 180;
  var e = 2 / 1.8;
  var i = 0.9;
  var a = Math.PI / 200;
  var b = /^([+\-]=)?([\d+.\-]+)(.*)$/;
  g.extend({
    angle : {
      runit : /(deg|g?rad)/,
      radianToDegree : function(l) {
        return l * d;
      },
      radianToGrad : function(l) {
        return l * k;
      },
      degreeToRadian : function(l) {
        return l * f;
      },
      degreeToGrad : function(l) {
        return l * e;
      },
      gradToDegree : function(l) {
        return l * i;
      },
      gradToRadian : function(l) {
        return l * a;
      },
      toDegree : function(n) {
        var l = b.exec(n);
        if (l) {
          n = parseFloat(l[2]);
          switch(l[3]||"deg") {
            case"grad":
              n = g.angle.gradToDegree(n);
              break;
            case"rad":
              n = g.angle.radianToDegree(n);
              break;
          }
          return n;
        }
        return 0;
      }
    }
  });
})(jQuery, this, this.document);
(function(f, e, b, g) {
  if ( typeof (f.matrix) == "undefined") {
    f.extend({
      matrix : {}
    });
  }
  var d = f.matrix;
  f.extend(d, {
    V2 : function(h, i) {
      if (f.isArray(arguments[0])) {
        this.elements = arguments[0].slice(0, 2);
      } else {
        this.elements = [h, i];
      }
      this.length = 2;
    },
    V3 : function(h, j, i) {
      if (f.isArray(arguments[0])) {
        this.elements = arguments[0].slice(0, 3);
      } else {
        this.elements = [h, j, i];
      }
      this.length = 3;
    },
    M2x2 : function(i, h, k, j) {
      if (f.isArray(arguments[0])) {
        this.elements = arguments[0].slice(0, 4);
      } else {
        this.elements = Array.prototype.slice.call(arguments).slice(0, 4);
      }
      this.rows = 2;
      this.cols = 2;
    },
    M3x3 : function(n, l, k, j, i, h, q, p, o) {
      if (f.isArray(arguments[0])) {
        this.elements = arguments[0].slice(0, 9);
      } else {
        this.elements = Array.prototype.slice.call(arguments).slice(0, 9);
      }
      this.rows = 3;
      this.cols = 3;
    }
  });
  var c = {
    e : function(k, h) {
      var i = this.rows, j = this.cols;
      if (k > i || h > i || k < 1 || h < 1) {
        return 0;
      }
      return this.elements[(k - 1) * j + h - 1];
    },
    decompose : function() {
      var v = this.e(1, 1), t = this.e(2, 1), q = this.e(1, 2), p = this.e(2, 2), o = this.e(1, 3), n = this.e(2, 3);
      if (Math.abs(v * p - t * q) < 0.01) {
        return {
          rotate : 0 + "deg",
          skewX : 0 + "deg",
          scaleX : 1,
          scaleY : 1,
          translateX : 0 + "px",
          translateY : 0 + "px"
        };
      }
      var l = o, j = n;
      var u = Math.sqrt(v * v + t * t);
      v = v / u;
      t = t / u;
      var i = v * q + t * p;
      q -= v * i;
      p -= t * i;
      var s = Math.sqrt(q * q + p * p);
      q = q / s;
      p = p / s;
      i = i / s;
      if ((v * p - t * q) < 0) {
        v = -v;
        t = -t;
        u = -u;
      }
      var w = f.angle.radianToDegree;
      var h = w(Math.atan2(t, v));
      i = w(Math.atan(i));
      return {
        rotate : h + "deg",
        skewX : i + "deg",
        scaleX : u,
        scaleY : s,
        translateX : l + "px",
        translateY : j + "px"
      };
    }
  };
  f.extend(d.M2x2.prototype, c, {
    toM3x3 : function() {
      var h = this.elements;
      return new d.M3x3(h[0], h[1], 0, h[2], h[3], 0, 0, 0, 1);
    },
    x : function(j) {
      var k = typeof (j.rows) === "undefined";
      if (!k && j.rows == 3) {
        return this.toM3x3().x(j);
      }
      var i = this.elements, h = j.elements;
      if (k && h.length == 2) {
        return new d.V2(i[0] * h[0] + i[1] * h[1], i[2] * h[0] + i[3] * h[1]);
      } else {
        if (h.length == i.length) {
          return new d.M2x2(i[0] * h[0] + i[1] * h[2], i[0] * h[1] + i[1] * h[3], i[2] * h[0] + i[3] * h[2], i[2] * h[1] + i[3] * h[3]);
        }
      }
      return false;
    },
    inverse : function() {
      var i = 1 / this.determinant(), h = this.elements;
      return new d.M2x2(i * h[3], i * -h[1], i * -h[2], i * h[0]);
    },
    determinant : function() {
      var h = this.elements;
      return h[0] * h[3] - h[1] * h[2];
    }
  });
  f.extend(d.M3x3.prototype, c, {
    x : function(j) {
      var k = typeof (j.rows) === "undefined";
      if (!k && j.rows < 3) {
        j = j.toM3x3();
      }
      var i = this.elements, h = j.elements;
      if (k && h.length == 3) {
        return new d.V3(i[0] * h[0] + i[1] * h[1] + i[2] * h[2], i[3] * h[0] + i[4] * h[1] + i[5] * h[2], i[6] * h[0] + i[7] * h[1] + i[8] * h[2]);
      } else {
        if (h.length == i.length) {
          return new d.M3x3(i[0] * h[0] + i[1] * h[3] + i[2] * h[6], i[0] * h[1] + i[1] * h[4] + i[2] * h[7], i[0] * h[2] + i[1] * h[5] + i[2] * h[8], i[3] * h[0] + i[4] * h[3] + i[5] * h[6], i[3] * h[1] + i[4] * h[4] + i[5] * h[7], i[3] * h[2] + i[4] * h[5] + i[5] * h[8], i[6] * h[0] + i[7] * h[3] + i[8] * h[6], i[6] * h[1] + i[7] * h[4] + i[8] * h[7], i[6] * h[2] + i[7] * h[5] + i[8] * h[8]);
        }
      }
      return false;
    },
    inverse : function() {
      var i = 1 / this.determinant(), h = this.elements;
      return new d.M3x3(i * (h[8] * h[4] - h[7] * h[5]), i * (-(h[8] * h[1] - h[7] * h[2])), i * (h[5] * h[1] - h[4] * h[2]), i * (-(h[8] * h[3] - h[6] * h[5])), i * (h[8] * h[0] - h[6] * h[2]), i * (-(h[5] * h[0] - h[3] * h[2])), i * (h[7] * h[3] - h[6] * h[4]), i * (-(h[7] * h[0] - h[6] * h[1])), i * (h[4] * h[0] - h[3] * h[1]));
    },
    determinant : function() {
      var h = this.elements;
      return h[0] * (h[8] * h[4] - h[7] * h[5]) - h[3] * (h[8] * h[1] - h[7] * h[2]) + h[6] * (h[5] * h[1] - h[4] * h[2]);
    }
  });
  var a = {
    e : function(h) {
      return this.elements[h - 1];
    }
  };
  f.extend(d.V2.prototype, a);
  f.extend(d.V3.prototype, a);
})(jQuery, this, this.document);
(function(c, b, a, d) {
  if ( typeof (c.matrix) == "undefined") {
    c.extend({
      matrix : {}
    });
  }
  c.extend(c.matrix, {
    calc : function(e, f, g) {
      this.matrix = e;
      this.outerHeight = f;
      this.outerWidth = g;
    }
  });
  c.matrix.calc.prototype = {
    coord : function(e, i, h) {
      h = typeof (h) !== "undefined" ? h : 0;
      var g = this.matrix, f;
      switch(g.rows) {
        case 2:
          f = g.x(new c.matrix.V2(e, i));
          break;
        case 3:
          f = g.x(new c.matrix.V3(e, i, h));
          break;
      }
      return f;
    },
    corners : function(e, h) {
      var f = !( typeof (e) !== "undefined" || typeof (h) !== "undefined"), g;
      if (!this.c || !f) {
        h = h || this.outerHeight;
        e = e || this.outerWidth;
        g = {
          tl : this.coord(0, 0),
          bl : this.coord(0, h),
          tr : this.coord(e, 0),
          br : this.coord(e, h)
        };
      } else {
        g = this.c;
      }
      if (f) {
        this.c = g;
      }
      return g;
    },
    sides : function(e) {
      var f = e || this.corners();
      return {
        top : Math.min(f.tl.e(2), f.tr.e(2), f.br.e(2), f.bl.e(2)),
        bottom : Math.max(f.tl.e(2), f.tr.e(2), f.br.e(2), f.bl.e(2)),
        left : Math.min(f.tl.e(1), f.tr.e(1), f.br.e(1), f.bl.e(1)),
        right : Math.max(f.tl.e(1), f.tr.e(1), f.br.e(1), f.bl.e(1))
      };
    },
    offset : function(e) {
      var f = this.sides(e);
      return {
        height : Math.abs(f.bottom - f.top),
        width : Math.abs(f.right - f.left)
      };
    },
    area : function(e) {
      var h = e || this.corners();
      var g = {
        x : h.tr.e(1) - h.tl.e(1) + h.br.e(1) - h.bl.e(1),
        y : h.tr.e(2) - h.tl.e(2) + h.br.e(2) - h.bl.e(2)
      }, f = {
        x : h.bl.e(1) - h.tl.e(1) + h.br.e(1) - h.tr.e(1),
        y : h.bl.e(2) - h.tl.e(2) + h.br.e(2) - h.tr.e(2)
      };
      return 0.25 * Math.abs(g.e(1) * f.e(2) - g.e(2) * f.e(1));
    },
    nonAffinity : function() {
      var f = this.sides(), g = f.top - f.bottom, e = f.left - f.right;
      return parseFloat(parseFloat(Math.abs((Math.pow(g, 2) + Math.pow(e, 2)) / (f.top * f.bottom + f.left * f.right))).toFixed(8));
    },
    originOffset : function(h, g) {
      h = h ? h : new c.matrix.V2(this.outerWidth * 0.5, this.outerHeight * 0.5);
      g = g ? g : new c.matrix.V2(0, 0);
      var e = this.coord(h.e(1), h.e(2));
      var f = this.coord(g.e(1), g.e(2));
      return {
        top : (f.e(2) - g.e(2)) - (e.e(2) - h.e(2)),
        left : (f.e(1) - g.e(1)) - (e.e(1) - h.e(1))
      };
    }
  };
})(jQuery, this, this.document);
(function(e, d, a, f) {
  if ( typeof (e.matrix) == "undefined") {
    e.extend({
      matrix : {}
    });
  }
  var c = e.matrix, g = c.M2x2, b = c.M3x3;
  e.extend(c, {
    identity : function(k) {
      k = k || 2;
      var l = k * k, n = new Array(l), j = k + 1;
      for (var h = 0; h < l; h++) {
        n[h] = (h % j) === 0 ? 1 : 0;
      }
      return new c["M"+k+"x"+k](n);
    },
    matrix : function() {
      var h = Array.prototype.slice.call(arguments);
      switch(arguments.length) {
        case 4:
          return new g(h[0], h[2], h[1], h[3]);
        case 6:
          return new b(h[0], h[2], h[4], h[1], h[3], h[5], 0, 0, 1);
      }
    },
    reflect : function() {
      return new g(-1, 0, 0, -1);
    },
    reflectX : function() {
      return new g(1, 0, 0, -1);
    },
    reflectXY : function() {
      return new g(0, 1, 1, 0);
    },
    reflectY : function() {
      return new g(-1, 0, 0, 1);
    },
    rotate : function(l) {
      var i = e.angle.degreeToRadian(l), k = Math.cos(i), n = Math.sin(i);
      var j = k, h = n, p = -n, o = k;
      return new g(j, p, h, o);
    },
    scale : function(i, h) {
      i = i || i === 0 ? i : 1;
      h = h || h === 0 ? h : i;
      return new g(i, 0, 0, h);
    },
    scaleX : function(h) {
      return c.scale(h, 1);
    },
    scaleY : function(h) {
      return c.scale(1, h);
    },
    skew : function(k, i) {
      k = k || 0;
      i = i || 0;
      var l = e.angle.degreeToRadian(k), j = e.angle.degreeToRadian(i), h = Math.tan(l), n = Math.tan(j);
      return new g(1, h, n, 1);
    },
    skewX : function(h) {
      return c.skew(h);
    },
    skewY : function(h) {
      return c.skew(0, h);
    },
    translate : function(i, h) {
      i = i || 0;
      h = h || 0;
      return new b(1, 0, i, 0, 1, h, 0, 0, 1);
    },
    translateX : function(h) {
      return c.translate(h);
    },
    translateY : function(h) {
      return c.translate(0, h);
    }
  });
})(jQuery, this, this.document);
(function($) {
  $.fn.activityWrapper = function(action, options) {
    var shouldReturnResults = false;
    var results = [];
    var params = null;
    action = action || "initialize";
    if ( typeof (action) == "object") {
      options = action;
      action = "initialize";
    }
    if (action == "initialize") {
      if (!options) {
        options = $.fn.activityWrapper.defaults;
      } else {
        options = $.extend(true, {}, $.fn.activityWrapper.defaults, options);
      }
    } else {
      params = options;
    }
    var optionsReference = options;
    $(this).each(function() {
      switch(action) {
        case"initialize":
          initialize(this, optionsReference);
          break;
        case"getContentContainer":
          var options = $(this).data("activityWrapper:options");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.containers.content.reference
          });
          break;
        case"getHeaderContainer":
          var options = $(this).data("activityWrapper:options");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.containers.header.reference
          });
          break;
        case"getFooterContainer":
          var options = $(this).data("activityWrapper:options");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.containers.footer.reference
          });
          break;
        case"getState":
          var options = $(this).data("activityWrapper:options");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getState(this, options)
          });
          break;
        case"setState":
          var options = $(this).data("activityWrapper:options");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : setState(this, options, params.state, params.completed)
          });
          break;
        case"getType":
          var options = $(this).data("activityWrapper:options");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getType(this, options, params)
          });
          break;
        case"setEnabled":
          var options = $(this).data("activityWrapper:options");
          options.data.enabled = params;
          $(this).data("activityWrapper:options", options);
          setEnabled(this, options);
          break;
        case"finish":
          var options = $(this).data("activityWrapper:options");
          finish(this, options);
          break;
      }
    });
    if (shouldReturnResults == true) {
      return results;
    }
    function log(target, options, data, level) {
      level = level || "debug";
      level = $.trim(level).toLowerCase();
      if (options.data.enableLogging && window.console) {
        if (level == "info" && window.console.info && options.logging.info) {
          if ($(target).attr("id")) {
            window.console.info("[ActivityWrapper][" + target + ", id=" + $(target).attr("id") + "]" + data);
          } else {
            if ($(target).attr("name")) {
              window.console.info("[ActivityWrapper][" + target + ", name=" + $(target).attr("name") + "]" + data);
            } else {
              window.console.info("[ActivityWrapper][" + target + "]" + data);
            }
          }
        } else {
          if (level == "warn" && window.console.warn && options.logging.warn) {
            if ($(target).attr("id")) {
              window.console.warn("[ActivityWrapper][" + target + ", id=" + $(target).attr("id") + "]" + data);
            } else {
              if ($(target).attr("name")) {
                window.console.warn("[ActivityWrapper][" + target + ", name=" + $(target).attr("name") + "]" + data);
              } else {
                window.console.warn("[ActivityWrapper][" + target + "]" + data);
              }
            }
          } else {
            if (level == "error" && window.console.error && options.logging.error) {
              if ($(target).attr("id")) {
                window.console.error("[ActivityWrapper][" + target + ", id=" + $(target).attr("id") + "]" + data);
              } else {
                if ($(target).attr("name")) {
                  window.console.error("[ActivityWrapper][" + target + ", name=" + $(target).attr("name") + "]" + data);
                } else {
                  window.console.error("[ActivityWrapper][" + target + "]" + data);
                }
              }
            } else {
              if (window.console.log && options.logging.debug) {
                if ($(target).attr("id")) {
                  window.console.log("[ActivityWrapper][" + target + ", id=" + $(target).attr("id") + "]" + data);
                } else {
                  if ($(target).attr("name")) {
                    window.console.log("[ActivityWrapper][" + target + ", name=" + $(target).attr("name") + "]" + data);
                  } else {
                    window.console.log("[ActivityWrapper][" + target + "]" + data);
                  }
                }
              }
            }
          }
        }
      }
    }

    function initialize(target, options) {
      log(target, options, "Initializing Activity Wrapper", "info");
      options = $.extend(true, {}, options);
      options.containers.activity.reference = target;
      if (options.data.clearContainerContent) {
        $(options.containers.activity.reference).html("");
      }
      if (!$(options.containers.activity.reference).hasClass(options.containers.activity.css.identifier)) {
        $(options.containers.activity.reference).addClass(options.containers.activity.css.identifier);
      }
      if (options.containers.wrapper.reference == null) {
        options.containers.wrapper.reference = $("<div />");
        $(target).append(options.containers.wrapper.reference);
      }
      options.containers.wrapper.reference.addClass(options.containers.wrapper.css.identifier);
      if (options.containers.header.container.reference == null) {
        options.containers.header.container.reference = $("<div />");
        $(options.containers.wrapper.reference).append(options.containers.header.container.reference);
      }
      if (options.containers.header.container.reference) {
        options.containers.header.container.reference.addClass(options.containers.header.container.css.identifier);
      }
      if (options.containers.header.content.reference == null) {
        options.containers.header.content.reference = $("<div />");
        $(options.containers.header.container.reference).append(options.containers.header.content.reference);
      }
      if (options.containers.header.content.reference) {
        options.containers.header.content.reference.addClass(options.containers.header.content.css.identifier);
      }
      if (options.containers.content.reference == null) {
        options.containers.content.reference = $("<div />");
        $(options.containers.wrapper.reference).append(options.containers.content.reference);
      }
      if (options.containers.content.reference) {
        options.containers.content.reference.addClass(options.containers.content.css.identifier);
      }
      if (options.containers.footer.container.reference == null) {
        options.containers.footer.container.reference = $("<div />");
        $(target).append(options.containers.footer.container.reference);
      }
      if (options.containers.footer.container.reference) {
        options.containers.footer.container.reference.addClass(options.containers.footer.container.css.identifier);
        $(options.containers.footer.container.reference).activityControls();
      }
      $(target).data("activityWrapper:options", options);
      $(target).bind("resize", function(event) {
        var options = $(this).data("activityWrapper:options");
        if (event.target != options.containers.header.container.reference && event.target != options.containers.footer.container.reference && event.target != options.containers.content.reference) {
          handleResize(target, options);
        }
      });
      registerControlsEvents(target, options);
      if (options.data.activityType) {
        switch(options.data.activityType) {
          case 203:
          case"203":
          case"selection":
          case"selectAll":
          case"selectAllActivity":
            options.data.activityType = "selectAllActivity";
            $(target).data("activityWrapper:options", options);
            registerSelectAllEvents(target, options);
            break;
          case 204:
          case"204":
          case"sequence":
          case"ordering":
          case"orderingActivity":
            options.data.activityType = "orderingActivity";
            $(target).data("activityWrapper:options", options);
            registerOrderingEvents(target, options);
            break;
          case 205:
          case"205":
          case"sets":
          case"pairs":
          case"matching":
          case"matchingActivity":
            options.data.activityType = "matchingActivity";
            $(target).data("activityWrapper:options", options);
            registerMatchingEvents(target, options);
            break;
          case 200:
          case"200":
          case"align":
          case"slideSlot":
          case"slideSlotActivity":
            options.data.activityType = "slideSlotActivity";
            $(target).data("activityWrapper:options", options);
            registerSlideSlotEvents(target, options);
            break;
          case 201:
          case"201":
          case"identify":
          case"slideIdentification":
          case"slideIdentificationActivity":
            options.data.activityType = "slideIdentificationActivity";
            $(target).data("activityWrapper:options", options);
            registerSlideIdentificationEvents(target, options);
            break;
          case 202:
          case"202":
          case"presenter":
          case"slideShow":
          case"slideShowActivity":
            options.data.activityType = "slideShowActivity";
            $(target).data("activityWrapper:options", options);
            registerSlideShowEvents(target, options);
            break;
        }
      }
      handleResize(target, options);
    }

    function registerSlideShowEvents(target, options) {
      if ($.fn.slideShowActivity) {
        $(options.containers.content.reference).slideShowActivity(options.data.activityData);
        $(options.containers.content.reference).bind("activityLoaded.slideShowActivity", function(event, numberOfSets, position) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : false
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          if (!options.data.enabled) {
            setTimeout(function() {
              setEnabled(target, options);
            }, 1000);
          }
        });
        $(options.containers.content.reference).bind("disabled.slideShowActivity", function(event, numberOfSets) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : false
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : false
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("titleChanged.slideShowActivity", function(event, headerContent) {
          var options = $(target).data("activityWrapper:options");
          setHeaderContent(target, options, headerContent);
        });
        $(options.containers.content.reference).bind("contentShown.slideShowActivity", function(event, headerContent) {
          var options = $(target).data("activityWrapper:options");
          $(options.containers.footer.container.reference).activityControls("showOrHideMoreAndLess", {
            moreButton : false,
            lessButton : true
          });
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", {
            enableMore : false,
            enableLess : true
          });
        });
        $(options.containers.content.reference).bind("contentHidden.slideShowActivity", function(event, headerContent) {
          var options = $(target).data("activityWrapper:options");
          $(options.containers.footer.container.reference).activityControls("showOrHideMoreAndLess", {
            moreButton : true,
            lessButton : false
          });
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", {
            enableMore : true,
            enableLess : false
          });
        });
        $(options.containers.content.reference).bind("setChanged.slideShowActivity", function(event, numberOfSets, position, hasDetails, contentShown, enabled) {
          var options = $(target).data("activityWrapper:options");
          $(options.containers.footer.container.reference).activityControls("setStatus", (position + 1) + "/" + numberOfSets);
          $(options.containers.footer.container.reference).activityControls("setPositionIndicator", {
            numberOfSets : numberOfSets,
            position : position
          });
          $(options.containers.footer.container.reference).activityControls("updateControlsBasedOnSetPosition", {
            numberOfSets : numberOfSets,
            position : position
          });
          var controlVisibility = {
            finishButton : false,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : (!contentShown) ? true : false,
            lessButton : (hasDetails && contentShown) ? true : false,
            saveButton : false
          };
          var moreAndLessEnabled = {
            enableMore : (hasDetails && !contentShown) ? true : false,
            enableLess : contentShown
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
        });
        if (options.data.activityData.xmlData) {
          if (options.data.activityData.xmlDataEncoding) {
            options.data.activityData.xmlData = unescape(options.data.activityData.xmlData.replace(/\+/g, " "));
          }
          $(options.containers.content.reference).slideShowActivity("parseXMLAndBuildActivity", options.data.activityData.xmlData);
        } else {
          if (options.data.activityData.xmlFile) {
            $(options.containers.content.reference).slideShowActivity("loadXMLAndBuildActivity", options.data.activityData.xmlFile);
          }
        }
        if (options.data.activityData.state) {
          $(options.containers.content.reference).slideShowActivity("setState", options.data.activityData.state);
        }
      }
    }

    function registerSlideIdentificationEvents(target, options) {
      if ($.fn.slideIdentificationActivity) {
        $(options.containers.content.reference).slideIdentificationActivity(options.data.activityData);
        $(options.containers.content.reference).bind("activityLoaded.slideIdentificationActivity", function(event, numberOfSets, setShown, allowRetry, gradeSetsIndividually) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : true,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : true,
            enableReset : allowRetry
          };
          if (!gradeSetsIndividually && options.data.requireAllSetsShownForFinish) {
            var found = false;
            options.data.setsShown = [];
            options.data.setsShown.push(setShown);
            $(target).data("activityWrapper:options", options);
            if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
              finishAndResetEnabled.enableFinish = false;
            }
          }
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : true
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          if (!options.data.enabled) {
            setTimeout(function() {
              if (options.data.activityData.state && options.data.activityData.completed != null && options.data.activityData.completed != undefined) {
                $(options.containers.content.reference).slideIdentificationActivity("setState", {
                  state : options.data.activityData.state,
                  completed : options.data.activityData.completed
                });
              }
              setEnabled(target, options);
            }, 1000);
          }
        });
        $(options.containers.content.reference).bind("disabled.slideIdentificationActivity", function(event, numberOfSets) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : false
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : false
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("activityScoreChanged.slideIdentificationActivity", function(event, numberOfSets, position, allowRetry, gradeSetsIndividually, calculatedScore, calculatedPossible, activeSetCompleted, doNotUpdateExternalScore) {
          var options = $(target).data("activityWrapper:options");
          calculatedScore = Math.round(calculatedScore * 10) / 10;
          calculatedPossible = Math.round(calculatedPossible * 10) / 10;
          if (calculatedPossible > 0) {
            $(options.containers.footer.container.reference).activityControls("setStatus", calculatedScore + "/" + calculatedPossible);
          } else {
            $(options.containers.footer.container.reference).activityControls("setStatus", "");
          }
          if (gradeSetsIndividually) {
            var controlVisibility = {
              finishButton : !activeSetCompleted,
              resetButton : activeSetCompleted,
              nextSetButton : ((numberOfSets > 1) ? true : false),
              previousSetButton : ((numberOfSets > 1) ? true : false),
              positionIndicator : ((numberOfSets > 1) ? true : false),
              moreButton : false,
              lessButton : false,
              saveButton : true
            };
            var finishAndResetEnabled = {
              enableFinish : !activeSetCompleted,
              enableReset : allowRetry
            };
            var moreAndLessEnabled = {
              enableMore : false,
              enableLess : false
            };
            var saveEnabled = {
              enableSave : !activeSetCompleted
            };
            $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          }
          if (options.data.activityIdentifier && calculatedPossible > 0) {
            if (options.data.initialUpdateGradeCalled && !options.data.onlyCallCookitOnCompleteEvents && !doNotUpdateExternalScore && window.cookit) {
              log(target, options, "Calling Cookit:");
              window.cookit(options.data.activityIdentifier + "score", (calculatedScore / calculatedPossible * 100), options.data.activityIdentifier + "attempts", 1);
            }
            if (!options.data.initialUpdateGradeCalled) {
              options.data.initialUpdateGradeCalled = true;
              $(target).data("activityWrapper:options", options);
            }
          }
        });
        $(options.containers.content.reference).bind("activityComplete.slideIdentificationActivity", function(event, numberOfSets, position, allowRetry, gradeSetsIndividually, calculatedScore, calculatedPossible, doNotUpdateExternalScore) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : true,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : allowRetry
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          if (options.data.activityIdentifier && calculatedPossible > 0) {
            if (options.data.initialUpdateGradeCalled && !doNotUpdateExternalScore && window.cookit) {
              log(target, options, "Calling Cookit:");
              window.cookit(options.data.activityIdentifier + "score", (calculatedScore / calculatedPossible * 100), options.data.activityIdentifier + "attempts", 0);
            }
            if (!options.data.initialUpdateGradeCalled) {
              options.data.initialUpdateGradeCalled = true;
              $(target).data("activityWrapper:options", options);
            }
          }
        });
        $(options.containers.content.reference).bind("reset.slideIdentificationActivity", function(event, numberOfSets, setShown, allowRetry, gradeSetsIndividually) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : true,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : true,
            enableReset : false
          };
          if (!gradeSetsIndividually && options.data.requireAllSetsShownForFinish) {
            var found = false;
            options.data.setsShown = [];
            options.data.setsShown.push(setShown);
            $(target).data("activityWrapper:options", options);
            if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
              finishAndResetEnabled.enableFinish = false;
            }
          }
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : true
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("titleChanged.slideIdentificationActivity", function(event, headerContent) {
          var options = $(target).data("activityWrapper:options");
          setHeaderContent(target, options, headerContent);
        });
        $(options.containers.content.reference).bind("setChanged.slideIdentificationActivity", function(event, numberOfSets, position, gradeSetsIndividually, allowReset, setCompleted, enabled) {
          var options = $(target).data("activityWrapper:options");
          $(options.containers.footer.container.reference).activityControls("setPositionIndicator", {
            numberOfSets : numberOfSets,
            position : position
          });
          $(options.containers.footer.container.reference).activityControls("updateControlsBasedOnSetPosition", {
            numberOfSets : numberOfSets,
            position : position
          });
          if (!options.data.enabled && !enabled) {
            var controlVisibility = {
              finishButton : false,
              resetButton : false,
              nextSetButton : (numberOfSets > 1) ? true : false,
              previousSetButton : (numberOfSets > 1) ? true : false,
              positionIndicator : (numberOfSets > 1) ? true : false,
              moreButton : false,
              lessButton : false,
              saveButton : false
            };
            var finishAndResetEnabled = {
              enableFinish : false,
              enableReset : false
            };
            var moreAndLessEnabled = {
              enableMore : false,
              enableLess : false
            };
            var saveEnabled = {
              enableSave : false
            };
            $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          } else {
            if (gradeSetsIndividually) {
              var controlVisibility = {
                finishButton : !setCompleted,
                resetButton : setCompleted,
                nextSetButton : (numberOfSets > 1) ? true : false,
                previousSetButton : (numberOfSets > 1) ? true : false,
                positionIndicator : (numberOfSets > 1) ? true : false,
                moreButton : false,
                lessButton : false,
                saveButton : true
              };
              var finishAndResetEnabled = {
                enableFinish : !setCompleted,
                enableReset : allowReset
              };
              var moreAndLessEnabled = {
                enableMore : false,
                enableLess : false
              };
              var saveEnabled = {
                enableSave : !setCompleted
              };
              $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
            } else {
              if (options.data.requireAllSetsShownForFinish) {
                var finishAndResetEnabled = {
                  enableFinish : true,
                  enableReset : allowReset
                };
                var found = false;
                $.each(options.data.setsShown, function(i, setId) {
                  if (setId == position) {
                    found = true;
                  }
                });
                if (!found) {
                  options.data.setsShown.push(position);
                  $(target).data("activityWrapper:options", options);
                }
                if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
                  finishAndResetEnabled.enableFinish = false;
                }
                $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
              }
            }
          }
        });
        if (options.data.activityData.xmlData) {
          if (options.data.activityData.xmlDataEncoding) {
            options.data.activityData.xmlData = unescape(options.data.activityData.xmlData.replace(/\+/g, " "));
          }
          $(options.containers.content.reference).slideIdentificationActivity("parseXMLAndBuildActivity", options.data.activityData.xmlData);
        } else {
          if (options.data.activityData.xmlFile) {
            $(options.containers.content.reference).slideIdentificationActivity("loadXMLAndBuildActivity", options.data.activityData.xmlFile);
          }
        }
      }
    }

    function registerSlideSlotEvents(target, options) {
      if ($.fn.slideSlotActivity) {
        $(options.containers.content.reference).slideSlotActivity(options.data.activityData);
        $(options.containers.content.reference).bind("activityLoaded.slideSlotActivity", function(event, numberOfSets, setShown, allowRetry, gradeSetsIndividually) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : true,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : true,
            enableReset : allowRetry
          };
          if (!gradeSetsIndividually && options.data.requireAllSetsShownForFinish) {
            var found = false;
            options.data.setsShown = [];
            options.data.setsShown.push(setShown);
            $(target).data("activityWrapper:options", options);
            if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
              finishAndResetEnabled.enableFinish = false;
            }
          }
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : true
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          if (!options.data.enabled) {
            setTimeout(function() {
              if (options.data.activityData.state && options.data.activityData.completed != null && options.data.activityData.completed != undefined) {
                $(options.containers.content.reference).slideSlotActivity("setState", {
                  state : options.data.activityData.state,
                  completed : options.data.activityData.completed
                });
              }
              setEnabled(target, options);
            }, 1000);
          }
        });
        $(options.containers.content.reference).bind("disabled.slideSlotActivity", function(event, numberOfSets) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : false
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : false
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("activityScoreChanged.slideSlotActivity", function(event, numberOfSets, position, allowRetry, gradeSetsIndividually, calculatedScore, calculatedPossible, activeSetCompleted, doNotUpdateExternalScore) {
          var options = $(target).data("activityWrapper:options");
          calculatedScore = Math.round(calculatedScore * 10) / 10;
          calculatedPossible = Math.round(calculatedPossible * 10) / 10;
          if (calculatedPossible > 0) {
            $(options.containers.footer.container.reference).activityControls("setStatus", calculatedScore + "/" + calculatedPossible);
          } else {
            $(options.containers.footer.container.reference).activityControls("setStatus", "");
          }
          if (gradeSetsIndividually) {
            var controlVisibility = {
              finishButton : !activeSetCompleted,
              resetButton : activeSetCompleted,
              nextSetButton : ((numberOfSets > 1) ? true : false),
              previousSetButton : ((numberOfSets > 1) ? true : false),
              positionIndicator : ((numberOfSets > 1) ? true : false),
              moreButton : false,
              lessButton : false,
              saveButton : true
            };
            var finishAndResetEnabled = {
              enableFinish : !activeSetCompleted,
              enableReset : allowRetry
            };
            var moreAndLessEnabled = {
              enableMore : false,
              enableLess : false
            };
            var saveEnabled = {
              enableSave : !activeSetCompleted
            };
            $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          }
          if (options.data.activityIdentifier && calculatedPossible > 0) {
            if (options.data.initialUpdateGradeCalled && !options.data.onlyCallCookitOnCompleteEvents && !doNotUpdateExternalScore && window.cookit) {
              log(target, options, "Calling Cookit:");
              window.cookit(options.data.activityIdentifier + "score", (calculatedScore / calculatedPossible * 100), options.data.activityIdentifier + "attempts", 0);
            }
            if (!options.data.initialUpdateGradeCalled) {
              options.data.initialUpdateGradeCalled = true;
              $(target).data("activityWrapper:options", options);
            }
          }
        });
        $(options.containers.content.reference).bind("activityComplete.slideSlotActivity", function(event, numberOfSets, position, allowRetry, gradeSetsIndividually, calculatedScore, calculatedPossible, doNotUpdateExternalScore) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : true,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : allowRetry
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          if (options.data.activityIdentifier && calculatedPossible > 0) {
            if (options.data.initialUpdateGradeCalled && !doNotUpdateExternalScore && window.cookit) {
              log(target, options, "Calling Cookit:");
              window.cookit(options.data.activityIdentifier + "score", (calculatedScore / calculatedPossible * 100), options.data.activityIdentifier + "attempts", 1);
            }
            if (!options.data.initialUpdateGradeCalled) {
              options.data.initialUpdateGradeCalled = true;
              $(target).data("activityWrapper:options", options);
            }
          }
        });
        $(options.containers.content.reference).bind("reset.slideSlotActivity", function(event, numberOfSets, setShown, allowRetry, gradeSetsIndividually) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : true,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : true,
            enableReset : false
          };
          if (!gradeSetsIndividually && options.data.requireAllSetsShownForFinish) {
            var found = false;
            options.data.setsShown = [];
            options.data.setsShown.push(setShown);
            $(target).data("activityWrapper:options", options);
            if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
              finishAndResetEnabled.enableFinish = false;
            }
          }
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : true
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("titleChanged.slideSlotActivity", function(event, headerContent) {
          var options = $(target).data("activityWrapper:options");
          setHeaderContent(target, options, headerContent);
        });
        $(options.containers.content.reference).bind("setChanged.slideSlotActivity", function(event, numberOfSets, position, gradeSetsIndividually, allowReset, setCompleted, enabled) {
          var options = $(target).data("activityWrapper:options");
          $(options.containers.footer.container.reference).activityControls("setPositionIndicator", {
            numberOfSets : numberOfSets,
            position : position
          });
          $(options.containers.footer.container.reference).activityControls("updateControlsBasedOnSetPosition", {
            numberOfSets : numberOfSets,
            position : position
          });
          if (!options.data.enabled && !enabled) {
            var controlVisibility = {
              finishButton : false,
              resetButton : false,
              nextSetButton : (numberOfSets > 1) ? true : false,
              previousSetButton : (numberOfSets > 1) ? true : false,
              positionIndicator : (numberOfSets > 1) ? true : false,
              moreButton : false,
              lessButton : false,
              saveButton : false
            };
            var finishAndResetEnabled = {
              enableFinish : false,
              enableReset : false
            };
            var moreAndLessEnabled = {
              enableMore : false,
              enableLess : false
            };
            var saveEnabled = {
              enableSave : false
            };
            $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          } else {
            if (gradeSetsIndividually) {
              var controlVisibility = {
                finishButton : !setCompleted,
                resetButton : setCompleted,
                nextSetButton : (numberOfSets > 1) ? true : false,
                previousSetButton : (numberOfSets > 1) ? true : false,
                positionIndicator : (numberOfSets > 1) ? true : false,
                moreButton : false,
                lessButton : false,
                saveButton : true
              };
              var finishAndResetEnabled = {
                enableFinish : !setCompleted,
                enableReset : allowReset
              };
              var moreAndLessEnabled = {
                enableMore : false,
                enableLess : false
              };
              var saveEnabled = {
                enableSave : !setCompleted
              };
              $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
            } else {
              if (options.data.requireAllSetsShownForFinish) {
                var finishAndResetEnabled = {
                  enableFinish : true,
                  enableReset : allowReset
                };
                var found = false;
                $.each(options.data.setsShown, function(i, setId) {
                  if (setId == position) {
                    found = true;
                  }
                });
                if (!found) {
                  options.data.setsShown.push(position);
                  $(target).data("activityWrapper:options", options);
                }
                if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
                  finishAndResetEnabled.enableFinish = false;
                }
                $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
              }
            }
          }
        });
        if (options.data.activityData.xmlData) {
          if (options.data.activityData.xmlDataEncoding) {
            options.data.activityData.xmlData = unescape(options.data.activityData.xmlData.replace(/\+/g, " "));
          }
          $(options.containers.content.reference).slideSlotActivity("parseXMLAndBuildActivity", options.data.activityData.xmlData);
        } else {
          if (options.data.activityData.xmlFile) {
            $(options.containers.content.reference).slideSlotActivity("loadXMLAndBuildActivity", options.data.activityData.xmlFile);
          }
        }
      }
    }

    function registerMatchingEvents(target, options) {
      if ($.fn.matchingActivity) {
        $(options.containers.content.reference).matchingActivity(options.data.activityData);
        $(options.containers.content.reference).bind("activityLoaded.matchingActivity", function(event, numberOfSets, setShown, allowRetry, gradeSetsIndividually) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : allowRetry,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : true,
            enableReset : false
          };
          if (!gradeSetsIndividually && options.data.requireAllSetsShownForFinish) {
            var found = false;
            options.data.setsShown = [];
            options.data.setsShown.push(setShown);
            $(target).data("activityWrapper:options", options);
            if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
              finishAndResetEnabled.enableFinish = false;
            }
          }
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : true
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          if (!options.data.enabled) {
            setTimeout(function() {
              if (options.data.activityData.state && options.data.activityData.completed != null && options.data.activityData.completed != undefined) {
                $(options.containers.content.reference).matchingActivity("setState", {
                  state : options.data.activityData.state,
                  completed : options.data.activityData.completed
                });
              }
              setEnabled(target, options);
            }, 1000);
          }
        });
        $(options.containers.content.reference).bind("disabled.matchingActivity", function(event, numberOfSets) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : false
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : false
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("activityScoreChanged.matchingActivity", function(event, numberOfSets, position, allowRetry, gradeSetsIndividually, calculatedScore, calculatedPossible, activeSetCompleted, doNotUpdateExternalScore) {
          var options = $(target).data("activityWrapper:options");
          calculatedScore = Math.round(calculatedScore * 10) / 10;
          calculatedPossible = Math.round(calculatedPossible * 10) / 10;
          if (calculatedPossible > 0) {
            $(options.containers.footer.container.reference).activityControls("setStatus", calculatedScore + "/" + calculatedPossible);
          } else {
            $(options.containers.footer.container.reference).activityControls("setStatus", "");
          }
          if (gradeSetsIndividually) {
            var controlVisibility = {
              finishButton : false,
              resetButton : activeSetCompleted,
              nextSetButton : ((numberOfSets > 1) ? true : false),
              previousSetButton : ((numberOfSets > 1) ? true : false),
              positionIndicator : ((numberOfSets > 1) ? true : false),
              moreButton : false,
              lessButton : false,
              saveButton : true
            };
            var finishAndResetEnabled = {
              enableFinish : !activeSetCompleted,
              enableReset : allowRetry
            };
            var moreAndLessEnabled = {
              enableMore : false,
              enableLess : false
            };
            var saveEnabled = {
              enableSave : !activeSetCompleted
            };
            $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          }
          if (options.data.activityIdentifier && calculatedPossible > 0) {
            if (options.data.initialUpdateGradeCalled && !options.data.onlyCallCookitOnCompleteEvents && !doNotUpdateExternalScore && window.cookit) {
              log(target, options, "Calling Cookit:");
              window.cookit(options.data.activityIdentifier + "score", (calculatedScore / calculatedPossible * 100), options.data.activityIdentifier + "attempts", 0);
            }
            if (!options.data.initialUpdateGradeCalled) {
              options.data.initialUpdateGradeCalled = true;
              $(target).data("activityWrapper:options", options);
            }
          }
        });
        $(options.containers.content.reference).bind("activityComplete.matchingActivity", function(event, numberOfSets, position, allowRetry, gradeSetsIndividually, calculatedScore, calculatedPossible, doNotUpdateExternalScore) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : true,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : allowRetry
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          if (options.data.activityIdentifier && calculatedPossible > 0) {
            if (options.data.initialUpdateGradeCalled && !doNotUpdateExternalScore && window.cookit) {
              log(target, options, "Calling Cookit:");
              window.cookit(options.data.activityIdentifier + "score", (calculatedScore / calculatedPossible * 100), options.data.activityIdentifier + "attempts", 1);
            }
            if (!options.data.initialUpdateGradeCalled) {
              options.data.initialUpdateGradeCalled = true;
              $(target).data("activityWrapper:options", options);
            }
          }
        });
        $(options.containers.content.reference).bind("reset.matchingActivity", function(event, numberOfSets, setShown, allowRetry, gradeSetsIndividually) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : allowRetry,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : true,
            enableReset : false
          };
          if (!gradeSetsIndividually && options.data.requireAllSetsShownForFinish) {
            var found = false;
            options.data.setsShown = [];
            options.data.setsShown.push(setShown);
            $(target).data("activityWrapper:options", options);
            if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
              finishAndResetEnabled.enableFinish = false;
            }
          }
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : true
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("titleChanged.matchingActivity", function(event, headerContent) {
          var options = $(target).data("activityWrapper:options");
          setHeaderContent(target, options, headerContent);
        });
        $(options.containers.content.reference).bind("setChanged.matchingActivity", function(event, numberOfSets, position, gradeSetsIndividually, allowReset, setCompleted, enabled) {
          var options = $(target).data("activityWrapper:options");
          $(options.containers.footer.container.reference).activityControls("setPositionIndicator", {
            numberOfSets : numberOfSets,
            position : position
          });
          $(options.containers.footer.container.reference).activityControls("updateControlsBasedOnSetPosition", {
            numberOfSets : numberOfSets,
            position : position
          });
          if (!options.data.enabled && !enabled) {
            var controlVisibility = {
              finishButton : false,
              resetButton : false,
              nextSetButton : (numberOfSets > 1) ? true : false,
              previousSetButton : (numberOfSets > 1) ? true : false,
              positionIndicator : (numberOfSets > 1) ? true : false,
              moreButton : false,
              lessButton : false,
              saveButton : false
            };
            var finishAndResetEnabled = {
              enableFinish : false,
              enableReset : false
            };
            var moreAndLessEnabled = {
              enableMore : false,
              enableLess : false
            };
            var saveEnabled = {
              enableSave : false
            };
            $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          } else {
            if (gradeSetsIndividually) {
              var controlVisibility = {
                finishButton : false,
                resetButton : setCompleted,
                nextSetButton : (numberOfSets > 1) ? true : false,
                previousSetButton : (numberOfSets > 1) ? true : false,
                positionIndicator : (numberOfSets > 1) ? true : false,
                moreButton : false,
                lessButton : false,
                saveButton : true
              };
              var finishAndResetEnabled = {
                enableFinish : !setCompleted,
                enableReset : allowReset
              };
              var moreAndLessEnabled = {
                enableMore : false,
                enableLess : false
              };
              var saveEnabled = {
                enableSave : !setCompleted
              };
              $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
            }
          }
        });
        if (options.data.activityData.xmlData) {
          if (options.data.activityData.xmlDataEncoding) {
            options.data.activityData.xmlData = unescape(options.data.activityData.xmlData.replace(/\+/g, " "));
          }
          $(options.containers.content.reference).matchingActivity("parseXMLAndBuildActivity", options.data.activityData.xmlData);
        } else {
          if (options.data.activityData.xmlFile) {
            $(options.containers.content.reference).matchingActivity("loadXMLAndBuildActivity", options.data.activityData.xmlFile);
          }
        }
      }
    }

    function registerOrderingEvents(target, options) {
      if ($.fn.orderingActivity) {
        $(options.containers.content.reference).orderingActivity(options.data.activityData);
        $(options.containers.content.reference).bind("activityLoaded.orderingActivity", function(event, numberOfSets, setShown, allowRetry, gradeSetsIndividually) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : true,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : true,
            enableReset : allowRetry
          };
          if (!gradeSetsIndividually && options.data.requireAllSetsShownForFinish) {
            var found = false;
            options.data.setsShown = [];
            options.data.setsShown.push(setShown);
            $(target).data("activityWrapper:options", options);
            if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
              finishAndResetEnabled.enableFinish = false;
            }
          }
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : true
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          if (!options.data.enabled) {
            setTimeout(function() {
              if (options.data.activityData.state && options.data.activityData.completed != null && options.data.activityData.completed != undefined) {
                $(options.containers.content.reference).orderingActivity("setState", {
                  state : options.data.activityData.state,
                  completed : options.data.activityData.completed
                });
              }
              setEnabled(target, options);
            }, 1000);
          }
        });
        $(options.containers.content.reference).bind("disabled.orderingActivity", function(event, numberOfSets) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : false
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : false
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("activityScoreChanged.orderingActivity", function(event, numberOfSets, position, allowRetry, gradeSetsIndividually, calculatedScore, calculatedPossible, activeSetCompleted, doNotUpdateExternalScore) {
          var options = $(target).data("activityWrapper:options");
          calculatedScore = Math.round(calculatedScore * 10) / 10;
          calculatedPossible = Math.round(calculatedPossible * 10) / 10;
          if (calculatedPossible > 0) {
            $(options.containers.footer.container.reference).activityControls("setStatus", calculatedScore + "/" + calculatedPossible);
          } else {
            $(options.containers.footer.container.reference).activityControls("setStatus", "");
          }
          if (gradeSetsIndividually) {
            var controlVisibility = {
              finishButton : !activeSetCompleted,
              resetButton : activeSetCompleted,
              nextSetButton : ((numberOfSets > 1) ? true : false),
              previousSetButton : ((numberOfSets > 1) ? true : false),
              positionIndicator : ((numberOfSets > 1) ? true : false),
              moreButton : false,
              lessButton : false,
              saveButton : true
            };
            var finishAndResetEnabled = {
              enableFinish : !activeSetCompleted,
              enableReset : allowRetry
            };
            var moreAndLessEnabled = {
              enableMore : false,
              enableLess : false
            };
            var saveEnabled = {
              enableSave : !activeSetCompleted
            };
            $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          }
          if (options.data.activityIdentifier && calculatedPossible > 0) {
            if (options.data.initialUpdateGradeCalled && !options.data.onlyCallCookitOnCompleteEvents && !doNotUpdateExternalScore && window.cookit) {
              log(target, options, "Calling Cookit:");
              window.cookit(options.data.activityIdentifier + "score", (calculatedScore / calculatedPossible * 100), options.data.activityIdentifier + "attempts", 0);
            }
            if (!options.data.initialUpdateGradeCalled) {
              options.data.initialUpdateGradeCalled = true;
              $(target).data("activityWrapper:options", options);
            }
          }
        });
        $(options.containers.content.reference).bind("activityComplete.orderingActivity", function(event, numberOfSets, position, allowRetry, gradeSetsIndividually, calculatedScore, calculatedPossible, doNotUpdateExternalScore) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : true,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : allowRetry
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          if (options.data.activityIdentifier && calculatedPossible > 0) {
            if (options.data.initialUpdateGradeCalled && !doNotUpdateExternalScore && window.cookit) {
              log(target, options, "Calling Cookit:");
              window.cookit(options.data.activityIdentifier + "score", (calculatedScore / calculatedPossible * 100), options.data.activityIdentifier + "attempts", 1);
            }
            if (!options.data.initialUpdateGradeCalled) {
              options.data.initialUpdateGradeCalled = true;
              $(target).data("activityWrapper:options", options);
            }
          }
        });
        $(options.containers.content.reference).bind("reset.orderingActivity", function(event, numberOfSets, setShown, allowRetry, gradeSetsIndividually) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : true,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : true,
            enableReset : false
          };
          if (!gradeSetsIndividually && options.data.requireAllSetsShownForFinish) {
            var found = false;
            options.data.setsShown = [];
            options.data.setsShown.push(setShown);
            $(target).data("activityWrapper:options", options);
            if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
              finishAndResetEnabled.enableFinish = false;
            }
          }
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : true
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("titleChanged.orderingActivity", function(event, headerContent) {
          var options = $(target).data("activityWrapper:options");
          setHeaderContent(target, options, headerContent);
        });
        $(options.containers.content.reference).bind("setChanged.orderingActivity", function(event, numberOfSets, position, gradeSetsIndividually, allowReset, setCompleted, enabled) {
          var options = $(target).data("activityWrapper:options");
          $(options.containers.footer.container.reference).activityControls("setPositionIndicator", {
            numberOfSets : numberOfSets,
            position : position
          });
          $(options.containers.footer.container.reference).activityControls("updateControlsBasedOnSetPosition", {
            numberOfSets : numberOfSets,
            position : position
          });
          if (!options.data.enabled && !enabled) {
            var controlVisibility = {
              finishButton : false,
              resetButton : false,
              nextSetButton : (numberOfSets > 1) ? true : false,
              previousSetButton : (numberOfSets > 1) ? true : false,
              positionIndicator : (numberOfSets > 1) ? true : false,
              moreButton : false,
              lessButton : false,
              saveButton : false
            };
            var finishAndResetEnabled = {
              enableFinish : false,
              enableReset : false
            };
            var moreAndLessEnabled = {
              enableMore : false,
              enableLess : false
            };
            var saveEnabled = {
              enableSave : false
            };
            $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          } else {
            if (gradeSetsIndividually) {
              var controlVisibility = {
                finishButton : !setCompleted,
                resetButton : setCompleted,
                nextSetButton : (numberOfSets > 1) ? true : false,
                previousSetButton : (numberOfSets > 1) ? true : false,
                positionIndicator : (numberOfSets > 1) ? true : false,
                moreButton : false,
                lessButton : false,
                saveButton : true
              };
              var finishAndResetEnabled = {
                enableFinish : !setCompleted,
                enableReset : allowReset
              };
              var moreAndLessEnabled = {
                enableMore : false,
                enableLess : false
              };
              var saveEnabled = {
                enableSave : !setCompleted
              };
              $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
            } else {
              if (options.data.requireAllSetsShownForFinish) {
                var finishAndResetEnabled = {
                  enableFinish : true,
                  enableReset : allowReset
                };
                var found = false;
                $.each(options.data.setsShown, function(i, setId) {
                  if (setId == position) {
                    found = true;
                  }
                });
                if (!found) {
                  options.data.setsShown.push(position);
                  $(target).data("activityWrapper:options", options);
                }
                if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
                  finishAndResetEnabled.enableFinish = false;
                }
                $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
              }
            }
          }
        });
        if (options.data.activityData.xmlData) {
          if (options.data.activityData.xmlDataEncoding) {
            options.data.activityData.xmlData = unescape(options.data.activityData.xmlData.replace(/\+/g, " "));
          }
          $(options.containers.content.reference).orderingActivity("parseXMLAndBuildActivity", options.data.activityData.xmlData);
        } else {
          if (options.data.activityData.xmlFile) {
            $(options.containers.content.reference).orderingActivity("loadXMLAndBuildActivity", options.data.activityData.xmlFile);
          }
        }
      }
    }

    function registerSelectAllEvents(target, options) {
      if ($.fn.selectAllActivity) {
        $(options.containers.content.reference).selectAllActivity(options.data.activityData);
        $(options.containers.content.reference).bind("activityLoaded.selectAllActivity", function(event, numberOfSets, setShown, allowRetry, gradeSetsIndividually) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : true,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : true,
            enableReset : allowRetry
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          if (!gradeSetsIndividually && options.data.requireAllSetsShownForFinish) {
            var found = false;
            options.data.setsShown = [];
            options.data.setsShown.push(setShown);
            $(target).data("activityWrapper:options", options);
            if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
              finishAndResetEnabled.enableFinish = false;
            }
          }
          var saveEnabled = {
            enableSave : true
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          if (!options.data.enabled) {
            setTimeout(function() {
              if (options.data.activityData.state && options.data.activityData.completed != null && options.data.activityData.completed != undefined) {
                $(options.containers.content.reference).selectAllActivity("setState", {
                  state : options.data.activityData.state,
                  completed : options.data.activityData.completed
                });
              }
              setEnabled(target, options);
            }, 1000);
          }
        });
        $(options.containers.content.reference).bind("disabled.selectAllActivity", function(event, numberOfSets) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : false
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : false
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("activityScoreChanged.selectAllActivity", function(event, numberOfSets, position, allowRetry, gradeSetsIndividually, calculatedScore, calculatedPossible, activeSetCompleted, doNotUpdateExternalScore) {
          var options = $(target).data("activityWrapper:options");
          calculatedScore = Math.round(calculatedScore * 10) / 10;
          calculatedPossible = Math.round(calculatedPossible * 10) / 10;
          if (calculatedPossible > 0) {
            $(options.containers.footer.container.reference).activityControls("setStatus", calculatedScore + "/" + calculatedPossible);
          } else {
            $(options.containers.footer.container.reference).activityControls("setStatus", "");
          }
          if (gradeSetsIndividually) {
            var controlVisibility = {
              finishButton : !activeSetCompleted,
              resetButton : activeSetCompleted,
              nextSetButton : ((numberOfSets > 1) ? true : false),
              previousSetButton : ((numberOfSets > 1) ? true : false),
              positionIndicator : ((numberOfSets > 1) ? true : false),
              moreButton : false,
              lessButton : false,
              saveButton : true
            };
            var finishAndResetEnabled = {
              enableFinish : !activeSetCompleted,
              enableReset : allowRetry
            };
            var moreAndLessEnabled = {
              enableMore : false,
              enableLess : false
            };
            var saveEnabled = {
              enableSave : !activeSetCompleted
            };
            $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          }
          if (options.data.activityIdentifier && calculatedPossible > 0) {
            if (options.data.initialUpdateGradeCalled && !options.data.onlyCallCookitOnCompleteEvents && !doNotUpdateExternalScore && window.cookit) {
              log(target, options, "Calling Cookit:");
              window.cookit(options.data.activityIdentifier + "score", (calculatedScore / calculatedPossible * 100), options.data.activityIdentifier + "attempts", 0);
            }
            if (!options.data.initialUpdateGradeCalled) {
              options.data.initialUpdateGradeCalled = true;
              $(target).data("activityWrapper:options", options);
            }
          }
        });
        $(options.containers.content.reference).bind("activityComplete.selectAllActivity", function(event, numberOfSets, position, allowRetry, gradeSetsIndividually, calculatedScore, calculatedPossible, doNotUpdateExternalScore) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : false,
            resetButton : true,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : false,
            enableReset : allowRetry
          };
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : false
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          if (options.data.activityIdentifier && calculatedPossible > 0) {
            if (options.data.initialUpdateGradeCalled && !doNotUpdateExternalScore && window.cookit) {
              log(target, options, "Calling Cookit:");
              window.cookit(options.data.activityIdentifier + "score", (calculatedScore / calculatedPossible * 100), options.data.activityIdentifier + "attempts", 1);
            }
            if (!options.data.initialUpdateGradeCalled) {
              options.data.initialUpdateGradeCalled = true;
              $(target).data("activityWrapper:options", options);
            }
          }
        });
        $(options.containers.content.reference).bind("reset.selectAllActivity", function(event, numberOfSets, setShown, allowRetry, gradeSetsIndividually) {
          var options = $(target).data("activityWrapper:options");
          var controlVisibility = {
            finishButton : true,
            resetButton : false,
            nextSetButton : (numberOfSets > 1) ? true : false,
            previousSetButton : (numberOfSets > 1) ? true : false,
            positionIndicator : (numberOfSets > 1) ? true : false,
            moreButton : false,
            lessButton : false,
            saveButton : true
          };
          var finishAndResetEnabled = {
            enableFinish : true,
            enableReset : false
          };
          if (!gradeSetsIndividually && options.data.requireAllSetsShownForFinish) {
            var found = false;
            options.data.setsShown = [];
            options.data.setsShown.push(setShown);
            $(target).data("activityWrapper:options", options);
            if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
              finishAndResetEnabled.enableFinish = false;
            }
          }
          var moreAndLessEnabled = {
            enableMore : false,
            enableLess : false
          };
          var saveEnabled = {
            enableSave : true
          };
          $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
          $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
        });
        $(options.containers.content.reference).bind("titleChanged.selectAllActivity", function(event, headerContent) {
          var options = $(target).data("activityWrapper:options");
          setHeaderContent(target, options, headerContent);
        });
        $(options.containers.content.reference).bind("setChanged.selectAllActivity", function(event, numberOfSets, position, gradeSetsIndividually, allowReset, setCompleted, enabled) {
          var options = $(target).data("activityWrapper:options");
          $(options.containers.footer.container.reference).activityControls("setPositionIndicator", {
            numberOfSets : numberOfSets,
            position : position
          });
          $(options.containers.footer.container.reference).activityControls("updateControlsBasedOnSetPosition", {
            numberOfSets : numberOfSets,
            position : position
          });
          if (!options.data.enabled && !enabled) {
            var controlVisibility = {
              finishButton : false,
              resetButton : false,
              nextSetButton : (numberOfSets > 1) ? true : false,
              previousSetButton : (numberOfSets > 1) ? true : false,
              positionIndicator : (numberOfSets > 1) ? true : false,
              moreButton : false,
              lessButton : false,
              saveButton : false
            };
            var finishAndResetEnabled = {
              enableFinish : false,
              enableReset : false
            };
            var moreAndLessEnabled = {
              enableMore : false,
              enableLess : false
            };
            var saveEnabled = {
              enableSave : false
            };
            $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
            $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
          } else {
            if (gradeSetsIndividually) {
              var controlVisibility = {
                finishButton : !setCompleted,
                resetButton : setCompleted,
                nextSetButton : (numberOfSets > 1) ? true : false,
                previousSetButton : (numberOfSets > 1) ? true : false,
                positionIndicator : (numberOfSets > 1) ? true : false,
                moreButton : false,
                lessButton : false,
                saveButton : true
              };
              var finishAndResetEnabled = {
                enableFinish : !setCompleted,
                enableReset : allowReset
              };
              var moreAndLessEnabled = {
                enableMore : false,
                enableLess : false
              };
              var saveEnabled = {
                enableSave : !setCompleted
              };
              $(options.containers.footer.container.reference).activityControls("showOrHideControls", controlVisibility);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableMoreAndLess", moreAndLessEnabled);
              $(options.containers.footer.container.reference).activityControls("enableOrDisableSave", saveEnabled);
            } else {
              if (options.data.requireAllSetsShownForFinish) {
                var finishAndResetEnabled = {
                  enableFinish : true,
                  enableReset : allowReset
                };
                var found = false;
                $.each(options.data.setsShown, function(i, setId) {
                  if (setId == position) {
                    found = true;
                  }
                });
                if (!found) {
                  options.data.setsShown.push(position);
                  $(target).data("activityWrapper:options", options);
                }
                if (finishAndResetEnabled.enableFinish && options.data.setsShown.length < numberOfSets) {
                  finishAndResetEnabled.enableFinish = false;
                }
                $(options.containers.footer.container.reference).activityControls("enableOrDisableFinishAndReset", finishAndResetEnabled);
              }
            }
          }
        });
        if (options.data.activityData.xmlData) {
          if (options.data.activityData.xmlDataEncoding) {
            options.data.activityData.xmlData = unescape(options.data.activityData.xmlData.replace(/\+/g, " "));
          }
          $(options.containers.content.reference).selectAllActivity("parseXMLAndBuildActivity", options.data.activityData.xmlData);
        } else {
          if (options.data.activityData.xmlFile) {
            $(options.containers.content.reference).selectAllActivity("loadXMLAndBuildActivity", options.data.activityData.xmlFile);
          }
        }
      }
    }

    function registerControlsEvents(target, options) {
      $(options.containers.footer.container.reference).bind("finish.activityControls", function() {
        if (options.data.activityType) {
          switch(options.data.activityType) {
            case"selectAllActivity":
              if ($.fn.selectAllActivity) {
                $(options.containers.content.reference).selectAllActivity("finish");
              }
              break;
            case"orderingActivity":
              if ($.fn.orderingActivity) {
                $(options.containers.content.reference).orderingActivity("finish");
              }
              break;
            case"matchingActivity":
              if ($.fn.matchingActivity) {
                $(options.containers.content.reference).matchingActivity("finish");
              }
              break;
            case"slideSlotActivity":
              if ($.fn.slideSlotActivity) {
                $(options.containers.content.reference).slideSlotActivity("finish");
              }
              break;
            case"slideIdentificationActivity":
              if ($.fn.slideIdentificationActivity) {
                $(options.containers.content.reference).slideIdentificationActivity("finish");
              }
              break;
            case"slideShowActivity":
              if ($.fn.slideShowActivity) {
                $(options.containers.content.reference).slideShowActivity("finish");
              }
              break;
          }
        }
      });
      $(options.containers.footer.container.reference).bind("reset.activityControls", function() {
        if (options.data.activityType) {
          switch(options.data.activityType) {
            case"selectAllActivity":
              if ($.fn.selectAllActivity) {
                $(options.containers.content.reference).selectAllActivity("reset");
              }
              break;
            case"orderingActivity":
              if ($.fn.orderingActivity) {
                $(options.containers.content.reference).orderingActivity("reset");
              }
              break;
            case"matchingActivity":
              if ($.fn.matchingActivity) {
                $(options.containers.content.reference).matchingActivity("reset");
              }
              break;
            case"slideSlotActivity":
              if ($.fn.slideSlotActivity) {
                $(options.containers.content.reference).slideSlotActivity("reset");
              }
              break;
            case"slideIdentificationActivity":
              if ($.fn.slideIdentificationActivity) {
                $(options.containers.content.reference).slideIdentificationActivity("reset");
              }
              break;
            case"slideShowActivity":
              if ($.fn.slideShowActivity) {
                $(options.containers.content.reference).slideShowActivity("reset");
              }
              break;
          }
        }
      });
      $(options.containers.footer.container.reference).bind("more.activityControls", function() {
        if (options.data.activityType) {
          switch(options.data.activityType) {
            case"slideShow":
            case"slideShowActivity":
              if ($.fn.slideShowActivity) {
                $(options.containers.content.reference).slideShowActivity("toggleSetContent");
              }
              break;
          }
        }
      });
      $(options.containers.footer.container.reference).bind("less.activityControls", function() {
        if (options.data.activityType) {
          switch(options.data.activityType) {
            case"slideShowActivity":
              if ($.fn.slideShowActivity) {
                $(options.containers.content.reference).slideShowActivity("toggleSetContent");
              }
              break;
          }
        }
      });
      $(options.containers.footer.container.reference).bind("nextSet.activityControls", function() {
        if (options.data.activityType) {
          switch(options.data.activityType) {
            case"selectAllActivity":
              if ($.fn.selectAllActivity) {
                $(options.containers.content.reference).selectAllActivity("showNextSet");
              }
              break;
            case"orderingActivity":
              if ($.fn.orderingActivity) {
                $(options.containers.content.reference).orderingActivity("showNextSet");
              }
              break;
            case"matchingActivity":
              if ($.fn.matchingActivity) {
                $(options.containers.content.reference).matchingActivity("showNextSet");
              }
              break;
            case"slideSlotActivity":
              if ($.fn.slideSlotActivity) {
                $(options.containers.content.reference).slideSlotActivity("showNextSet");
              }
              break;
            case"slideIdentificationActivity":
              if ($.fn.slideIdentificationActivity) {
                $(options.containers.content.reference).slideIdentificationActivity("showNextSet");
              }
              break;
            case"slideShowActivity":
              if ($.fn.slideShowActivity) {
                $(options.containers.content.reference).slideShowActivity("showNextSet");
              }
              break;
          }
        }
      });
      $(options.containers.footer.container.reference).bind("previousSet.activityControls", function() {
        if (options.data.activityType) {
          switch(options.data.activityType) {
            case"selectAllActivity":
              if ($.fn.selectAllActivity) {
                $(options.containers.content.reference).selectAllActivity("showPreviousSet");
              }
              break;
            case"orderingActivity":
              if ($.fn.orderingActivity) {
                $(options.containers.content.reference).orderingActivity("showPreviousSet");
              }
              break;
            case"matchingActivity":
              if ($.fn.matchingActivity) {
                $(options.containers.content.reference).matchingActivity("showPreviousSet");
              }
              break;
            case"slideSlotActivity":
              if ($.fn.slideSlotActivity) {
                $(options.containers.content.reference).slideSlotActivity("showPreviousSet");
              }
              break;
            case"slideIdentificationActivity":
              if ($.fn.slideIdentificationActivity) {
                $(options.containers.content.reference).slideIdentificationActivity("showPreviousSet");
              }
              break;
            case"slideShowActivity":
              if ($.fn.slideShowActivity) {
                $(options.containers.content.reference).slideShowActivity("showPreviousSet");
              }
              break;
          }
        }
      });
      $(options.containers.footer.container.reference).bind("save.activityControls", function() {
        if (options.data.activityType) {
          if (window.cookit) {
            window.cookit(options.data.activityIdentifier + "score", 0, options.data.activityIdentifier + "attempts", 0);
          }
        }
      });
    }

    function getState(target, options) {
      var state = null;
      if (options.data.activityType) {
        switch(options.data.activityType) {
          case"selectAllActivity":
            if ($.fn.selectAllActivity) {
              state = $(options.containers.content.reference).selectAllActivity("getState")[0].result;
            }
            break;
          case"orderingActivity":
            if ($.fn.orderingActivity) {
              state = $(options.containers.content.reference).orderingActivity("getState")[0].result;
            }
            break;
          case"matchingActivity":
            if ($.fn.matchingActivity) {
              state = $(options.containers.content.reference).matchingActivity("getState")[0].result;
            }
            break;
          case"slideSlotActivity":
            if ($.fn.slideSlotActivity) {
              state = $(options.containers.content.reference).slideSlotActivity("getState")[0].result;
            }
            break;
          case"slideIdentificationActivity":
            if ($.fn.slideIdentificationActivity) {
              state = $(options.containers.content.reference).slideIdentificationActivity("getState")[0].result;
            }
            break;
          case"slideShowActivity":
            if ($.fn.slideShowActivity) {
              state = $(options.containers.content.reference).slideShowActivity("getState")[0].result;
            }
            break;
        }
      }
      return state;
    }

    function setState(target, options, state, completed) {
      if (options.data.activityType) {
        switch(options.data.activityType) {
          case"selectAllActivity":
            if ($.fn.selectAllActivity) {
              $(options.containers.content.reference).selectAllActivity("setState", {
                state : state,
                completed : completed
              });
            }
            break;
          case"orderingActivity":
            if ($.fn.orderingActivity) {
              $(options.containers.content.reference).orderingActivity("setState", {
                state : state,
                completed : completed
              });
            }
            break;
          case"matchingActivity":
            if ($.fn.matchingActivity) {
              $(options.containers.content.reference).matchingActivity("setState", {
                state : state,
                completed : completed
              });
            }
            break;
          case"slideSlotActivity":
            if ($.fn.slideSlotActivity) {
              $(options.containers.content.reference).slideSlotActivity("setState", {
                state : state,
                completed : completed
              });
            }
            break;
          case"slideIdentificationActivity":
            if ($.fn.slideIdentificationActivity) {
              $(options.containers.content.reference).slideIdentificationActivity("setState", {
                state : state,
                completed : completed
              });
            }
            break;
          case"slideShowActivity":
            if ($.fn.slideShowActivity) {
              $(options.containers.content.reference).slideShowActivity("setState", {
                state : state,
                completed : completed
              });
            }
            break;
        }
      }
    }

    function getType(target, options, getLessonBuilderType) {
      getLessonBuilderType = getLessonBuilderType || false;
      var type = null;
      if (options.data.activityType) {
        if (getLessonBuilderType) {
          switch(options.data.activityType) {
            case"selectAllActivity":
              type = 203;
              break;
            case"orderingActivity":
              type = 204;
              break;
            case"matchingActivity":
              type = 205;
              break;
            case"slideSlotActivity":
              type = 200;
              break;
            case"slideIdentificationActivity":
              type = 201;
              break;
            case"slideShowActivity":
              type = 202;
              break;
          }
        } else {
          type = options.data.activityType;
        }
      }
      return type;
    }

    function setEnabled(target, options) {
      if (options.data.activityType) {
        switch(options.data.activityType) {
          case"selectAllActivity":
            if ($.fn.selectAllActivity) {
              $(options.containers.content.reference).selectAllActivity("setEnabled", options.data.enabled);
            }
            break;
          case"orderingActivity":
            if ($.fn.orderingActivity) {
              $(options.containers.content.reference).orderingActivity("setEnabled", options.data.enabled);
            }
            break;
          case"matchingActivity":
            if ($.fn.matchingActivity) {
              $(options.containers.content.reference).matchingActivity("setEnabled", options.data.enabled);
            }
            break;
          case"slideSlotActivity":
            if ($.fn.slideSlotActivity) {
              $(options.containers.content.reference).slideSlotActivity("setEnabled", options.data.enabled);
            }
            break;
          case"slideIdentificationActivity":
            if ($.fn.slideIdentificationActivity) {
              $(options.containers.content.reference).slideIdentificationActivity("setEnabled", options.data.enabled);
            }
            break;
          case"slideShowActivity":
            if ($.fn.slideShowActivity) {
              $(options.containers.content.reference).slideShowActivity("setEnabled", options.data.enabled);
            }
            break;
        }
      }
      $(target).data("activityWrapper:options", options);
    }

    function finish(target, options) {
      log(target, options, "Finishing Activity:" + options.data.activityType, "info");
      if (options.data.activityType) {
        switch(options.data.activityType) {
          case"selectAllActivity":
            if ($.fn.selectAllActivity) {
              $(options.containers.content.reference).selectAllActivity("finish");
            }
            break;
          case"orderingActivity":
            if ($.fn.orderingActivity) {
              $(options.containers.content.reference).orderingActivity("finish");
            }
            break;
          case"matchingActivity":
            if ($.fn.matchingActivity) {
              $(options.containers.content.reference).matchingActivity("finish");
            }
            break;
          case"slideSlotActivity":
            if ($.fn.slideSlotActivity) {
              $(options.containers.content.reference).slideSlotActivity("finish");
            }
            break;
          case"slideIdentificationActivity":
            if ($.fn.slideIdentificationActivity) {
              $(options.containers.content.reference).slideIdentificationActivity("finish");
            }
            break;
          case"slideShowActivity":
            if ($.fn.slideShowActivity) {
              $(options.containers.content.reference).slideShowActivity("finish");
            }
            break;
        }
      }
      $(target).data("activityWrapper:options", options);
    }

    function setHeaderContent(target, options, content) {
      $(options.containers.header.content.reference).css("left", 0);
      $(options.containers.header.content.reference).css("top", 0);
      $(options.containers.header.content.reference).html(content);
      alignToParent(target, options, options.containers.header.content.horizontalAlign, options.containers.header.content.verticalAlign, options.containers.header.content.reference);
    }

    function alignToParent(target, options, horizontalAlign, verticalAlign, container) {
      $(container).css("position", "absolute");
      if (horizontalAlign) {
        switch(horizontalAlign.toLowerCase()) {
          case"left":
            $(container).css("right", null).css("left", "0px");
            break;
          case"right":
            $(container).css("left", null).css("right", "0px");
            break;
          case"center":
            $(container).css("right", null).css("left", ($(container).parent().innerWidth() / 2 - $(container).outerWidth() / 2) + "px");
            break;
        }
      }
      if (verticalAlign) {
        switch(verticalAlign.toLowerCase()) {
          case"top":
            $(container).css("bottom", null).css("top", "0px");
            break;
          case"bottom":
            $(container).css("top", null).css("bottom", "0px");
            break;
          case"middle":
            $(container).css("bottom", null).css("top", ($(container).parent().innerHeight() / 2 - $(container).outerHeight() / 2) + "px");
            break;
        }
      }
    }

    function handleResize(target, options) {
      alignToParent(target, options, options.containers.header.content.horizontalAlign, options.containers.header.content.verticalAlign, options.containers.header.content.reference);
      $(options.containers.footer.container.reference).activityControls("resize");
      var width = $(options.containers.content.reference).parent().width();
      var height = $(options.containers.content.reference).parent().height();
      height -= $(options.containers.header.container.reference).outerHeight();
      height -= $(options.containers.footer.container.reference).outerHeight();
      $(options.containers.content.reference).width(width);
      $(options.containers.content.reference).height(height);
      if (options.data.activityType) {
        switch(options.data.activityType) {
          case"selectAllActivity":
            if ($.fn.selectAllActivity) {
              $(options.containers.content.reference).selectAllActivity("resize");
            }
            break;
          case"orderingActivity":
            if ($.fn.orderingActivity) {
              $(options.containers.content.reference).orderingActivity("resize");
            }
            break;
          case"matchingActivity":
            if ($.fn.matchingActivity) {
              $(options.containers.content.reference).matchingActivity("resize");
            }
            break;
          case"slideSlotActivity":
            if ($.fn.slideSlotActivity) {
              $(options.containers.content.reference).slideSlotActivity("resize");
            }
            break;
          case"slideIdentificationActivity":
            if ($.fn.slideIdentificationActivity) {
              $(options.containers.content.reference).slideIdentificationActivity("resize");
            }
            break;
          case"slideShowActivity":
            if ($.fn.slideShowActivity) {
              $(options.containers.content.reference).slideShowActivity("resize");
            }
            break;
        }
      }
    }
    return this;
  };
  $.fn.activityWrapper.defaults = {};
  $.fn.activityWrapper.defaults.containers = {
    activity : {
      reference : null,
      css : {
        identifier : "softchalk-activity-wrapper"
      }
    },
    wrapper : {
      reference : null,
      css : {
        identifier : "softchalk-activity-wrapper-container"
      }
    },
    header : {
      container : {
        reference : null,
        css : {
          identifier : "softchalk-activity-wrapper-header-container"
        }
      },
      content : {
        reference : null,
        horizontalAlign : "center",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-activity-wrapper-header-content"
        }
      }
    },
    content : {
      reference : null,
      css : {
        identifier : "softchalk-activity-wrapper-content-container"
      }
    },
    footer : {
      container : {
        reference : null,
        css : {
          identifier : "softchalk-activity-wrapper-footer-container"
        }
      }
    }
  };
  $.fn.activityWrapper.defaults.data = {
    activityIdentifier : null,
    initialUpdateGradeCalled : false,
    clearContainerContent : true,
    enableLogging : false,
    activityType : null,
    activityData : null,
    onlyCallCookitOnCompleteEvents : true,
    enabled : true,
    requireAllSetsShownForFinish : true,
    setsShown : []
  };
  $.fn.activityWrapper.defaults.logging = {
    debug : false,
    info : true,
    warn : false,
    error : false
  };
})(jQuery);
(function($) {
  $.fn.activityControls = function(action, options) {
    var shouldReturnResults = false;
    var results = [];
    var params = null;
    action = action || "initialize";
    if ( typeof (action) == "object") {
      options = action;
      action = "initialize";
    }
    if (action == "initialize") {
      if (!options) {
        options = $.fn.activityControls.defaults;
      } else {
        options = $.extend(true, {}, $.fn.activityControls.defaults, options);
      }
    } else {
      params = options;
    }
    var optionsReference = options;
    $(this).each(function() {
      switch(action) {
        case"initialize":
          initialize(this, optionsReference);
          break;
        case"setStatus":
          var options = $(this).data("activityControls:options");
          setStatus(this, options, params);
          break;
        case"getStatus":
          var options = $(this).data("activityControls:options");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getStatus(this, options)
          });
          break;
        case"setPositionIndicator":
          var options = $(this).data("activityControls:options");
          setPositionIndicator(this, options, params.numberOfSets, params.position);
          break;
        case"updateControlsBasedOnSetPosition":
          var options = $(this).data("activityControls:options");
          updateControlsBasedOnSetPosition(this, options, params.numberOfSets, params.position);
          break;
        case"showOrHideControls":
          var options = $(this).data("activityControls:options");
          showOrHideControls(this, options, params.previousSetButton, params.finishButton, params.resetButton, params.moreButton, params.lessButton, params.nextSetButton, params.positionIndicator, params.saveButton);
          break;
        case"showOrHideMoreAndLess":
          var options = $(this).data("activityControls:options");
          showOrHideMoreAndLess(this, options, params.moreButton, params.lessButton);
          break;
        case"enableOrDisableFinishAndReset":
          var options = $(this).data("activityControls:options");
          enableOrDisableFinishAndReset(this, options, params.enableFinish, params.enableReset);
          break;
        case"enableOrDisableMoreAndLess":
          var options = $(this).data("activityControls:options");
          enableOrDisableMoreAndLess(this, options, params.enableMore, params.enableLess);
          break;
        case"enableOrDisableSave":
          var options = $(this).data("activityControls:options");
          enableOrDisableSave(this, options, params.enableSave);
          break;
        case"setAllowSaveButton":
          var options = $(this).data("activityControls:options");
          options.data.allowSaveButton = params;
          showOrHideControls(this, options, options.containers.buttons.previousSet.container.show, options.containers.buttons.finish.container.show, options.containers.buttons.reset.container.show, options.containers.buttons.more.container.show, options.containers.buttons.less.container.show, options.containers.buttons.nextSet.container.show, options.containers.top.show, options.containers.buttons.save.container.show);
          break;
        case"getAllowSaveButton":
          var options = $(this).data("activityControls:options");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.allowSaveButton
          });
          break;
        case"resize":
          var options = $(this).data("activityControls:options");
          log(this, options, "Action:Resizing the controls", "info");
          handleResize(this, options);
          break;
      }
    });
    if (shouldReturnResults == true) {
      return results;
    }
    function log(target, options, data, level) {
      level = level || "debug";
      level = $.trim(level).toLowerCase();
      if (options.data.enableLogging && window.console) {
        if (level == "info" && window.console.info && options.logging.info) {
          if ($(target).attr("id")) {
            window.console.info("[ActivityControls][" + target + ", id=" + $(target).attr("id") + "]" + data);
          } else {
            if ($(target).attr("name")) {
              window.console.info("[ActivityControls][" + target + ", name=" + $(target).attr("name") + "]" + data);
            } else {
              window.console.info("[ActivityControls][" + target + "]" + data);
            }
          }
        } else {
          if (level == "warn" && window.console.warn && options.logging.warn) {
            if ($(target).attr("id")) {
              window.console.warn("[ActivityControls][" + target + ", id=" + $(target).attr("id") + "]" + data);
            } else {
              if ($(target).attr("name")) {
                window.console.warn("[ActivityControls][" + target + ", name=" + $(target).attr("name") + "]" + data);
              } else {
                window.console.warn("[ActivityControls][" + target + "]" + data);
              }
            }
          } else {
            if (level == "error" && window.console.error && options.logging.error) {
              if ($(target).attr("id")) {
                window.console.error("[ActivityControls][" + target + ", id=" + $(target).attr("id") + "]" + data);
              } else {
                if ($(target).attr("name")) {
                  window.console.error("[ActivityControls][" + target + ", name=" + $(target).attr("name") + "]" + data);
                } else {
                  window.console.error("[ActivityControls][" + target + "]" + data);
                }
              }
            } else {
              if (window.console.log && options.logging.debug) {
                if ($(target).attr("id")) {
                  window.console.log("[ActivityControls][" + target + ", id=" + $(target).attr("id") + "]" + data);
                } else {
                  if ($(target).attr("name")) {
                    window.console.log("[ActivityControls][" + target + ", name=" + $(target).attr("name") + "]" + data);
                  } else {
                    window.console.log("[ActivityControls][" + target + "]" + data);
                  }
                }
              }
            }
          }
        }
      }
    }

    function initialize(target, options) {
      log(target, options, "Initializing Activity Controls", "info");
      options = $.extend(true, {}, options);
      options.containers.controls.reference = target;
      if (!$(options.containers.controls.reference).hasClass(options.containers.controls.css.identifier)) {
        $(options.containers.controls.reference).addClass(options.containers.controls.css.identifier);
      }
      if (!options.containers.top.reference) {
        options.containers.top.reference = $("<div />");
        $(options.containers.controls.reference).append(options.containers.top.reference);
      }
      if (!$(options.containers.top.reference).hasClass(options.containers.top.css.identifier)) {
        $(options.containers.top.reference).addClass(options.containers.top.css.identifier);
      }
      if (!options.containers.top.show && !$(options.containers.top.reference).hasClass(options.containers.top.css.hidden)) {
        $(options.containers.top.reference).addClass(options.containers.top.css.hidden);
      }
      if (!options.containers.bottom.reference) {
        options.containers.bottom.reference = $("<div />");
        $(options.containers.controls.reference).append(options.containers.bottom.reference);
      }
      if (!$(options.containers.bottom.reference).hasClass(options.containers.bottom.css.identifier)) {
        $(options.containers.bottom.reference).addClass(options.containers.bottom.css.identifier);
      }
      if (!options.containers.bottom.show && !$(options.containers.bottom.reference).hasClass(options.containers.bottom.css.hidden)) {
        $(options.containers.bottom.reference).addClass(options.containers.bottom.css.hidden);
      }
      if (!options.containers.positionIndicator.container.reference) {
        options.containers.positionIndicator.container.reference = $("<ul />");
        $(options.containers.top.reference).append(options.containers.positionIndicator.container.reference);
      }
      if (!$(options.containers.positionIndicator.container.reference).hasClass(options.containers.positionIndicator.container.css.identifier)) {
        $(options.containers.positionIndicator.container.reference).addClass(options.containers.positionIndicator.container.css.identifier);
      }
      if (!options.containers.status.reference) {
        options.containers.status.reference = $("<div />");
        $(options.containers.bottom.reference).append(options.containers.status.reference);
      }
      if (!$(options.containers.status.reference).hasClass(options.containers.status.css.identifier)) {
        $(options.containers.status.reference).addClass(options.containers.status.css.identifier);
      }
      if (!options.containers.buttons.container.reference) {
        options.containers.buttons.container.reference = $("<div />");
        $(options.containers.bottom.reference).append(options.containers.buttons.container.reference);
      }
      if (!$(options.containers.buttons.container.reference).hasClass(options.containers.buttons.container.css.identifier)) {
        $(options.containers.buttons.container.reference).addClass(options.containers.buttons.container.css.identifier);
      }
      if (!options.containers.buttons.previousSet.container.reference) {
        options.containers.buttons.previousSet.container.reference = $("<div />");
        $(options.containers.buttons.container.reference).append(options.containers.buttons.previousSet.container.reference);
      }
      if (!$(options.containers.buttons.previousSet.container.reference).hasClass(options.containers.buttons.previousSet.container.css.identifier)) {
        $(options.containers.buttons.previousSet.container.reference).addClass(options.containers.buttons.previousSet.container.css.identifier);
      }
      if (!options.containers.buttons.previousSet.container.show && !$(options.containers.buttons.previousSet.container.reference).hasClass(options.containers.buttons.previousSet.container.css.hidden)) {
        $(options.containers.buttons.previousSet.container.reference).addClass(options.containers.buttons.previousSet.container.css.hidden);
      }
      if (!options.containers.buttons.previousSet.label.reference) {
        options.containers.buttons.previousSet.label.reference = $("<div>" + options.containers.buttons.previousSet.label.label + "</div>");
        $(options.containers.buttons.previousSet.container.reference).append(options.containers.buttons.previousSet.label.reference);
      }
      if (!$(options.containers.buttons.previousSet.label.reference).hasClass(options.containers.buttons.previousSet.label.css.identifier)) {
        $(options.containers.buttons.previousSet.label.reference).addClass(options.containers.buttons.previousSet.label.css.identifier);
      }
      if (!options.containers.buttons.previousSet.overlay.reference) {
        options.containers.buttons.previousSet.overlay.reference = $("<div />");
        $(options.containers.buttons.previousSet.container.reference).append(options.containers.buttons.previousSet.overlay.reference);
      }
      if (!$(options.containers.buttons.previousSet.overlay.reference).hasClass(options.containers.buttons.previousSet.overlay.css.identifier)) {
        $(options.containers.buttons.previousSet.overlay.reference).addClass(options.containers.buttons.previousSet.overlay.css.identifier);
      }
      if (!options.containers.buttons.finish.container.reference) {
        options.containers.buttons.finish.container.reference = $("<div />");
        $(options.containers.buttons.container.reference).append(options.containers.buttons.finish.container.reference);
      }
      if (!$(options.containers.buttons.finish.container.reference).hasClass(options.containers.buttons.finish.container.css.identifier)) {
        $(options.containers.buttons.finish.container.reference).addClass(options.containers.buttons.finish.container.css.identifier);
      }
      if (!options.containers.buttons.finish.container.show && !$(options.containers.buttons.finish.container.reference).hasClass(options.containers.buttons.finish.container.css.hidden)) {
        $(options.containers.buttons.finish.container.reference).addClass(options.containers.buttons.finish.container.css.hidden);
      }
      if (!options.containers.buttons.finish.label.reference) {
        options.containers.buttons.finish.label.reference = $("<div>" + options.containers.buttons.finish.label.label + "</div>");
        $(options.containers.buttons.finish.container.reference).append(options.containers.buttons.finish.label.reference);
      }
      if (!$(options.containers.buttons.finish.label.reference).hasClass(options.containers.buttons.finish.label.css.identifier)) {
        $(options.containers.buttons.finish.label.reference).addClass(options.containers.buttons.finish.label.css.identifier);
      }
      if (!options.containers.buttons.finish.overlay.reference) {
        options.containers.buttons.finish.overlay.reference = $("<div />");
        $(options.containers.buttons.finish.container.reference).append(options.containers.buttons.finish.overlay.reference);
      }
      if (!$(options.containers.buttons.finish.overlay.reference).hasClass(options.containers.buttons.finish.overlay.css.identifier)) {
        $(options.containers.buttons.finish.overlay.reference).addClass(options.containers.buttons.finish.overlay.css.identifier);
      }
      if (!options.containers.buttons.reset.container.reference) {
        options.containers.buttons.reset.container.reference = $("<div />");
        $(options.containers.buttons.container.reference).append(options.containers.buttons.reset.container.reference);
      }
      if (!$(options.containers.buttons.reset.container.reference).hasClass(options.containers.buttons.reset.container.css.identifier)) {
        $(options.containers.buttons.reset.container.reference).addClass(options.containers.buttons.reset.container.css.identifier);
      }
      if (!options.containers.buttons.reset.container.show && !$(options.containers.buttons.reset.container.reference).hasClass(options.containers.buttons.reset.container.css.hidden)) {
        $(options.containers.buttons.reset.container.reference).addClass(options.containers.buttons.reset.container.css.hidden);
      }
      if (!options.containers.buttons.reset.label.reference) {
        options.containers.buttons.reset.label.reference = $("<div>" + options.containers.buttons.reset.label.label + "</div>");
        $(options.containers.buttons.reset.container.reference).append(options.containers.buttons.reset.label.reference);
      }
      if (!$(options.containers.buttons.reset.label.reference).hasClass(options.containers.buttons.reset.label.css.identifier)) {
        $(options.containers.buttons.reset.label.reference).addClass(options.containers.buttons.reset.label.css.identifier);
      }
      if (!options.containers.buttons.reset.overlay.reference) {
        options.containers.buttons.reset.overlay.reference = $("<div />");
        $(options.containers.buttons.reset.container.reference).append(options.containers.buttons.reset.overlay.reference);
      }
      if (!$(options.containers.buttons.reset.overlay.reference).hasClass(options.containers.buttons.reset.overlay.css.identifier)) {
        $(options.containers.buttons.reset.overlay.reference).addClass(options.containers.buttons.reset.overlay.css.identifier);
      }
      if (!options.containers.buttons.save.container.reference) {
        options.containers.buttons.save.container.reference = $("<div />");
        $(options.containers.buttons.container.reference).append(options.containers.buttons.save.container.reference);
      }
      if (!$(options.containers.buttons.save.container.reference).hasClass(options.containers.buttons.save.container.css.identifier)) {
        $(options.containers.buttons.save.container.reference).addClass(options.containers.buttons.save.container.css.identifier);
      }
      if (!options.containers.buttons.save.container.show && !$(options.containers.buttons.save.container.reference).hasClass(options.containers.buttons.save.container.css.hidden)) {
        $(options.containers.buttons.save.container.reference).addClass(options.containers.buttons.save.container.css.hidden);
      }
      if (!options.containers.buttons.save.label.reference) {
        options.containers.buttons.save.label.reference = $("<div>" + options.containers.buttons.save.label.label + "</div>");
        $(options.containers.buttons.save.container.reference).append(options.containers.buttons.save.label.reference);
      }
      if (!$(options.containers.buttons.save.label.reference).hasClass(options.containers.buttons.save.label.css.identifier)) {
        $(options.containers.buttons.save.label.reference).addClass(options.containers.buttons.save.label.css.identifier);
      }
      if (!options.containers.buttons.save.overlay.reference) {
        options.containers.buttons.save.overlay.reference = $("<div />");
        $(options.containers.buttons.save.container.reference).append(options.containers.buttons.save.overlay.reference);
      }
      if (!$(options.containers.buttons.save.overlay.reference).hasClass(options.containers.buttons.save.overlay.css.identifier)) {
        $(options.containers.buttons.save.overlay.reference).addClass(options.containers.buttons.save.overlay.css.identifier);
      }
      if (!options.containers.buttons.more.container.reference) {
        options.containers.buttons.more.container.reference = $("<div />");
        $(options.containers.buttons.container.reference).append(options.containers.buttons.more.container.reference);
      }
      if (!$(options.containers.buttons.more.container.reference).hasClass(options.containers.buttons.more.container.css.identifier)) {
        $(options.containers.buttons.more.container.reference).addClass(options.containers.buttons.more.container.css.identifier);
      }
      if (!options.containers.buttons.more.container.show && !$(options.containers.buttons.more.container.reference).hasClass(options.containers.buttons.more.container.css.hidden)) {
        $(options.containers.buttons.more.container.reference).addClass(options.containers.buttons.more.container.css.hidden);
      }
      if (!options.containers.buttons.more.label.reference) {
        options.containers.buttons.more.label.reference = $("<div>" + options.containers.buttons.more.label.label + "</div>");
        $(options.containers.buttons.more.container.reference).append(options.containers.buttons.more.label.reference);
      }
      if (!$(options.containers.buttons.more.label.reference).hasClass(options.containers.buttons.more.label.css.identifier)) {
        $(options.containers.buttons.more.label.reference).addClass(options.containers.buttons.more.label.css.identifier);
      }
      if (!options.containers.buttons.more.overlay.reference) {
        options.containers.buttons.more.overlay.reference = $("<div />");
        $(options.containers.buttons.more.container.reference).append(options.containers.buttons.more.overlay.reference);
      }
      if (!$(options.containers.buttons.more.overlay.reference).hasClass(options.containers.buttons.more.overlay.css.identifier)) {
        $(options.containers.buttons.more.overlay.reference).addClass(options.containers.buttons.more.overlay.css.identifier);
      }
      if (!options.containers.buttons.less.container.reference) {
        options.containers.buttons.less.container.reference = $("<div />");
        $(options.containers.buttons.container.reference).append(options.containers.buttons.less.container.reference);
      }
      if (!$(options.containers.buttons.less.container.reference).hasClass(options.containers.buttons.less.container.css.identifier)) {
        $(options.containers.buttons.less.container.reference).addClass(options.containers.buttons.less.container.css.identifier);
      }
      if (!options.containers.buttons.less.container.show && !$(options.containers.buttons.less.container.reference).hasClass(options.containers.buttons.less.container.css.hidden)) {
        $(options.containers.buttons.less.container.reference).addClass(options.containers.buttons.less.container.css.hidden);
      }
      if (!options.containers.buttons.less.label.reference) {
        options.containers.buttons.less.label.reference = $("<div>" + options.containers.buttons.less.label.label + "</div>");
        $(options.containers.buttons.less.container.reference).append(options.containers.buttons.less.label.reference);
      }
      if (!$(options.containers.buttons.less.label.reference).hasClass(options.containers.buttons.less.label.css.identifier)) {
        $(options.containers.buttons.less.label.reference).addClass(options.containers.buttons.less.label.css.identifier);
      }
      if (!options.containers.buttons.less.overlay.reference) {
        options.containers.buttons.less.overlay.reference = $("<div />");
        $(options.containers.buttons.less.container.reference).append(options.containers.buttons.less.overlay.reference);
      }
      if (!$(options.containers.buttons.less.overlay.reference).hasClass(options.containers.buttons.less.overlay.css.identifier)) {
        $(options.containers.buttons.less.overlay.reference).addClass(options.containers.buttons.less.overlay.css.identifier);
      }
      if (!options.containers.buttons.nextSet.container.reference) {
        options.containers.buttons.nextSet.container.reference = $("<div />");
        $(options.containers.buttons.container.reference).append(options.containers.buttons.nextSet.container.reference);
      }
      if (!$(options.containers.buttons.nextSet.container.reference).hasClass(options.containers.buttons.nextSet.container.css.identifier)) {
        $(options.containers.buttons.nextSet.container.reference).addClass(options.containers.buttons.nextSet.container.css.identifier);
      }
      if (!options.containers.buttons.nextSet.container.show && !$(options.containers.buttons.nextSet.container.reference).hasClass(options.containers.buttons.nextSet.container.css.hidden)) {
        $(options.containers.buttons.nextSet.container.reference).addClass(options.containers.buttons.nextSet.container.css.hidden);
      }
      if (!options.containers.buttons.nextSet.label.reference) {
        options.containers.buttons.nextSet.label.reference = $("<div>" + options.containers.buttons.nextSet.label.label + "</div>");
        $(options.containers.buttons.nextSet.container.reference).append(options.containers.buttons.nextSet.label.reference);
      }
      if (!$(options.containers.buttons.nextSet.label.reference).hasClass(options.containers.buttons.nextSet.label.css.identifier)) {
        $(options.containers.buttons.nextSet.label.reference).addClass(options.containers.buttons.nextSet.label.css.identifier);
      }
      if (!options.containers.buttons.nextSet.overlay.reference) {
        options.containers.buttons.nextSet.overlay.reference = $("<div />");
        $(options.containers.buttons.nextSet.container.reference).append(options.containers.buttons.nextSet.overlay.reference);
      }
      if (!$(options.containers.buttons.nextSet.overlay.reference).hasClass(options.containers.buttons.nextSet.overlay.css.identifier)) {
        $(options.containers.buttons.nextSet.overlay.reference).addClass(options.containers.buttons.nextSet.overlay.css.identifier);
      }
      $(options.containers.buttons.finish.container.reference).bind("click", function() {
        if (!$(this).attr("disabled")) {
          $(target).trigger("finish.activityControls");
        }
      });
      $(options.containers.buttons.reset.container.reference).bind("click", function() {
        if (!$(this).attr("disabled")) {
          $(target).trigger("reset.activityControls");
        }
      });
      $(options.containers.buttons.more.container.reference).bind("click", function() {
        if (!$(this).attr("disabled")) {
          $(target).trigger("more.activityControls");
        }
      });
      $(options.containers.buttons.less.container.reference).bind("click", function() {
        if (!$(this).attr("disabled")) {
          $(target).trigger("less.activityControls");
        }
      });
      $(options.containers.buttons.nextSet.container.reference).bind("click", function() {
        if (!$(this).attr("disabled")) {
          $(target).trigger("nextSet.activityControls");
        }
      });
      $(options.containers.buttons.previousSet.container.reference).bind("click", function() {
        if (!$(this).attr("disabled")) {
          $(target).trigger("previousSet.activityControls");
        }
      });
      $(options.containers.buttons.save.container.reference).bind("click", function() {
        if (!$(this).attr("disabled")) {
          $(target).trigger("save.activityControls");
        }
      });
      $(target).data("activityControls:options", options);
      handleResize(target, options);
    }

    function showOrHideControls(target, options, previousSetButton, finishButton, resetButton, moreButton, lessButton, nextSetButton, positionIndicator, saveButton) {
      if (!previousSetButton && !$(options.containers.buttons.previousSet.container.reference).hasClass(options.containers.buttons.previousSet.container.css.hidden)) {
        $(options.containers.buttons.previousSet.container.reference).addClass(options.containers.buttons.previousSet.container.css.hidden);
      } else {
        if (previousSetButton && $(options.containers.buttons.previousSet.container.reference).hasClass(options.containers.buttons.previousSet.container.css.hidden)) {
          $(options.containers.buttons.previousSet.container.reference).removeClass(options.containers.buttons.previousSet.container.css.hidden);
        }
      }
      if (!finishButton && !$(options.containers.buttons.finish.container.reference).hasClass(options.containers.buttons.finish.container.css.hidden)) {
        $(options.containers.buttons.finish.container.reference).addClass(options.containers.buttons.finish.container.css.hidden);
      } else {
        if (finishButton && $(options.containers.buttons.finish.container.reference).hasClass(options.containers.buttons.finish.container.css.hidden)) {
          $(options.containers.buttons.finish.container.reference).removeClass(options.containers.buttons.finish.container.css.hidden);
        }
      }
      if (!resetButton && !$(options.containers.buttons.reset.container.reference).hasClass(options.containers.buttons.reset.container.css.hidden)) {
        $(options.containers.buttons.reset.container.reference).addClass(options.containers.buttons.reset.container.css.hidden);
      } else {
        if (resetButton && $(options.containers.buttons.reset.container.reference).hasClass(options.containers.buttons.reset.container.css.hidden)) {
          $(options.containers.buttons.reset.container.reference).removeClass(options.containers.buttons.reset.container.css.hidden);
        }
      }
      if (!moreButton && !$(options.containers.buttons.more.container.reference).hasClass(options.containers.buttons.more.container.css.hidden)) {
        $(options.containers.buttons.more.container.reference).addClass(options.containers.buttons.more.container.css.hidden);
      } else {
        if (moreButton && $(options.containers.buttons.more.container.reference).hasClass(options.containers.buttons.more.container.css.hidden)) {
          $(options.containers.buttons.more.container.reference).removeClass(options.containers.buttons.more.container.css.hidden);
        }
      }
      if (!lessButton && !$(options.containers.buttons.less.container.reference).hasClass(options.containers.buttons.less.container.css.hidden)) {
        $(options.containers.buttons.less.container.reference).addClass(options.containers.buttons.less.container.css.hidden);
      } else {
        if (lessButton && $(options.containers.buttons.less.container.reference).hasClass(options.containers.buttons.less.container.css.hidden)) {
          $(options.containers.buttons.less.container.reference).removeClass(options.containers.buttons.less.container.css.hidden);
        }
      }
      if (!nextSetButton && !$(options.containers.buttons.nextSet.container.reference).hasClass(options.containers.buttons.nextSet.container.css.hidden)) {
        $(options.containers.buttons.nextSet.container.reference).addClass(options.containers.buttons.nextSet.container.css.hidden);
      } else {
        if (nextSetButton && $(options.containers.buttons.nextSet.container.reference).hasClass(options.containers.buttons.nextSet.container.css.hidden)) {
          $(options.containers.buttons.nextSet.container.reference).removeClass(options.containers.buttons.nextSet.container.css.hidden);
        }
      }
      if (!positionIndicator && !$(options.containers.top.reference).hasClass(options.containers.top.css.hidden)) {
        $(options.containers.top.reference).addClass(options.containers.top.css.hidden);
      } else {
        if (positionIndicator && $(options.containers.top.reference).hasClass(options.containers.top.css.hidden)) {
          $(options.containers.top.reference).removeClass(options.containers.top.css.hidden);
        }
      }
      if (options.data.allowSaveButton) {
        if (!saveButton && !$(options.containers.buttons.save.container.reference).hasClass(options.containers.buttons.save.container.css.hidden)) {
          $(options.containers.buttons.save.container.reference).addClass(options.containers.buttons.save.container.css.hidden);
        } else {
          if (saveButton && $(options.containers.buttons.save.container.reference).hasClass(options.containers.buttons.save.container.css.hidden)) {
            $(options.containers.buttons.save.container.reference).removeClass(options.containers.buttons.save.container.css.hidden);
          }
        }
      } else {
        if (!$(options.containers.buttons.save.container.reference).hasClass(options.containers.buttons.save.container.css.hidden)) {
          $(options.containers.buttons.save.container.reference).addClass(options.containers.buttons.save.container.css.hidden);
        }
      }
      options.containers.buttons.previousSet.container.show = previousSetButton;
      options.containers.buttons.finish.container.show = finishButton;
      options.containers.buttons.reset.container.show = resetButton;
      options.containers.buttons.more.container.show = moreButton;
      options.containers.buttons.less.container.show = lessButton;
      options.containers.buttons.nextSet.container.show = nextSetButton;
      options.containers.buttons.save.container.show = saveButton;
      options.containers.top.show = positionIndicator;
      $(target).data("activityControls:options");
      handleResize(target, options);
    }

    function showOrHideMoreAndLess(target, options, moreButton, lessButton) {
      if (!moreButton && !$(options.containers.buttons.more.container.reference).hasClass(options.containers.buttons.more.container.css.hidden)) {
        $(options.containers.buttons.more.container.reference).addClass(options.containers.buttons.more.container.css.hidden);
      } else {
        if (moreButton && $(options.containers.buttons.more.container.reference).hasClass(options.containers.buttons.more.container.css.hidden)) {
          $(options.containers.buttons.more.container.reference).removeClass(options.containers.buttons.more.container.css.hidden);
        }
      }
      if (!lessButton && !$(options.containers.buttons.less.container.reference).hasClass(options.containers.buttons.less.container.css.hidden)) {
        $(options.containers.buttons.less.container.reference).addClass(options.containers.buttons.less.container.css.hidden);
      } else {
        if (lessButton && $(options.containers.buttons.less.container.reference).hasClass(options.containers.buttons.less.container.css.hidden)) {
          $(options.containers.buttons.less.container.reference).removeClass(options.containers.buttons.less.container.css.hidden);
        }
      }
      options.containers.buttons.more.container.show = moreButton;
      options.containers.buttons.less.container.show = lessButton;
      $(target).data("activityControls:options");
      handleResize(target, options);
    }

    function updateControlsBasedOnSetPosition(target, options, numberOfSets, position) {
      if (position == 0 || numberOfSets == 0) {
        $(options.containers.buttons.previousSet.container.reference).attr("disabled", "disabled");
        $(options.containers.buttons.previousSet.container.reference).addClass(options.containers.buttons.previousSet.container.css.disabled);
      } else {
        $(options.containers.buttons.previousSet.container.reference).removeAttr("disabled");
        $(options.containers.buttons.previousSet.container.reference).removeClass(options.containers.buttons.previousSet.container.css.disabled);
      }
      if (position == numberOfSets - 1 || numberOfSets == 0) {
        $(options.containers.buttons.nextSet.container.reference).attr("disabled", "disabled");
        $(options.containers.buttons.nextSet.container.reference).addClass(options.containers.buttons.nextSet.container.css.disabled);
      } else {
        $(options.containers.buttons.nextSet.container.reference).removeAttr("disabled");
        $(options.containers.buttons.nextSet.container.reference).removeClass(options.containers.buttons.nextSet.container.css.disabled);
      }
    }

    function enableOrDisableFinishAndReset(target, options, enableFinish, enableReset) {
      if (enableFinish) {
        $(options.containers.buttons.finish.container.reference).removeAttr("disabled");
        $(options.containers.buttons.finish.container.reference).removeClass(options.containers.buttons.finish.container.css.disabled);
      } else {
        $(options.containers.buttons.finish.container.reference).attr("disabled", "disabled");
        $(options.containers.buttons.finish.container.reference).addClass(options.containers.buttons.finish.container.css.disabled);
      }
      if (enableReset) {
        $(options.containers.buttons.reset.container.reference).removeAttr("disabled");
        $(options.containers.buttons.reset.container.reference).removeClass(options.containers.buttons.reset.container.css.disabled);
      } else {
        $(options.containers.buttons.reset.container.reference).attr("disabled", "disabled");
        $(options.containers.buttons.reset.container.reference).addClass(options.containers.buttons.reset.container.css.disabled);
      }
    }

    function enableOrDisableSave(target, options, enableSave) {
      if (enableSave) {
        $(options.containers.buttons.save.container.reference).removeAttr("disabled");
        $(options.containers.buttons.save.container.reference).removeClass(options.containers.buttons.save.container.css.disabled);
      } else {
        $(options.containers.buttons.save.container.reference).attr("disabled", "disabled");
        $(options.containers.buttons.save.container.reference).addClass(options.containers.buttons.save.container.css.disabled);
      }
    }

    function enableOrDisableMoreAndLess(target, options, enableMore, enableLess) {
      if (enableMore) {
        $(options.containers.buttons.more.container.reference).removeAttr("disabled");
        $(options.containers.buttons.more.container.reference).removeClass(options.containers.buttons.more.container.css.disabled);
      } else {
        $(options.containers.buttons.more.container.reference).attr("disabled", "disabled");
        $(options.containers.buttons.more.container.reference).addClass(options.containers.buttons.more.container.css.disabled);
      }
      if (enableLess) {
        $(options.containers.buttons.less.container.reference).removeAttr("disabled");
        $(options.containers.buttons.less.container.reference).removeClass(options.containers.buttons.less.container.css.disabled);
      } else {
        $(options.containers.buttons.less.container.reference).attr("disabled", "disabled");
        $(options.containers.buttons.less.container.reference).addClass(options.containers.buttons.less.container.css.disabled);
      }
    }

    function setPositionIndicator(target, options, numberOfSets, position) {
      var currentIndicators = $(options.containers.positionIndicator.container.reference).find("." + options.containers.positionIndicator.indicator.css.identifier);
      if (currentIndicators.length > numberOfSets) {
        var delta = currentIndicators.length - numberOfSets;
        $(currentIndicators.splice(currentIndicators.length - delta - 1, delta)).remove();
      } else {
        if (currentIndicators.length < numberOfSets) {
          var delta = numberOfSets - currentIndicators.length;
          var indicator = null;
          for (var i = 0; i < delta; i++) {
            indicator = $("<li />");
            $(indicator).addClass(options.containers.positionIndicator.indicator.css.identifier);
            $(options.containers.positionIndicator.container.reference).append(indicator);
            currentIndicators.push(indicator);
          }
        }
      }
      $(currentIndicators).removeClass(options.containers.positionIndicator.indicator.css.active);
      $(currentIndicators).removeClass(options.containers.positionIndicator.indicator.css.inactive);
      $(currentIndicators).addClass(options.containers.positionIndicator.indicator.css.inactive);
      $(currentIndicators[position]).removeClass(options.containers.positionIndicator.indicator.css.inactive);
      $(currentIndicators[position]).addClass(options.containers.positionIndicator.indicator.css.active);
      alignToParent(target, options, options.containers.positionIndicator.container.horizontalAlign, options.containers.positionIndicator.container.verticalAlign, options.containers.positionIndicator.container.reference, options.containers.positionIndicator.container.horizontalOffset, options.containers.positionIndicator.container.verticalOffset);
    }

    function setStatus(target, options, status) {
      $(options.containers.status.reference).html(status);
      alignToParent(target, options, options.containers.status.horizontalAlign, options.containers.status.verticalAlign, options.containers.status.reference);
    }

    function getStatus(target, options) {
      return $(options.containers.status.reference).html();
    }

    function alignToParent(target, options, horizontalAlign, verticalAlign, container, horizontalOffset, verticalOffset) {
      horizontalOffset = horizontalOffset || 0;
      verticalOffset = verticalOffset || 0;
      $(container).css("position", "absolute");
      if (horizontalAlign) {
        switch(horizontalAlign.toLowerCase()) {
          case"left":
            $(container).css("right", null).css("left", horizontalOffset + "px");
            break;
          case"right":
            $(container).css("left", null).css("right", horizontalOffset + "px");
            break;
          case"center":
            $(container).css("right", null).css("left", ($(container).parent().innerWidth() / 2 - $(container).outerWidth() / 2) + horizontalOffset + "px");
            break;
        }
      }
      if (verticalAlign) {
        switch(verticalAlign.toLowerCase()) {
          case"top":
            $(container).css("bottom", null).css("top", verticalOffset + "px");
            break;
          case"bottom":
            $(container).css("top", null).css("bottom", verticalOffset + "px");
            break;
          case"middle":
            $(container).css("bottom", null).css("top", ($(container).parent().innerHeight() / 2 - $(container).outerHeight() / 2) + verticalOffset + "px");
            break;
        }
      }
    }

    function calculateContainerPadding(target, options, container) {
      var paddingTestDiv = $('<div style="padding:0px 0px 0px 0px;"/>');
      paddingTestDiv.css("padding-top", $(container).css("padding-top"));
      var paddingTop = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-top", "0px");
      paddingTestDiv.css("padding-right", $(container).css("padding-right"));
      var paddingRight = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-right", "0px");
      paddingTestDiv.css("padding-bottom", $(container).css("padding-bottom"));
      var paddingBottom = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-bottom", "0px");
      paddingTestDiv.css("padding-left", $(container).css("padding-left"));
      var paddingLeft = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-left", "0px");
      return {
        top : paddingTop,
        right : paddingRight,
        bottom : paddingBottom,
        left : paddingLeft
      };
    }

    function handleResize(target, options) {
      var controlsContainerPadding = calculateContainerPadding(target, options, options.containers.controls.reference);
      $(options.containers.bottom.reference).height($(options.containers.controls.reference).innerHeight() - $(options.containers.top.reference).outerHeight() - controlsContainerPadding.top - controlsContainerPadding.bottom);
      alignToParent(target, options, options.containers.positionIndicator.container.horizontalAlign, options.containers.positionIndicator.container.verticalAlign, options.containers.positionIndicator.container.reference, options.containers.positionIndicator.container.horizontalOffset, options.containers.positionIndicator.container.verticalOffset);
      alignToParent(target, options, options.containers.status.horizontalAlign, options.containers.status.verticalAlign, options.containers.status.reference);
      alignToParent(target, options, options.containers.buttons.container.horizontalAlign, options.containers.buttons.container.verticalAlign, options.containers.buttons.container.reference);
      alignToParent(target, options, options.containers.buttons.previousSet.label.horizontalAlign, options.containers.buttons.previousSet.label.verticalAlign, options.containers.buttons.previousSet.label.reference);
      alignToParent(target, options, options.containers.buttons.finish.label.horizontalAlign, options.containers.buttons.finish.label.verticalAlign, options.containers.buttons.finish.label.reference);
      alignToParent(target, options, options.containers.buttons.reset.label.horizontalAlign, options.containers.buttons.reset.label.verticalAlign, options.containers.buttons.reset.label.reference);
      alignToParent(target, options, options.containers.buttons.more.label.horizontalAlign, options.containers.buttons.more.label.verticalAlign, options.containers.buttons.more.label.reference);
      alignToParent(target, options, options.containers.buttons.less.label.horizontalAlign, options.containers.buttons.less.label.verticalAlign, options.containers.buttons.less.label.reference);
      alignToParent(target, options, options.containers.buttons.nextSet.label.horizontalAlign, options.containers.buttons.nextSet.label.verticalAlign, options.containers.buttons.nextSet.label.reference);
      alignToParent(target, options, options.containers.buttons.save.label.horizontalAlign, options.containers.buttons.save.label.verticalAlign, options.containers.buttons.save.label.reference);
    }
    return this;
  };
  $.fn.activityControls.defaults = {};
  $.fn.activityControls.defaults.containers = {
    controls : {
      reference : null,
      css : {
        identifier : "softchalk-activity-controls"
      }
    },
    top : {
      reference : null,
      show : true,
      css : {
        identifier : "softchalk-activity-controls-top",
        hidden : "hidden"
      }
    },
    bottom : {
      reference : null,
      show : true,
      css : {
        identifier : "softchalk-activity-controls-bottom",
        hidden : "hidden"
      }
    },
    status : {
      reference : null,
      horizontalAlign : "left",
      verticalAlign : "middle",
      css : {
        identifier : "softchalk-activity-controls-status"
      }
    },
    positionIndicator : {
      container : {
        reference : null,
        horizontalAlign : "center",
        horizontalOffset : 0,
        verticalAlign : "middle",
        verticalOffset : 2,
        css : {
          identifier : "softchalk-activity-controls-position-indicator-container",
          hidden : "hidden"
        }
      },
      indicator : {
        references : [],
        css : {
          identifier : "softchalk-activity-controls-position-indicator",
          active : "active",
          inactive : "inactive"
        }
      }
    },
    buttons : {
      container : {
        reference : null,
        horizontalAlign : "right",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-activity-controls-button-container"
        }
      },
      finish : {
        container : {
          reference : null,
          show : false,
          css : {
            identifier : "softchalk-activity-controls-finish-button",
            hidden : "hidden",
            disabled : "disabled"
          }
        },
        overlay : {
          reference : null,
          show : true,
          css : {
            identifier : "softchalk-activity-controls-finish-overlay"
          }
        },
        label : {
          reference : null,
          label : "",
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-activity-controls-finish-label"
          }
        }
      },
      reset : {
        container : {
          reference : null,
          show : false,
          css : {
            identifier : "softchalk-activity-controls-reset-button",
            hidden : "hidden",
            disabled : "disabled"
          }
        },
        overlay : {
          reference : null,
          show : true,
          css : {
            identifier : "softchalk-activity-controls-reset-overlay"
          }
        },
        label : {
          reference : null,
          label : "",
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-activity-controls-reset-label"
          }
        }
      },
      more : {
        container : {
          reference : null,
          show : false,
          css : {
            identifier : "softchalk-activity-controls-more-button",
            hidden : "hidden",
            disabled : "disabled"
          }
        },
        overlay : {
          reference : null,
          show : true,
          css : {
            identifier : "softchalk-activity-controls-more-overlay"
          }
        },
        label : {
          reference : null,
          label : "",
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-activity-controls-more-label"
          }
        }
      },
      less : {
        container : {
          reference : null,
          show : false,
          css : {
            identifier : "softchalk-activity-controls-less-button",
            hidden : "hidden",
            disabled : "disabled"
          }
        },
        overlay : {
          reference : null,
          show : true,
          css : {
            identifier : "softchalk-activity-controls-less-overlay"
          }
        },
        label : {
          reference : null,
          label : "",
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-activity-controls-less-label"
          }
        }
      },
      nextSet : {
        container : {
          reference : null,
          show : false,
          css : {
            identifier : "softchalk-activity-controls-next-set-button",
            hidden : "hidden",
            disabled : "disabled"
          }
        },
        overlay : {
          reference : null,
          show : true,
          css : {
            identifier : "softchalk-activity-controls-next-set-overlay"
          }
        },
        label : {
          reference : null,
          label : "",
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-activity-controls-next-set-label"
          }
        }
      },
      previousSet : {
        container : {
          reference : null,
          show : false,
          css : {
            identifier : "softchalk-activity-controls-previous-set-button",
            hidden : "hidden",
            disabled : "disabled"
          }
        },
        overlay : {
          reference : null,
          show : true,
          css : {
            identifier : "softchalk-activity-controls-previous-set-overlay"
          }
        },
        label : {
          reference : null,
          label : "",
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-activity-controls-previous-set-label"
          }
        }
      },
      save : {
        container : {
          reference : null,
          show : false,
          css : {
            identifier : "softchalk-activity-controls-save-button",
            hidden : "hidden",
            disabled : "disabled"
          }
        },
        overlay : {
          reference : null,
          show : true,
          css : {
            identifier : "softchalk-activity-controls-save-overlay"
          }
        },
        label : {
          reference : null,
          label : "",
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-activity-controls-save-label"
          }
        }
      }
    }
  };
  $.fn.activityControls.defaults.data = {
    allowSaveButton : false,
    enableLogging : false
  };
  $.fn.activityControls.defaults.logging = {
    debug : false,
    info : true,
    warn : false,
    error : false
  };
})(jQuery);
(function($) {
  $.fn.activityEmbed = function(action, options, params) {
    var shouldReturnResults = false;
    var results = [];
    action = action || "initialize";
    if ( typeof (action) == "object") {
      if (!params) {
        params = action;
        options = null;
      } else {
        params = options;
        options = action;
      }
      action = "initialize";
    }
    if (action == "initialize") {
      if (!$.fn.activityEmbed.defaults.data.browserChecksPerformed) {
        try {
          if (document.createElement("canvas")) {
            $.fn.activityEmbed.defaults.data.hasCanvas = true;
          }
          if (document.createElement("audio")) {
            $.fn.activityEmbed.defaults.data.hasAudio = true;
          }
          $.fn.activityEmbed.defaults.data.browserMajorVersion = parseInt($.browser.version.split(".")[0]);
          if ($.browser.msie && $.fn.activityEmbed.defaults.data.browserMajorVersion < 9) {
            $.fn.activityEmbed.defaults.data.useFlashAsDefault = true;
          }
        } catch(e) {
        } finally {
          $.fn.activityEmbed.defaults.data.browserChecksPerformed = true;
        }
      }
      if (!options) {
        options = $.fn.activityEmbed.defaults;
      } else {
        options = $.extend(true, {}, $.fn.activityEmbed.defaults, options);
      }
    }
    var optionsReference = options;
    $(this).each(function() {
      switch(action) {
        case"initialize":
          initialize(this, optionsReference, params);
          break;
      }
    });
    if (shouldReturnResults == true) {
      return results;
    }
    function log(target, options, data, level) {
      level = level || "debug";
      level = $.trim(level).toLowerCase();
      if (options.data.enableLogging && window.console) {
        if (level == "info" && window.console.info && options.logging.info) {
          if ($(target).attr("id")) {
            window.console.info("[ActivityWrapper][" + target + ", id=" + $(target).attr("id") + "]" + data);
          } else {
            if ($(target).attr("name")) {
              window.console.info("[ActivityWrapper][" + target + ", name=" + $(target).attr("name") + "]" + data);
            } else {
              window.console.info("[ActivityWrapper][" + target + "]" + data);
            }
          }
        } else {
          if (level == "warn" && window.console.warn && options.logging.warn) {
            if ($(target).attr("id")) {
              window.console.warn("[ActivityWrapper][" + target + ", id=" + $(target).attr("id") + "]" + data);
            } else {
              if ($(target).attr("name")) {
                window.console.warn("[ActivityWrapper][" + target + ", name=" + $(target).attr("name") + "]" + data);
              } else {
                window.console.warn("[ActivityWrapper][" + target + "]" + data);
              }
            }
          } else {
            if (level == "error" && window.console.error && options.logging.error) {
              if ($(target).attr("id")) {
                window.console.error("[ActivityWrapper][" + target + ", id=" + $(target).attr("id") + "]" + data);
              } else {
                if ($(target).attr("name")) {
                  window.console.error("[ActivityWrapper][" + target + ", name=" + $(target).attr("name") + "]" + data);
                } else {
                  window.console.error("[ActivityWrapper][" + target + "]" + data);
                }
              }
            } else {
              if (window.console.log && options.logging.debug) {
                if ($(target).attr("id")) {
                  window.console.log("[ActivityWrapper][" + target + ", id=" + $(target).attr("id") + "]" + data);
                } else {
                  if ($(target).attr("name")) {
                    window.console.log("[ActivityWrapper][" + target + ", name=" + $(target).attr("name") + "]" + data);
                  } else {
                    window.console.log("[ActivityWrapper][" + target + "]" + data);
                  }
                }
              }
            }
          }
        }
      }
    }

    function initialize(target, options, params) {
      log(target, options, "Initializing Activity Embed", "info");
      options = $.extend(true, {}, options);
      var type = new String(params.type);
      type = type.toLowerCase();
      try {
        switch(type) {
          case"2":
          case"flashcard":
            embedFlashCard(target, options, params);
            break;
          case"3":
          case"seekaword":
            embedSeekAWord(target, options, params);
            break;
          case"4":
          case"dragndrop":
            embedDragNDrop(target, options, params);
            break;
          case"5":
          case"ordering":
          case"oldordering":
            embedOldOrdering(target, options, params);
            break;
          case"6":
          case"crossword":
            embedCrossword(target, options, params);
            break;
          case"7":
          case"labeling":
            embedLabeling(target, options, params);
            break;
          case"8":
          case"sorting":
            embedSorting(target, options, params);
            break;
          case"9":
          case"hotspot":
            embedHotSpot(target, options, params);
            break;
          case"10":
          case"timeline":
            embedTimeline(target, options, params);
            break;
          case"11":
          case"slideshow":
            embedSlideshow(target, options, params);
            break;
          case"12":
          case"photoalbum":
            embedPhotoAlbum(target, options, params);
            break;
          case"13":
          case"sectionedshape":
            embedSectionedShape(target, options, params);
            break;
          case"14":
          case"tabbedpane":
            embedTabbedPane(target, options, params);
            break;
          case"15":
          case"didyouknow":
            embedDidYouKnow(target, options, params);
            break;
          case"16":
          case"jigsawpuzzle":
          case"puzzle":
            embedJigsawPuzzle(target, options, params);
            break;
          default:
            embedActivityWrapper(target, options, params);
            break;
        }
      } catch(error) {
        log(target, options, error, "error");
      }
    }

    function embedJigsawPuzzle(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var templateScript = $("script[id='PUZZLE_EJS_SCRIPT']");
        if (templateScript.length == 0) {
          templateScript = document.createElement("script");
          $(templateScript).attr("type", "text/ejs");
          $(templateScript).attr("id", "PUZZLE_EJS_SCRIPT");
          $(templateScript).text(PUZZLE_EJS);
          $("head").append(templateScript);
        }
        var width = (params.width) ? params.width : 720;
        var height = (params.height) ? params.height : 450;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "jigsawpuzzle",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          showRestart : params.restart,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
        var handleScoring = function(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              window.cookit(jsonObj.id + "score", (jsonObj.curScore / jsonObj.maxScore * 100), jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        };
        $(target).bind("sc.jigsawpuzzle.complete", function(event, jsonObj) {
          log(target, options, "Jigsaw Puzzle Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        }).bind("sc.jigsawpuzzle.reset", function(event, jsonObj) {
          log(target, options, "Jigsaw Puzzle Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        });
      } else {
        var swf = options.swf.jigsawPuzzle;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedDidYouKnow(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML4Version = true;
      var hasHTML5Version = true;
      if (hasHTML4Version || (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio)) {
        var width = (params.width) ? params.width : 800;
        var height = (params.height) ? params.height : 200;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "didyouknow",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
      } else {
        var swf = options.swf.didYouKnow;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedTabbedPane(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML4Version = true;
      var hasHTML5Version = true;
      if (hasHTML4Version || (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio)) {
        var width = (params.width) ? params.width : 800;
        var height = (params.height) ? params.height : 200;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "tabbedpane",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
      } else {
        var swf = options.swf.tabbedPane;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedSectionedShape(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var width = (params.width) ? params.width : 720;
        var height = (params.height) ? params.height : 450;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "sectionedshape",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
      } else {
        var swf = options.swf.sectionedShape;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedPhotoAlbum(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var width = (params.width) ? params.width : 800;
        var height = (params.height) ? params.height : 560;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "photoalbum",
          xmlPath : params.dataFile,
          id : params.actNum,
		      textAlign : params.textAlign || "left",
          width : width,
          height : height,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
      } else {
        var swf = options.swf.photoAlbum;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedSlideshow(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var width = (params.width) ? params.width : 640;
        var height = (params.height) ? params.height : 580;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "slideshow",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
      } else {
        var swf = options.swf.slideshow;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedTimeline(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var templateScript = $("script[id='TIMELINE_EJS_SCRIPT']");
        if (templateScript.length == 0) {
          templateScript = document.createElement("script");
          $(templateScript).attr("type", "text/ejs");
          $(templateScript).attr("id", "TIMELINE_EJS_SCRIPT");
          $(templateScript).text(TIMELINE_EJS);
          $("head").append(templateScript);
        }
        var width = (params.width) ? params.width : 540;
        var height = (params.height) ? params.height : 410;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "timeline",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          showRestart : params.restart,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
      } else {
        var swf = options.swf.timeline;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedSorting(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var templateScript = $("script[id='SORTING_EJS_SCRIPT']");
        if (templateScript.length == 0) {
          templateScript = document.createElement("script");
          $(templateScript).attr("type", "text/ejs");
          $(templateScript).attr("id", "SORTING_EJS_SCRIPT");
          $(templateScript).text(SORTING_EJS);
          $("head").append(templateScript);
        }
        var width = (params.width) ? params.width : 550;
        var height = (params.height) ? params.height : 450;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "sorting",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          showRestart : params.restart,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
        var handleScoring = function(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              var pts = jsonObj.curScore * (jsonObj.maxScore / jsonObj.innerState.length);
              pts = Math.round(10 * pts) / 10;
              var percent = (pts / jsonObj.maxScore * 100);
              window.cookit(jsonObj.id + "score", percent, jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        };
        $(target).bind("sc.sorting.complete", function(event, jsonObj) {
          log(target, options, "Sorting Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        }).bind("sc.sorting.reset", function(event, jsonObj) {
          log(target, options, "Sorting Score Reset [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        });
      } else {
        var swf = options.swf.sorting;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedSeekAWord(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var templateScript = $("script[id='SEEK_A_WORD_EJS_SCRIPT']");
        if (templateScript.length == 0) {
          templateScript = document.createElement("script");
          $(templateScript).attr("type", "text/ejs");
          $(templateScript).attr("id", "SEEK_A_WORD_EJS_SCRIPT");
          $(templateScript).text(SEEK_A_WORD_EJS);
          $("head").append(templateScript);
        }
        var width = (params.width) ? params.width : 638;
        var height = (params.height) ? params.height : 500;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "seekaword",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          showRestart : params.restart,
          sqrsize : parseInt(params.flashVars.sqrsize),
          instructions : params.flashVars.instructions,
          hint : params.flashVars.hint,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
        function handleScoring(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              window.cookit(jsonObj.id + "score", (jsonObj.curScore / jsonObj.maxScore * 100), jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        }

        var handleScoring = function(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              window.cookit(jsonObj.id + "score", (jsonObj.curScore / jsonObj.maxScore * 100), jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        };
        $(target).bind("sc.seekaword.complete", function(event, jsonObj) {
          log(target, options, "SeekAWord Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        }).bind("sc.seekaword.reset", function(event, jsonObj) {
          log(target, options, "SeekAWord Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        });
      } else {
        var swf = options.swf.seekAWord;
        var flashVars = $.extend({}, {
          datafile : params.dataFile,
          bgcolor : params.color,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedOldOrdering(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var templateScript = $("script[id='ORDERING_EJS_SCRIPT']");
        if (templateScript.length == 0) {
          templateScript = document.createElement("script");
          $(templateScript).attr("type", "text/ejs");
          $(templateScript).attr("id", "ORDERING_EJS_SCRIPT");
          $(templateScript).text(ORDERING_EJS);
          $("head").append(templateScript);
        }
        var width = (params.width) ? params.width : 550;
        var height = (params.height) ? params.height : 500;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "ordering",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          showRestart : params.restart,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
        var handleScoring = function(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              var pts = jsonObj.curScore * (jsonObj.maxScore / jsonObj.innerState.length);
              pts = Math.round(10 * pts) / 10;
              var percent = (pts / jsonObj.maxScore * 100);
              window.cookit(jsonObj.id + "score", percent, jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        };
        $(target).bind("sc.ordering.complete", function(event, jsonObj) {
          log(target, options, "Ordering Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        }).bind("sc.ordering.reset", function(event, jsonObj) {
          log(target, options, "Ordering Puzzle Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        });
      } else {
        var swf = options.swf.ordering;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedFlashCard(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var width = (params.width) ? params.width : 550;
        var height = (params.height) ? params.height : 400;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "flashcard",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          showRestart : params.restart,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
      } else {
        var swf = options.swf.flashCard;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedDragNDrop(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var templateScript = $("script[id='DRAG_N_DROP_EJS_SCRIPT']");
        if (templateScript.length == 0) {
          templateScript = document.createElement("script");
          $(templateScript).attr("type", "text/ejs");
          $(templateScript).attr("id", "DRAG_N_DROP_EJS_SCRIPT");
          $(templateScript).text(DRAG_N_DROP_EJS);
          $("head").append(templateScript);
        }
        var width = (params.width) ? params.width : 550;
        var height = (params.height) ? params.height : 500;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "dragndrop",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          showRestart : params.restart,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
        function handleScoring(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              var pts = jsonObj.curScore * (jsonObj.maxScore / jsonObj.innerState.length);
              pts = Math.round(10 * pts) / 10;
              var percent = (pts / jsonObj.maxScore * 100);
              window.cookit(jsonObj.id + "score", percent, jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        }

        var handleScoring = function(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              var pts = jsonObj.curScore * (jsonObj.maxScore / jsonObj.innerState.length);
              pts = Math.round(10 * pts) / 10;
              var percent = (pts / jsonObj.maxScore * 100);
              window.cookit(jsonObj.id + "score", percent, jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        };
        $(target).bind("sc.dragndrop.complete", function(event, jsonObj) {
          log(target, options, "DragNDrop Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        }).bind("sc.dragndrop.reset", function(event, jsonObj) {
          log(target, options, "DragNDrop Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        });
      } else {
        var swf = options.swf.dragNDrop;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedCrossword(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var templateScript = $("script[id='CROSSWORD_EJS_SCRIPT']");
        if (templateScript.length == 0) {
          templateScript = document.createElement("script");
          $(templateScript).attr("type", "text/ejs");
          $(templateScript).attr("id", "CROSSWORD_EJS_SCRIPT");
          $(templateScript).text(CROSSWORD_EJS);
          $("head").append(templateScript);
        }
        var width = (params.width) ? params.width : 640;
        var height = (params.height) ? params.height : 500;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "crossword",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          showRestart : params.restart,
          solve : params.flashVars.solve,
          sclb_version : params.flashVars.sclb_version,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
        function handleScoring(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              var pts = jsonObj.curScore * (jsonObj.maxScore / jsonObj.pointsArr.length);
              pts = Math.round(10 * pts) / 10;
              var percent = (pts / jsonObj.maxScore * 100);
              window.cookit(jsonObj.id + "score", percent, jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        }

        var handleScoring = function(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              var pts = jsonObj.curScore * (jsonObj.maxScore / jsonObj.pointsArr.length);
              pts = Math.round(10 * pts) / 10;
              var percent = (pts / jsonObj.maxScore * 100);
              window.cookit(jsonObj.id + "score", percent, jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        };
        $(target).bind("sc.crossword.complete", function(event, jsonObj) {
          log(target, options, "Crossword Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        }).bind("sc.crossword.reset", function(event, jsonObj) {
          log(target, options, "Crossword Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        });
      } else {
        var swf = options.swf.crossword;
        var flashVars = $.extend({}, {
          datafile : params.dataFile,
          bgcolor : params.color,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedHotSpot(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var templateScript = $("script[id='HOTSPOT_EJS_SCRIPT']");
        if (templateScript.length == 0) {
          templateScript = document.createElement("script");
          $(templateScript).attr("type", "text/ejs");
          $(templateScript).attr("id", "HOTSPOT_EJS_SCRIPT");
          $(templateScript).text(HOTSPOT_EJS);
          $("head").append(templateScript);
        }
        var width = (params.width) ? params.width : 550;
        var height = (params.height) ? params.height : 500;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "hotspot",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          showRestart : params.restart,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
        var handleScoring = function(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              var pts = jsonObj.curScore * (jsonObj.maxScore / jsonObj.innerState.length);
              pts = Math.round(10 * pts) / 10;
              var percent = (pts / jsonObj.maxScore * 100);
              window.cookit(jsonObj.id + "score", percent, jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        };
        $(target).bind("sc.hotspot.complete", function(event, jsonObj) {
          log(target, options, "HotSpot Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        }).bind("sc.hotspot.reset", function(event, jsonObj) {
          log(target, options, "HotSpot Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        });
      } else {
        var swf = options.swf.hotSpot;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedLabeling(target, options, params) {
      setTargetDimensions(target, options, params);
      var hasHTML5Version = true;
      if (hasHTML5Version && !options.data.useFlashAsDefault && options.data.hasCanvas && options.data.hasAudio) {
        var templateScript = $("script[id='LABELING_EJS_SCRIPT']");
        if (templateScript.length == 0) {
          templateScript = document.createElement("script");
          $(templateScript).attr("type", "text/ejs");
          $(templateScript).attr("id", "LABELING_EJS_SCRIPT");
          $(templateScript).text(LABELING_EJS);
          $("head").append(templateScript);
        }
        var width = (params.width) ? params.width : 600;
        var height = (params.height) ? params.height : 500;
        if (params.id && params.id[0] == "#") {
          params.id = params.id.substr(1);
        }
        $(target).data("activityEmbed:type", "html");
        $(target).html("");
        $(target).plugin("initialize", {
          containerId : params.id,
          type : "labeling",
          xmlPath : params.dataFile,
          id : params.actNum,
          width : width,
          height : height,
          showRestart : params.restart,
          backgroundColor : "#" + params.color.replace("#", "").replace("0x", "")
        });
        var handleScoring = function(jsonObj) {
          if (window.cookit) {
            if (jsonObj.maxScore > 0) {
              var pts = jsonObj.curScore * (jsonObj.maxScore / jsonObj.innerState.length);
              pts = Math.round(10 * pts) / 10;
              var percent = (pts / jsonObj.maxScore * 100);
              window.cookit(jsonObj.id + "score", percent, jsonObj.id + "attempts", jsonObj.attempts);
            }
          }
        };
        $(target).bind("sc.labeling.complete", function(event, jsonObj) {
          log(target, options, "Labeling Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        }).bind("sc.labeling.reset", function(event, jsonObj) {
          log(target, options, "Labeling Score Changed [" + jsonObj.id + "]:" + jsonObj.curScore + "/" + jsonObj.maxScore, "debug");
          handleScoring(jsonObj);
        });
      } else {
        var swf = options.swf.labeling;
        var flashVars = $.extend({}, {
          xmlfile : params.dataFile,
          restart : params.restart,
          actNum : params.actNum
        }, params.flashVars);
        embedFlash(target, options, params, swf, flashVars);
      }
    }

    function embedFlash(target, options, params, swf, flashVars) {
      var id = $(target).attr("id");
      var swfName = swf.replace(".swf", "");
      var serializedFlashVars = "";
      $.each(flashVars, function(key, value) {
        if (value != null && value != undefined) {
          if (serializedFlashVars != "") {
            serializedFlashVars += "&";
          }
          serializedFlashVars += key + "=" + value;
        }
      });
      if (serializedFlashVars != "") {
        serializedFlashVars = "?" + serializedFlashVars;
      }
      var fo = new FlashObject(swf + serializedFlashVars, swfName, params.width, params.height, options.data.minimumFlashVersion, params.color);
      fo.addParam("allowScriptAccess", "sameDomain");
      fo.addParam("quality", "high");
      fo.addParam("scale", "noscale");
      fo.addParam("redirectUrl", "http://get.adobe.com/flashplayer");
      fo.addParam("wmode", "transparent");
      fo.write(id);
      $(target).data("activityEmbed:type", "flash");
    }

    function setTargetDimensions(target, options, params) {
      if (params.width && params.height) {
        $(target).css({
          width : params.width,
          height : params.height
        });
      }
    }

    function embedActivityWrapper(target, options, params) {
      log(target, options, "Initializing Activity Wrapper for activityid:" + params.id + ", type:" + params.type + ", dataFile:" + params.dataFile, "info");
      $(target).data("activityEmbed:type", "html");
      $(target).activityWrapper({
        data : {
          activityIdentifier : params.actNum,
          activityType : params.type,
          activityData : {
            xmlFile : params.dataFile,
            allowRetry : params.restart
          }
        }
      });
    }
    return this;
  };
  $.fn.activityEmbed.defaults = {};
  $.fn.activityEmbed.defaults.data = {
    enableLogging : false,
    browserChecksPerformed : false,
    browserMajorVersion : 0,
    hasCanvas : false,
    hasAudio : false,
    minimumFlashVersion : "10",
    useFlashAsDefault : false
  };
  $.fn.activityEmbed.defaults.swf = {
    flashCard : "flashcard.swf",
    seekAWord : "seekaword.swf",
    dragNDrop : "dragndrop.swf",
    ordering : "ordering.swf",
    crossword : "crossword.swf",
    labeling : "labeling.swf",
    sorting : "sorting.swf",
    hotSpot : "hotspot.swf",
    timeline : "timeline.swf",
    slideshow : "slideshow.swf",
    photoAlbum : "photoalbum.swf",
    sectionedShape : "sectionedshape.swf",
    tabbedPane : "tabbedpane.swf",
    didYouKnow : "didyouknow.swf",
    jigsawPuzzle : "jigsawpuzzle.swf"
  };
  $.fn.activityEmbed.defaults.logging = {
    debug : false,
    info : true,
    warn : false,
    error : false
  };
})(jQuery);
(function($) {
  $.fn.matchingActivity = function(action, options) {
    var shouldReturnResults = false;
    var results = [];
    var params = null;
    action = action || "initialize";
    if ( typeof (action) == "object") {
      options = action;
      action = "initialize";
    }
    if (action == "initialize") {
      if (!options) {
        options = $.fn.matchingActivity.defaults;
      } else {
        options = $.extend(true, {}, $.fn.matchingActivity.defaults, options);
      }
    } else {
      params = options;
    }
    var optionsReference = options;
    $(this).each(function() {
      switch(action) {
        case"initialize":
          log(this, optionsReference, "Action:Initializing Activity", "info");
          initialize(this, optionsReference);
          break;
        case"loadXMLAndBuildActivity":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Loading XML", "info");
          loadXMLAndBuildActivity(this, options, params);
          break;
        case"parseXMLAndBuildActivity":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Parsing XML", "info");
          parseXMLAndBuildActivity(this, options, params);
          break;
        case"calculateScore":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Calculating Score", "info");
          calculateScore(this, options);
          break;
        case"finish":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Finishing Activity", "info");
          calculateActivityScore(this, options, true, true);
          break;
        case"reset":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Resetting Activity", "info");
          resetActivity(this, options);
          break;
        case"showNextSet":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Showing Next Set", "info");
          showNextSet(this, options);
          break;
        case"showPreviousSet":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Showing Previous Set", "info");
          showPreviousSet(this, options);
          break;
        case"getState":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Getting Activity State", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getActivityState(this, options)
          });
          break;
        case"setState":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Setting Activity State", "info");
          setActivityState(this, options, params.state, params.completed);
          break;
        case"getEnabled":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Getting Enabled", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.enabled
          });
          break;
        case"setEnabled":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Setting Enabled", "info");
          options.data.enabled = params;
          $(this).data("matchingActivity:options", options);
          enableDisable(this, options);
          break;
        case"getSetIds":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Getting Set Ids", "info");
          var setContainers = getSetContainers(this, options);
          var setContainer = null;
          var setContainerData = null;
          var setIds = [];
          for (var i = 0; i < setContainers.length; i++) {
            setContainer = setContainers[i];
            setContainerData = $(setContainer).data("matchingActivity:set");
            setIds.push(setContainerData.id);
          }
          shouldReturnResults = true;
          results.push({
            target : this,
            result : setIds
          });
          break;
        case"getNumberOfSets":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getSetContainers(this, options).length
          });
          break;
        case"showSet":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          showSet(this, options, params);
          break;
        case"getAllowReset":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Getting allow reset", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.allowRetry
          });
          break;
        case"resize":
          var options = $(this).data("matchingActivity:options");
          log(this, options, "Action:Resizing the activity", "info");
          handleResize(this, options);
          break;
      }
    });
    if (shouldReturnResults == true) {
      return results;
    }
    function log(target, options, data, level) {
      level = level || "debug";
      level = $.trim(level).toLowerCase();
      if (options.data.enableLogging && window.console) {
        if (level == "info" && window.console.info && options.logging.info) {
          if ($(target).attr("id")) {
            window.console.info("[matchingActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
          } else {
            if ($(target).attr("name")) {
              window.console.info("[matchingActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
            } else {
              window.console.info("[matchingActivity][" + target + "]" + data);
            }
          }
        } else {
          if (level == "warn" && window.console.warn && options.logging.warn) {
            if ($(target).attr("id")) {
              window.console.warn("[matchingActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
            } else {
              if ($(target).attr("name")) {
                window.console.warn("[matchingActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
              } else {
                window.console.warn("[matchingActivity][" + target + "]" + data);
              }
            }
          } else {
            if (level == "error" && window.console.error && options.logging.error) {
              if ($(target).attr("id")) {
                window.console.error("[matchingActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
              } else {
                if ($(target).attr("name")) {
                  window.console.error("[matchingActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                } else {
                  window.console.error("[matchingActivity][" + target + "]" + data);
                }
              }
            } else {
              if (window.console.log && options.logging.debug) {
                if ($(target).attr("id")) {
                  window.console.log("[matchingActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
                } else {
                  if ($(target).attr("name")) {
                    window.console.log("[matchingActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                  } else {
                    window.console.log("[matchingActivity][" + target + "]" + data);
                  }
                }
              }
            }
          }
        }
      }
    }

    function initialize(target, options) {
      options = $.extend(true, {}, options);
      options.containers.activity.reference = target;
      $(options.containers.activity.reference).addClass(options.containers.activity.css.identifier);
      options.containers.content.reference = target;
      $(options.containers.content.reference).addClass(options.containers.content.css.identifier);
      if (options.containers.matchset.reference == null) {
        options.containers.matchset.reference = $("<div />");
        $(options.containers.content.reference).append(options.containers.matchset.reference);
      }
      options.containers.matchset.reference.addClass(options.containers.matchset.css.identifier);
      $(target).data("matchingActivity:options", options);
    }

    function handleResize(target, options) {
      alignSets(target, options);
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var matches = null;
      var matchsetDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.matchset.reference);
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("matchingActivity:set");
        matches = getMatchesInSet(target, options, setContainer);
        matchsetDimensions = calculateMatchSetDimensions(target, options, setContainerData.rows, setContainerData.columns);
        resizeMatches(target, options, matchsetDimensions.width, matchsetDimensions.height, matches);
        positionMatches(target, options, matches);
        alignMatches(target, options, matches);
      }
      log(target, options, "Activity Container Resized", "info");
    }

    function registerAccessibilityEvents(target, options, matches) {
      var handleMiceEvents = function(event) {
        var options = $(this).data("matchingActivity:options");
        if (options.data.enabled && event.pageX && event.pageY) {
          var offset = $(this).offset();
          var width = $(this).outerWidth();
          var height = $(this).outerHeight();
          if (!options.accessibility.hasFocus && event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
            options.accessibility.hasFocus = true;
            $(this).data("matchingActivity:options", options);
          } else {
            if (options.accessibility.hasFocus && (event.pageX < offset.left || event.pageX > offset.left + width || event.pageY < offset.top || event.pageY > offset.top + height)) {
              options.accessibility.hasFocus = false;
              $(this).data("matchingActivity:options", options);
            }
          }
        }
      };
      $(target).bind("mouseover", handleMiceEvents).bind("mouseout", handleMiceEvents).bind("mousemove", handleMiceEvents);
      $(target).bind("focusin", function(event) {
        var options = $(this).data("matchingActivity:options");
        if (options.data.enabled && !options.accessibility.hasFocus) {
          log(target, options, "Giving Focus", "info");
          options.accessibility.hasFocus = true;
          $(this).data("matchingActivity:options", options);
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("matchingActivity:set");
          if (activeSetData.focusedmatchsetRow < 0 || activeSetData.focusedmatchsetColumn < 0 || !activeSetData.focusedmatchsetId) {
            focusMatchSetInSet(target, options, activeSet, null, 0, 0, false);
          }
        }
      });
      $(target).bind("focusout", function(event) {
        var options = $(this).data("matchingActivity:options");
        if (options.data.enabled && options.accessibility.hasFocus) {
          options.accessibility.hasFocus = false;
          $(this).data("matchingActivity:options", options);
        }
      });
      if (options.accessibility.keyboard.allow) {
        registerKeyboardEvents(target, options, matches);
      }
      if (options.accessibility.pseudoMouse.allow) {
        registerPseudoMouseEvents(target, options, matches);
      }
    }

    function calculateMatchSetDimensions(target, options, rows, columns) {
      var containerWidth = $(options.containers.matchset.reference).width();
      var containerHeight = $(options.containers.matchset.reference).height();
      var borderTestDiv = $("<div />").css("display", "none").addClass(options.containers.matches.container.css.identifier).width(100).height(100);
      $(target).append(borderTestDiv);
      var borderWidthOffset = ($(borderTestDiv).outerWidth() - $(borderTestDiv).innerWidth()) / 2;
      var borderHeightOffset = ($(borderTestDiv).outerHeight() - $(borderTestDiv).innerHeight()) / 2;
      $(borderTestDiv).remove();
      containerWidth -= borderWidthOffset * (2 * columns);
      containerHeight -= borderHeightOffset * (2 * rows);
      var matchsetMaxWidth = containerWidth / columns;
      var matchsetMaxHeight = containerHeight / rows;
      return {
        width : matchsetMaxWidth,
        height : matchsetMaxHeight
      };
    }

    function calculateContainerPadding(target, options, container) {
      var paddingTestDiv = $('<div style="padding:0px 0px 0px 0px;"/>');
      paddingTestDiv.css("padding-top", $(container).css("padding-top"));
      var paddingTop = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-top", "0px");
      paddingTestDiv.css("padding-right", $(container).css("padding-right"));
      var paddingRight = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-right", "0px");
      paddingTestDiv.css("padding-bottom", $(container).css("padding-bottom"));
      var paddingBottom = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-bottom", "0px");
      paddingTestDiv.css("padding-left", $(container).css("padding-left"));
      var paddingLeft = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-left", "0px");
      return {
        top : paddingTop,
        right : paddingRight,
        bottom : paddingBottom,
        left : paddingLeft
      };
    }

    function createMatchSetContainer(target, options, contentHtml) {
      var matchset = $("<div />").addClass(options.containers.matches.container.css.identifier).css("position", "absolute");
      var contentDiv = $("<div />").addClass(options.containers.matches.content.css.identifier);
      $(matchset).append(contentDiv);
      var feedbackDiv = $("<div />").addClass(options.containers.matches.feedback.css.identifier);
      $(matchset).append(feedbackDiv);
      var feedbackIconDiv = $("<div />").addClass(options.containers.matches.feedbackIcon.css.identifier);
      $(matchset).append(feedbackIconDiv);
      var indicatorDiv = $("<div />").addClass(options.containers.matches.pairIndicator.css.identifier);
      $(matchset).append(indicatorDiv);
      var overlayDiv = $("<div />").addClass(options.containers.matches.overlay.css.identifier);
      $(matchset).append(overlayDiv);
      if (contentHtml) {
        $(contentDiv).html(contentHtml);
      }
      return matchset;
    }

    function enableDisable(target, options, matches) {
      log(target, options, "Enabling/Disabling Activity:" + options.data.enabled, "info");
      matches = matches || getMatches(target, options);
      if (options.data.enabled) {
        $(options.containers.content.reference).removeClass(options.containers.content.css.disabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.enabled);
        $(target).trigger("enabled.matchingActivity", [options.data.dataSets.length]);
      } else {
        $(options.containers.content.reference).removeClass(options.containers.content.css.enabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.disabled);
        clearMatchesHover(target, options, matches);
        $(target).trigger("disabled.matchingActivity", [options.data.dataSets.length]);
      }
    }

    function resizeMatches(target, options, width, height, matches) {
      matches = matches || getMatches(target, options);
      var matchset = null;
      for (var i = 0; i < matches.length; i++) {
        matchset = matches[i];
        $(matchset).width(width);
        $(matchset).height(height);
      }
    }

    function positionMatches(target, options, matches, containerPadding) {
      matches = matches || getMatches(target, options);
      containerPadding = containerPadding || calculateContainerPadding(target, options, options.containers.matchset.reference);
      var matchsetData = null;
      var matchset = null;
      for (var i = 0; i < matches.length; i++) {
        matchset = matches[i];
        matchsetData = $(matchset).data("matchingActivity:matchset");
        $(matchset).css("left", (-containerPadding.left + $(matchset).outerWidth() * matchsetData.column) + "px");
        $(matchset).css("top", (-containerPadding.top + $(matchset).outerHeight() * matchsetData.row) + "px");
      }
    }

    function randomizeMatchSetPositionsInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var setData = $(setContainer).data("matchingActivity:set");
      var matches = getMatchesInSet(target, options, setContainer);
      var matchset = null;
      var matchsetData = null;
      var unpositionedmatches = [];
      for (var i = 0; i < matches.length; i++) {
        matchset = matches[i];
        matchsetData = $(matchset).data("matchingActivity:matchset");
        matchsetData.row = null;
        matchsetData.column = null;
        matchsetData.correct = false;
        $(matchset).data("matchingActivity:matchset", matchsetData);
        unpositionedmatches.push(matchset);
      }
      var matchsetMatrix = [];
      var currentRow = 0;
      var currentColumn = 0;
      var currentRowArray = null;
      for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
        currentRowArray = [];
        for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
          currentRowArray.push(null);
        }
        matchsetMatrix.push(currentRowArray);
      }
      var positioningmatchset = null;
      var randomSelector = null;
      var found = false;
      while (unpositionedmatches.length > 0) {
        randomSelector = Math.floor(Math.random() * unpositionedmatches.length);
        matchset = unpositionedmatches.splice(randomSelector, 1);
        matchsetData = $(matchset).data("matchingActivity:matchset");
        found = false;
        for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
          for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
            if (!matchsetMatrix[currentRow][currentColumn] && !found) {
              found = true;
              matchsetMatrix[currentRow][currentColumn] = matchset;
            }
          }
        }
        matchset = null;
      }
      for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
        for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
          matchset = matchsetMatrix[currentRow][currentColumn];
          matchsetData = $(matchset).data("matchingActivity:matchset");
          matchsetData.row = currentRow;
          matchsetData.column = currentColumn;
          $(matchset).data("matchingActivity:matchset", matchsetData);
        }
      }
    }

    function registerMatchSetEvents(target, options, matchset) {
      $(matchset).children("." + options.containers.matches.overlay.css.identifier).bind("mouseover", function() {
        var options = $(target).data("matchingActivity:options");
        var matchsetOptions = $(matchset).data("matchingActivity:matchset");
        var setOptions = $(matchset).parent().data("matchingActivity:set");
        if (options.data.enabled && !matchsetOptions.completed) {
          if (!$(this).parent().hasClass(options.containers.matches.container.css.correct) && !$(this).parent().hasClass(options.containers.matches.container.css.incorrect)) {
            if (!$(this).parent().hasClass(options.containers.matches.container.css.hover)) {
              clearMatchesHover(target, options);
              $(this).parent().addClass(options.containers.matches.container.css.hover);
              setOptions.focusedmatchsetId = matchsetOptions.id;
              setOptions.focusedmatchsetRow = matchsetOptions.row;
              setOptions.focusedmatchsetColumn = matchsetOptions.column;
              $(matchset).parent().data("matchingActivity:set", setOptions);
              options.accessibility.hasFocus = true;
              $(target).data("matchingActivity:options", options);
            }
          }
        }
      });
      $(matchset).children("." + options.containers.matches.overlay.css.identifier).bind("mouseout", function() {
        var options = $(target).data("matchingActivity:options");
        var matchsetOptions = $(matchset).data("matchingActivity:matchset");
        var setOptions = $(matchset).parent().data("matchingActivity:set");
        if (options.data.enabled && !matchsetOptions.completed) {
          if (!$(this).parent().hasClass(options.containers.matches.container.css.correct) && !$(this).parent().hasClass(options.containers.matches.container.css.incorrect)) {
            if ($(this).parent().hasClass(options.containers.matches.container.css.hover)) {
              $(this).parent().removeClass(options.containers.matches.container.css.hover);
              options.accessibility.hasFocus = true;
              $(target).data("matchingActivity:options", options);
            }
          }
        }
      });
      $(matchset).children("." + options.containers.matches.overlay.css.identifier).bind("click", function() {
        var options = $(target).data("matchingActivity:options");
        var matchsetOptions = $(matchset).data("matchingActivity:matchset");
        var setOptions = $(matchset).parent().data("matchingActivity:set");
        if (options.data.enabled && !matchsetOptions.completed) {
          var shouldRecalculate = false;
          if (setOptions.gradeIndividually) {
            if (!$(this).parent().hasClass(options.containers.matches.container.css.correct) && !$(this).parent().hasClass(options.containers.matches.container.css.incorrect)) {
              if (!$(this).parent().hasClass(options.containers.matches.container.css.selected)) {
                $(this).parent().addClass(options.containers.matches.container.css.selected);
              } else {
                if ($(this).parent().hasClass(options.containers.matches.container.css.selected) && setOptions.allowRetry) {
                  $(this).parent().removeClass(options.containers.matches.container.css.selected);
                }
              }
              shouldRecalculate = true;
            }
          } else {
            if (setOptions.allowRetry || (!setOptions.allowRetry && setOptions.attempts == 0)) {
              if (!$(this).parent().hasClass(options.containers.matches.container.css.correct) && !$(this).parent().hasClass(options.containers.matches.container.css.incorrect)) {
                if (!$(this).parent().hasClass(options.containers.matches.container.css.selected)) {
                  $(this).parent().addClass(options.containers.matches.container.css.selected);
                } else {
                  if ($(this).parent().hasClass(options.containers.matches.container.css.selected)) {
                    $(this).parent().removeClass(options.containers.matches.container.css.selected);
                  }
                }
                shouldRecalculate = true;
              }
            }
          }
          options.accessibility.hasFocus = true;
          $(target).data("matchingActivity:options", options);
          if (shouldRecalculate) {
            calculateActivityScore(target, options);
          }
        }
      });
    }

    function getSetContainers(target, options) {
      return $(options.containers.matchset.reference).children("." + options.containers.set.css.identifier) || [];
    }

    function getActiveSetContainer(target, options) {
      return $(options.containers.matchset.reference).children("."+options.containers.set.css.identifier).filter("."+options.containers.set.css.selected)[0] || null;
    }

    function getMatches(target, options) {
      var activeSetContainer = getActiveSetContainer(target, options);
      return $(activeSetContainer).children("." + options.containers.matches.container.css.identifier) || [];
    }

    function getMatchesInSet(target, options, setContainer) {
      return $(setContainer).children("." + options.containers.matches.container.css.identifier) || [];
    }

    function clearMatchesHover(target, options, matches) {
      if (!matches) {
        matches = getMatches(target, options);
      }
      var matchset = null;
      for (var i = 0; i < matches.length; i++) {
        matchset = matches[i];
        $(matchset).removeClass(options.containers.matches.container.css.hover);
      }
    }

    function focusMatchSetInSet(target, options, setContainer, id, row, column, selectmatchset) {
      log(target, options, "Focusing matchset:{id:" + id + ",row:" + row + ",column:" + column + "}", "info");
      var matches = getMatchesInSet(target, options, setContainer);
      var matchset = null;
      var matchsetOptions = null;
      selectmatchset = selectmatchset || false;
      clearMatchesHover(target, options, matches);
      for (var i = 0; i < matches.length; i++) {
        matchset = matches[i];
        matchsetOptions = $(matchset).data("matchingActivity:matchset");
        if (id == matchsetOptions.id) {
          $(matchset).children("." + options.containers.matches.overlay.css.identifier).trigger("mouseover");
          if (selectmatchset) {
            $(matchset).children("." + options.containers.matches.overlay.css.identifier).trigger("click");
          }
        } else {
          if (row == matchsetOptions.row && column == matchsetOptions.column) {
            $(matchset).children("." + options.containers.matches.overlay.css.identifier).trigger("mouseover");
            if (selectmatchset) {
              $(matchset).children("." + options.containers.matches.overlay.css.identifier).trigger("click");
            }
          } else {
            $(matchset).children("." + options.containers.matches.overlay.css.identifier).trigger("mouseout");
          }
        }
      }
    }

    function clearSelectedMatchesInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var matches = getMatchesInSet(target, options, setContainer);
      var matchset = null;
      for (var i = 0; i < matches.length; i++) {
        matchset = matches[i];
        $(matchset).removeClass(options.containers.matches.container.css.selected);
      }
    }

    function clearSelectedMatches(target, options, matches) {
      matches = matches || getMatches(target, options);
      var matchset = null;
      for (var i = 0; i < matches.length; i++) {
        matchset = matches[i];
        $(matchset).removeClass(options.containers.matches.container.css.selected);
      }
    }

    function registerKeyboardEvents(target, options, matches) {
      $(document).keydown(function(event) {
        var options = $(target).data("matchingActivity:options");
        if (options.data.enabled && options.accessibility.keyboard.allow && options.accessibility.hasFocus) {
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("matchingActivity:set");
          switch(event.keyCode) {
            case 38:
              if (activeSetData.focusedmatchsetRow - 1 >= 0) {
                focusMatchSetInSet(target, options, activeSet, null, activeSetData.focusedmatchsetRow - 1, activeSetData.focusedmatchsetColumn);
              }
              break;
            case 40:
              if (activeSetData.focusedmatchsetRow + 1 < activeSetData.rows) {
                focusMatchSetInSet(target, options, activeSet, null, activeSetData.focusedmatchsetRow + 1, activeSetData.focusedmatchsetColumn);
              }
              break;
            case 37:
              if (activeSetData.focusedmatchsetColumn - 1 >= 0) {
                focusMatchSetInSet(target, options, activeSet, null, activeSetData.focusedmatchsetRow, activeSetData.focusedmatchsetColumn - 1);
              }
              break;
            case 39:
              if (activeSetData.focusedmatchsetColumn + 1 < activeSetData.columns) {
                focusMatchSetInSet(target, options, activeSet, null, activeSetData.focusedmatchsetRow, activeSetData.focusedmatchsetColumn + 1);
              }
              break;
            case 32:
              focusMatchSetInSet(target, options, activeSet, null, activeSetData.focusedmatchsetRow, activeSetData.focusedmatchsetColumn, true);
              break;
            case 13:
              calculateActivityScore(target, options);
              break;
          }
        }
      });
    }

    function registerPseudoMouseEvents(target, options, matches) {
      var pseudoMice = options.accessibility.pseudoMouse.mice;
      var mouse = null;
      var offset = null;
      var width = null;
      var height = null;
      var container = null;
      var found = false;
      for (var i = 0; i < pseudoMice.length; i++) {
        mouse = pseudoMice[i];
        $(mouse).bind("mousemove", function(event) {
          var options = $(target).data("matchingActivity:options");
          if (options.data.enabled) {
            var event2 = new $.Event("mousemove");
            event2.pageX = event.pageX;
            event2.pageY = event.pageY;
            $(target).trigger(event2);
          }
          options = $(target).data("matchingActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            var activeSet = getActiveSetContainer(target, options);
            var matches = getMatchesInSet(target, options, activeSet);
            for (var j = 0; j < matches.length; j++) {
              found = false;
              container = $(matches[j]).children("." + options.containers.matches.overlay.css.identifier).first();
              offset = $(container).offset();
              if ($(container).hasClass(options.containers.matches.container.css.hover)) {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      found = true;
                    }
                  }
                }
                if (!found) {
                  $(container).trigger("mouseout");
                }
              } else {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      $(container).trigger("mouseover");
                    }
                  }
                }
              }
            }
          }
        });
        $(mouse).bind("mouseup", function(event) {
          var options = $(target).data("matchingActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            container = null;
            for (var j = 0; j < matches.length; j++) {
              container = $(matches[j]).children("." + options.containers.matches.overlay.css.identifier).first();
              offset = $(container).offset();
              width = $(container).width();
              height = $(container).height();
              if (event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
                $(container).trigger("click");
              }
            }
          }
        });
      }
    }

    function parseXMLAndBuildActivity(target, options, data) {
      log(target, options, "Parsing Activity XML", "info");
      try {
        if (window.ActiveXObject) {
          var doc = new ActiveXObject("Microsoft.XMLDOM");
          doc.loadXML(data);
          data = doc;
        } else {
          if (window.DOMParser) {
            data = (new DOMParser).parseFromString(data, "text/xml");
          }
        }
      } catch(error) {
        data = null;
        log(target, options, "XML Parse Error:{error:" + error + "}", "error");
      }
      if (data) {
        var activityData = {
          allowRetry : true,
          randomizeOnRetry : true,
          gradeSetsIndividually : false,
          dataSets : []
        };
        var idIndex = 0;
        var dataSet = null;
        var matchset = null;
        if ($(data).children("matchingActivity").attr("retry")) {
          activityData.allowRetry = ($(data).children("matchingActivity").attr("retry").toLowerCase() == "true") ? true : false;
        }
        if ($(data).children("matchingActivity").attr("randomizeOnRetry")) {
          activityData.randomizeOnRetry = ($(data).children("matchingActivity").attr("randomizeOnRetry").toLowerCase() == "true") ? true : false;
        }
        $(data).children("matchingActivity").children("set").each(function() {
          dataSet = {
            id : $(this).attr("id"),
            allowRetry : false,
            showFeedback : true,
            gradeIndividually : true,
            autoComplete : false,
            title : $(this).children("title:first").text(),
            rows : parseInt($(this).attr("rows")),
            columns : parseInt($(this).attr("columns")),
            matches : []
          };
          if ($(this).children("title:first").attr("encoding")) {
            dataSet.title = unescape(dataSet.title.replace(/\+/g, " "));
          }
          $(this).children("matches").children("matchset").each(function() {
            matchset = {
              id : $(this).attr("id"),
              left : $(this).children("left").text(),
              right : $(this).children("right").text(),
              value : parseFloat($(this).attr("value"))
            };
            if ($(this).children("left").attr("encoding")) {
              matchset.left = unescape(matchset.left.replace(/\+/g, " "));
            }
            if ($(this).children("right").attr("encoding")) {
              matchset.right = unescape(matchset.right.replace(/\+/g, " "));
            }
            dataSet.matches.push(matchset);
          });
          activityData.dataSets.push(dataSet);
        });
        buildActivity(target, options, activityData);
      } else {
        log(target, options, "XML Activity Build Error:{error:No data to build activity}", "error");
      }
    }

    function loadXMLAndBuildActivity(target, options, url) {
      log(target, options, "Loading XML", "info");
      $.ajax({
        url : url,
        dataType : "text",
        success : function(data, textStatus, xhr) {
          var options = $(target).data("matchingActivity:options");
          log(target, options, "XML Loaded", "info");
          parseXMLAndBuildActivity(target, options, data);
        },
        error : function(xhr, textStatus, errorThrown) {
          log(target, options, "XML Load Error:{textStatus:" + textStatus + ",errorThrown:" + errorThrown + "}", "error");
        }
      });
    }

    function buildActivity(target, options, activityData) {
      var dataSet = null;
      var matchsetDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.matchset.reference);
      var currentmatchset = null;
      var matches = [];
      var currentRow = 0;
      var currentColumn = 0;
      var matchset = null;
      var setContainer = null;
      options.data.allowRetry = activityData.allowRetry;
      options.data.randomizeOnRetry = activityData.randomizeOnRetry;
      options.data.gradeSetsIndividually = activityData.gradeSetsIndividually;
      if (options.data.overridePoints || options.data.overridePoints == 0) {
        var totalCorrectPoints = 0;
        $.each(activityData.dataSets, function(i, dataSet) {
          $.each(dataSet.matches, function(j, matchSet) {
            if (matchSet.value > 0) {
              totalCorrectPoints += matchSet.value;
            }
          });
        });
        if (totalCorrectPoints == 0 || options.data.overridePoints == 0) {
          totalCorrectPoints = 0;
          $.each(activityData.dataSets, function(i, dataSet) {
            $.each(dataSet.matches, function(j, matchSet) {
              if (options.data.overridePoints > 0) {
                matchSet.value = 1;
                totalCorrectPoints += matchSet.value;
              } else {
                matchSet.value = 0;
              }
            });
          });
        }
        var factor = options.data.overridePoints / totalCorrectPoints;
        $.each(activityData.dataSets, function(i, dataSet) {
          $.each(dataSet.matches, function(j, matchSet) {
            matchSet.value = matchSet.value * factor;
          });
        });
      }
      for (var i = 0; i < activityData.dataSets.length; i++) {
        dataSet = $.extend({}, activityData.dataSets[i], {
          matches : [],
          attempts : 0,
          currentMatchIndicator : 0,
          focusedmatchsetId : null,
          focusedmatchsetRow : -1,
          focusedmatchsetColumn : -1,
          completed : false
        });
        options.data.dataSets.push(dataSet);
        matchsetDimensions = calculateMatchSetDimensions(target, options, dataSet.rows, dataSet.columns);
        currentRow = 0;
        currentColumn = 0;
        matchset = null;
        num_of_matches = activityData.dataSets[i].matches.length;
        for (var j = 0; j < num_of_matches; j++) {
          matchset = activityData.dataSets[i].matches[j];
          currentmatchset = createMatchSetContainer(target, options, matchset.left);
          $(currentmatchset).data("matchingActivity:matchset", {
            id : parseInt(matchset.id),
            row : currentRow,
            column : currentColumn,
            value : matchset.value,
            pairID : matchset.id,
            matchIndicator : null,
            correct : false
          });
          registerMatchSetEvents(target, options, currentmatchset);
          dataSet.matches.push(currentmatchset);
          matches.push(currentmatchset);
          currentColumn++;
          if (currentColumn >= dataSet.columns) {
            currentColumn = 0;
            currentRow++;
          }
          currentmatchset = createMatchSetContainer(target, options, matchset.right);
          newID = parseInt(matchset.id) + num_of_matches;
          $(currentmatchset).data("matchingActivity:matchset", {
            id : newID,
            row : currentRow,
            column : currentColumn,
            value : matchset.value,
            pairID : matchset.id
          });
          registerMatchSetEvents(target, options, currentmatchset);
          dataSet.matches.push(currentmatchset);
          matches.push(currentmatchset);
          currentColumn++;
          if (currentColumn >= dataSet.columns) {
            currentColumn = 0;
            currentRow++;
          }
        }
        setContainer = createSetContainer(target, options);
        options.containers.set.references.push(setContainer);
        $(setContainer).data("matchingActivity:set", dataSet);
        $(options.containers.matchset.reference).append(setContainer);
        for (var j = 0; j < dataSet.matches.length; j++) {
          $(setContainer).append(dataSet.matches[j]);
        }
        resizeMatches(target, options, matchsetDimensions.width, matchsetDimensions.height, dataSet.matches);
        randomizeMatchSetPositionsInSet(target, options, setContainer);
        positionMatches(target, options, dataSet.matches);
        alignMatches(target, options, dataSet.matches);
      }
      registerAccessibilityEvents(target, options, matches);
      enableDisable(target, options, matches);
      $(target).data("matchingActivity:options", options);
      alignSets(target, options);
      showSet(target, options, activityData.dataSets[0].id);
      calculateActivityScore(target, options, false);
      $(target).trigger("activityLoaded.matchingActivity", [options.data.dataSets.length, 0, options.data.allowRetry, options.data.gradeSetsIndividually]);
    }

    function createSetContainer(target, options) {
      return $("<div />").addClass(options.containers.set.css.identifier);
    }

    function showSet(target, options, id, setContainers, reset, resetPosition) {
      setContainers = setContainers || getSetContainers(target, options);
      reset = reset || false;
      resetPosition = resetPosition || false;
      var setContainer = null;
      var setContainerData = null;
      var selectedSetContainerData = null;
      var selectedSetContainer = null;
      var setPosition = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("matchingActivity:set");
        $(setContainer).removeClass(options.containers.set.css.selected);
        if (setContainerData.id == id) {
          setPosition = i;
          selectedSetContainerData = setContainerData;
          selectedSetContainer = setContainer;
          $(setContainer).addClass(options.containers.set.css.selected);
        }
      }
      var matches = getMatches(target, options);
      positionMatches(target, options, matches);
      alignMatches(target, options, matches);
      if (reset && selectedSetContainerData) {
        options.data.enabled = true;
        enableDisable(target, options, matches);
        $(target).data("matchingActivity:data", options);
      }
      if (resetPosition) {
        var width = $(options.containers.matchset.reference).outerWidth();
        var finalPosition = -(width * [id]);
        $(options.containers.matchset.reference).css("left", finalPosition + "px");
      }
      $(target).trigger("titleChanged.matchingActivity", [selectedSetContainerData.title]);
      $(target).trigger("setChanged.matchingActivity", [setContainers.length, setPosition, options.data.gradeSetsIndividually, options.data.allowRetry, selectedSetContainerData.completed, options.data.enabled]);
    }

    function showNextSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          if (setContainers[i] == currentSetContainer && i < setContainers.length - 1) {
            var width = $(options.containers.matchset.reference).outerWidth();
            var finalPosition = -(width * [i + 1]);
            if (options.data.animate) {
              $(options.containers.matchset.reference).stop(true, false).addClass(options.containers.matchset.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.matchset.css.animating);
              });
            } else {
              $(options.containers.matchset.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i + 1]).data("matchingActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function showPreviousSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          $(setContainers[i]).stop(true, true);
          if (setContainers[i] == currentSetContainer && i > 0) {
            var width = $(options.containers.matchset.reference).outerWidth();
            var finalPosition = -(width * [i - 1]);
            if (options.data.animate) {
              $(options.containers.matchset.reference).stop(true, false).addClass(options.containers.matchset.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.matchset.css.animating);
              });
            } else {
              $(options.containers.matchset.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i - 1]).data("matchingActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function getSetState(target, options, setContainer) {
      var setContainerData = $(setContainer).data("matchingActivity:set");
      var setState = {
        id : setContainerData.id,
        allowRetry : setContainerData.allowRetry,
        showFeedback : setContainerData.showFeedback,
        gradeIndividually : setContainerData.gradeIndividually,
        attempts : setContainerData.attempts,
        completed : setContainerData.completed,
        matches : []
      };
      var setmatches = getMatchesInSet(target, options, setContainer);
      var matchset = null;
      var matchsetOptions = null;
      var normalizedmatchsetData = null;
      for (var i = 0; i < setmatches.length; i++) {
        matchset = setmatches[i];
        matchsetOptions = $(matchset).data("matchingActivity:matchset");
        normalizedmatchsetData = {
          id : matchsetOptions.id,
          row : matchsetOptions.row,
          column : matchsetOptions.column,
          correct : matchsetOptions.correct,
          value : matchsetOptions.value / 2,
          pairID : matchsetOptions.pairID,
          matchIndicator : matchsetOptions.matchIndicator,
          selected : $(matchset).hasClass(options.containers.matches.container.css.selected),
          finished : $(matchset).hasClass(options.containers.matches.container.css.correct) || $(matchset).hasClass(options.containers.matches.container.css.incorrect) || false
        };
        setState.matches.push(normalizedmatchsetData);
      }
      return setState;
    }

    function setSetState(target, options, setContainer, setState) {
      log(target, options, "Setting Set State:" + setState.id);
      var setContainerData = $(setContainer).data("matchingActivity:set");
      setContainerData.allowRetry = setState.allowRetry;
      setContainerData.showFeedback = setState.showFeedback;
      setContainerData.gradeIndividually = setState.gradeIndividually;
      setContainerData.attempts = setState.attempts;
      setContainerData.completed = setState.completed;
      $(setContainer).data("matchingActivity:set", setContainerData);
      if (setContainerData.completed && !$(setContainer).hasClass(options.containers.set.css.completed)) {
        $(setContainer).addClass(options.containers.set.css.completed);
      }
      var setmatches = getMatchesInSet(target, options, setContainer);
      var matchset = null;
      var matchsetOptions = null;
      var normalizedmatchsetData = null;
      for (var i = 0; i < setmatches.length; i++) {
        matchset = setmatches[i];
        matchsetOptions = $(matchset).data("matchingActivity:matchset");
        for (var j = 0; j < setState.matches.length; j++) {
          normalizedmatchsetData = setState.matches[j];
          if ((normalizedmatchsetData.id == matchsetOptions.id)) {
            matchsetOptions.row = normalizedmatchsetData.row;
            matchsetOptions.column = normalizedmatchsetData.column;
            matchsetOptions.correct = normalizedmatchsetData.correct;
            matchsetOptions.value = normalizedmatchsetData.value * 2;
            matchsetOptions.pairID = normalizedmatchsetData.pairID;
            matchsetOptions.matchIndicator = normalizedmatchsetData.matchIndicator;
            $(matchset).removeClass(options.containers.matches.container.css.selected);
            if (normalizedmatchsetData.selected) {
              $(matchset).addClass(options.containers.matches.container.css.selected);
            }
            if (normalizedmatchsetData.finished) {
              if (normalizedmatchsetData.correct) {
                $(matchset).addClass(options.containers.matches.container.css.correct);
              } else {
                $(matchset).addClass(options.containers.matches.container.css.incorrect);
              }
              if (normalizedmatchsetData.matchIndicator) {
                $(matchset).find("." + options.containers.matches.pairIndicator.css.identifier).text(normalizedmatchsetData.matchIndicator);
              }
            }
          }
        }
        $(matchset).data("matchingActivity:matchset", matchsetOptions);
      }
    }

    function calculateActivityScore(target, options, incrementAttempts, autoCompleteOverride, doNotUpdateExternalScore) {
      incrementAttempts = incrementAttempts || true;
      autoCompleteOverride = autoCompleteOverride || false;
      doNotUpdateExternalScore = doNotUpdateExternalScore || false;
      var matchesets = getSetContainers(target, options);
      var activeSet = getActiveSetContainer(target, options);
      var setScore = null;
      var setScores = [];
      var calculatedScore = 0;
      var calculatedPossible = 0;
      var totalCorrect = 0;
      var totalIncorrect = 0;
      var correctSelected = 0;
      var incorrectSelected = 0;
      var totalPossibleSelected = 0;
      for (var i = 0; i < matchesets.length; i++) {
        if (matchesets[i] == activeSet) {
          activeSetPosition = i;
        }
        if (options.data.gradeSetsIndividually && matchesets[i] == activeSet) {
          setScore = calculateSetScore(target, options, matchesets[i], incrementAttempts, autoCompleteOverride);
        } else {
          if (options.data.gradeSetsIndividually && matchesets[i] != activeSet) {
            setScore = calculateSetScore(target, options, matchesets[i], false, false);
          } else {
            setScore = calculateSetScore(target, options, matchesets[i], incrementAttempts, autoCompleteOverride);
          }
        }
        log(target, options, "Set Score: " + setScore.calculatedScore + "/" + setScore.calculatedPossible);
        calculatedScore += setScore.calculatedScore;
        calculatedPossible += setScore.calculatedPossible;
        totalCorrect += setScore.totalCorrect;
        totalIncorrect += setScore.totalIncorrect;
        correctSelected += setScore.correctSelected;
        incorrectSelected += setScore.incorrectSelected;
        totalPossibleSelected += setScore.totalPossibleSelected;
        $(target).trigger("setScoreChanged.matchingActivity", [options.data.dataSets.length, i, options.data.allowRetry, options.data.gradeSetsIndividually, setScore.calculatedScore, setScore.calculatedPossible, $(matchesets[i]).data("matchingActivity:set").completed, doNotUpdateExternalScore]);
      }
      log(target, options, "Score Recalculated:" + calculatedScore + "/" + calculatedPossible, "info");
      $(target).trigger("activityScoreChanged.matchingActivity", [options.data.dataSets.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually, calculatedScore, calculatedPossible, $(activeSet).data("matchingActivity:set").completed, doNotUpdateExternalScore]);
      if (totalPossibleSelected == (correctSelected + incorrectSelected)) {
        options.data.enabled = false;
        $(target).data("matchingActivity:options", options);
        enableDisable(target, options);
        log(target, options, "Activity Completed:" + calculatedScore + "/" + calculatedPossible, "info");
        $(target).trigger("activityComplete.matchingActivity", [options.data.dataSets.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually, calculatedScore, calculatedPossible, doNotUpdateExternalScore]);
      }
      return {
        calculatedScore : calculatedScore,
        calculatedPossible : calculatedPossible,
        totalCorrect : totalCorrect,
        totalIncorrect : totalIncorrect,
        correctSelected : correctSelected,
        incorrectSelected : incorrectSelected
      };
    }

    function calculateSetScore(target, options, setContainer, incrementAttempts, autoCompleteOverride) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      incrementAttempts = incrementAttempts || true;
      autoCompleteOverride = autoCompleteOverride || false;
      var setData = $(setContainer).data("matchingActivity:set");
      var itemsSelected = 0;
      var firstSelected = null;
      var firstSelectedData = null;
      for (var i = 0; i < setData.matches.length; i++) {
        matchset = setData.matches[i];
        matchsetData = $(matchset).data("matchingActivity:matchset");
        if ($(matchset).hasClass(options.containers.matches.container.css.selected)) {
          itemsSelected++;
          if (itemsSelected == 1) {
            firstSelected = matchset;
            firstSelectedData = matchsetData;
          }
          if (itemsSelected == 2) {
            itemsSelected = 0;
            if (firstSelectedData.pairID == matchsetData.pairID) {
              setData.currentMatchIndicator++;
              firstSelectedData.correct = true;
              matchsetData.correct = true;
              firstSelectedData.matchIndicator = setData.currentMatchIndicator;
              matchsetData.matchIndicator = setData.currentMatchIndicator;
              $(matchset).data("matchingActivity:matchset", matchsetData);
              $(firstSelected).data("matchingActivity:matchset", firstSelectedData);
              $(matchset).find("." + options.containers.matches.pairIndicator.css.identifier).text(setData.currentMatchIndicator);
              $(firstSelected).find("." + options.containers.matches.pairIndicator.css.identifier).text(setData.currentMatchIndicator);
              if ($(matchset).hasClass(options.containers.matches.container.css.hover)) {
                $(matchset).removeClass(options.containers.matches.container.css.hover);
              }
              if ($(firstSelected).hasClass(options.containers.matches.container.css.hover)) {
                $(firstSelected).removeClass(options.containers.matches.container.css.hover);
              }
            } else {
              setData.currentMatchIndicator++;
              firstSelectedData.correct = false;
              matchsetData.correct = false;
              firstSelectedData.matchIndicator = setData.currentMatchIndicator;
              matchsetData.matchIndicator = setData.currentMatchIndicator;
              $(matchset).data("matchingActivity:matchset", matchsetData);
              $(firstSelected).data("matchingActivity:matchset", firstSelectedData);
              $(matchset).find("." + options.containers.matches.pairIndicator.css.identifier).text(setData.currentMatchIndicator);
              $(firstSelected).find("." + options.containers.matches.pairIndicator.css.identifier).text(setData.currentMatchIndicator);
              if ($(matchset).hasClass(options.containers.matches.container.css.hover)) {
                $(matchset).removeClass(options.containers.matches.container.css.hover);
              }
              if ($(firstSelected).hasClass(options.containers.matches.container.css.hover)) {
                $(firstSelected).removeClass(options.containers.matches.container.css.hover);
              }
            }
          }
        }
      }
      $(setContainer).data("matchingActivity:set", setData);
      if (setData.gradeIndividually) {
        if (setData.showFeedback) {
          showCorrectAndIncorrect(target, options, setContainer, true);
        }
      } else {
        if (setData.autoComplete && scoreResults.totalCorrect == scoreResults.correctSelected) {
          setData.completed = true;
          if (setData.showFeedback) {
            showCorrectAndIncorrect(target, options, setContainer, false);
          }
          if (incrementAttempts) {
            setData.attempts++;
          }
        } else {
          clearCorrectAndIncorrectInSet(target, options, setContainer);
          if (!setData.completed) {
            scoreResults.calculatedScore = 0;
          } else {
            if (setData.showFeedback) {
              showCorrectAndIncorrect(target, options, setContainer, false);
            }
          }
        }
      }
      $(setContainer).data("matchingActivity:set", setData);
      var setState = getSetState(target, options, setContainer);
      var scoreResults = options.data.calculateScore(setState);
      return scoreResults;
    }

    function showCorrectAndIncorrect(target, options, setContainer, showOnlySelected) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      showOnlySelected = showOnlySelected || true;
      var setData = $(setContainer).data("matchingActivity:set");
      if (options.data.enabled) {
        var matches = getMatchesInSet(target, options, setContainer);
        var matchset = null;
        var matchsetOptions = null;
        var showmatchset = false;
        var itemsSelected = 0;
        var allowWrongAnswers = true;
        for (var i = 0; i < matches.length; i++) {
          matchset = matches[i];
          matchsetOptions = $(matchset).data("matchingActivity:matchset");
          showmatchset = false;
          if (showOnlySelected && $(matchset).hasClass(options.containers.matches.container.css.selected)) {
            showmatchset = true;
          } else {
            if (!showOnlySelected) {
              showmatchset = true;
            }
          }
          if ($(matchset).hasClass(options.containers.matches.container.css.selected)) {
            itemsSelected++;
            if (itemsSelected == 1) {
              firstSelectedContainer = $(matchset);
              firstSelected = matchsetOptions;
            }
            if (itemsSelected == 2) {
              itemsSelected = 0;
              if (firstSelected.pairID == matchsetOptions.pairID) {
                firstSelectedContainer.removeClass(options.containers.matches.container.css.selected);
                $(matchset).removeClass(options.containers.matches.container.css.selected);
                firstSelectedContainer.addClass(options.containers.matches.container.css.correct);
                $(matchset).addClass(options.containers.matches.container.css.correct);
              } else {
                if (allowWrongAnswers) {
                  firstSelectedContainer.removeClass(options.containers.matches.container.css.selected);
                  $(matchset).removeClass(options.containers.matches.container.css.selected);
                  firstSelectedContainer.addClass(options.containers.matches.container.css.incorrect);
                  $(matchset).addClass(options.containers.matches.container.css.incorrect);
                } else {
                  firstSelectedContainer.removeClass(options.containers.matches.container.css.selected);
                  $(matchset).removeClass(options.containers.matches.container.css.selected);
                }
              }
            }
          }
        }
      }
    }

    function clearCorrectAndIncorrect(target, options, matches, showOnlySelected) {
      matches = matches || getMatches(target, options);
      showOnlySelected = showOnlySelected || true;
      if (options.data.enabled) {
        var matchset = null;
        var showmatchset = false;
        for (var i = 0; i < matches.length; i++) {
          matchset = matches[i];
          $(matchset).removeClass(options.containers.matches.container.css.incorrect);
          $(matchset).removeClass(options.containers.matches.container.css.correct);
        }
      }
    }

    function clearIndicators(target, options, matches) {
      matches = matches || getMatches(target, options);
      if (options.data.enabled) {
        var matchset = null;
        for (var i = 0; i < matches.length; i++) {
          matchset = matches[i];
          $(matchset).find("." + options.containers.matches.pairIndicator.css.identifier).text("");
        }
      }
    }

    function clearCorrectAndIncorrectInSet(target, options, setContainer, showOnlySelected) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      showOnlySelected = showOnlySelected || true;
      matches = getMatchesInSet(target, options, setContainer);
      var matchset = null;
      var showmatchset = false;
      for (var i = 0; i < matches.length; i++) {
        matchset = matches[i];
        $(matchset).removeClass(options.containers.matches.container.css.incorrect);
        $(matchset).removeClass(options.containers.matches.container.css.correct);
      }
    }

    function alignMatches(target, options, matches) {
      matches = matches || getMatches(target, options);
      if (matches) {
        var matchset = null;
        var matchsetContent = null;
        var matchsetIndicator = null;
        var matchsetOptions = null;
        for (var i = 0; i < matches.length; i++) {
          matchset = matches[i];
          matchsetContent = $(matchset).children("." + options.containers.matches.content.css.identifier + ":first");
          matchsetIndicator = $(matchset).children("." + options.containers.matches.pairIndicator.css.identifier + ":first");
          alignToParent(target, options, options.containers.matches.content.horizontalAlign, options.containers.matches.content.verticalAlign, matchsetContent);
          alignToParent(target, options, options.containers.matches.pairIndicator.horizontalAlign, options.containers.matches.pairIndicator.verticalAlign, matchsetIndicator);
        }
      }
    }

    function alignSets(target, options, setContainers) {
      setContainers = setContainers || getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var setWidth = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("matchingActivity:set");
        setWidth = $(setContainer).width();
        $(setContainer).css("left", (setWidth * setContainerData.id) + "px");
      }
    }

    function alignToParent(target, options, horizontalAlign, verticalAlign, container) {
      $(container).css("position", "absolute");
      if (horizontalAlign) {
        switch(horizontalAlign.toLowerCase()) {
          case"left":
            $(container).css("right", null).css("left", "0px");
            break;
          case"right":
            $(container).css("left", null).css("right", "0px");
            break;
          case"center":
            $(container).css("right", null).css("left", ($(container).parent().innerWidth() / 2 - $(container).outerWidth() / 2) + "px");
            break;
        }
      }
      if (verticalAlign) {
        switch(verticalAlign.toLowerCase()) {
          case"top":
            $(container).css("bottom", null).css("top", "0px");
            break;
          case"bottom":
            $(container).css("top", null).css("bottom", "0px");
            break;
          case"middle":
            $(container).css("bottom", null).css("top", ($(container).parent().innerHeight() / 2 - $(container).outerHeight() / 2) + "px");
            break;
        }
      }
    }

    function resetActivity(target, options) {
      if (options.data.allowRetry) {
        log(target, options, "Resetting Activity", "info");
        var setContainers = getSetContainers(target, options);
        var activeSet = getActiveSetContainer(target, options);
        var activeSetPosition = 0;
        var setContainer = null;
        var setContainerData = null;
        var matches = null;
        var calculatedScore = 0;
        var calculatedPossible = 0;
        var setScore = null;
        options.data.enabled = true;
        for (var i = 0; i < setContainers.length; i++) {
          setContainer = setContainers[i];
          setContainerData = $(setContainer).data("matchingActivity:set");
          if (setContainer == activeSet) {
            activeSetPosition = i;
          }
          if ((options.data.gradeSetsIndividually && setContainer == activeSet) || !options.data.gradeSetsIndividually) {
            setContainerData.attempts = 0;
            setContainerData.currentMatchIndicator = 0;
            setContainerData.focusedmatchsetId = null;
            setContainerData.focusedmatchsetRow = -1;
            setContainerData.focusedmatchsetColumn = -1;
            $(setContainer).data("matchingActivity:set", setContainerData);
            matches = getMatchesInSet(target, options, setContainer);
            clearMatchesHover(target, options, matches);
            clearCorrectAndIncorrectInSet(target, options, setContainer);
            clearSelectedMatches(target, options, matches);
            clearIndicators(target, options, matches);
            setScore = calculateSetScore(target, options, setContainer);
            calculatedScore += setScore.calculatedScore;
            calculatedPossible += setScore.calculatedPossible;
            for (var j = 0; j < setContainerData.matches.length; j++) {
              matchset = setContainerData.matches[j];
              match = $(matchset).data("matchingActivity:matchset");
              match.correct = false;
              match.matchIndicator = null;
              $(matchset).data("matchingActivity:matchset", match);
            }
            if (options.data.randomizeOnRetry) {
              randomizeMatchSetPositionsInSet(target, options, setContainer);
              positionMatches(target, options, matches);
            }
          }
        }
        enableDisable(target, options);
        var setPosition = 0;
        if (options.data.randomizeOnRetry) {
          setPosition = Math.floor(Math.random() * setContainers.length);
        }
        setContainer = setContainers[setPosition];
        setContainerData = $(setContainer).data("matchingActivity:set");
        showSet(target, options, setContainerData.id, setContainers, false, true);
        activeSet = getActiveSetContainer(target, options);
        for (var i = 0; i < setContainers.length; i++) {
          setContainer = setContainers[i];
          setContainerData = $(setContainer).data("matchingActivity:set");
          if (setContainer == activeSet) {
            activeSetPosition = i;
          }
        }
        $(target).data("matchingActivity:options", options);
        $(target).trigger("reset.matchingActivity", [setContainers.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually]);
        calculateActivityScore(target, options, false);
      }
    }

    function getActiveSetContainerId(target, options) {
      return $(getActiveSetContainer(target, options)).data("matchingActivity:set").id || null;
    }

    function getActivityState(target, options) {
      var activityState = {
        enabled : options.data.enabled,
        allowRetry : options.data.allowRetry,
        randomizeOnRetry : options.data.randomizeOnRetry,
        activeSetId : getActiveSetContainerId(target, options),
        sets : []
      };
      var setContainers = getSetContainers(target, options);
      for (var i = 0; i < setContainers.length; i++) {
        activityState.sets.push(getSetState(target, options, setContainers[i]));
      }
      return activityState;
    }

    function setActivityState(target, options, activityState, completed) {
      log(target, options, "Setting Activity State");
      var setData = null;
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var matches = null;
      showSet(target, options, activityState.activeSetId, false, true);
      for (var i = 0; i < activityState.sets.length; i++) {
        setData = activityState.sets[i];
        for (var j = 0; j < setContainers.length; j++) {
          setContainer = setContainers[j];
          setContainerData = $(setContainer).data("matchingActivity:set");
          matches = getMatchesInSet(target, options, setContainer);
          if (setData.id == setContainerData.id) {
            setSetState(target, options, setContainer, setData);
          }
          positionMatches(target, options, matches);
        }
      }
      options.data.enabled = activityState.enabled;
      options.data.allowRetry = activityState.allowRetry;
      options.data.randomizeOnRetry = activityState.randomizeOnRetry;
      $(target).data("matchingActivity:options", options);
      enableDisable(target, options);
      calculateActivityScore(target, options, false, completed, true);
    }
    return this;
  };
  $.fn.matchingActivity.defaults = {};
  $.fn.matchingActivity.defaults.containers = {
    activity : {
      reference : null,
      css : {
        identifier : "softchalk-matching-activity"
      }
    },
    content : {
      reference : null,
      css : {
        identifier : "softchalk-matching-activity-content",
        enabled : "enabled",
        disabled : "disabled"
      }
    },
    matchset : {
      reference : null,
      css : {
        identifier : "softchalk-matching-activity-sets",
        animating : "animating"
      }
    },
    set : {
      references : [],
      css : {
        identifier : "softchalk-matching-activity-set",
        selected : "selected",
        completed : "completed"
      }
    },
    matches : {
      references : [],
      container : {
        css : {
          identifier : "softchalk-matching-activity-choice",
          selected : "selected",
          correct : "correct",
          incorrect : "incorrect",
          hover : "hover"
        }
      },
      content : {
        horizontalAlign : "center",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-matching-activity-choice-content"
        }
      },
      pairIndicator : {
        horizontalAlign : "left",
        verticalAlign : "top",
        css : {
          identifier : "softchalk-matching-activity-choice-pair-indicator"
        }
      },
      feedback : {
        css : {
          identifier : "softchalk-matching-activity-choice-feedback"
        }
      },
      feedbackIcon : {
        css : {
          identifier : "softchalk-matching-activity-choice-feedback-icon"
        }
      },
      overlay : {
        css : {
          identifier : "softchalk-matching-activity-choice-overlay"
        }
      }
    }
  };
  $.fn.matchingActivity.defaults.data = {
    dataSets : [],
    calculateScore : function(setState) {
      var calculatedCorrect = 0;
      var calculatedIncorrect = 0;
      var calculatedPossible = 0;
      var matchsetData = null;
      var matchsetData2 = null;
      var correctSelected = 0;
      var incorrectSelected = 0;
      var totalCorrect = setState.matches.length;
      var totalIncorrect = 0;
      var totalMatches = 0;
      for (var i = 0; i < setState.matches.length; i++) {
        matchsetData = setState.matches[i];
        totalMatches++;
        calculatedPossible += matchsetData.value;
        if (matchsetData.finished) {
          if (matchsetData.correct) {
            calculatedCorrect += matchsetData.value;
            correctSelected++;
          } else {
            calculatedIncorrect += matchsetData.value;
            incorrectSelected++;
          }
        }
      }
      var calculatedScore = calculatedCorrect;
      return {
        calculatedScore : calculatedScore,
        calculatedPossible : calculatedPossible,
        totalCorrect : totalCorrect,
        totalIncorrect : totalIncorrect,
        correctSelected : correctSelected,
        incorrectSelected : incorrectSelected,
        totalPossibleSelected : totalMatches
      };
    },
    enabled : true,
    enableLogging : false,
    allowRetry : true,
    randomizeOnRetry : true,
    animate : true,
    gradeSetsIndividually : false,
    overridePoints : null
  };
  $.fn.matchingActivity.defaults.accessibility = {
    pseudoMouse : {
      allow : false,
      mice : []
    },
    keyboard : {
      allow : true
    },
    hasFocus : false
  };
  $.fn.matchingActivity.defaults.logging = {
    debug : false,
    info : true,
    warn : false,
    error : false
  };
})(jQuery);
(function($) {
  $.fn.orderingActivity = function(action, options) {
    var shouldReturnResults = false;
    var results = [];
    var params = null;
    action = action || "initialize";
    if ( typeof (action) == "object") {
      options = action;
      action = "initialize";
    }
    if (action == "initialize") {
      if (!options) {
        options = $.fn.orderingActivity.defaults;
      } else {
        options = $.extend(true, {}, $.fn.orderingActivity.defaults, options);
      }
    } else {
      params = options;
    }
    var optionsReference = options;
    $(this).each(function() {
      switch(action) {
        case"initialize":
          log(this, optionsReference, "Action:Initializing Activity", "info");
          initialize(this, optionsReference);
          break;
        case"loadXMLAndBuildActivity":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Loading XML", "info");
          loadXMLAndBuildActivity(this, options, params);
          break;
        case"parseXMLAndBuildActivity":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Parsing XML", "info");
          parseXMLAndBuildActivity(this, options, params);
          break;
        case"calculateScore":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Calculating Score", "info");
          calculateScore(this, options);
          break;
        case"reset":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Resetting Activity", "info");
          resetActivity(this, options);
          break;
        case"finish":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Finishing Activity", "info");
          calculateActivityScore(this, options, true, true);
          break;
        case"showNextSet":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Showing Next Set", "info");
          showNextSet(this, options);
          break;
        case"showPreviousSet":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Showing Previous Set", "info");
          showPreviousSet(this, options);
          break;
        case"getState":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Getting Activity State", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getActivityState(this, options)
          });
          break;
        case"setState":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Setting Activity State", "info");
          setActivityState(this, options, params.state, params.completed);
          break;
        case"getEnabled":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Getting Enabled", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.enabled
          });
          break;
        case"setEnabled":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Setting Enabled", "info");
          options.data.enabled = params;
          $(this).data("orderingActivity:options", options);
          enableDisable(this, options);
          break;
        case"getSetIds":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Getting Set Ids", "info");
          var setContainers = getSetContainers(this, options);
          var setContainer = null;
          var setContainerData = null;
          var setIds = [];
          for (var i = 0; i < setContainers.length; i++) {
            setContainer = setContainers[i];
            setContainerData = $(setContainer).data("orderingActivity:set");
            setIds.push(setContainerData.id);
          }
          shouldReturnResults = true;
          results.push({
            target : this,
            result : setIds
          });
          break;
        case"getNumberOfSets":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getSetContainers(this, options).length
          });
          break;
        case"showSet":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          showSet(this, options, params);
          break;
        case"getAllowReset":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Getting allow reset", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.allowRetry
          });
          break;
        case"resize":
          var options = $(this).data("orderingActivity:options");
          log(this, options, "Action:Resizing the activity", "info");
          handleResize(this, options);
          break;
      }
    });
    if (shouldReturnResults == true) {
      return results;
    }
    function log(target, options, data, level) {
      level = level || "debug";
      level = $.trim(level).toLowerCase();
      if (options.data.enableLogging && window.console) {
        if (level == "info" && window.console.info && options.logging.info) {
          if ($(target).attr("id")) {
            window.console.info("[orderingActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
          } else {
            if ($(target).attr("name")) {
              window.console.info("[orderingActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
            } else {
              window.console.info("[orderingActivity][" + target + "]" + data);
            }
          }
        } else {
          if (level == "warn" && window.console.warn && options.logging.warn) {
            if ($(target).attr("id")) {
              window.console.warn("[orderingActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
            } else {
              if ($(target).attr("name")) {
                window.console.warn("[orderingActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
              } else {
                window.console.warn("[orderingActivity][" + target + "]" + data);
              }
            }
          } else {
            if (level == "error" && window.console.error && options.logging.error) {
              if ($(target).attr("id")) {
                window.console.error("[orderingActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
              } else {
                if ($(target).attr("name")) {
                  window.console.error("[orderingActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                } else {
                  window.console.error("[orderingActivity][" + target + "]" + data);
                }
              }
            } else {
              if (window.console.log && options.logging.debug) {
                if ($(target).attr("id")) {
                  window.console.log("[orderingActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
                } else {
                  if ($(target).attr("name")) {
                    window.console.log("[orderingActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                  } else {
                    window.console.log("[orderingActivity][" + target + "]" + data);
                  }
                }
              }
            }
          }
        }
      }
    }

    function initialize(target, options) {
      options = $.extend(true, {}, options);
      options.containers.activity.reference = target;
      $(options.containers.activity.reference).addClass(options.containers.activity.css.identifier);
      options.containers.content.reference = target;
      $(options.containers.content.reference).addClass(options.containers.content.css.identifier);
      if (options.containers.choice.reference == null) {
        options.containers.choice.reference = $("<div />");
        $(options.containers.content.reference).append(options.containers.choice.reference);
      }
      options.containers.choice.reference.addClass(options.containers.choice.css.identifier);
      $(target).data("orderingActivity:options", options);
    }

    function handleResize(target, options) {
      alignSets(target, options);
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var choices = null;
      var choiceDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("orderingActivity:set");
        choices = getChoicesInSet(target, options, setContainer);
        choiceDimensions = calculateChoiceDimensions(target, options, setContainerData.rows, setContainerData.columns);
        resizeChoices(target, options, choiceDimensions.width, choiceDimensions.height, choices);
        positionChoices(target, options, choices);
        alignChoices(target, options, choices);
      }
      log(target, options, "Activity Container Resized", "info");
    }

    function registerAccessibilityEvents(target, options, choices) {
      var handleMiceEvents = function(event) {
        var options = $(this).data("orderingActivity:options");
        if (options.data.enabled && event.pageX && event.pageY) {
          var offset = $(this).offset();
          var width = $(this).outerWidth();
          var height = $(this).outerHeight();
          if (!options.accessibility.hasFocus && event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
            options.accessibility.hasFocus = true;
            $(this).data("orderingActivity:options", options);
          } else {
            if (options.accessibility.hasFocus && (event.pageX < offset.left || event.pageX > offset.left + width || event.pageY < offset.top || event.pageY > offset.top + height)) {
              options.accessibility.hasFocus = false;
              $(this).data("orderingActivity:options", options);
            }
          }
        }
      };
      $(target).bind("mouseover", handleMiceEvents).bind("mouseout", handleMiceEvents).bind("mousemove", handleMiceEvents);
      $(target).bind("focusin", function(event) {
        var options = $(this).data("orderingActivity:options");
        if (options.data.enabled && !options.accessibility.hasFocus) {
          log(target, options, "Giving Focus", "info");
          options.accessibility.hasFocus = true;
          $(this).data("orderingActivity:options", options);
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("orderingActivity:set");
          if (activeSetData.focusedChoiceRow < 0 || activeSetData.focusedChoiceColumn < 0 || !activeSetData.focusedChoiceId) {
            focusChoiceInSet(target, options, activeSet, null, 0, 0, false);
          }
        }
      });
      $(target).bind("focusout", function(event) {
        var options = $(this).data("orderingActivity:options");
        if (options.data.enabled && options.accessibility.hasFocus) {
          options.accessibility.hasFocus = false;
          $(this).data("orderingActivity:options", options);
        }
      });
      if (options.accessibility.keyboard.allow) {
        registerKeyboardEvents(target, options, choices);
      }
      if (options.accessibility.pseudoMouse.allow) {
        registerPseudoMouseEvents(target, options, choices);
      }
    }

    function calculateChoiceDimensions(target, options, rows, columns) {
      var containerWidth = $(options.containers.choice.reference).width();
      var containerHeight = $(options.containers.choice.reference).height();
      var borderTestDiv = $("<div />").css("display", "none").addClass(options.containers.choices.container.css.identifier).width(100).height(100);
      $(target).append(borderTestDiv);
      var borderWidthOffset = ($(borderTestDiv).outerWidth() - $(borderTestDiv).innerWidth()) / 2;
      var borderHeightOffset = ($(borderTestDiv).outerHeight() - $(borderTestDiv).innerHeight()) / 2;
      $(borderTestDiv).remove();
      containerWidth -= borderWidthOffset + 2;
      containerHeight -= borderHeightOffset * (2 * rows);
      var choiceMaxWidth = containerWidth / columns;
      var choiceMaxHeight = containerHeight / rows;
      return {
        width : choiceMaxWidth,
        height : choiceMaxHeight
      };
    }

    function calculateContainerPadding(target, options, container) {
      var paddingTestDiv = $('<div style="padding:0px 0px 0px 0px;"/>');
      paddingTestDiv.css("padding-top", $(container).css("padding-top"));
      var paddingTop = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-top", "0px");
      paddingTestDiv.css("padding-right", $(container).css("padding-right"));
      var paddingRight = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-right", "0px");
      paddingTestDiv.css("padding-bottom", $(container).css("padding-bottom"));
      var paddingBottom = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-bottom", "0px");
      paddingTestDiv.css("padding-left", $(container).css("padding-left"));
      var paddingLeft = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-left", "0px");
      return {
        top : paddingTop,
        right : paddingRight,
        bottom : paddingBottom,
        left : paddingLeft
      };
    }

    function createChoiceContainer(target, options, contentHtml) {
      var choice = $("<div />").addClass(options.containers.choices.container.css.identifier).css("position", "absolute");
      var contentDiv = $("<div />").addClass(options.containers.choices.content.css.identifier);
      $(choice).append(contentDiv);
      var feedbackDiv = $("<div />").addClass(options.containers.choices.feedback.css.identifier);
      $(choice).append(feedbackDiv);
      var feedbackIconDiv = $("<div />").addClass(options.containers.choices.feedbackIcon.css.identifier);
      $(choice).append(feedbackIconDiv);
      var overlayDiv = $("<div />").addClass(options.containers.choices.overlay.css.identifier);
      $(choice).append(overlayDiv);
      var leftButtonDiv = $("<div />").addClass(options.containers.choices.leftButton.container.css.identifier);
      $(choice).append(leftButtonDiv);
      var leftButton = $("<div />").addClass(options.containers.choices.leftButton.button.css.identifier);
      $(leftButtonDiv).append(leftButton);
      var rightButtonDiv = $("<div />").addClass(options.containers.choices.rightButton.container.css.identifier);
      $(choice).append(rightButtonDiv);
      var rightButton = $("<div />").addClass(options.containers.choices.rightButton.button.css.identifier);
      $(rightButtonDiv).append(rightButton);
      if (contentHtml) {
        $(contentDiv).html(contentHtml);
      }
      return choice;
    }

    function enableDisable(target, options, choices) {
      log(target, options, "Enabling/Disabling Activity:" + options.data.enabled, "info");
      choices = choices || getChoices(target, options);
      if (options.data.enabled) {
        $(options.containers.content.reference).removeClass(options.containers.content.css.disabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.enabled);
        $(target).trigger("enabled.orderingActivity", [options.data.dataSets.length]);
      } else {
        $(options.containers.content.reference).removeClass(options.containers.content.css.enabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.disabled);
        clearChoicesHover(target, options, choices);
        $(target).trigger("disabled.orderingActivity", [options.data.dataSets.length]);
      }
    }

    function resizeChoices(target, options, width, height, choices) {
      choices = choices || getChoices(target, options);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).width(width);
        $(choice).height(height);
      }
    }

    function positionChoices(target, options, choices, containerPadding) {
      choices = choices || getChoices(target, options);
      containerPadding = containerPadding || calculateContainerPadding(target, options, options.containers.choice.reference);
      var choiceData = null;
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceData = $(choice).data("orderingActivity:choice");
        $(choice).css("left", (-containerPadding.left + $(choice).outerWidth() * choiceData.column) + "px");
        $(choice).css("top", (-containerPadding.top + $(choice).outerHeight() * choiceData.row) + "px");
      }
    }

    function randomizeChoicePositionsInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var setData = $(setContainer).data("orderingActivity:set");
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceData = null;
      var unpositionedChoices = [];
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceData = $(choice).data("orderingActivity:choice");
        choiceData.row = null;
        choiceData.column = null;
        $(choice).data("orderingActivity:choice", choiceData);
        unpositionedChoices.push(choice);
      }
      var choiceMatrix = [];
      var currentRow = 0;
      var currentColumn = 0;
      var currentRowArray = null;
      for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
        currentRowArray = [];
        for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
          currentRowArray.push(null);
        }
        choiceMatrix.push(currentRowArray);
      }
      var positioningChoice = null;
      var randomSelector = null;
      var found = false;
      while (unpositionedChoices.length > 0) {
        randomSelector = Math.floor(Math.random() * unpositionedChoices.length);
        choice = unpositionedChoices.splice(randomSelector, 1);
        choiceData = $(choice).data("orderingActivity:choice");
        found = false;
        for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
          for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
            if (!choiceMatrix[currentRow][currentColumn] && !found) {
              found = true;
              choiceMatrix[currentRow][currentColumn] = choice;
            }
          }
        }
        choice = null;
      }
      for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
        for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
          choice = choiceMatrix[currentRow][currentColumn];
          choiceData = $(choice).data("orderingActivity:choice");
          choiceData.row = currentRow;
          choiceData.column = currentColumn;
          $(choice).data("orderingActivity:choice", choiceData);
        }
      }
    }

    function registerChoiceEvents(target, options, choice) {
      $(choice).children("." + options.containers.choices.rightButton.container.css.identifier).bind("mouseover", function() {
        var options = $(target).data("orderingActivity:options");
        var choiceOptions = $(choice).data("orderingActivity:choice");
        var setOptions = $(choice).parent().data("orderingActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if (!$(this).hasClass(options.containers.choices.rightButton.container.css.hover)) {
            clearChoicesHover(target, options);
            $(this).addClass(options.containers.choices.rightButton.container.css.hover);
            setOptions.focusedChoiceId = choiceOptions.id;
            setOptions.focusedChoiceRow = choiceOptions.row;
            setOptions.focusedChoiceColumn = choiceOptions.column;
            $(choice).parent().data("orderingActivity:set", setOptions);
            options.accessibility.hasFocus = true;
            $(target).data("orderingActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.rightButton.container.css.identifier).bind("mouseout", function() {
        var options = $(target).data("orderingActivity:options");
        var choiceOptions = $(choice).data("orderingActivity:choice");
        var setOptions = $(choice).parent().data("orderingActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if ($(this).hasClass(options.containers.choices.rightButton.container.css.hover)) {
            $(this).removeClass(options.containers.choices.rightButton.container.css.hover);
            options.accessibility.hasFocus = true;
            $(target).data("orderingActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.rightButton.container.css.identifier).bind("click", function(event) {
        var options = $(target).data("orderingActivity:options");
        var choiceOptions = $(choice).data("orderingActivity:choice");
        var setOptions = $(choice).parent().data("orderingActivity:set");
        if (options.data.enabled && !setOptions.completed && !$(choice).hasClass(options.containers.choices.container.css.animating)) {
          var shouldRecalculate = false;
          moveChoice(target, options, null, $(this).parent(), 0, -1);
          if (setOptions.gradeIndividually) {
            shouldRecalculate = true;
          } else {
            if (setOptions.allowRetry || (!setOptions.allowRetry && setOptions.attempts == 0)) {
              shouldRecalculate = true;
            }
          }
          options.accessibility.hasFocus = true;
          $(target).data("orderingActivity:options", options);
          if (shouldRecalculate) {
            calculateActivityScore(target, options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.leftButton.container.css.identifier).bind("mouseover", function() {
        var options = $(target).data("orderingActivity:options");
        var choiceOptions = $(choice).data("orderingActivity:choice");
        var setOptions = $(choice).parent().data("orderingActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if (!$(this).hasClass(options.containers.choices.leftButton.container.css.hover)) {
            clearChoicesHover(target, options);
            $(this).addClass(options.containers.choices.leftButton.container.css.hover);
            setOptions.focusedChoiceId = choiceOptions.id;
            setOptions.focusedChoiceRow = choiceOptions.row;
            setOptions.focusedChoiceColumn = choiceOptions.column;
            $(choice).parent().data("orderingActivity:set", setOptions);
            options.accessibility.hasFocus = true;
            $(target).data("orderingActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.leftButton.container.css.identifier).bind("mouseout", function() {
        var options = $(target).data("orderingActivity:options");
        var choiceOptions = $(choice).data("orderingActivity:choice");
        var setOptions = $(choice).parent().data("orderingActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if ($(this).hasClass(options.containers.choices.leftButton.container.css.hover)) {
            $(this).removeClass(options.containers.choices.leftButton.container.css.hover);
            options.accessibility.hasFocus = true;
            $(target).data("orderingActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.leftButton.container.css.identifier).bind("click", function(event) {
        var options = $(target).data("orderingActivity:options");
        var choiceOptions = $(choice).data("orderingActivity:choice");
        var setOptions = $(choice).parent().data("orderingActivity:set");
        if (options.data.enabled && !setOptions.completed && !$(choice).hasClass(options.containers.choices.container.css.animating)) {
          var shouldRecalculate = false;
          moveChoice(target, options, null, $(this).parent(), 0, 1);
          if (setOptions.gradeIndividually) {
            shouldRecalculate = true;
          } else {
            if (setOptions.allowRetry || (!setOptions.allowRetry && setOptions.attempts == 0)) {
              shouldRecalculate = true;
            }
          }
          options.accessibility.hasFocus = true;
          $(target).data("orderingActivity:options", options);
          if (shouldRecalculate) {
            calculateActivityScore(target, options);
          }
        }
      });
    }

    function moveChoice(target, options, setContainer, choice, columnDelta, rowDelta) {
      log(target, options, choice, "info");
      setContainer = setContainer || getActiveSetContainer(target, options);
      columnDelta = columnDelta || 0;
      rowDelta = rowDelta || 0;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      var choiceOptions = $(choice).data("orderingActivity:choice");
      var setOptions = $(setContainer).data("orderingActivity:set");
      var allChoicesInSet = getChoicesInSet(target, options, setContainer);
      var workingChoice = null;
      var workingChoiceData = null;
      var targetChoice = null;
      var targetChoiceData = null;
      var targetColumn = choiceOptions.column + columnDelta;
      var targetRow = choiceOptions.row + rowDelta;
      targetColumn = Math.min(Math.max(targetColumn, 0), setOptions.columns - 1);
      targetRow = Math.min(Math.max(targetRow, 0), setOptions.rows - 1);
      if (choiceOptions.row != targetRow || choiceOptions.column != targetColumn) {
        for (var i = 0; i < allChoicesInSet.length; i++) {
          workingChoice = allChoicesInSet[i];
          workingChoiceData = $(workingChoice).data("orderingActivity:choice");
          if (workingChoiceData.column == targetColumn && workingChoiceData.row == targetRow) {
            var movingChoiceColumn = choiceOptions.column;
            var movingChoiceRow = choiceOptions.row;
            choiceOptions.column = workingChoiceData.column;
            choiceOptions.row = workingChoiceData.row;
            workingChoiceData.column = movingChoiceColumn;
            workingChoiceData.row = movingChoiceRow;
            $(workingChoice).data("orderingActivity:choice", workingChoiceData);
            $(choice).data("orderingActivity:choice", choiceOptions);
            if (options.data.animate) {
              var workingZIndex = $(workingChoice).css("z-index");
              $(workingChoice).addClass(options.containers.choices.container.css.animating);
              $(workingChoice).css("z-index", 0).animate({
                left : -containerPadding.left + $(workingChoice).outerWidth() * workingChoiceData.column,
                top : -containerPadding.top + $(workingChoice).outerHeight() * workingChoiceData.row
              }, "slow", null, function() {
                var reference = this;
                setTimeout(function() {
                  $(reference).removeClass(options.containers.choices.container.css.animating);
                  $(reference).css("z-index", workingZIndex);
                }, 50);
              });
              var choiceZIndex = $(choice).css("z-index");
              $(choice).addClass(options.containers.choices.container.css.animating);
              $(choice).css("z-index", 1).animate({
                left : -containerPadding.left + $(choice).outerWidth() * choiceOptions.column,
                top : -containerPadding.top + $(choice).outerHeight() * choiceOptions.row
              }, "slow", null, function() {
                var reference = this;
                setTimeout(function() {
                  $(reference).removeClass(options.containers.choices.container.css.animating);
                  $(reference).css("z-index", choiceZIndex);
                }, 50);
              });
            } else {
              positionChoices(target, options);
            }
            break;
          }
        }
      }
    }

    function getSetContainers(target, options) {
      return $(options.containers.choice.reference).children("." + options.containers.set.css.identifier) || [];
    }

    function getActiveSetContainer(target, options) {
      return $(options.containers.choice.reference).children("."+options.containers.set.css.identifier).filter("."+options.containers.set.css.selected)[0] || null;
    }

    function getChoices(target, options) {
      var activeSetContainer = getActiveSetContainer(target, options);
      return $(activeSetContainer).children("." + options.containers.choices.container.css.identifier) || [];
    }

    function getChoicesInSet(target, options, setContainer) {
      return $(setContainer).children("." + options.containers.choices.container.css.identifier) || [];
    }

    function clearChoicesHover(target, options, choices) {
      if (!choices) {
        choices = getChoices(target, options);
      }
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.hover);
      }
    }

    function focusChoiceInSet(target, options, setContainer, id, row, column, selectChoice) {
      log(target, options, "Focusing Choice:{id:" + id + ",row:" + row + ",column:" + column + "}", "info");
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      selectChoice = selectChoice || false;
      clearChoicesHover(target, options, choices);
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceOptions = $(choice).data("orderingActivity:choice");
        if (id == choiceOptions.id) {
          $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseover");
          if (selectChoice) {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("click");
          }
        } else {
          if (row == choiceOptions.row && column == choiceOptions.column) {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseover");
            if (selectChoice) {
              $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("click");
            }
          } else {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseout");
          }
        }
      }
    }

    function clearSelectedChoicesInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.selected);
      }
    }

    function clearSelectedChoices(target, options, choices) {
      choices = choices || getChoices(target, options);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.selected);
      }
    }

    function registerKeyboardEvents(target, options, choices) {
      $(document).keydown(function(event) {
        var options = $(target).data("orderingActivity:options");
        if (options.data.enabled && options.accessibility.keyboard.allow && options.accessibility.hasFocus) {
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("orderingActivity:set");
          switch(event.keyCode) {
            case 38:
              if (activeSetData.focusedChoiceRow - 1 >= 0) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow - 1, activeSetData.focusedChoiceColumn);
              }
              break;
            case 40:
              if (activeSetData.focusedChoiceRow + 1 < activeSetData.rows) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow + 1, activeSetData.focusedChoiceColumn);
              }
              break;
            case 37:
              if (activeSetData.focusedChoiceColumn - 1 >= 0) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn - 1);
              }
              break;
            case 39:
              if (activeSetData.focusedChoiceColumn + 1 < activeSetData.columns) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn + 1);
              }
              break;
            case 32:
              focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn, true);
              break;
            case 13:
              calculateActivityScore(target, options);
              break;
          }
        }
      });
    }

    function registerPseudoMouseEvents(target, options, choices) {
      var pseudoMice = options.accessibility.pseudoMouse.mice;
      var mouse = null;
      var offset = null;
      var width = null;
      var height = null;
      var container = null;
      var found = false;
      for (var i = 0; i < pseudoMice.length; i++) {
        mouse = pseudoMice[i];
        $(mouse).bind("mousemove", function(event) {
          var options = $(target).data("orderingActivity:options");
          if (options.data.enabled) {
            var event2 = new $.Event("mousemove");
            event2.pageX = event.pageX;
            event2.pageY = event.pageY;
            $(target).trigger(event2);
          }
          options = $(target).data("orderingActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            var activeSet = getActiveSetContainer(target, options);
            var choices = getChoicesInSet(target, options, activeSet);
            for (var j = 0; j < choices.length; j++) {
              found = false;
              container = $(choices[j]).children("." + options.containers.choices.downarrow.css.identifier).first();
              offset = $(container).offset();
              if ($(container).hasClass(options.containers.choices.container.css.hover)) {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      found = true;
                    }
                  }
                }
                if (!found) {
                  $(container).trigger("mouseout");
                }
              } else {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      $(container).trigger("mouseover");
                    }
                  }
                }
              }
            }
          }
        });
        $(mouse).bind("mouseup", function(event) {
          var options = $(target).data("orderingActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            container = null;
            for (var j = 0; j < choices.length; j++) {
              container = $(choices[j]).children("." + options.containers.choices.downarrow.css.identifier).first();
              offset = $(container).offset();
              width = $(container).width();
              height = $(container).height();
              if (event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
                $(container).trigger("click");
              }
            }
          }
        });
      }
    }

    function parseXMLAndBuildActivity(target, options, data) {
      log(target, options, "Parsing Activity XML", "info");
      try {
        if (window.ActiveXObject) {
          var doc = new ActiveXObject("Microsoft.XMLDOM");
          doc.loadXML(data);
          data = doc;
        } else {
          if (window.DOMParser) {
            data = (new DOMParser).parseFromString(data, "text/xml");
          }
        }
      } catch(error) {
        data = null;
        log(target, options, "XML Parse Error:{error:" + error + "}", "error");
      }
      if (data) {
        var activityData = {
          allowRetry : true,
          randomizeOnRetry : true,
          gradeSetsIndividually : false,
          dataSets : []
        };
        var idIndex = 0;
        var dataSet = null;
        var choice = null;
        if ($(data).children("orderingActivity").attr("retry")) {
          activityData.allowRetry = ($(data).children("orderingActivity").attr("retry").toLowerCase() == "true") ? true : false;
        }
        if ($(data).children("orderingActivity").attr("randomizeOnRetry")) {
          activityData.randomizeOnRetry = ($(data).children("orderingActivity").attr("randomizeOnRetry").toLowerCase() == "true") ? true : false;
        }
        if ($(data).children("orderingActivity").attr("gradeSetsIndividually")) {
          activityData.gradeSetsIndividually = ($(data).children("orderingActivity").attr("gradeSetsIndividually").toLowerCase() == "true") ? true : false;
        }
        $(data).children("orderingActivity").children("set").each(function() {
          dataSet = {
            id : $(this).attr("id"),
            allowRetry : false,
            showFeedback : true,
            gradeIndividually : false,
            autoComplete : false,
            title : $(this).children("title:first").text(),
            rows : parseInt($(this).attr("rows")),
            columns : parseInt($(this).attr("columns")),
            choices : []
          };
          if ($(this).children("title:first").attr("encoding")) {
            dataSet.title = unescape(dataSet.title.replace(/\+/g, " "));
          }
          $(this).children("choices").children("choice").each(function() {
            choice = {
              id : $(this).attr("id"),
              content : $(this).text(),
              value : parseFloat($(this).attr("value")),
              selectOnce : false
            };
            if ($(this).attr("encoding")) {
              choice.content = unescape(choice.content.replace(/\+/g, " "));
            }
            if ($(this).attr("selectOnce")) {
              choice.selectOnce = ($(this).attr("selectOnce").toLowerCase() == "true") ? true : false;
            }
            dataSet.choices.push(choice);
          });
          activityData.dataSets.push(dataSet);
        });
        buildActivity(target, options, activityData);
      } else {
        log(target, options, "XML Activity Build Error:{error:No data to build activity}", "error");
      }
    }

    function loadXMLAndBuildActivity(target, options, url) {
      log(target, options, "Loading XML", "info");
      $.ajax({
        url : url,
        dataType : "text",
        success : function(data, textStatus, xhr) {
          var options = $(target).data("orderingActivity:options");
          log(target, options, "XML Loaded", "info");
          parseXMLAndBuildActivity(target, options, data);
        },
        error : function(xhr, textStatus, errorThrown) {
          log(target, options, "XML Load Error:{textStatus:" + textStatus + ",errorThrown:" + errorThrown + "}", "error");
        }
      });
    }

    function buildActivity(target, options, activityData) {
      var dataSet = null;
      var choiceDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      var currentChoice = null;
      var choices = [];
      var currentRow = 0;
      var currentColumn = 0;
      var choice = null;
      var setContainer = null;
      options.data.allowRetry = activityData.allowRetry;
      options.data.randomizeOnRetry = activityData.randomizeOnRetry;
      options.data.gradeSetsIndividually = activityData.gradeSetsIndividually;
      if (options.data.overridePoints || options.data.overridePoints == 0) {
        var totalCorrectPoints = 0;
        $.each(activityData.dataSets, function(i, dataSet) {
          $.each(dataSet.choices, function(j, choice) {
            if (choice.value > 0) {
              totalCorrectPoints += choice.value;
            }
          });
        });
        if (totalCorrectPoints == 0 || options.data.overridePoints == 0) {
          totalCorrectPoints = 0;
          $.each(activityData.dataSets, function(i, dataSet) {
            $.each(dataSet.choices, function(j, choice) {
              if (options.data.overridePoints > 0) {
                choice.value = 1;
                totalCorrectPoints++;
              } else {
                choice.value = 0;
              }
            });
          });
        }
        var factor = options.data.overridePoints / totalCorrectPoints;
        $.each(activityData.dataSets, function(i, dataSet) {
          $.each(dataSet.choices, function(j, choice) {
            choice.value = choice.value * factor;
          });
        });
      }
      for (var i = 0; i < activityData.dataSets.length; i++) {
        dataSet = $.extend({}, activityData.dataSets[i], {
          choices : [],
          attempts : 0,
          focusedChoiceId : null,
          focusedChoiceRow : -1,
          focusedChoiceColumn : -1,
          completed : false
        });
        if (activityData.dataSets[i].choices.length % dataSet.columns) {
          dataSet.rows = parseInt(activityData.dataSets[i].choices.length / dataSet.columns) + 1;
        } else {
          dataSet.rows = parseInt(activityData.dataSets[i].choices.length / dataSet.columns);
        }
        options.data.dataSets.push(dataSet);
        choiceDimensions = calculateChoiceDimensions(target, options, dataSet.rows, dataSet.columns);
        currentRow = 0;
        currentColumn = 0;
        choice = null;
        for (var j = 0; j < activityData.dataSets[i].choices.length; j++) {
          choice = activityData.dataSets[i].choices[j];
          currentChoice = createChoiceContainer(target, options, choice.content);
          $(currentChoice).data("orderingActivity:choice", {
            id : choice.id,
            row : currentRow,
            column : currentColumn,
            value : choice.value,
            correct : choice.correct,
            selectOnce : choice.selectOnce
          });
          registerChoiceEvents(target, options, currentChoice);
          dataSet.choices.push(currentChoice);
          choices.push(currentChoice);
          currentColumn++;
          if (currentColumn >= dataSet.columns) {
            currentColumn = 0;
            currentRow++;
          }
        }
        setContainer = createSetContainer(target, options);
        options.containers.set.references.push(setContainer);
        $(setContainer).data("orderingActivity:set", dataSet);
        $(options.containers.choice.reference).append(setContainer);
        for (var j = 0; j < dataSet.choices.length; j++) {
          $(setContainer).append(dataSet.choices[j]);
        }
        resizeChoices(target, options, choiceDimensions.width, choiceDimensions.height, dataSet.choices);
        randomizeChoicePositionsInSet(target, options, setContainer);
        positionChoices(target, options, dataSet.choices);
        alignChoices(target, options, dataSet.choices);
      }
      registerAccessibilityEvents(target, options, choices);
      enableDisable(target, options, choices);
      $(target).data("orderingActivity:options", options);
      alignSets(target, options);
      showSet(target, options, activityData.dataSets[0].id);
      calculateActivityScore(target, options, false);
      $(target).trigger("activityLoaded.orderingActivity", [options.data.dataSets.length, 0, options.data.allowRetry, options.data.gradeSetsIndividually]);
    }

    function createSetContainer(target, options) {
      return $("<div />").addClass(options.containers.set.css.identifier);
    }

    function showSet(target, options, id, setContainers, reset, resetPosition) {
      setContainers = setContainers || getSetContainers(target, options);
      reset = reset || false;
      resetPosition = resetPosition || false;
      var setContainer = null;
      var setContainerData = null;
      var selectedSetContainerData = null;
      var selectedSetContainer = null;
      var setPosition = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("orderingActivity:set");
        $(setContainer).removeClass(options.containers.set.css.selected);
        if (setContainerData.id == id) {
          setPosition = i;
          selectedSetContainerData = setContainerData;
          selectedSetContainer = setContainer;
          $(setContainer).addClass(options.containers.set.css.selected);
        }
      }
      var choices = getChoices(target, options);
      positionChoices(target, options, choices);
      alignChoices(target, options, choices);
      if (reset && selectedSetContainerData) {
        options.data.enabled = true;
        enableDisable(target, options, choices);
        $(target).data("orderingActivity:data", options);
      }
      if (resetPosition) {
        var width = $(options.containers.choice.reference).outerWidth();
        var finalPosition = -(width * [id]);
        $(options.containers.choice.reference).css("left", finalPosition + "px");
      }
      $(target).trigger("titleChanged.orderingActivity", [selectedSetContainerData.title]);
      $(target).trigger("setChanged.orderingActivity", [setContainers.length, setPosition, options.data.gradeSetsIndividually, options.data.allowRetry, selectedSetContainerData.completed, options.data.enabled]);
    }

    function showNextSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          if (setContainers[i] == currentSetContainer && i < setContainers.length - 1) {
            var width = $(options.containers.choice.reference).outerWidth();
            var finalPosition = -(width * [i + 1]);
            if (options.data.animate) {
              $(options.containers.choice.reference).stop(true, false).addClass(options.containers.choice.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.choice.css.animating);
              });
            } else {
              $(options.containers.choice.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i + 1]).data("orderingActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function showPreviousSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          if (setContainers[i] == currentSetContainer && i > 0) {
            var width = $(options.containers.choice.reference).outerWidth();
            var finalPosition = -(width * [i - 1]);
            if (options.data.animate) {
              $(options.containers.choice.reference).stop(true, false).addClass(options.containers.choice.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.choice.css.animating);
              });
            } else {
              $(options.containers.choice.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i - 1]).data("orderingActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function getSetState(target, options, setContainer) {
      var setContainerData = $(setContainer).data("orderingActivity:set");
      var setState = {
        id : setContainerData.id,
        allowRetry : setContainerData.allowRetry,
        showFeedback : setContainerData.showFeedback,
        gradeIndividually : setContainerData.gradeIndividually,
        attempts : setContainerData.attempts,
        completed : setContainerData.completed,
        choices : []
      };
      var setChoices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      var normalizedChoiceData = null;
      for (var i = 0; i < setChoices.length; i++) {
        choice = setChoices[i];
        choiceOptions = $(choice).data("orderingActivity:choice");
        normalizedChoiceData = {
          id : choiceOptions.id,
          row : choiceOptions.row,
          column : choiceOptions.column,
          correct : (choiceOptions.id == choiceOptions.row),
          value : choiceOptions.value,
          selected : $(choice).hasClass(options.containers.choices.container.css.selected)
        };
        setState.choices.push(normalizedChoiceData);
      }
      return setState;
    }

    function setSetState(target, options, setContainer, setState) {
      log(target, options, "Setting Set State:" + setState.id);
      var setContainerData = $(setContainer).data("orderingActivity:set");
      setContainerData.allowRetry = setState.allowRetry;
      setContainerData.showFeedback = setState.showFeedback;
      setContainerData.gradeIndividually = setState.gradeIndividually;
      setContainerData.attempts = setState.attempts;
      setContainerData.completed = setState.completed;
      $(setContainer).data("orderingActivity:set", setContainerData);
      if (setContainerData.completed && !$(setContainer).hasClass(options.containers.set.css.completed)) {
        $(setContainer).addClass(options.containers.set.css.completed);
      }
      var setChoices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      var normalizedChoiceData = null;
      for (var i = 0; i < setChoices.length; i++) {
        choice = setChoices[i];
        choiceOptions = $(choice).data("orderingActivity:choice");
        for (var j = 0; j < setState.choices.length; j++) {
          normalizedChoiceData = setState.choices[j];
          if (normalizedChoiceData.id == choiceOptions.id) {
            choiceOptions.row = normalizedChoiceData.row;
            choiceOptions.column = normalizedChoiceData.column;
            choiceOptions.correct = normalizedChoiceData.correct;
            choiceOptions.value = normalizedChoiceData.value;
            $(choice).removeClass(options.containers.choices.container.css.selected);
            if (normalizedChoiceData.selected) {
              $(choice).addClass(options.containers.choices.container.css.selected);
            }
            if (setContainerData.completed) {
              if (choiceOptions.correct) {
                $(choice).addClass(options.containers.choices.container.css.correct);
              } else {
                $(choice).addClass(options.containers.choices.container.css.incorrect);
              }
            }
          }
        }
        $(choice).data("orderingActivity:choice", choiceOptions);
      }
    }

    function calculateActivityScore(target, options, incrementAttempts, autoCompleteOverride, doNotUpdateExternalScore) {
      incrementAttempts = incrementAttempts || true;
      autoCompleteOverride = autoCompleteOverride || false;
      doNotUpdateExternalScore = doNotUpdateExternalScore || false;
      var choiceSets = getSetContainers(target, options);
      var activeSet = getActiveSetContainer(target, options);
      var activeSetPosition = 0;
      var setScore = null;
      var setScores = [];
      var calculatedScore = 0;
      var calculatedPossible = 0;
      var totalCorrect = 0;
      var totalIncorrect = 0;
      var correctSelected = 0;
      var incorrectSelected = 0;
      for (var i = 0; i < choiceSets.length; i++) {
        if (choiceSets[i] == activeSet) {
          activeSetPosition = i;
        }
        if (options.data.gradeSetsIndividually && choiceSets[i] == activeSet) {
          setScore = calculateSetScore(target, options, choiceSets[i], incrementAttempts, autoCompleteOverride);
        } else {
          if (options.data.gradeSetsIndividually && choiceSets[i] != activeSet) {
            setScore = calculateSetScore(target, options, choiceSets[i], false, false);
          } else {
            setScore = calculateSetScore(target, options, choiceSets[i], incrementAttempts, autoCompleteOverride);
          }
        }
        calculatedScore += setScore.calculatedScore;
        calculatedPossible += setScore.calculatedPossible;
        totalCorrect += setScore.totalCorrect;
        totalIncorrect += setScore.totalIncorrect;
        correctSelected += setScore.correctSelected;
        incorrectSelected += setScore.incorrectSelected;
        $(target).trigger("setScoreChanged.orderingActivity", [options.data.dataSets.length, i, options.data.allowRetry, options.data.gradeSetsIndividually, setScore.calculatedScore, setScore.calculatedPossible, $(choiceSets[i]).data("orderingActivity:set").completed, doNotUpdateExternalScore]);
      }
      log(target, options, "Score Recalculated:" + calculatedScore + "/" + calculatedPossible, "info");
      $(target).trigger("activityScoreChanged.orderingActivity", [options.data.dataSets.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually, calculatedScore, calculatedPossible, $(activeSet).data("orderingActivity:set").completed, doNotUpdateExternalScore]);
      if (!options.data.gradeSetsIndividually && autoCompleteOverride) {
        options.data.enabled = false;
        $(target).data("orderingActivity:options", options);
        enableDisable(target, options);
        log(target, options, "Activity Completed:" + calculatedScore + "/" + calculatedPossible, "info");
        $(target).trigger("activityComplete.orderingActivity", [options.data.dataSets.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually, calculatedScore, calculatedPossible, doNotUpdateExternalScore]);
      }
      return {
        calculatedScore : calculatedScore,
        calculatedPossible : calculatedPossible,
        totalCorrect : totalCorrect,
        totalIncorrect : totalIncorrect,
        correctSelected : correctSelected,
        incorrectSelected : incorrectSelected
      };
    }

    function calculateSetScore(target, options, setContainer, incrementAttempts, autoCompleteOverride) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      incrementAttempts = incrementAttempts || true;
      autoCompleteOverride = autoCompleteOverride || false;
      var setData = $(setContainer).data("orderingActivity:set");
      var setState = getSetState(target, options, setContainer);
      var scoreResults = options.data.calculateScore(setState);
      if (setData.gradeIndividually) {
        if (setData.showFeedback) {
          showCorrectAndIncorrect(target, options, setContainer, true);
        }
      } else {
        if (setData.autoComplete && scoreResults.totalCorrect == scoreResults.correctSelected || autoCompleteOverride == true) {
          setData.completed = true;
          if (!$(setContainer).hasClass(options.containers.set.css.completed)) {
            $(setContainer).addClass(options.containers.set.css.completed);
          }
          if (setData.showFeedback) {
            showCorrectAndIncorrect(target, options, setContainer, false);
          }
          if (incrementAttempts) {
            setData.attempts++;
          }
        } else {
          clearCorrectAndIncorrectInSet(target, options, setContainer);
          if (!setData.completed) {
            scoreResults.calculatedScore = 0;
          } else {
            if (setData.showFeedback) {
              showCorrectAndIncorrectInSet(target, options, setContainer, false);
            }
          }
        }
      }
      $(setContainer).data("orderingActivity:set", setData);
      return scoreResults;
    }

    function showCorrectAndIncorrect(target, options, setContainer, showOnlySelected) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      showOnlySelected = showOnlySelected || true;
      if (options.data.enabled) {
        var choices = getChoicesInSet(target, options, setContainer);
        var choice = null;
        var choiceOptions = null;
        var showChoice = false;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          choiceOptions = $(choice).data("orderingActivity:choice");
          showChoice = true;
          if (showChoice) {
            if (choiceOptions.row == choiceOptions.id) {
              $(choice).removeClass(options.containers.choices.container.css.incorrect);
              if (!$(choice).hasClass(options.containers.choices.container.css.correct)) {
                $(choice).addClass(options.containers.choices.container.css.correct);
              }
            } else {
              $(choice).removeClass(options.containers.choices.container.css.correct);
              if (!$(choice).hasClass(options.containers.choices.container.css.incorrect)) {
                $(choice).addClass(options.containers.choices.container.css.incorrect);
              }
            }
          } else {
            $(choice).removeClass(options.containers.choices.container.css.correct);
            $(choice).removeClass(options.containers.choices.container.css.incorrect);
          }
        }
      }
    }

    function clearCorrectAndIncorrect(target, options, choices, showOnlySelected) {
      choices = choices || getChoices(target, options);
      showOnlySelected = showOnlySelected || true;
      if (options.data.enabled) {
        var choice = null;
        var showChoice = false;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          $(choice).removeClass(options.containers.choices.container.css.incorrect);
          $(choice).removeClass(options.containers.choices.container.css.correct);
        }
      }
    }

    function clearCorrectAndIncorrectInSet(target, options, setContainer, showOnlySelected) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      showOnlySelected = showOnlySelected || true;
      choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var showChoice = false;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.incorrect);
        $(choice).removeClass(options.containers.choices.container.css.correct);
      }
    }

    function alignChoices(target, options, choices) {
      choices = choices || getChoices(target, options);
      if (choices) {
        var choice = null;
        var choiceContent = null;
        var choiceOptions = null;
        var leftContent = null;
        var rightContent = null;
        var feedbackIconContent = null;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          choiceContent = $(choice).children("." + options.containers.choices.content.css.identifier + ":first");
          leftContent = $(choice).find("." + options.containers.choices.leftButton.button.css.identifier + ":first");
          rightContent = $(choice).find("." + options.containers.choices.rightButton.button.css.identifier + ":first");
          feedbackIconContent = $(choice).find("." + options.containers.choices.feedbackIcon.css.identifier + ":first");
          alignToParent(target, options, options.containers.choices.content.horizontalAlign, options.containers.choices.content.verticalAlign, choiceContent);
          alignToParent(target, options, "left", "middle", leftContent);
          alignToParent(target, options, "right", "middle", rightContent);
          alignToParent(target, options, options.containers.choices.feedbackIcon.horizontalAlign, options.containers.choices.feedbackIcon.verticalAlign, feedbackIconContent);
        }
      }
    }

    function alignSets(target, options, setContainers) {
      setContainers = setContainers || getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var setWidth = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("orderingActivity:set");
        setWidth = $(setContainer).width();
        $(setContainer).css("left", (setWidth * setContainerData.id) + "px");
      }
    }

    function alignToParent(target, options, horizontalAlign, verticalAlign, container) {
      $(container).css("position", "absolute");
      if (horizontalAlign) {
        switch(horizontalAlign.toLowerCase()) {
          case"left":
            $(container).css("right", null).css("left", "0px");
            break;
          case"right":
            $(container).css("left", null).css("right", "0px");
            break;
          case"center":
            $(container).css("right", null).css("left", ($(container).parent().innerWidth() / 2 - $(container).outerWidth() / 2) + "px");
            break;
        }
      }
      if (verticalAlign) {
        switch(verticalAlign.toLowerCase()) {
          case"top":
            $(container).css("bottom", null).css("top", "0px");
            break;
          case"bottom":
            $(container).css("top", null).css("bottom", "0px");
            break;
          case"middle":
            $(container).css("bottom", null).css("top", ($(container).parent().innerHeight() / 2 - $(container).outerHeight() / 2) + "px");
            break;
        }
      }
    }

    function resetActivity(target, options) {
      if (options.data.allowRetry) {
        log(target, options, "Resetting Activity", "info");
        var setContainers = getSetContainers(target, options);
        var activeSet = getActiveSetContainer(target, options);
        var activeSetPosition = 0;
        var setContainer = null;
        var setContainerData = null;
        var choices = null;
        var calculatedScore = 0;
        var calculatedPossible = 0;
        var setScore = null;
        options.data.enabled = true;
        for (var i = 0; i < setContainers.length; i++) {
          setContainer = setContainers[i];
          setContainerData = $(setContainer).data("orderingActivity:set");
          if (setContainer == activeSet) {
            activeSetPosition = i;
          }
          if ((options.data.gradeSetsIndividually && setContainer == activeSet) || !options.data.gradeSetsIndividually) {
            setContainerData.attempts = 0;
            setContainerData.completed = false;
            setContainerData.focusedChoiceId = null;
            setContainerData.focusedChoiceRow = -1;
            setContainerData.focusedChoiceColumn = -1;
            $(setContainer).data("orderingActivity:set", setContainerData);
            choices = getChoicesInSet(target, options, setContainer);
            clearChoicesHover(target, options, choices);
            clearCorrectAndIncorrectInSet(target, options, setContainer);
            clearSelectedChoices(target, options, choices);
            setScore = calculateSetScore(target, options, setContainer);
            calculatedScore += setScore.calculatedScore;
            calculatedPossible += setScore.calculatedPossible;
            if (options.data.randomizeOnRetry) {
              randomizeChoicePositionsInSet(target, options, setContainer);
              positionChoices(target, options, choices);
            }
            if ($(setContainer).hasClass(options.containers.set.css.completed)) {
              $(setContainer).removeClass(options.containers.set.css.completed);
            }
          }
        }
        enableDisable(target, options);
        var setPosition = $(activeSet).data("orderingActivity:set").id;
        if (!options.data.gradeSetsIndividually && options.data.randomizeOnRetry) {
          setPosition = Math.floor(Math.random() * setContainers.length);
        }
        setContainer = setContainers[setPosition];
        setContainerData = $(setContainer).data("orderingActivity:set");
        showSet(target, options, setContainerData.id, setContainers, false, true);
        activeSet = getActiveSetContainer(target, options);
        for (var i = 0; i < setContainers.length; i++) {
          setContainer = setContainers[i];
          setContainerData = $(setContainer).data("orderingActivity:set");
          if (setContainer == activeSet) {
            activeSetPosition = i;
          }
        }
        $(target).data("orderingActivity:options", options);
        $(target).trigger("reset.orderingActivity", [setContainers.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually]);
        calculateActivityScore(target, options, false);
      }
    }

    function getActiveSetContainerId(target, options) {
      return $(getActiveSetContainer(target, options)).data("orderingActivity:set").id || null;
    }

    function getActivityState(target, options) {
      var activityState = {
        enabled : options.data.enabled,
        allowRetry : options.data.allowRetry,
        randomizeOnRetry : options.data.randomizeOnRetry,
        activeSetId : getActiveSetContainerId(target, options),
        sets : []
      };
      var setContainers = getSetContainers(target, options);
      for (var i = 0; i < setContainers.length; i++) {
        activityState.sets.push(getSetState(target, options, setContainers[i]));
      }
      return activityState;
    }

    function setActivityState(target, options, activityState, completed) {
      log(target, options, "Setting Activity State for completed:" + completed);
      var setData = null;
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var choices = null;
      var allSetsCompleted = false;
      showSet(target, options, activityState.activeSetId, false, true);
      for (var i = 0; i < activityState.sets.length; i++) {
        setData = activityState.sets[i];
        for (var j = 0; j < setContainers.length; j++) {
          setContainer = setContainers[j];
          setContainerData = $(setContainer).data("orderingActivity:set");
          choices = getChoicesInSet(target, options, setContainer);
          if (setData.id == setContainerData.id) {
            setSetState(target, options, setContainer, setData, setData.completed);
          }
          positionChoices(target, options, choices);
        }
      }
      options.data.enabled = activityState.enabled;
      options.data.allowRetry = activityState.allowRetry;
      options.data.randomizeOnRetry = activityState.randomizeOnRetry;
      $(target).data("orderingActivity:options", options);
      enableDisable(target, options);
      calculateActivityScore(target, options, false, completed, true);
    }
    return this;
  };
  $.fn.orderingActivity.defaults = {};
  $.fn.orderingActivity.defaults.containers = {
    activity : {
      reference : null,
      css : {
        identifier : "softchalk-ordering-activity"
      }
    },
    content : {
      reference : null,
      css : {
        identifier : "softchalk-ordering-activity-content",
        enabled : "enabled",
        disabled : "disabled"
      }
    },
    choice : {
      reference : null,
      css : {
        identifier : "softchalk-ordering-activity-sets",
        animating : "animating"
      }
    },
    set : {
      references : [],
      css : {
        identifier : "softchalk-ordering-activity-set",
        selected : "selected",
        completed : "completed"
      }
    },
    choices : {
      references : [],
      container : {
        css : {
          identifier : "softchalk-ordering-activity-choice",
          selected : "selected",
          correct : "correct",
          incorrect : "incorrect",
          hover : "hover",
          animating : "animating"
        }
      },
      content : {
        horizontalAlign : "center",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-ordering-activity-choice-content"
        }
      },
      leftButton : {
        container : {
          css : {
            identifier : "softchalk-ordering-activity-choice-left-button-container",
            hover : "hover"
          }
        },
        button : {
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-ordering-activity-choice-left-button",
            hover : "hover"
          }
        }
      },
      rightButton : {
        container : {
          css : {
            identifier : "softchalk-ordering-activity-choice-right-button-container",
            hover : "hover"
          }
        },
        button : {
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-ordering-activity-choice-right-button",
            hover : "hover"
          }
        }
      },
      feedback : {
        css : {
          identifier : "softchalk-ordering-activity-choice-feedback"
        }
      },
      feedbackIcon : {
        horizontalAlign : "right",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-ordering-activity-choice-feedback-icon"
        }
      },
      overlay : {
        css : {
          identifier : "softchalk-ordering-activity-choice-overlay"
        }
      }
    }
  };
  $.fn.orderingActivity.defaults.data = {
    dataSets : [],
    calculateScore : function(setState) {
      var calculatedCorrect = 0;
      var calculatedIncorrect = 0;
      var calculatedPossible = 0;
      var choiceData = null;
      var correctSelected = 0;
      var incorrectSelected = 0;
      var totalCorrect = 0;
      var totalIncorrect = 0;
      for (var i = 0; i < setState.choices.length; i++) {
        choiceData = setState.choices[i];
        calculatedPossible += choiceData.value;
        if (choiceData.row == choiceData.id) {
          totalCorrect++;
          calculatedCorrect += choiceData.value;
          correctSelected++;
        } else {
          totalIncorrect++;
          calculatedIncorrect += choiceData.value;
          incorrectSelected++;
        }
      }
      var calculatedScore = Math.max(0, calculatedCorrect - calculatedIncorrect);
      var calculatedScore = calculatedCorrect;
      return {
        calculatedScore : calculatedScore,
        calculatedPossible : calculatedPossible,
        totalCorrect : totalCorrect,
        totalIncorrect : totalIncorrect,
        correctSelected : correctSelected,
        incorrectSelected : incorrectSelected
      };
    },
    enabled : true,
    enableLogging : false,
    allowRetry : true,
    randomizeOnRetry : true,
    animate : true,
    gradeSetsIndividually : false,
    overridePoints : null
  };
  $.fn.orderingActivity.defaults.accessibility = {
    pseudoMouse : {
      allow : true,
      mice : []
    },
    keyboard : {
      allow : true
    },
    hasFocus : false
  };
  $.fn.orderingActivity.defaults.logging = {
    debug : false,
    info : true,
    warn : false,
    error : false
  };
})(jQuery);
(function($) {
  $.fn.selectAllActivity = function(action, options) {
    var shouldReturnResults = false;
    var results = [];
    var params = null;
    action = action || "initialize";
    if ( typeof (action) == "object") {
      options = action;
      action = "initialize";
    }
    if (action == "initialize") {
      if (!options) {
        options = $.fn.selectAllActivity.defaults;
      } else {
        options = $.extend(true, {}, $.fn.selectAllActivity.defaults, options);
      }
    } else {
      params = options;
    }
    var optionsReference = options;
    $(this).each(function() {
      switch(action) {
        case"initialize":
          log(this, optionsReference, "Action:Initializing Activity", "info");
          initialize(this, optionsReference);
          break;
        case"loadXMLAndBuildActivity":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Loading XML", "info");
          loadXMLAndBuildActivity(this, options, params);
          break;
        case"parseXMLAndBuildActivity":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Parsing XML", "info");
          parseXMLAndBuildActivity(this, options, params);
          break;
        case"calculateScore":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Calculating Score", "info");
          calculateActivityScore(this, options);
          break;
        case"finish":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Finishing Activity", "info");
          calculateActivityScore(this, options, true, true);
          break;
        case"reset":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Resetting Activity", "info");
          resetActivity(this, options);
          break;
        case"showNextSet":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Showing Next Set", "info");
          showNextSet(this, options);
          break;
        case"showPreviousSet":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Showing Previous Set", "info");
          showPreviousSet(this, options);
          break;
        case"getState":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Getting Activity State", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getActivityState(this, options)
          });
          break;
        case"setState":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Setting Activity State", "info");
          setActivityState(this, options, params.state, params.completed);
          break;
        case"getEnabled":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Getting Enabled", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.enabled
          });
          break;
        case"setEnabled":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Setting Enabled", "info");
          options.data.enabled = params;
          $(this).data("selectAllActivity:options", options);
          enableDisable(this, options);
          break;
        case"getSetIds":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Getting Set Ids", "info");
          var setContainers = getSetContainers(this, options);
          var setContainer = null;
          var setContainerData = null;
          var setIds = [];
          for (var i = 0; i < setContainers.length; i++) {
            setContainer = setContainers[i];
            setContainerData = $(setContainer).data("selectAllActivity:set");
            setIds.push(setContainerData.id);
          }
          shouldReturnResults = true;
          results.push({
            target : this,
            result : setIds
          });
          break;
        case"getNumberOfSets":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getSetContainers(this, options).length
          });
          break;
        case"showSet":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Showing set", "info");
          showSet(this, options, params);
          break;
        case"getAllowReset":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Getting allow reset", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.allowRetry
          });
          break;
        case"resize":
          var options = $(this).data("selectAllActivity:options");
          log(this, options, "Action:Resizing the activity", "info");
          handleResize(this, options);
          break;
      }
    });
    if (shouldReturnResults == true) {
      return results;
    }
    function log(target, options, data, level) {
      level = level || "debug";
      level = $.trim(level).toLowerCase();
      if (options.data.enableLogging && window.console) {
        if (level == "info" && window.console.info && options.logging.info) {
          if ($(target).attr("id")) {
            window.console.info("[SelectAllActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
          } else {
            if ($(target).attr("name")) {
              window.console.info("[SelectAllActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
            } else {
              window.console.info("[SelectAllActivity][" + target + "]" + data);
            }
          }
        } else {
          if (level == "warn" && window.console.warn && options.logging.warn) {
            if ($(target).attr("id")) {
              window.console.warn("[SelectAllActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
            } else {
              if ($(target).attr("name")) {
                window.console.warn("[SelectAllActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
              } else {
                window.console.warn("[SelectAllActivity][" + target + "]" + data);
              }
            }
          } else {
            if (level == "error" && window.console.error && options.logging.error) {
              if ($(target).attr("id")) {
                window.console.error("[SelectAllActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
              } else {
                if ($(target).attr("name")) {
                  window.console.error("[SelectAllActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                } else {
                  window.console.error("[SelectAllActivity][" + target + "]" + data);
                }
              }
            } else {
              if (window.console.log && options.logging.debug) {
                if ($(target).attr("id")) {
                  window.console.log("[SelectAllActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
                } else {
                  if ($(target).attr("name")) {
                    window.console.log("[SelectAllActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                  } else {
                    window.console.log("[SelectAllActivity][" + target + "]" + data);
                  }
                }
              }
            }
          }
        }
      }
    }

    function initialize(target, options) {
      options = $.extend(true, {}, options);
      options.containers.activity.reference = target;
      $(options.containers.activity.reference).addClass(options.containers.activity.css.identifier);
      options.containers.content.reference = target;
      $(options.containers.content.reference).addClass(options.containers.content.css.identifier);
      if (options.containers.choice.reference == null) {
        options.containers.choice.reference = $("<div />");
        $(options.containers.content.reference).append(options.containers.choice.reference);
      }
      options.containers.choice.reference.addClass(options.containers.choice.css.identifier);
      $(target).data("selectAllActivity:options", options);
    }

    function handleResize(target, options) {
      alignSets(target, options);
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var choices = null;
      var choiceDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("selectAllActivity:set");
        choices = getChoicesInSet(target, options, setContainer);
        choiceDimensions = calculateChoiceDimensions(target, options, setContainerData.rows, setContainerData.columns);
        resizeChoices(target, options, choiceDimensions.width, choiceDimensions.height, choices);
        positionChoices(target, options, choices);
        alignChoices(target, options, choices);
      }
      log(target, options, "Activity Container Resized", "info");
    }

    function registerAccessibilityEvents(target, options, choices) {
      var handleMiceEvents = function(event) {
        var options = $(this).data("selectAllActivity:options");
        if (options.data.enabled && event.pageX && event.pageY) {
          var offset = $(this).offset();
          var width = $(this).outerWidth();
          var height = $(this).outerHeight();
          if (!options.accessibility.hasFocus && event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
            options.accessibility.hasFocus = true;
            $(this).data("selectAllActivity:options", options);
          } else {
            if (options.accessibility.hasFocus && (event.pageX < offset.left || event.pageX > offset.left + width || event.pageY < offset.top || event.pageY > offset.top + height)) {
              options.accessibility.hasFocus = false;
              $(this).data("selectAllActivity:options", options);
            }
          }
        }
      };
      $(target).bind("mouseover", handleMiceEvents).bind("mouseout", handleMiceEvents).bind("mousemove", handleMiceEvents);
      $(target).bind("focusin", function(event) {
        var options = $(this).data("selectAllActivity:options");
        if (options.data.enabled && !options.accessibility.hasFocus) {
          log(target, options, "Giving Focus", "info");
          options.accessibility.hasFocus = true;
          $(this).data("selectAllActivity:options", options);
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("selectAllActivity:set");
          if (activeSetData.focusedChoiceRow < 0 || activeSetData.focusedChoiceColumn < 0 || !activeSetData.focusedChoiceId) {
            focusChoiceInSet(target, options, activeSet, null, 0, 0, false);
          }
        }
      });
      $(target).bind("focusout", function(event) {
        var options = $(this).data("selectAllActivity:options");
        if (options.data.enabled && options.accessibility.hasFocus) {
          options.accessibility.hasFocus = false;
          $(this).data("selectAllActivity:options", options);
        }
      });
      if (options.accessibility.keyboard.allow) {
        registerKeyboardEvents(target, options, choices);
      }
      if (options.accessibility.pseudoMouse.allow) {
        registerPseudoMouseEvents(target, options, choices);
      }
      if (options.data.xmlFile) {
        loadXMLAndBuildActivity(target, options, options.data.xmlFile);
      }
    }

    function calculateChoiceDimensions(target, options, rows, columns) {
      var containerWidth = $(options.containers.choice.reference).width();
      var containerHeight = $(options.containers.choice.reference).height();
      var borderTestDiv = $("<div />").css("display", "none").addClass(options.containers.choices.container.css.identifier).width(100).height(100);
      $(target).append(borderTestDiv);
      var borderWidthOffset = ($(borderTestDiv).outerWidth() - $(borderTestDiv).innerWidth()) / 2;
      var borderHeightOffset = ($(borderTestDiv).outerHeight() - $(borderTestDiv).innerHeight()) / 2;
      $(borderTestDiv).remove();
      containerWidth -= borderWidthOffset * (2 * columns);
      containerHeight -= borderHeightOffset * (2 * rows);
      var choiceMaxWidth = containerWidth / columns;
      var choiceMaxHeight = containerHeight / rows;
      return {
        width : choiceMaxWidth,
        height : choiceMaxHeight
      };
    }

    function calculateContainerPadding(target, options, container) {
      var paddingTestDiv = $('<div style="padding:0px 0px 0px 0px;"/>');
      paddingTestDiv.css("padding-top", $(container).css("padding-top"));
      var paddingTop = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-top", "0px");
      paddingTestDiv.css("padding-right", $(container).css("padding-right"));
      var paddingRight = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-right", "0px");
      paddingTestDiv.css("padding-bottom", $(container).css("padding-bottom"));
      var paddingBottom = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-bottom", "0px");
      paddingTestDiv.css("padding-left", $(container).css("padding-left"));
      var paddingLeft = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-left", "0px");
      return {
        top : paddingTop,
        right : paddingRight,
        bottom : paddingBottom,
        left : paddingLeft
      };
    }

    function createChoiceContainer(target, options, contentHtml) {
      var choice = $("<div />").addClass(options.containers.choices.container.css.identifier).css("position", "absolute");
      var contentDiv = $("<div />").addClass(options.containers.choices.content.css.identifier);
      $(choice).append(contentDiv);
      var feedbackDiv = $("<div />").addClass(options.containers.choices.feedback.css.identifier);
      $(choice).append(feedbackDiv);
      var feedbackIconDiv = $("<div />").addClass(options.containers.choices.feedbackIcon.css.identifier);
      $(choice).append(feedbackIconDiv);
      var overlayDiv = $("<div />").addClass(options.containers.choices.overlay.css.identifier);
      $(choice).append(overlayDiv);
      if (contentHtml) {
        $(contentDiv).html(contentHtml);
      }
      return choice;
    }

    function enableDisable(target, options, choices) {
      log(target, options, "Enabling/Disabling Activity:" + options.data.enabled, "info");
      choices = choices || getChoices(target, options);
      if (options.data.enabled) {
        $(options.containers.content.reference).removeClass(options.containers.content.css.disabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.enabled);
        $(target).trigger("enabled.selectAllActivity", [options.data.dataSets.length]);
      } else {
        $(options.containers.content.reference).removeClass(options.containers.content.css.enabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.disabled);
        clearChoicesHover(target, options, choices);
        $(target).trigger("disabled.selectAllActivity", [options.data.dataSets.length]);
      }
    }

    function resizeChoices(target, options, width, height, choices) {
      choices = choices || getChoices(target, options);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).width(width);
        $(choice).height(height);
      }
    }

    function positionChoices(target, options, choices, containerPadding) {
      choices = choices || getChoices(target, options);
      containerPadding = containerPadding || calculateContainerPadding(target, options, options.containers.choice.reference);
      var choiceData = null;
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceData = $(choice).data("selectAllActivity:choice");
        $(choice).css("left", (-containerPadding.left + $(choice).outerWidth() * choiceData.column) + "px");
        $(choice).css("top", (-containerPadding.top + $(choice).outerHeight() * choiceData.row) + "px");
      }
    }

    function randomizeChoicePositionsInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var setData = $(setContainer).data("selectAllActivity:set");
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceData = null;
      var unpositionedChoices = [];
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceData = $(choice).data("selectAllActivity:choice");
        choiceData.row = null;
        choiceData.column = null;
        $(choice).data("selectAllActivity:choice", choiceData);
        unpositionedChoices.push(choice);
      }
      var choiceMatrix = [];
      var currentRow = 0;
      var currentColumn = 0;
      var currentRowArray = null;
      for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
        currentRowArray = [];
        for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
          currentRowArray.push(null);
        }
        choiceMatrix.push(currentRowArray);
      }
      var positioningChoice = null;
      var randomSelector = null;
      var found = false;
      while (unpositionedChoices.length > 0) {
        randomSelector = Math.floor(Math.random() * unpositionedChoices.length);
        choice = unpositionedChoices.splice(randomSelector, 1);
        choiceData = $(choice).data("selectAllActivity:choice");
        found = false;
        for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
          for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
            if (!choiceMatrix[currentRow][currentColumn] && !found) {
              found = true;
              choiceMatrix[currentRow][currentColumn] = choice;
            }
          }
        }
        choice = null;
      }
      for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
        for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
          choice = choiceMatrix[currentRow][currentColumn];
          choiceData = $(choice).data("selectAllActivity:choice");
          choiceData.row = currentRow;
          choiceData.column = currentColumn;
          $(choice).data("selectAllActivity:choice", choiceData);
        }
      }
    }

    function registerChoiceEvents(target, options, choice) {
      $(choice).children("." + options.containers.choices.overlay.css.identifier).bind("mouseover", function() {
        var options = $(target).data("selectAllActivity:options");
        var choiceOptions = $(choice).data("selectAllActivity:choice");
        var setOptions = $(choice).parent().data("selectAllActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if (!$(this).parent().hasClass(options.containers.choices.container.css.hover)) {
            clearChoicesHover(target, options);
            $(this).parent().addClass(options.containers.choices.container.css.hover);
            setOptions.focusedChoiceId = choiceOptions.id;
            setOptions.focusedChoiceRow = choiceOptions.row;
            setOptions.focusedChoiceColumn = choiceOptions.column;
            $(choice).parent().data("selectAllActivity:set", setOptions);
            options.accessibility.hasFocus = true;
            $(target).data("selectAllActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.overlay.css.identifier).bind("mouseout", function() {
        var options = $(target).data("selectAllActivity:options");
        var choiceOptions = $(choice).data("selectAllActivity:choice");
        var setOptions = $(choice).parent().data("selectAllActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if ($(this).parent().hasClass(options.containers.choices.container.css.hover)) {
            $(this).parent().removeClass(options.containers.choices.container.css.hover);
            options.accessibility.hasFocus = true;
            $(target).data("selectAllActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.overlay.css.identifier).bind("click", function() {
        var options = $(target).data("selectAllActivity:options");
        var choiceOptions = $(choice).data("selectAllActivity:choice");
        var setOptions = $(choice).parent().data("selectAllActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          var shouldRecalculate = false;
          if (setOptions.gradeIndividually) {
            if (!$(this).parent().hasClass(options.containers.choices.container.css.selected)) {
              $(this).parent().addClass(options.containers.choices.container.css.selected);
            } else {
              if ($(this).parent().hasClass(options.containers.choices.container.css.selected) && setOptions.allowRetry) {
                $(this).parent().removeClass(options.containers.choices.container.css.selected);
              }
            }
            shouldRecalculate = true;
          } else {
            if (setOptions.allowRetry || (!setOptions.allowRetry && setOptions.attempts == 0)) {
              if (!$(this).parent().hasClass(options.containers.choices.container.css.selected)) {
                $(this).parent().addClass(options.containers.choices.container.css.selected);
              } else {
                if ($(this).parent().hasClass(options.containers.choices.container.css.selected)) {
                  $(this).parent().removeClass(options.containers.choices.container.css.selected);
                }
              }
              shouldRecalculate = true;
            }
          }
          options.accessibility.hasFocus = true;
          $(target).data("selectAllActivity:options", options);
          if (shouldRecalculate) {
            calculateActivityScore(target, options);
          }
        }
      });
    }

    function getSetContainers(target, options) {
      return $(options.containers.choice.reference).children("." + options.containers.set.css.identifier) || [];
    }

    function getActiveSetContainer(target, options) {
      return $(options.containers.choice.reference).children("."+options.containers.set.css.identifier).filter("."+options.containers.set.css.selected)[0] || null;
    }

    function getChoices(target, options) {
      var activeSetContainer = getActiveSetContainer(target, options);
      return $(activeSetContainer).children("." + options.containers.choices.container.css.identifier) || [];
    }

    function getChoicesInSet(target, options, setContainer) {
      return $(setContainer).children("." + options.containers.choices.container.css.identifier) || [];
    }

    function clearChoicesHover(target, options, choices) {
      if (!choices) {
        choices = getChoices(target, options);
      }
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.hover);
      }
    }

    function focusChoiceInSet(target, options, setContainer, id, row, column, selectChoice) {
      log(target, options, "Focusing Choice:{id:" + id + ",row:" + row + ",column:" + column + "}", "info");
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      selectChoice = selectChoice || false;
      clearChoicesHover(target, options, choices);
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceOptions = $(choice).data("selectAllActivity:choice");
        if (id == choiceOptions.id) {
          $(choice).children("." + options.containers.choices.overlay.css.identifier).trigger("mouseover");
          if (selectChoice) {
            $(choice).children("." + options.containers.choices.overlay.css.identifier).trigger("click");
          }
        } else {
          if (row == choiceOptions.row && column == choiceOptions.column) {
            $(choice).children("." + options.containers.choices.overlay.css.identifier).trigger("mouseover");
            if (selectChoice) {
              $(choice).children("." + options.containers.choices.overlay.css.identifier).trigger("click");
            }
          } else {
            $(choice).children("." + options.containers.choices.overlay.css.identifier).trigger("mouseout");
          }
        }
      }
    }

    function clearSelectedChoicesInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.selected);
      }
    }

    function clearSelectedChoices(target, options, choices) {
      choices = choices || getChoices(target, options);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.selected);
      }
    }

    function registerKeyboardEvents(target, options, choices) {
      $(document).keydown(function(event) {
        var options = $(target).data("selectAllActivity:options");
        if (options.data.enabled && options.accessibility.keyboard.allow && options.accessibility.hasFocus) {
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("selectAllActivity:set");
          switch(event.keyCode) {
            case 38:
              if (activeSetData.focusedChoiceRow - 1 >= 0) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow - 1, activeSetData.focusedChoiceColumn);
              }
              break;
            case 40:
              if (activeSetData.focusedChoiceRow + 1 < activeSetData.rows) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow + 1, activeSetData.focusedChoiceColumn);
              }
              break;
            case 37:
              if (activeSetData.focusedChoiceColumn - 1 >= 0) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn - 1);
              }
              break;
            case 39:
              if (activeSetData.focusedChoiceColumn + 1 < activeSetData.columns) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn + 1);
              }
              break;
            case 32:
              focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn, true);
              break;
            case 13:
              calculateActivityScore(target, options);
              break;
          }
        }
      });
    }

    function registerPseudoMouseEvents(target, options, choices) {
      var pseudoMice = options.accessibility.pseudoMouse.mice;
      var mouse = null;
      var offset = null;
      var width = null;
      var height = null;
      var container = null;
      var found = false;
      for (var i = 0; i < pseudoMice.length; i++) {
        mouse = pseudoMice[i];
        $(mouse).bind("mousemove", function(event) {
          var options = $(target).data("selectAllActivity:options");
          if (options.data.enabled) {
            var event2 = new $.Event("mousemove");
            event2.pageX = event.pageX;
            event2.pageY = event.pageY;
            $(target).trigger(event2);
          }
          options = $(target).data("selectAllActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            var activeSet = getActiveSetContainer(target, options);
            var choices = getChoicesInSet(target, options, activeSet);
            for (var j = 0; j < choices.length; j++) {
              found = false;
              container = $(choices[j]).children("." + options.containers.choices.overlay.css.identifier).first();
              offset = $(container).offset();
              if ($(container).hasClass(options.containers.choices.container.css.hover)) {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      found = true;
                    }
                  }
                }
                if (!found) {
                  $(container).trigger("mouseout");
                }
              } else {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      $(container).trigger("mouseover");
                    }
                  }
                }
              }
            }
          }
        });
        $(mouse).bind("mouseup", function(event) {
          var options = $(target).data("selectAllActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            container = null;
            for (var j = 0; j < choices.length; j++) {
              container = $(choices[j]).children("." + options.containers.choices.overlay.css.identifier).first();
              offset = $(container).offset();
              width = $(container).width();
              height = $(container).height();
              if (event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
                $(container).trigger("click");
              }
            }
          }
        });
      }
    }

    function parseXMLAndBuildActivity(target, options, data) {
      log(target, options, "Parsing Activity XML", "info");
      try {
        if (window.ActiveXObject) {
          var doc = new ActiveXObject("Microsoft.XMLDOM");
          doc.loadXML(data);
          data = doc;
        } else {
          if (window.DOMParser) {
            data = (new DOMParser).parseFromString(data, "text/xml");
          }
        }
      } catch(error) {
        data = null;
        log(target, options, "XML Parse Error:{error:" + error + "}", "error");
      }
      if (data) {
        var activityData = {
          allowRetry : true,
          randomizeOnRetry : true,
          gradeSetsIndividually : false,
          dataSets : []
        };
        var idIndex = 0;
        var dataSet = null;
        var choice = null;
        if ($(data).children("selectAllActivity").attr("retry")) {
          activityData.allowRetry = ($(data).children("selectAllActivity").attr("retry").toLowerCase() == "true") ? true : false;
        }
        if ($(data).children("selectAllActivity").attr("randomizeOnRetry")) {
          activityData.randomizeOnRetry = ($(data).children("selectAllActivity").attr("randomizeOnRetry").toLowerCase() == "true") ? true : false;
        }
        if ($(data).children("selectAllActivity").attr("gradeSetsIndividually")) {
          activityData.gradeSetsIndividually = ($(data).children("selectAllActivity").attr("gradeSetsIndividually").toLowerCase() == "true") ? true : false;
        }
        $(data).children("selectAllActivity").children("set").each(function() {
          dataSet = {
            id : $(this).attr("id"),
            allowRetry : false,
            showFeedback : true,
            gradeIndividually : false,
            autoComplete : false,
            title : $(this).children("title:first").text(),
            rows : parseInt($(this).attr("rows")),
            columns : parseInt($(this).attr("columns")),
            choices : []
          };
          if ($(this).children("title:first").attr("encoding")) {
            dataSet.title = unescape(dataSet.title.replace(/\+/g, " "));
          }
          $(this).children("choices").children("choice").each(function() {
            choice = {
              id : $(this).attr("id"),
              content : $(this).text(),
              value : parseFloat($(this).attr("value")),
              correct : (($(this).attr("correct").toLowerCase() == "true") ? true : false),
              selectOnce : false
            };
            if ($(this).attr("encoding")) {
              choice.content = unescape(choice.content.replace(/\+/g, " "));
            }
            if ($(this).attr("selectOnce")) {
              choice.selectOnce = ($(this).attr("selectOnce").toLowerCase() == "true") ? true : false;
            }
            dataSet.choices.push(choice);
          });
          activityData.dataSets.push(dataSet);
        });
        buildActivity(target, options, activityData);
      } else {
        log(target, options, "XML Activity Build Error:{error:No data to build activity}", "error");
      }
    }

    function loadXMLAndBuildActivity(target, options, url) {
      log(target, options, "Loading XML", "info");
      $.ajax({
        url : url,
        dataType : "text",
        success : function(data, textStatus, xhr) {
          var options = $(target).data("selectAllActivity:options");
          log(target, options, "XML Loaded", "info");
          parseXMLAndBuildActivity(target, options, data);
        },
        error : function(xhr, textStatus, errorThrown) {
          log(target, options, "XML Load Error:{textStatus:" + textStatus + ",errorThrown:" + errorThrown + "}", "error");
        }
      });
    }

    function buildActivity(target, options, activityData) {
      var dataSet = null;
      var choiceDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      var currentChoice = null;
      var choices = [];
      var currentRow = 0;
      var currentColumn = 0;
      var choice = null;
      var setContainer = null;
      options.data.allowRetry = activityData.allowRetry;
      options.data.randomizeOnRetry = activityData.randomizeOnRetry;
      options.data.gradeSetsIndividually = activityData.gradeSetsIndividually;
      if (options.data.overridePoints || options.data.overridePoints == 0) {
        var totalCorrectPoints = 0;
        $.each(activityData.dataSets, function(i, dataSet) {
          $.each(dataSet.choices, function(j, choice) {
            if (choice.correct) {
              totalCorrectPoints += choice.value;
            }
          });
        });
        if (totalCorrectPoints == 0 || options.data.overridePoints == 0) {
          totalCorrectPoints = 0;
          $.each(activityData.dataSets, function(i, dataSet) {
            $.each(dataSet.choices, function(j, choice) {
              if (choice.correct) {
                if (options.data.overridePoints > 0) {
                  choice.value = 1;
                  totalCorrectPoints++;
                } else {
                  choice.value = 0;
                }
              }
            });
          });
        }
        var factor = options.data.overridePoints / totalCorrectPoints;
        $.each(activityData.dataSets, function(i, dataSet) {
          $.each(dataSet.choices, function(j, choice) {
            choice.value = choice.value * factor;
          });
        });
      }
      for (var i = 0; i < activityData.dataSets.length; i++) {
        dataSet = $.extend({}, activityData.dataSets[i], {
          choices : [],
          attempts : 0,
          focusedChoiceId : null,
          focusedChoiceRow : -1,
          focusedChoiceColumn : -1,
          completed : false
        });
        if (activityData.dataSets[i].choices.length % dataSet.columns) {
          dataSet.rows = parseInt(activityData.dataSets[i].choices.length / dataSet.columns) + 1;
        } else {
          dataSet.rows = parseInt(activityData.dataSets[i].choices.length / dataSet.columns);
        }
        options.data.dataSets.push(dataSet);
        choiceDimensions = calculateChoiceDimensions(target, options, dataSet.rows, dataSet.columns);
        currentRow = 0;
        currentColumn = 0;
        choice = null;
        for (var j = 0; j < activityData.dataSets[i].choices.length; j++) {
          choice = activityData.dataSets[i].choices[j];
          currentChoice = createChoiceContainer(target, options, choice.content);
          $(currentChoice).data("selectAllActivity:choice", {
            id : choice.id,
            row : currentRow,
            column : currentColumn,
            value : choice.value,
            correct : choice.correct,
            selectOnce : choice.selectOnce
          });
          registerChoiceEvents(target, options, currentChoice);
          dataSet.choices.push(currentChoice);
          choices.push(currentChoice);
          currentColumn++;
          if (currentColumn >= dataSet.columns) {
            currentColumn = 0;
            currentRow++;
          }
        }
        setContainer = createSetContainer(target, options);
        options.containers.set.references.push(setContainer);
        $(setContainer).data("selectAllActivity:set", dataSet);
        $(options.containers.choice.reference).append(setContainer);
        for (var j = 0; j < dataSet.choices.length; j++) {
          $(setContainer).append(dataSet.choices[j]);
        }
        resizeChoices(target, options, choiceDimensions.width, choiceDimensions.height, dataSet.choices);
        randomizeChoicePositionsInSet(target, options, setContainer);
        positionChoices(target, options, dataSet.choices);
        alignChoices(target, options, dataSet.choices);
      }
      registerAccessibilityEvents(target, options, choices);
      enableDisable(target, options, choices);
      $(target).data("selectAllActivity:options", options);
      alignSets(target, options);
      showSet(target, options, activityData.dataSets[0].id);
      calculateActivityScore(target, options, false);
      $(target).trigger("activityLoaded.selectAllActivity", [options.data.dataSets.length, 0, options.data.allowRetry, options.data.gradeSetsIndividually]);
    }

    function alignSets(target, options, setContainers) {
      setContainers = setContainers || getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var setWidth = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("selectAllActivity:set");
        setWidth = $(setContainer).width();
        $(setContainer).css("left", (setWidth * setContainerData.id) + "px");
      }
    }

    function createSetContainer(target, options) {
      return $("<div />").addClass(options.containers.set.css.identifier);
    }

    function showSet(target, options, id, setContainers, reset, resetPosition) {
      setContainers = setContainers || getSetContainers(target, options);
      reset = reset || false;
      resetPosition = resetPosition || false;
      var setContainer = null;
      var setContainerData = null;
      var selectedSetContainerData = null;
      var selectedSetContainer = null;
      var setPosition = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("selectAllActivity:set");
        $(setContainer).removeClass(options.containers.set.css.selected);
        if (setContainerData.id == id) {
          setPosition = i;
          selectedSetContainerData = setContainerData;
          selectedSetContainer = setContainer;
          $(setContainer).addClass(options.containers.set.css.selected);
        }
      }
      var choices = getChoices(target, options);
      positionChoices(target, options, choices);
      alignChoices(target, options, choices);
      if (reset && selectedSetContainerData) {
        options.data.enabled = true;
        enableDisable(target, options, choices);
        $(target).data("selectAllActivity:data", options);
      }
      if (resetPosition) {
        var width = $(options.containers.choice.reference).outerWidth();
        var finalPosition = -(width * [id]);
        $(options.containers.choice.reference).css("left", finalPosition + "px");
      }
      $(target).trigger("titleChanged.selectAllActivity", [selectedSetContainerData.title]);
      $(target).trigger("setChanged.selectAllActivity", [setContainers.length, setPosition, options.data.gradeSetsIndividually, options.data.allowRetry, selectedSetContainerData.completed, options.data.enabled]);
    }

    function showNextSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          if (setContainers[i] == currentSetContainer && i < setContainers.length - 1) {
            var width = $(options.containers.choice.reference).outerWidth();
            var finalPosition = -(width * [i + 1]);
            if (options.data.animate) {
              $(options.containers.choice.reference).stop(true, false).addClass(options.containers.choice.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.choice.css.animating);
              });
            } else {
              $(options.containers.choice.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i + 1]).data("selectAllActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function showPreviousSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          $(setContainers[i]).stop(true, true);
          if (setContainers[i] == currentSetContainer && i > 0) {
            var width = $(options.containers.choice.reference).outerWidth();
            var finalPosition = -(width * [i - 1]);
            if (options.data.animate) {
              $(options.containers.choice.reference).stop(true, false).addClass(options.containers.choice.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.choice.css.animating);
              });
            } else {
              $(options.containers.choice.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i - 1]).data("selectAllActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function getSetState(target, options, setContainer) {
      var setContainerData = $(setContainer).data("selectAllActivity:set");
      var setState = {
        id : setContainerData.id,
        allowRetry : setContainerData.allowRetry,
        showFeedback : setContainerData.showFeedback,
        gradeIndividually : setContainerData.gradeIndividually,
        attempts : setContainerData.attempts,
        completed : setContainerData.completed,
        choices : []
      };
      var setChoices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      var normalizedChoiceData = null;
      for (var i = 0; i < setChoices.length; i++) {
        choice = setChoices[i];
        choiceOptions = $(choice).data("selectAllActivity:choice");
        normalizedChoiceData = {
          id : choiceOptions.id,
          row : choiceOptions.row,
          column : choiceOptions.column,
          correct : choiceOptions.correct,
          value : choiceOptions.value,
          selected : $(choice).hasClass(options.containers.choices.container.css.selected),
          finished : $(choice).hasClass(options.containers.choices.container.css.correct) || $(choice).hasClass(options.containers.choices.container.css.incorrect) || false
        };
        setState.choices.push(normalizedChoiceData);
      }
      return setState;
    }

    function setSetState(target, options, setContainer, setState) {
      log(target, options, "Setting Set State:" + setState.id);
      var setContainerData = $(setContainer).data("selectAllActivity:set");
      setContainerData.allowRetry = setState.allowRetry;
      setContainerData.showFeedback = setState.showFeedback;
      setContainerData.gradeIndividually = setState.gradeIndividually;
      setContainerData.attempts = setState.attempts;
      setContainerData.completed = setState.completed;
      $(setContainer).data("selectAllActivity:set", setContainerData);
      if (setContainerData.completed && !$(setContainer).hasClass(options.containers.set.css.completed)) {
        $(setContainer).addClass(options.containers.set.css.completed);
      }
      var setChoices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      var normalizedChoiceData = null;
      for (var i = 0; i < setChoices.length; i++) {
        choice = setChoices[i];
        choiceOptions = $(choice).data("selectAllActivity:choice");
        for (var j = 0; j < setState.choices.length; j++) {
          normalizedChoiceData = setState.choices[j];
          if (normalizedChoiceData.id == choiceOptions.id) {
            choiceOptions.row = normalizedChoiceData.row;
            choiceOptions.column = normalizedChoiceData.column;
            choiceOptions.correct = normalizedChoiceData.correct;
            choiceOptions.value = normalizedChoiceData.value;
            $(choice).removeClass(options.containers.choices.container.css.selected);
            if (normalizedChoiceData.selected) {
              $(choice).addClass(options.containers.choices.container.css.selected);
            }
            if (normalizedChoiceData.finished) {
              if (normalizedChoiceData.correct) {
                $(choice).addClass(options.containers.choices.container.css.correct);
              } else {
                $(choice).addClass(options.containers.choices.container.css.incorrect);
              }
            }
          }
        }
        $(choice).data("selectAllActivity:choice", choiceOptions);
      }
    }

    function calculateActivityScore(target, options, incrementAttempts, autoCompleteOverride, doNotUpdateExternalScore) {
      incrementAttempts = incrementAttempts || true;
      autoCompleteOverride = autoCompleteOverride || false;
      doNotUpdateExternalScore = doNotUpdateExternalScore || false;
      var choiceSets = getSetContainers(target, options);
      var activeSet = getActiveSetContainer(target, options);
      var activeSetPosition = 0;
      var setScore = null;
      var setData = null;
      var setScores = [];
      var calculatedScore = 0;
      var calculatedPossible = 0;
      var totalCorrect = 0;
      var totalIncorrect = 0;
      var correctSelected = 0;
      var incorrectSelected = 0;
      for (var i = 0; i < choiceSets.length; i++) {
        setData = $(choiceSets[i]).data("selectAllActivity:set");
        if (choiceSets[i] == activeSet) {
          activeSetPosition = i;
        }
        if (options.data.gradeSetsIndividually && choiceSets[i] == activeSet) {
          setScore = calculateSetScore(target, options, choiceSets[i], incrementAttempts, autoCompleteOverride);
        } else {
          if (options.data.gradeSetsIndividually && choiceSets[i] != activeSet) {
            setScore = calculateSetScore(target, options, choiceSets[i], false, false);
          } else {
            setScore = calculateSetScore(target, options, choiceSets[i], incrementAttempts, autoCompleteOverride);
          }
        }
        calculatedScore += setScore.calculatedScore;
        calculatedPossible += setScore.calculatedPossible;
        totalCorrect += setScore.totalCorrect;
        totalIncorrect += setScore.totalIncorrect;
        correctSelected += setScore.correctSelected;
        incorrectSelected += setScore.incorrectSelected;
        $(target).trigger("setScoreChanged.selectAllActivity", [options.data.dataSets.length, i, options.data.allowRetry, options.data.gradeSetsIndividually, setScore.calculatedScore, setScore.calculatedPossible, $(choiceSets[i]).data("selectAllActivity:set").completed, doNotUpdateExternalScore]);
      }
      log(target, options, "Score Recalculated:" + calculatedScore + "/" + calculatedPossible, "info");
      $(target).trigger("activityScoreChanged.selectAllActivity", [options.data.dataSets.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually, calculatedScore, calculatedPossible, $(activeSet).data("selectAllActivity:set").completed, doNotUpdateExternalScore]);
      if (!options.data.gradeSetsIndividually && autoCompleteOverride) {
        options.data.enabled = false;
        $(target).data("selectAllActivity:options", options);
        enableDisable(target, options);
        log(target, options, "Activity Completed:" + calculatedScore + "/" + calculatedPossible, "info");
        $(target).trigger("activityComplete.selectAllActivity", [options.data.dataSets.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually, calculatedScore, calculatedPossible, doNotUpdateExternalScore]);
      }
      return {
        calculatedScore : calculatedScore,
        calculatedPossible : calculatedPossible,
        totalCorrect : totalCorrect,
        totalIncorrect : totalIncorrect,
        correctSelected : correctSelected,
        incorrectSelected : incorrectSelected
      };
    }

    function calculateSetScore(target, options, setContainer, incrementAttempts, autoCompleteOverride) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      incrementAttempts = incrementAttempts || true;
      autoCompleteOverride = autoCompleteOverride || false;
      var setData = $(setContainer).data("selectAllActivity:set");
      var setState = getSetState(target, options, setContainer);
      var scoreResults = options.data.calculateScore(setState);
      if (setData.gradeIndividually) {
        if (setData.showFeedback) {
          showCorrectAndIncorrect(target, options, setContainer, true);
        }
      } else {
        if (setData.autoComplete && scoreResults.totalCorrect == scoreResults.correctSelected || autoCompleteOverride == true) {
          setData.completed = true;
          if (!$(setContainer).hasClass(options.containers.set.css.completed)) {
            $(setContainer).addClass(options.containers.set.css.completed);
          }
          if (setData.showFeedback) {
            showCorrectAndIncorrect(target, options, setContainer, false);
          }
          if (incrementAttempts) {
            setData.attempts++;
          }
        } else {
          clearCorrectAndIncorrectInSet(target, options, setContainer);
          if (!setData.completed) {
            scoreResults.calculatedScore = 0;
          } else {
            if (setData.showFeedback) {
              showCorrectAndIncorrect(target, options, setContainer, false);
            }
          }
        }
      }
      $(setContainer).data("selectAllActivity:set", setData);
      return scoreResults;
    }

    function showCorrectAndIncorrect(target, options, setContainer, showOnlySelected) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      showOnlySelected = showOnlySelected || true;
      if (options.data.enabled) {
        var choices = getChoicesInSet(target, options, setContainer);
        var choice = null;
        var choiceOptions = null;
        var showChoice = false;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          choiceOptions = $(choice).data("selectAllActivity:choice");
          showChoice = false;
          if (showOnlySelected && $(choice).hasClass(options.containers.choices.container.css.selected)) {
            showChoice = true;
          } else {
            if (!showOnlySelected) {
              showChoice = true;
            }
          }
          if (showChoice) {
            if (choiceOptions.correct) {
              $(choice).removeClass(options.containers.choices.container.css.incorrect);
              if (!$(choice).hasClass(options.containers.choices.container.css.correct)) {
                $(choice).addClass(options.containers.choices.container.css.correct);
              }
            } else {
              $(choice).removeClass(options.containers.choices.container.css.correct);
              if (!$(choice).hasClass(options.containers.choices.container.css.incorrect)) {
                $(choice).addClass(options.containers.choices.container.css.incorrect);
              }
            }
          } else {
            $(choice).removeClass(options.containers.choices.container.css.correct);
            $(choice).removeClass(options.containers.choices.container.css.incorrect);
          }
        }
      }
    }

    function clearCorrectAndIncorrect(target, options, choices, showOnlySelected) {
      choices = choices || getChoices(target, options);
      showOnlySelected = showOnlySelected || true;
      if (options.data.enabled) {
        var choice = null;
        var showChoice = false;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          $(choice).removeClass(options.containers.choices.container.css.incorrect);
          $(choice).removeClass(options.containers.choices.container.css.correct);
        }
      }
    }

    function clearCorrectAndIncorrectInSet(target, options, setContainer, showOnlySelected) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      showOnlySelected = showOnlySelected || true;
      choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var showChoice = false;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.incorrect);
        $(choice).removeClass(options.containers.choices.container.css.correct);
      }
    }

    function alignChoices(target, options, choices) {
      choices = choices || getChoices(target, options);
      if (choices) {
        var choice = null;
        var choiceContent = null;
        var choiceOptions = null;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          choiceContent = $(choice).children("." + options.containers.choices.content.css.identifier + ":first");
          alignToParent(target, options, options.containers.choices.content.horizontalAlign, options.containers.choices.content.verticalAlign, choiceContent);
        }
      }
    }

    function alignToParent(target, options, horizontalAlign, verticalAlign, container) {
      $(container).css("position", "absolute");
      if (horizontalAlign) {
        switch(horizontalAlign.toLowerCase()) {
          case"left":
            $(container).css("right", null).css("left", "0px");
            break;
          case"right":
            $(container).css("left", null).css("right", "0px");
            break;
          case"center":
            $(container).css("right", null).css("left", ($(container).parent().innerWidth() / 2 - $(container).outerWidth() / 2) + "px");
            break;
        }
      }
      if (verticalAlign) {
        switch(verticalAlign.toLowerCase()) {
          case"top":
            $(container).css("bottom", null).css("top", "0px");
            break;
          case"bottom":
            $(container).css("top", null).css("bottom", "0px");
            break;
          case"middle":
            $(container).css("bottom", null).css("top", ($(container).parent().innerHeight() / 2 - $(container).outerHeight() / 2) + "px");
            break;
        }
      }
    }

    function resetActivity(target, options) {
      if (options.data.allowRetry) {
        log(target, options, "Resetting Activity", "info");
        var setContainers = getSetContainers(target, options);
        var activeSet = getActiveSetContainer(target, options);
        var activeSetPosition = 0;
        var setContainer = null;
        var setContainerData = null;
        var choices = null;
        var calculatedScore = 0;
        var calculatedPossible = 0;
        var setScore = null;
        options.data.enabled = true;
        for (var i = 0; i < setContainers.length; i++) {
          setContainer = setContainers[i];
          setContainerData = $(setContainer).data("selectAllActivity:set");
          if (setContainer == activeSet) {
            activeSetPosition = i;
          }
          if ((options.data.gradeSetsIndividually && setContainer == activeSet) || !options.data.gradeSetsIndividually) {
            setContainerData.attempts = 0;
            setContainerData.completed = false;
            setContainerData.focusedChoiceId = null;
            setContainerData.focusedChoiceRow = -1;
            setContainerData.focusedChoiceColumn = -1;
            $(setContainer).data("selectAllActivity:set", setContainerData);
            choices = getChoicesInSet(target, options, setContainer);
            clearChoicesHover(target, options, choices);
            clearCorrectAndIncorrectInSet(target, options, setContainer);
            clearSelectedChoices(target, options, choices);
            setScore = calculateSetScore(target, options, setContainer);
            calculatedScore += setScore.calculatedScore;
            calculatedPossible += setScore.calculatedPossible;
            if (options.data.randomizeOnRetry) {
              randomizeChoicePositionsInSet(target, options, setContainer);
              positionChoices(target, options, choices);
            }
            if ($(setContainer).hasClass(options.containers.set.css.completed)) {
              $(setContainer).removeClass(options.containers.set.css.completed);
            }
          }
        }
        enableDisable(target, options);
        var setPosition = $(activeSet).data("selectAllActivity:set").id;
        if (!options.data.gradeSetsIndividually && options.data.randomizeOnRetry) {
          setPosition = Math.floor(Math.random() * setContainers.length);
        }
        setContainer = setContainers[setPosition];
        setContainerData = $(setContainer).data("selectAllActivity:set");
        showSet(target, options, setContainerData.id, setContainers, false, true);
        activeSet = getActiveSetContainer(target, options);
        for (var i = 0; i < setContainers.length; i++) {
          setContainer = setContainers[i];
          setContainerData = $(setContainer).data("selectAllActivity:set");
          if (setContainer == activeSet) {
            activeSetPosition = i;
          }
        }
        $(target).data("selectAllActivity:options", options);
        $(target).trigger("reset.selectAllActivity", [setContainers.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually]);
        calculateActivityScore(target, options, false);
      }
    }

    function getActiveSetContainerId(target, options) {
      return $(getActiveSetContainer(target, options)).data("selectAllActivity:set").id || null;
    }

    function getActivityState(target, options) {
      var activityState = {
        completed : options.data.completed,
        enabled : options.data.enabled,
        allowRetry : options.data.allowRetry,
        randomizeOnRetry : options.data.randomizeOnRetry,
        activeSetId : getActiveSetContainerId(target, options),
        sets : []
      };
      var setContainers = getSetContainers(target, options);
      for (var i = 0; i < setContainers.length; i++) {
        activityState.sets.push(getSetState(target, options, setContainers[i]));
      }
      return activityState;
    }

    function setActivityState(target, options, activityState, completed) {
      log(target, options, "Setting Activity State");
      var setData = null;
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var choices = null;
      showSet(target, options, activityState.activeSetId, false, true);
      for (var i = 0; i < activityState.sets.length; i++) {
        setData = activityState.sets[i];
        for (var j = 0; j < setContainers.length; j++) {
          setContainer = setContainers[j];
          setContainerData = $(setContainer).data("selectAllActivity:set");
          choices = getChoicesInSet(target, options, setContainer);
          if (setData.id == setContainerData.id) {
            setSetState(target, options, setContainer, setData);
          }
          positionChoices(target, options, choices);
        }
      }
      options.data.completed = activityState.completed;
      options.data.enabled = activityState.enabled;
      options.data.allowRetry = activityState.allowRetry;
      options.data.randomizeOnRetry = activityState.randomizeOnRetry;
      $(target).data("selectAllActivity:options", options);
      enableDisable(target, options);
      calculateActivityScore(target, options, false, completed, true);
    }
    return this;
  };
  $.fn.selectAllActivity.defaults = {};
  $.fn.selectAllActivity.defaults.containers = {
    activity : {
      reference : null,
      css : {
        identifier : "softchalk-select-all-activity"
      }
    },
    content : {
      reference : null,
      css : {
        identifier : "softchalk-select-all-activity-content",
        enabled : "enabled",
        disabled : "disabled"
      }
    },
    choice : {
      reference : null,
      css : {
        identifier : "softchalk-select-all-activity-sets",
        animating : "animating"
      }
    },
    set : {
      references : [],
      css : {
        identifier : "softchalk-select-all-activity-set",
        selected : "selected",
        completed : "completed"
      }
    },
    choices : {
      references : [],
      container : {
        css : {
          identifier : "softchalk-select-all-activity-choice",
          selected : "selected",
          correct : "correct",
          incorrect : "incorrect",
          hover : "hover"
        }
      },
      content : {
        horizontalAlign : "center",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-select-all-activity-choice-content"
        }
      },
      feedback : {
        css : {
          identifier : "softchalk-select-all-activity-choice-feedback"
        }
      },
      feedbackIcon : {
        horizontalAlign : "right",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-select-all-activity-choice-feedback-icon"
        }
      },
      overlay : {
        css : {
          identifier : "softchalk-select-all-activity-choice-overlay"
        }
      }
    }
  };
  $.fn.selectAllActivity.defaults.data = {
    dataSets : [],
    completed : false,
    calculateScore : function(setState) {
      var calculatedCorrect = 0;
      var calculatedIncorrect = 0;
      var calculatedPossible = 0;
      var choiceData = null;
      var correctSelected = 0;
      var incorrectSelected = 0;
      var totalCorrect = 0;
      var totalIncorrect = 0;
      for (var i = 0; i < setState.choices.length; i++) {
        choiceData = setState.choices[i];
        if (choiceData.correct) {
          calculatedPossible += choiceData.value;
          totalCorrect++;
        } else {
          totalIncorrect++;
        }
        if (choiceData.selected && choiceData.correct) {
          calculatedCorrect += choiceData.value;
          correctSelected++;
        } else {
          if (choiceData.selected && !choiceData.correct) {
            calculatedIncorrect += choiceData.value;
            incorrectSelected++;
          }
        }
      }
      var calculatedScore = Math.max(0, calculatedCorrect - calculatedIncorrect);
      return {
        calculatedScore : calculatedScore,
        calculatedPossible : calculatedPossible,
        totalCorrect : totalCorrect,
        totalIncorrect : totalIncorrect,
        correctSelected : correctSelected,
        incorrectSelected : incorrectSelected
      };
    },
    enabled : true,
    enableLogging : false,
    allowRetry : true,
    randomizeOnRetry : true,
    animate : true,
    gradeSetsIndividually : false,
    overridePoints : null
  };
  $.fn.selectAllActivity.defaults.accessibility = {
    pseudoMouse : {
      allow : false,
      mice : []
    },
    keyboard : {
      allow : true
    },
    hasFocus : false
  };
  $.fn.selectAllActivity.defaults.logging = {
    debug : false,
    info : true,
    warn : false,
    error : false
  };
})(jQuery);
(function($) {
  $.fn.slideIdentificationActivity = function(action, options) {
    var shouldReturnResults = false;
    var results = [];
    var params = null;
    action = action || "initialize";
    if ( typeof (action) == "object") {
      options = action;
      action = "initialize";
    }
    if (action == "initialize") {
      if (!options) {
        options = $.fn.slideIdentificationActivity.defaults;
      } else {
        options = $.extend(true, {}, $.fn.slideIdentificationActivity.defaults, options);
      }
    } else {
      params = options;
    }
    var optionsReference = options;
    $(this).each(function() {
      switch(action) {
        case"initialize":
          log(this, optionsReference, "Action:Initializing Activity", "info");
          initialize(this, optionsReference);
          break;
        case"loadXMLAndBuildActivity":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Loading XML", "info");
          loadXMLAndBuildActivity(this, options, params);
          break;
        case"parseXMLAndBuildActivity":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Parsing XML", "info");
          parseXMLAndBuildActivity(this, options, params);
          break;
        case"calculateScore":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Calculating Score", "info");
          calculateScore(this, options);
          break;
        case"finish":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Finishing Activity", "info");
          calculateActivityScore(this, options, true, true);
          break;
        case"reset":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Resetting Activity", "info");
          resetActivity(this, options);
          break;
        case"showNextSet":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Showing Next Set", "info");
          showNextSet(this, options);
          break;
        case"showPreviousSet":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Showing Previous Set", "info");
          showPreviousSet(this, options);
          break;
        case"getState":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Getting Activity State", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getActivityState(this, options)
          });
          break;
        case"setState":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Setting Activity State", "info");
          setActivityState(this, options, params.state, params.completed);
          break;
        case"getEnabled":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Getting Enabled", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.enabled
          });
          break;
        case"setEnabled":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Setting Enabled", "info");
          options.data.enabled = params;
          $(this).data("slideIdentificationActivity:options", options);
          enableDisable(this, options);
          break;
        case"getSetIds":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Getting Set Ids", "info");
          var setContainers = getSetContainers(this, options);
          var setContainer = null;
          var setContainerData = null;
          var setIds = [];
          for (var i = 0; i < setContainers.length; i++) {
            setContainer = setContainers[i];
            setContainerData = $(setContainer).data("slideIdentificationActivity:set");
            setIds.push(setContainerData.id);
          }
          shouldReturnResults = true;
          results.push({
            target : this,
            result : setIds
          });
          break;
        case"getNumberOfSets":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getSetContainers(this, options).length
          });
          break;
        case"showSet":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          showSet(this, options, params);
          break;
        case"getAllowReset":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Getting allow reset", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.allowRetry
          });
          break;
        case"resize":
          var options = $(this).data("slideIdentificationActivity:options");
          log(this, options, "Action:Resizing the activity", "info");
          handleResize(this, options);
          break;
      }
    });
    if (shouldReturnResults == true) {
      return results;
    }
    function log(target, options, data, level) {
      level = level || "debug";
      level = $.trim(level).toLowerCase();
      if (options.data.enableLogging && window.console) {
        if (level == "info" && window.console.info && options.logging.info) {
          if ($(target).attr("id")) {
            window.console.info("[slideIdentificationActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
          } else {
            if ($(target).attr("name")) {
              window.console.info("[slideIdentificationActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
            } else {
              window.console.info("[slideIdentificationActivity][" + target + "]" + data);
            }
          }
        } else {
          if (level == "warn" && window.console.warn && options.logging.warn) {
            if ($(target).attr("id")) {
              window.console.warn("[slideIdentificationActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
            } else {
              if ($(target).attr("name")) {
                window.console.warn("[slideIdentificationActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
              } else {
                window.console.warn("[slideIdentificationActivity][" + target + "]" + data);
              }
            }
          } else {
            if (level == "error" && window.console.error && options.logging.error) {
              if ($(target).attr("id")) {
                window.console.error("[slideIdentificationActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
              } else {
                if ($(target).attr("name")) {
                  window.console.error("[slideIdentificationActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                } else {
                  window.console.error("[slideIdentificationActivity][" + target + "]" + data);
                }
              }
            } else {
              if (window.console.log && options.logging.debug) {
                if ($(target).attr("id")) {
                  window.console.log("[slideIdentificationActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
                } else {
                  if ($(target).attr("name")) {
                    window.console.log("[slideIdentificationActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                  } else {
                    window.console.log("[slideIdentificationActivity][" + target + "]" + data);
                  }
                }
              }
            }
          }
        }
      }
    }

    function initialize(target, options) {
      options = $.extend(true, {}, options);
      options.containers.activity.reference = target;
      $(options.containers.activity.reference).addClass(options.containers.activity.css.identifier);
      options.containers.content.reference = target;
      $(options.containers.content.reference).addClass(options.containers.content.css.identifier);
      if (options.containers.choice.reference == null) {
        options.containers.choice.reference = $("<div />");
        $(options.containers.content.reference).append(options.containers.choice.reference);
      }
      options.containers.choice.reference.addClass(options.containers.choice.css.identifier);
      $(target).data("slideIdentificationActivity:options", options);
    }

    function handleResize(target, options) {
      alignSets(target, options);
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var choices = null;
      var choiceDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("slideIdentificationActivity:set");
        choices = getChoicesInSet(target, options, setContainer);
        choiceDimensions = calculateChoiceDimensions(target, options, setContainerData.rows, setContainerData.columns);
        resizeChoices(target, options, choiceDimensions.width, choiceDimensions.height, choices);
        positionChoices(target, options, choices);
        alignChoices(target, options, choices);
        alignSetImage(target, options, setContainer);
      }
      log(target, options, "Activity Container Resized", "info");
    }

    function registerAccessibilityEvents(target, options, choices) {
      var handleMiceEvents = function(event) {
        var options = $(this).data("slideIdentificationActivity:options");
        if (options.data.enabled && event.pageX && event.pageY) {
          var offset = $(this).offset();
          var width = $(this).outerWidth();
          var height = $(this).outerHeight();
          if (!options.accessibility.hasFocus && event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
            options.accessibility.hasFocus = true;
            $(this).data("slideIdentificationActivity:options", options);
          } else {
            if (options.accessibility.hasFocus && (event.pageX < offset.left || event.pageX > offset.left + width || event.pageY < offset.top || event.pageY > offset.top + height)) {
              options.accessibility.hasFocus = false;
              $(this).data("slideIdentificationActivity:options", options);
            }
          }
        }
      };
      $(target).bind("mouseover", handleMiceEvents).bind("mouseout", handleMiceEvents).bind("mousemove", handleMiceEvents);
      $(target).bind("focusin", function(event) {
        var options = $(this).data("slideIdentificationActivity:options");
        if (options.data.enabled && !options.accessibility.hasFocus) {
          log(target, options, "Giving Focus", "info");
          options.accessibility.hasFocus = true;
          $(this).data("slideIdentificationActivity:options", options);
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("slideIdentificationActivity:set");
          if (activeSetData.focusedChoiceRow < 0 || activeSetData.focusedChoiceColumn < 0 || !activeSetData.focusedChoiceId) {
            focusChoiceInSet(target, options, activeSet, null, 0, 0, false);
          }
        }
      });
      $(target).bind("focusout", function(event) {
        var options = $(this).data("slideIdentificationActivity:options");
        if (options.data.enabled && options.accessibility.hasFocus) {
          options.accessibility.hasFocus = false;
          $(this).data("slideIdentificationActivity:options", options);
        }
      });
      if (options.accessibility.keyboard.allow) {
        registerKeyboardEvents(target, options, choices);
      }
      if (options.accessibility.pseudoMouse.allow) {
        registerPseudoMouseEvents(target, options, choices);
      }
    }

    function calculateChoiceDimensions(target, options, rows, columns) {
      var containerWidth = $(options.containers.choice.reference).width();
      var containerHeight = $(options.containers.choice.reference).height();
      var borderTestDiv = $("<div />").css("display", "none").addClass(options.containers.choices.container.css.identifier).width(100).height(100);
      $(target).append(borderTestDiv);
      var borderWidthOffset = ($(borderTestDiv).outerWidth() - $(borderTestDiv).innerWidth()) / 2;
      var borderHeightOffset = ($(borderTestDiv).outerHeight() - $(borderTestDiv).innerHeight()) / 2;
      $(borderTestDiv).remove();
      containerWidth -= borderWidthOffset + 2;
      containerHeight -= borderHeightOffset * (2 * rows);
      var choiceMaxWidth = containerWidth;
      var choiceMaxHeight = 50;
      return {
        width : choiceMaxWidth,
        height : choiceMaxHeight
      };
    }

    function calculateContainerPadding(target, options, container) {
      var paddingTestDiv = $('<div style="padding:0px 0px 0px 0px;"/>');
      paddingTestDiv.css("padding-top", $(container).css("padding-top"));
      var paddingTop = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-top", "0px");
      paddingTestDiv.css("padding-right", $(container).css("padding-right"));
      var paddingRight = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-right", "0px");
      paddingTestDiv.css("padding-bottom", $(container).css("padding-bottom"));
      var paddingBottom = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-bottom", "0px");
      paddingTestDiv.css("padding-left", $(container).css("padding-left"));
      var paddingLeft = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-left", "0px");
      return {
        top : paddingTop,
        right : paddingRight,
        bottom : paddingBottom,
        left : paddingLeft
      };
    }

    function createQuestionContainer(target, options, contentHtml) {
      var question = $("<div />").addClass(options.containers.question.css.identifier);
      var contentDiv = $("<div />").addClass(options.containers.question.content.css.identifier);
      alignToParent(target, options, "center", "middle", contentDiv);
      $(question).append(contentDiv);
      if (contentHtml) {
        $(contentDiv).html(contentHtml);
      }
      return question;
    }

    function createImageContainer(target, options, contentHtml, imageAlignDelay) {
      var imageContainer = $("<div />").addClass(options.containers.image.container.css.identifier);
      if (contentHtml) {
        var image = $("<div />").addClass(options.containers.image.image.css.identifier);
        if (options.data.overrideImages && contentHtml.indexOf("<img") != -1) {
          contentHtml = "<span class='" + options.containers.image.noImage.css.identifier + "'>Image not available</span>";
        }
        $(image).html(contentHtml);
        $(imageContainer).append(image);
        setTimeout(function() {
          alignSetImage(target, options, $(image).parent().parent());
        }, imageAlignDelay);
      }
      return imageContainer;
    }

    function createChoiceContainer(target, options, contentHtml) {
      var choice = $("<div />").addClass(options.containers.choices.container.css.identifier).css("position", "absolute");
      var contentDiv = $("<div />").addClass(options.containers.choices.content.css.identifier);
      $(choice).append(contentDiv);
      var feedbackDiv = $("<div />").addClass(options.containers.choices.feedback.css.identifier);
      $(choice).append(feedbackDiv);
      var feedbackIconDiv = $("<div />").addClass(options.containers.choices.feedbackIcon.css.identifier);
      $(choice).append(feedbackIconDiv);
      var overlayDiv = $("<div />").addClass(options.containers.choices.overlay.css.identifier);
      $(choice).append(overlayDiv);
      var leftButtonDiv = $("<div />").addClass(options.containers.choices.leftButton.container.css.identifier);
      $(choice).append(leftButtonDiv);
      var leftButton = $("<div />").addClass(options.containers.choices.leftButton.button.css.identifier);
      $(leftButtonDiv).append(leftButton);
      var rightButtonDiv = $("<div />").addClass(options.containers.choices.rightButton.container.css.identifier);
      $(choice).append(rightButtonDiv);
      var rightButton = $("<div />").addClass(options.containers.choices.rightButton.button.css.identifier);
      $(rightButtonDiv).append(rightButton);
      if (contentHtml) {
        $(contentDiv).html(contentHtml);
      }
      return choice;
    }

    function enableDisable(target, options, choices) {
      log(target, options, "Enabling/Disabling Activity:" + options.data.enabled, "info");
      choices = choices || getChoices(target, options);
      if (options.data.enabled) {
        $(options.containers.content.reference).removeClass(options.containers.content.css.disabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.enabled);
        $(target).trigger("enabled.slideIdentificationActivity", [options.data.dataSets.length]);
      } else {
        $(options.containers.content.reference).removeClass(options.containers.content.css.enabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.disabled);
        clearChoicesHover(target, options, choices);
        $(target).trigger("disabled.slideIdentificationActivity", [options.data.dataSets.length]);
      }
    }

    function resizeChoices(target, options, width, height, choices) {
      choices = choices || getChoices(target, options);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).width(width);
        $(choice).height(height);
      }
    }

    function positionChoices(target, options, choices, containerPadding) {
      choices = choices || getChoices(target, options);
      containerPadding = containerPadding || calculateContainerPadding(target, options, options.containers.choice.reference);
      var choiceData = null;
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceData = $(choice).data("slideIdentificationActivity:choice");
        $(choice).css("left", (-containerPadding.left + $(choice).outerWidth() * (choiceData.column - 1)) + "px");
        $(choice).css("top", ($(options.containers.choice.reference).height() - $(choice).outerHeight()) + "px");
      }
    }

    function randomizeChoicePositionsInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var setData = $(setContainer).data("slideIdentificationActivity:set");
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceData = null;
      var unpositionedChoices = [];
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceData = $(choice).data("slideIdentificationActivity:choice");
        choiceData.column = null;
        $(choice).data("slideIdentificationActivity:choice", choiceData);
        unpositionedChoices.push(choice);
      }
      var choiceMatrix = [];
      var currentRow = 0;
      var currentColumn = 0;
      var currentRowArray = null;
      for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
        currentRowArray = [];
        for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
          currentRowArray.push(null);
        }
        choiceMatrix.push(currentRowArray);
      }
      var positioningChoice = null;
      var randomSelector = null;
      var found = false;
      while (unpositionedChoices.length > 0) {
        randomSelector = Math.floor(Math.random() * unpositionedChoices.length);
        choice = unpositionedChoices.splice(randomSelector, 1);
        choiceData = $(choice).data("slideIdentificationActivity:choice");
        found = false;
        currentRow = 0;
        for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
          if (!choiceMatrix[currentRow][currentColumn] && !found) {
            found = true;
            choiceMatrix[currentRow][currentColumn] = choice;
          }
        }
        choice = null;
      }
      for ( currentRow = 0; currentRow < setData.rows; currentRow++) {
        for ( currentColumn = 0; currentColumn < setData.columns; currentColumn++) {
          choice = choiceMatrix[currentRow][currentColumn];
          choiceData = $(choice).data("slideIdentificationActivity:choice");
          choiceData.column = currentColumn;
          $(choice).data("slideIdentificationActivity:choice", choiceData);
        }
      }
    }

    function registerChoiceEvents(target, options, choice) {
      $(choice).children("." + options.containers.choices.rightButton.container.css.identifier).bind("mouseover", function() {
        var options = $(target).data("slideIdentificationActivity:options");
        var choiceOptions = $(choice).data("slideIdentificationActivity:choice");
        var setOptions = $(choice).parent().data("slideIdentificationActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if (!$(this).hasClass(options.containers.choices.rightButton.container.css.hover)) {
            clearChoicesHover(target, options);
            $(this).addClass(options.containers.choices.rightButton.container.css.hover);
            setOptions.focusedChoiceId = choiceOptions.id;
            setOptions.focusedChoiceRow = choiceOptions.row;
            setOptions.focusedChoiceColumn = choiceOptions.column;
            $(choice).parent().data("slideIdentificationActivity:set", setOptions);
            options.accessibility.hasFocus = true;
            $(target).data("slideIdentificationActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.rightButton.container.css.identifier).bind("mouseout", function() {
        var options = $(target).data("slideIdentificationActivity:options");
        var choiceOptions = $(choice).data("slideIdentificationActivity:choice");
        var setOptions = $(choice).parent().data("slideIdentificationActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if ($(this).hasClass(options.containers.choices.rightButton.container.css.hover)) {
            $(this).removeClass(options.containers.choices.rightButton.container.css.hover);
            options.accessibility.hasFocus = true;
            $(target).data("slideIdentificationActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.rightButton.container.css.identifier).bind("click", function(event) {
        var options = $(target).data("slideIdentificationActivity:options");
        var choiceOptions = $(choice).data("slideIdentificationActivity:choice");
        var setOptions = $(choice).parent().data("slideIdentificationActivity:set");
        if (options.data.enabled && !setOptions.completed && !$(choice).hasClass(options.containers.choices.container.css.animating)) {
          var shouldRecalculate = false;
          shiftRow(target, options, null, $(this).parent(), 1);
          if (setOptions.gradeIndividually) {
            shouldRecalculate = true;
          } else {
            if (setOptions.allowRetry || (!setOptions.allowRetry && setOptions.attempts == 0)) {
              shouldRecalculate = true;
            }
          }
          options.accessibility.hasFocus = true;
          $(target).data("slideIdentificationActivity:options", options);
          if (shouldRecalculate) {
            calculateActivityScore(target, options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.leftButton.container.css.identifier).bind("mouseover", function() {
        var options = $(target).data("slideIdentificationActivity:options");
        var choiceOptions = $(choice).data("slideIdentificationActivity:choice");
        var setOptions = $(choice).parent().data("slideIdentificationActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if (!$(this).hasClass(options.containers.choices.leftButton.container.css.hover)) {
            clearChoicesHover(target, options);
            $(this).addClass(options.containers.choices.leftButton.container.css.hover);
            setOptions.focusedChoiceId = choiceOptions.id;
            setOptions.focusedChoiceRow = choiceOptions.row;
            setOptions.focusedChoiceColumn = choiceOptions.column;
            $(choice).parent().data("slideIdentificationActivity:set", setOptions);
            options.accessibility.hasFocus = true;
            $(target).data("slideIdentificationActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.leftButton.container.css.identifier).bind("mouseout", function() {
        var options = $(target).data("slideIdentificationActivity:options");
        var choiceOptions = $(choice).data("slideIdentificationActivity:choice");
        var setOptions = $(choice).parent().data("slideIdentificationActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if ($(this).hasClass(options.containers.choices.leftButton.container.css.hover)) {
            $(this).removeClass(options.containers.choices.leftButton.container.css.hover);
            options.accessibility.hasFocus = true;
            $(target).data("slideIdentificationActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.leftButton.container.css.identifier).bind("click", function(event) {
        var options = $(target).data("slideIdentificationActivity:options");
        var choiceOptions = $(choice).data("slideIdentificationActivity:choice");
        var setOptions = $(choice).parent().data("slideIdentificationActivity:set");
        if (options.data.enabled && !setOptions.completed && !$(choice).hasClass(options.containers.choices.container.css.animating)) {
          var shouldRecalculate = false;
          shiftRow(target, options, null, $(this).parent(), -1);
          if (setOptions.gradeIndividually) {
            shouldRecalculate = true;
          } else {
            if (setOptions.allowRetry || (!setOptions.allowRetry && setOptions.attempts == 0)) {
              shouldRecalculate = true;
            }
          }
          options.accessibility.hasFocus = true;
          $(target).data("slideIdentificationActivity:options", options);
          if (shouldRecalculate) {
            calculateActivityScore(target, options);
          }
        }
      });
    }

    function shiftRow(target, options, setContainer, choice, columnDelta, wrapAround) {
      log(target, options, choice, "info");
      setContainer = setContainer || getActiveSetContainer(target, options);
      columnDelta = columnDelta || 0;
      wrapAround = wrapAround || true;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      var choiceOptions = $(choice).data("slideIdentificationActivity:choice");
      var setOptions = $(setContainer).data("slideIdentificationActivity:set");
      var allChoicesInSet = getChoicesInSet(target, options, setContainer);
      var workingChoice = null;
      var workingChoiceData = null;
      var originalColumn = null;
      if (options.data.animate) {
        for (var i = 0; i < allChoicesInSet.length; i++) {
          workingChoice = allChoicesInSet[i];
          workingChoiceData = $(workingChoice).data("slideIdentificationActivity:choice");
          if (workingChoiceData.row == choiceOptions.row) {
            originalColumn = workingChoiceData.column;
            $(workingChoice).css("left", -containerPadding.left + $(workingChoice).outerWidth() * (workingChoiceData.column - 1));
            workingChoiceData.column += columnDelta;
            $(workingChoice).data("slideIdentificationActivity:choice", workingChoiceData);
            if (true) {
              $(workingChoice).addClass(options.containers.choices.container.css.animating);
              if (setOptions.columns == 2 && columnDelta < 0) {
                if (workingChoiceData.column < 0) {
                  workingChoiceData.column += setOptions.columns;
                } else {
                  if (workingChoiceData.column >= setOptions.columns) {
                    workingChoiceData.column -= setOptions.columns;
                  }
                }
                $(workingChoice).css("left", -containerPadding.left + $(workingChoice).outerWidth() * (workingChoiceData.column));
              }
              $(workingChoice).animate({
                left : -containerPadding.left + $(workingChoice).outerWidth() * (workingChoiceData.column - 1)
              }, "slow", null, function() {
                var reference = this;
                setTimeout(function() {
                  $(reference).removeClass(options.containers.choices.container.css.animating);
                  var data = $(reference).data("slideIdentificationActivity:choice");
                  if (data.column < 0) {
                    data.column += setOptions.columns;
                  } else {
                    if (data.column >= setOptions.columns) {
                      data.column -= setOptions.columns;
                    }
                  }
                  $(reference).data("slideIdentificationActivity:choice", data);
                  $(reference).css("left", -containerPadding.left + $(reference).outerWidth() * (data.column - 1));
                }, 50);
              });
            } else {
              $(workingChoice).css("left", -containerPadding.left + $(workingChoice).outerWidth() * (workingChoiceData.column - 1));
            }
          }
        }
      } else {
        for (var i = 0; i < allChoicesInSet.length; i++) {
          workingChoice = allChoicesInSet[i];
          workingChoiceData = $(workingChoice).data("slideIdentificationActivity:choice");
          if (workingChoiceData.row == choiceOptions.row) {
            workingChoiceData.column += columnDelta;
            if (workingChoiceData.column < 0) {
              workingChoiceData.column += setOptions.columns;
            } else {
              if (workingChoiceData.column >= setOptions.columns) {
                workingChoiceData.column -= setOptions.columns;
              }
            }
            $(workingChoice).data("slideIdentificationActivity:choice", workingChoiceData);
          }
        }
        positionChoices(target, options);
      }
    }

    function getSetContainers(target, options) {
      return $(options.containers.choice.reference).children("." + options.containers.set.css.identifier) || [];
    }

    function getActiveSetContainer(target, options) {
      return $(options.containers.choice.reference).children("."+options.containers.set.css.identifier).filter("."+options.containers.set.css.selected)[0] || null;
    }

    function getChoices(target, options) {
      var activeSetContainer = getActiveSetContainer(target, options);
      return $(activeSetContainer).children("." + options.containers.choices.container.css.identifier) || [];
    }

    function getChoicesInSet(target, options, setContainer) {
      return $(setContainer).children("." + options.containers.choices.container.css.identifier) || [];
    }

    function clearChoicesHover(target, options, choices) {
      if (!choices) {
        choices = getChoices(target, options);
      }
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.hover);
      }
    }

    function focusChoiceInSet(target, options, setContainer, id, row, column, selectChoice) {
      log(target, options, "Focusing Choice:{id:" + id + ",row:" + row + ",column:" + column + "}", "info");
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      selectChoice = selectChoice || false;
      clearChoicesHover(target, options, choices);
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceOptions = $(choice).data("slideIdentificationActivity:choice");
        if (id == choiceOptions.id) {
          $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseover");
          if (selectChoice) {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("click");
          }
        } else {
          if (row == choiceOptions.row && column == choiceOptions.column) {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseover");
            if (selectChoice) {
              $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("click");
            }
          } else {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseout");
          }
        }
      }
    }

    function clearSelectedChoicesInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.selected);
      }
    }

    function clearSelectedChoices(target, options, choices) {
      choices = choices || getChoices(target, options);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.selected);
      }
    }

    function registerKeyboardEvents(target, options, choices) {
      $(document).keydown(function(event) {
        var options = $(target).data("slideIdentificationActivity:options");
        if (options.data.enabled && options.accessibility.keyboard.allow && options.accessibility.hasFocus) {
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("slideIdentificationActivity:set");
          switch(event.keyCode) {
            case 38:
              if (activeSetData.focusedChoiceRow - 1 >= 0) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow - 1, activeSetData.focusedChoiceColumn);
              }
              break;
            case 40:
              if (activeSetData.focusedChoiceRow + 1 < activeSetData.rows) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow + 1, activeSetData.focusedChoiceColumn);
              }
              break;
            case 37:
              if (activeSetData.focusedChoiceColumn - 1 >= 0) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn - 1);
              }
              break;
            case 39:
              if (activeSetData.focusedChoiceColumn + 1 < activeSetData.columns) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn + 1);
              }
              break;
            case 32:
              focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn, true);
              break;
            case 13:
              calculateActivityScore(target, options);
              break;
          }
        }
      });
    }

    function registerPseudoMouseEvents(target, options, choices) {
      var pseudoMice = options.accessibility.pseudoMouse.mice;
      var mouse = null;
      var offset = null;
      var width = null;
      var height = null;
      var container = null;
      var found = false;
      for (var i = 0; i < pseudoMice.length; i++) {
        mouse = pseudoMice[i];
        $(mouse).bind("mousemove", function(event) {
          var options = $(target).data("slideIdentificationActivity:options");
          if (options.data.enabled) {
            var event2 = new $.Event("mousemove");
            event2.pageX = event.pageX;
            event2.pageY = event.pageY;
            $(target).trigger(event2);
          }
          options = $(target).data("slideIdentificationActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            var activeSet = getActiveSetContainer(target, options);
            var choices = getChoicesInSet(target, options, activeSet);
            for (var j = 0; j < choices.length; j++) {
              found = false;
              container = $(choices[j]).children("." + options.containers.choices.downarrow.css.identifier).first();
              offset = $(container).offset();
              if ($(container).hasClass(options.containers.choices.container.css.hover)) {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      found = true;
                    }
                  }
                }
                if (!found) {
                  $(container).trigger("mouseout");
                }
              } else {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      $(container).trigger("mouseover");
                    }
                  }
                }
              }
            }
          }
        });
        $(mouse).bind("mouseup", function(event) {
          var options = $(target).data("slideIdentificationActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            container = null;
            for (var j = 0; j < choices.length; j++) {
              container = $(choices[j]).children("." + options.containers.choices.downarrow.css.identifier).first();
              offset = $(container).offset();
              width = $(container).width();
              height = $(container).height();
              if (event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
                $(container).trigger("click");
              }
            }
          }
        });
      }
    }

    function parseXMLAndBuildActivity(target, options, data) {
      log(target, options, "Parsing Activity XML", "info");
      try {
        if (window.ActiveXObject) {
          var doc = new ActiveXObject("Microsoft.XMLDOM");
          doc.loadXML(data);
          data = doc;
        } else {
          if (window.DOMParser) {
            data = (new DOMParser).parseFromString(data, "text/xml");
          }
        }
      } catch(error) {
        data = null;
        log(target, options, "XML Parse Error:{error:" + error + "}", "error");
      }
      if (data) {
        var activityData = {
          allowRetry : true,
          randomizeOnRetry : true,
          gradeSetsIndividually : false,
          dataSets : []
        };
        var idIndex = 0;
        var dataSet = null;
        var choice = null;
        if ($(data).children("slideIdentificationActivity").attr("retry")) {
          activityData.allowRetry = ($(data).children("slideIdentificationActivity").attr("retry").toLowerCase() == "true") ? true : false;
        }
        if ($(data).children("slideIdentificationActivity").attr("randomizeOnRetry")) {
          activityData.randomizeOnRetry = ($(data).children("slideIdentificationActivity").attr("randomizeOnRetry").toLowerCase() == "true") ? true : false;
        }
        if ($(data).children("slideIdentificationActivity").attr("gradeSetsIndividually")) {
          activityData.gradeSetsIndividually = ($(data).children("slideIdentificationActivity").attr("gradeSetsIndividually").toLowerCase() == "true") ? true : false;
        }
        $(data).children("slideIdentificationActivity").children("set").each(function() {
          dataSet = {
            id : $(this).attr("id"),
            allowRetry : false,
            showFeedback : true,
            gradeIndividually : false,
            autoComplete : false,
            title : $(this).children("title:first").text(),
            image : $(this).children("image:first").text(),
            allowImageScale : true,
            imageAlignDelay : 50,
            rows : parseInt($(this).attr("rows")),
            columns : parseInt($(this).attr("columns")),
            choices : []
          };
          if ($(this).children("title:first").attr("encoding")) {
            dataSet.title = unescape(dataSet.title.replace(/\+/g, " "));
          }
          if ($(this).children("image:first").attr("encoding")) {
            dataSet.image = unescape(dataSet.image.replace(/\+/g, " "));
          }
          if ($(this).children("image:first").attr("allowScale") == "false") {
            dataSet.allowImageScale = false;
          }
          if ($(this).children("image:first").attr("imageAlignDelay")) {
            dataSet.imageAlignDelay = parseInt($(this).children("image:first").attr("imageAlignDelay"));
          }
          $(this).children("choices").children("choice").each(function() {
            choice = {
              id : $(this).attr("id"),
              content : $(this).text(),
              value : parseFloat($(this).attr("value")),
              correct : (($(this).attr("correct").toLowerCase() == "true") ? true : false),
              row : parseFloat($(this).attr("row")),
              selectOnce : false
            };
            if ($(this).attr("encoding")) {
              choice.content = unescape(choice.content.replace(/\+/g, " "));
            }
            if ($(this).attr("selectOnce")) {
              choice.selectOnce = ($(this).attr("selectOnce").toLowerCase() == "true") ? true : false;
            }
            dataSet.choices.push(choice);
          });
          activityData.dataSets.push(dataSet);
        });
        buildActivity(target, options, activityData);
      } else {
        log(target, options, "XML Activity Build Error:{error:No data to build activity}", "error");
      }
    }

    function loadXMLAndBuildActivity(target, options, url) {
      log(target, options, "Loading XML", "info");
      $.ajax({
        url : url,
        dataType : "text",
        success : function(data, textStatus, xhr) {
          var options = $(target).data("slideIdentificationActivity:options");
          log(target, options, "XML Loaded", "info");
          parseXMLAndBuildActivity(target, options, data);
        },
        error : function(xhr, textStatus, errorThrown) {
          log(target, options, "XML Load Error:{textStatus:" + textStatus + ",errorThrown:" + errorThrown + "}", "error");
        }
      });
    }

    function buildActivity(target, options, activityData) {
      var dataSet = null;
      var choiceDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      var currentChoice = null;
      var choices = [];
      var currentRow = 0;
      var currentColumn = 0;
      var choice = null;
      var setContainer = null;
      options.data.allowRetry = activityData.allowRetry;
      options.data.randomizeOnRetry = activityData.randomizeOnRetry;
      options.data.gradeSetsIndividually = activityData.gradeSetsIndividually;
      if (options.data.overridePoints || options.data.overridePoints == 0) {
        var totalCorrectPoints = 0;
        $.each(activityData.dataSets, function(i, dataSet) {
          $.each(dataSet.choices, function(j, choice) {
            if (choice.correct) {
              totalCorrectPoints += choice.value;
            }
          });
        });
        if (totalCorrectPoints == 0 || options.data.overridePoints == 0) {
          totalCorrectPoints = 0;
          $.each(activityData.dataSets, function(i, dataSet) {
            $.each(dataSet.choices, function(j, choice) {
              if (choice.correct) {
                if (options.data.overridePoints > 0) {
                  choice.value = 1;
                  totalCorrectPoints++;
                } else {
                  choice.value = 0;
                }
              }
            });
          });
        }
        var factor = options.data.overridePoints / totalCorrectPoints;
        $.each(activityData.dataSets, function(i, dataSet) {
          $.each(dataSet.choices, function(j, choice) {
            choice.value = choice.value * factor;
          });
        });
      }
      for (var i = 0; i < activityData.dataSets.length; i++) {
        dataSet = $.extend({}, activityData.dataSets[i], {
          choices : [],
          attempts : 0,
          focusedChoiceId : null,
          focusedChoiceRow : -1,
          focusedChoiceColumn : -1,
          completed : false
        });
        if (activityData.dataSets[i].choices.length % dataSet.columns) {
          dataSet.rows = parseInt(activityData.dataSets[i].choices.length / dataSet.columns) + 1;
        } else {
          dataSet.rows = parseInt(activityData.dataSets[i].choices.length / dataSet.columns);
        }
        options.data.dataSets.push(dataSet);
        choiceDimensions = calculateChoiceDimensions(target, options, dataSet.rows, dataSet.columns);
        currentRow = 0;
        currentColumn = 0;
        choice = null;
        for (var j = 0; j < activityData.dataSets[i].choices.length; j++) {
          choice = activityData.dataSets[i].choices[j];
          currentChoice = createChoiceContainer(target, options, choice.content);
          $(currentChoice).data("slideIdentificationActivity:choice", {
            id : choice.id,
            row : 0,
            column : currentColumn,
            value : choice.value,
            correct : choice.correct,
            selectOnce : choice.selectOnce
          });
          registerChoiceEvents(target, options, currentChoice);
          dataSet.choices.push(currentChoice);
          choices.push(currentChoice);
          currentColumn++;
          if (currentColumn >= dataSet.columns) {
            currentColumn = 0;
            currentRow++;
          }
        }
        setContainer = createSetContainer(target, options);
        options.containers.set.references.push(setContainer);
        $(setContainer).data("slideIdentificationActivity:set", dataSet);
        imageContainer = createImageContainer(target, options, dataSet.image, dataSet.imageAlignDelay);
        $(setContainer).append(imageContainer);
        $(options.containers.choice.reference).append(setContainer);
        for (var j = 0; j < dataSet.choices.length; j++) {
          $(setContainer).append(dataSet.choices[j]);
        }
        resizeChoices(target, options, choiceDimensions.width, choiceDimensions.height, dataSet.choices);
        randomizeChoicePositionsInSet(target, options, setContainer);
        positionChoices(target, options, dataSet.choices);
        alignChoices(target, options, dataSet.choices);
      }
      registerAccessibilityEvents(target, options, choices);
      enableDisable(target, options, choices);
      $(target).data("slideIdentificationActivity:options", options);
      alignSets(target, options);
      showSet(target, options, activityData.dataSets[0].id);
      calculateActivityScore(target, options, false);
      $(target).trigger("activityLoaded.slideIdentificationActivity", [options.data.dataSets.length, 0, options.data.allowRetry, options.data.gradeSetsIndividually]);
    }

    function createSetContainer(target, options) {
      return $("<div />").addClass(options.containers.set.css.identifier);
    }

    function showSet(target, options, id, setContainers, reset, resetPosition) {
      setContainers = setContainers || getSetContainers(target, options);
      reset = reset || false;
      resetPosition = resetPosition || false;
      var setContainer = null;
      var setContainerData = null;
      var selectedSetContainerData = null;
      var selectedSetContainer = null;
      var setPosition = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("slideIdentificationActivity:set");
        $(setContainer).removeClass(options.containers.set.css.selected);
        if (setContainerData.id == id) {
          setPosition = i;
          selectedSetContainerData = setContainerData;
          selectedSetContainer = setContainer;
          $(setContainer).addClass(options.containers.set.css.selected);
        }
      }
      var choices = getChoices(target, options);
      positionChoices(target, options, choices);
      alignChoices(target, options, choices);
      if (reset && selectedSetContainerData) {
        options.data.enabled = true;
        enableDisable(target, options, choices);
        $(target).data("slideIdentificationActivity:data", options);
      }
      if (resetPosition) {
        var width = $(options.containers.choice.reference).outerWidth();
        var finalPosition = -(width * [id]);
        $(options.containers.choice.reference).css("left", finalPosition + "px");
      }
      $(target).trigger("titleChanged.slideIdentificationActivity", [selectedSetContainerData.title]);
      $(target).trigger("setChanged.slideIdentificationActivity", [setContainers.length, setPosition, options.data.gradeSetsIndividually, options.data.allowRetry, selectedSetContainerData.completed, options.data.enabled]);
    }

    function showNextSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          if (setContainers[i] == currentSetContainer && i < setContainers.length - 1) {
            var width = $(options.containers.choice.reference).outerWidth();
            var finalPosition = -(width * [i + 1]);
            if (options.data.animate) {
              $(options.containers.choice.reference).stop(true, false).addClass(options.containers.choice.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.choice.css.animating);
              });
            } else {
              $(options.containers.choice.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i + 1]).data("slideIdentificationActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function showPreviousSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          if (setContainers[i] == currentSetContainer && i > 0) {
            var width = $(options.containers.choice.reference).outerWidth();
            var finalPosition = -(width * [i - 1]);
            if (options.data.animate) {
              $(options.containers.choice.reference).stop(true, false).addClass(options.containers.choice.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.choice.css.animating);
              });
            } else {
              $(options.containers.choice.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i - 1]).data("slideIdentificationActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function getSetState(target, options, setContainer) {
      var setContainerData = $(setContainer).data("slideIdentificationActivity:set");
      var setState = {
        id : setContainerData.id,
        allowRetry : setContainerData.allowRetry,
        showFeedback : setContainerData.showFeedback,
        gradeIndividually : setContainerData.gradeIndividually,
        attempts : setContainerData.attempts,
        completed : setContainerData.completed,
        rows : setContainerData.rows,
        choices : []
      };
      var setChoices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      var normalizedChoiceData = null;
      for (var i = 0; i < setChoices.length; i++) {
        choice = setChoices[i];
        choiceOptions = $(choice).data("slideIdentificationActivity:choice");
        normalizedChoiceData = {
          id : choiceOptions.id,
          row : choiceOptions.row,
          column : choiceOptions.column,
          correct : choiceOptions.correct,
          value : choiceOptions.value,
          selected : $(choice).hasClass(options.containers.choices.container.css.selected),
          finished : $(choice).hasClass(options.containers.choices.container.css.correct) || $(choice).hasClass(options.containers.choices.container.css.incorrect) || false
        };
        setState.choices.push(normalizedChoiceData);
      }
      return setState;
    }

    function setSetState(target, options, setContainer, setState) {
      log(target, options, "Setting Set State:" + setState.id);
      var setContainerData = $(setContainer).data("slideIdentificationActivity:set");
      setContainerData.allowRetry = setState.allowRetry;
      setContainerData.showFeedback = setState.showFeedback;
      setContainerData.gradeIndividually = setState.gradeIndividually;
      setContainerData.attempts = setState.attempts;
      setContainerData.completed = setState.completed;
      $(setContainer).data("slideIdentificationActivity:set", setContainerData);
      if (setContainerData.completed && !$(setContainer).hasClass(options.containers.set.css.completed)) {
        $(setContainer).addClass(options.containers.set.css.completed);
      }
      var setChoices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      var normalizedChoiceData = null;
      for (var i = 0; i < setChoices.length; i++) {
        choice = setChoices[i];
        choiceOptions = $(choice).data("slideIdentificationActivity:choice");
        for (var j = 0; j < setState.choices.length; j++) {
          normalizedChoiceData = setState.choices[j];
          if (normalizedChoiceData.id == choiceOptions.id) {
            choiceOptions.row = normalizedChoiceData.row;
            choiceOptions.column = normalizedChoiceData.column;
            choiceOptions.correct = normalizedChoiceData.correct;
            choiceOptions.value = normalizedChoiceData.value;
            $(choice).removeClass(options.containers.choices.container.css.selected);
            if (normalizedChoiceData.selected) {
              $(choice).addClass(options.containers.choices.container.css.selected);
            }
            if (normalizedChoiceData.finished) {
              if (normalizedChoiceData.correct) {
                $(choice).addClass(options.containers.choices.container.css.correct);
              } else {
                $(choice).addClass(options.containers.choices.container.css.incorrect);
              }
            }
          }
        }
        $(choice).data("slideIdentificationActivity:choice", choiceOptions);
      }
    }

    function calculateActivityScore(target, options, incrementAttempts, autoCompleteOverride, doNotUpdateExternalScore) {
      incrementAttempts = incrementAttempts || true;
      autoCompleteOverride = autoCompleteOverride || false;
      doNotUpdateExternalScore = doNotUpdateExternalScore || false;
      var choiceSets = getSetContainers(target, options);
      var activeSet = getActiveSetContainer(target, options);
      var activeSetPosition = 0;
      var setScore = null;
      var setScores = [];
      var calculatedScore = 0;
      var calculatedPossible = 0;
      var totalCorrect = 0;
      var totalIncorrect = 0;
      var correctSelected = 0;
      var incorrectSelected = 0;
      for (var i = 0; i < choiceSets.length; i++) {
        if (choiceSets[i] == activeSet) {
          activeSetPosition = i;
        }
        if (options.data.gradeSetsIndividually && choiceSets[i] == activeSet) {
          setScore = calculateSetScore(target, options, choiceSets[i], incrementAttempts, autoCompleteOverride);
        } else {
          if (options.data.gradeSetsIndividually && choiceSets[i] != activeSet) {
            setScore = calculateSetScore(target, options, choiceSets[i], false, false);
          } else {
            setScore = calculateSetScore(target, options, choiceSets[i], incrementAttempts, autoCompleteOverride);
          }
        }
        calculatedScore += setScore.calculatedScore;
        calculatedPossible += setScore.calculatedPossible;
        totalCorrect += setScore.totalCorrect;
        totalIncorrect += setScore.totalIncorrect;
        correctSelected += setScore.correctSelected;
        incorrectSelected += setScore.incorrectSelected;
        $(target).trigger("setScoreChanged.slideIdentificationActivity", [options.data.dataSets.length, i, options.data.allowRetry, options.data.gradeSetsIndividually, setScore.calculatedScore, setScore.calculatedPossible, $(choiceSets[i]).data("slideIdentificationActivity:set").completed, doNotUpdateExternalScore]);
      }
      log(target, options, "Score Recalculated:" + calculatedScore + "/" + calculatedPossible, "info");
      $(target).trigger("activityScoreChanged.slideIdentificationActivity", [options.data.dataSets.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually, calculatedScore, calculatedPossible, $(activeSet).data("slideIdentificationActivity:set").completed, doNotUpdateExternalScore]);
      if (!options.data.gradeSetsIndividually && autoCompleteOverride) {
        options.data.enabled = false;
        $(target).data("slideIdentificationActivity:options", options);
        enableDisable(target, options);
        log(target, options, "Activity Completed:" + calculatedScore + "/" + calculatedPossible, "info");
        $(target).trigger("activityComplete.slideIdentificationActivity", [options.data.dataSets.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually, calculatedScore, calculatedPossible, doNotUpdateExternalScore]);
      }
      return {
        calculatedScore : calculatedScore,
        calculatedPossible : calculatedPossible,
        totalCorrect : totalCorrect,
        totalIncorrect : totalIncorrect,
        correctSelected : correctSelected,
        incorrectSelected : incorrectSelected
      };
    }

    function calculateSetScore(target, options, setContainer, incrementAttempts, autoCompleteOverride) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      incrementAttempts = incrementAttempts || true;
      autoCompleteOverride = autoCompleteOverride || false;
      var setData = $(setContainer).data("slideIdentificationActivity:set");
      var setState = getSetState(target, options, setContainer);
      var scoreResults = options.data.calculateScore(setState);
      if (setData.gradeIndividually) {
        if (setData.showFeedback) {
          showCorrectAndIncorrect(target, options, setContainer, true);
        }
      } else {
        if (setData.autoComplete && scoreResults.totalCorrect == scoreResults.correctSelected || autoCompleteOverride == true) {
          setData.completed = true;
          if (!$(setContainer).hasClass(options.containers.set.css.completed)) {
            $(setContainer).addClass(options.containers.set.css.completed);
          }
          if (setData.showFeedback) {
            showCorrectAndIncorrect(target, options, setContainer, false);
          }
          if (incrementAttempts) {
            setData.attempts++;
          }
        } else {
          clearCorrectAndIncorrectInSet(target, options, setContainer);
          if (!setData.completed) {
            scoreResults.calculatedScore = 0;
          } else {
            if (setData.showFeedback) {
              showCorrectAndIncorrect(target, options, setContainer, false);
            }
          }
        }
      }
      $(setContainer).data("slideIdentificationActivity:set", setData);
      return scoreResults;
    }

    function showCorrectAndIncorrect(target, options, setContainer, showOnlySelected) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      showOnlySelected = showOnlySelected || true;
      if (options.data.enabled) {
        var choices = getChoicesInSet(target, options, setContainer);
        var choice = null;
        var choiceOptions = null;
        var showChoice = false;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          choiceOptions = $(choice).data("slideIdentificationActivity:choice");
          showChoice = true;
          if (showChoice) {
            if (choiceOptions.correct) {
              $(choice).removeClass(options.containers.choices.container.css.incorrect);
              if (!$(choice).hasClass(options.containers.choices.container.css.correct)) {
                $(choice).addClass(options.containers.choices.container.css.correct);
              }
            } else {
              $(choice).removeClass(options.containers.choices.container.css.correct);
              if (!$(choice).hasClass(options.containers.choices.container.css.incorrect)) {
                $(choice).addClass(options.containers.choices.container.css.incorrect);
              }
            }
          } else {
            $(choice).removeClass(options.containers.choices.container.css.correct);
            $(choice).removeClass(options.containers.choices.container.css.incorrect);
          }
        }
      }
    }

    function clearCorrectAndIncorrect(target, options, choices, showOnlySelected) {
      choices = choices || getChoices(target, options);
      showOnlySelected = showOnlySelected || true;
      if (options.data.enabled) {
        var choice = null;
        var showChoice = false;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          $(choice).removeClass(options.containers.choices.container.css.incorrect);
          $(choice).removeClass(options.containers.choices.container.css.correct);
        }
      }
    }

    function clearCorrectAndIncorrectInSet(target, options, setContainer, showOnlySelected) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      showOnlySelected = showOnlySelected || true;
      choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var showChoice = false;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.incorrect);
        $(choice).removeClass(options.containers.choices.container.css.correct);
      }
    }

    function alignSetImage(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var setContainerData = $(setContainer).data("slideIdentificationActivity:set");
      var imageContainer = $(setContainer).find("." + options.containers.image.container.css.identifier).first();
      var image = $(imageContainer).find("." + options.containers.image.image.css.identifier).first();
      if (setContainerData.allowImageScale) {
        $(image).transform({
          scale : [1, 1]
        });
      }
      var choiceContainer = $(setContainer).find("." + options.containers.choices.container.css.identifier).first();
      var setWidth = $(setContainer).width();
      var setHeight = $(setContainer).height() - $(choiceContainer).outerHeight();
      $(imageContainer).height(setHeight);
      if (setContainerData.allowImageScale) {
        var imageContainerWidth = $(imageContainer).width();
        var imageContainerHeight = $(imageContainer).height();
        var imageWidth = $(image).outerWidth();
        var imageHeight = $(image).outerHeight();
        var imageNewWidth = null;
        var imageNewHeight = null;
        if ($(image).outerWidth() > imageContainerWidth) {
          imageNewWidth = imageContainerWidth;
        }
        if ($(image).outerHeight() > imageContainerHeight) {
          imageNewHeight = imageContainerHeight;
        }
        var scale = 1;
        if (imageNewWidth || imageNewHeight) {
          if (imageNewWidth && !imageNewHeight) {
            var scale = imageNewWidth / imageWidth;
          } else {
            if (imageNewHeight && !imageNewWidth) {
              scale = imageNewHeight / imageHeight;
            } else {
              scale = Math.min(imageNewWidth / imageWidth, imageNewHeight / imageHeight);
            }
          }
        }
        $(image).transform({
          scale : [scale, scale]
        });
      }
      alignToParent(target, options, options.containers.image.image.horizontalAlign, options.containers.image.image.verticalAlign, image);
    }

    function alignChoices(target, options, choices) {
      choices = choices || getChoices(target, options);
      if (choices) {
        var choice = null;
        var choiceContent = null;
        var choiceOptions = null;
        var leftContent = null;
        var rightContent = null;
        var feedbackIconContent = null;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          choiceContent = $(choice).children("." + options.containers.choices.content.css.identifier + ":first");
          leftContent = $(choice).find("." + options.containers.choices.leftButton.button.css.identifier + ":first");
          rightContent = $(choice).find("." + options.containers.choices.rightButton.button.css.identifier + ":first");
          feedbackIconContent = $(choice).find("." + options.containers.choices.feedbackIcon.css.identifier + ":first");
          alignToParent(target, options, options.containers.choices.content.horizontalAlign, options.containers.choices.content.verticalAlign, choiceContent);
          alignToParent(target, options, "left", "middle", leftContent);
          alignToParent(target, options, "right", "middle", rightContent);
          alignToParent(target, options, options.containers.choices.feedbackIcon.horizontalAlign, options.containers.choices.feedbackIcon.verticalAlign, feedbackIconContent);
        }
      }
    }

    function alignSets(target, options, setContainers) {
      setContainers = setContainers || getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var setWidth = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("slideIdentificationActivity:set");
        setWidth = $(setContainer).width();
        $(setContainer).css("left", (setWidth * setContainerData.id) + "px");
      }
    }

    function alignToParent(target, options, horizontalAlign, verticalAlign, container) {
      $(container).css("position", "absolute");
      if (horizontalAlign) {
        switch(horizontalAlign.toLowerCase()) {
          case"left":
            $(container).css("right", null).css("left", "0px");
            break;
          case"right":
            $(container).css("left", null).css("right", "0px");
            break;
          case"center":
            $(container).css("right", null).css("left", ($(container).parent().innerWidth() / 2 - $(container).outerWidth() / 2) + "px");
            break;
        }
      }
      if (verticalAlign) {
        switch(verticalAlign.toLowerCase()) {
          case"top":
            $(container).css("bottom", null).css("top", "0px");
            break;
          case"bottom":
            $(container).css("top", null).css("bottom", "0px");
            break;
          case"middle":
            $(container).css("bottom", null).css("top", ($(container).parent().innerHeight() / 2 - $(container).outerHeight() / 2) + "px");
            break;
        }
      }
    }

    function resetActivity(target, options) {
      if (options.data.allowRetry) {
        log(target, options, "Resetting Activity", "info");
        var setContainers = getSetContainers(target, options);
        var activeSet = getActiveSetContainer(target, options);
        var activeSetPosition = 0;
        var setContainer = null;
        var setContainerData = null;
        var choices = null;
        var calculatedScore = 0;
        var calculatedPossible = 0;
        var setScore = null;
        options.data.enabled = true;
        for (var i = 0; i < setContainers.length; i++) {
          setContainer = setContainers[i];
          setContainerData = $(setContainer).data("slideIdentificationActivity:set");
          if (setContainer == activeSet) {
            activeSetPosition = i;
          }
          if ((options.data.gradeSetsIndividually && setContainer == activeSet) || !options.data.gradeSetsIndividually) {
            setContainerData.attempts = 0;
            setContainerData.completed = false;
            setContainerData.focusedChoiceId = null;
            setContainerData.focusedChoiceRow = -1;
            setContainerData.focusedChoiceColumn = -1;
            $(setContainer).data("slideIdentificationActivity:set", setContainerData);
            choices = getChoicesInSet(target, options, setContainer);
            clearChoicesHover(target, options, choices);
            clearCorrectAndIncorrectInSet(target, options, setContainer);
            clearSelectedChoices(target, options, choices);
            setScore = calculateSetScore(target, options, setContainer);
            calculatedScore += setScore.calculatedScore;
            calculatedPossible += setScore.calculatedPossible;
            if (options.data.randomizeOnRetry) {
              randomizeChoicePositionsInSet(target, options, setContainer);
              positionChoices(target, options, choices);
            }
            if ($(setContainer).hasClass(options.containers.set.css.completed)) {
              $(setContainer).removeClass(options.containers.set.css.completed);
            }
          }
        }
        enableDisable(target, options);
        var setPosition = $(activeSet).data("slideIdentificationActivity:set").id;
        if (!options.data.gradeSetsIndividually && options.data.randomizeOnRetry) {
          setPosition = Math.floor(Math.random() * setContainers.length);
        }
        setContainer = setContainers[setPosition];
        setContainerData = $(setContainer).data("slideIdentificationActivity:set");
        showSet(target, options, setContainerData.id, setContainers, false, true);
        activeSet = getActiveSetContainer(target, options);
        for (var i = 0; i < setContainers.length; i++) {
          setContainer = setContainers[i];
          setContainerData = $(setContainer).data("slideIdentificationActivity:set");
          if (setContainer == activeSet) {
            activeSetPosition = i;
          }
        }
        $(target).data("slideIdentificationActivity:options", options);
        $(target).trigger("reset.slideIdentificationActivity", [setContainers.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually]);
        calculateActivityScore(target, options, false);
      }
    }

    function getActiveSetContainerId(target, options) {
      return $(getActiveSetContainer(target, options)).data("slideIdentificationActivity:set").id || null;
    }

    function getActivityState(target, options) {
      var activityState = {
        enabled : options.data.enabled,
        allowRetry : options.data.allowRetry,
        randomizeOnRetry : options.data.randomizeOnRetry,
        activeSetId : getActiveSetContainerId(target, options),
        sets : []
      };
      var setContainers = getSetContainers(target, options);
      for (var i = 0; i < setContainers.length; i++) {
        activityState.sets.push(getSetState(target, options, setContainers[i]));
      }
      return activityState;
    }

    function setActivityState(target, options, activityState, completed) {
      log(target, options, "Setting Activity State");
      var setData = null;
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var choices = null;
      showSet(target, options, activityState.activeSetId, false, true);
      for (var i = 0; i < activityState.sets.length; i++) {
        setData = activityState.sets[i];
        for (var j = 0; j < setContainers.length; j++) {
          setContainer = setContainers[j];
          setContainerData = $(setContainer).data("slideIdentificationActivity:set");
          choices = getChoicesInSet(target, options, setContainer);
          if (setData.id == setContainerData.id) {
            setSetState(target, options, setContainer, setData);
          }
          positionChoices(target, options, choices);
        }
      }
      options.data.enabled = activityState.enabled;
      options.data.allowRetry = activityState.allowRetry;
      options.data.randomizeOnRetry = activityState.randomizeOnRetry;
      $(target).data("slideIdentificationActivity:options", options);
      enableDisable(target, options);
      calculateActivityScore(target, options, false, completed, true);
    }
    return this;
  };
  $.fn.slideIdentificationActivity.defaults = {};
  $.fn.slideIdentificationActivity.defaults.containers = {
    activity : {
      reference : null,
      css : {
        identifier : "softchalk-slide-identification-activity"
      }
    },
    content : {
      reference : null,
      css : {
        identifier : "softchalk-slide-identification-activity-content",
        enabled : "enabled",
        disabled : "disabled"
      }
    },
    choice : {
      reference : null,
      css : {
        identifier : "softchalk-slide-identification-activity-sets",
        animating : "animating"
      }
    },
    set : {
      references : [],
      css : {
        identifier : "softchalk-slide-identification-activity-set",
        selected : "selected",
        completed : "completed"
      }
    },
    choices : {
      references : [],
      container : {
        css : {
          identifier : "softchalk-slide-identification-activity-choice",
          selected : "selected",
          correct : "correct",
          incorrect : "incorrect",
          hover : "hover",
          animating : "animating"
        }
      },
      content : {
        horizontalAlign : "center",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-slide-identification-activity-choice-content"
        }
      },
      leftButton : {
        container : {
          css : {
            identifier : "softchalk-slide-identification-activity-choice-left-button-container",
            hover : "hover"
          }
        },
        button : {
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-slide-identification-activity-choice-left-button",
            hover : "hover"
          }
        }
      },
      rightButton : {
        container : {
          css : {
            identifier : "softchalk-slide-identification-activity-choice-right-button-container",
            hover : "hover"
          }
        },
        button : {
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-slide-identification-activity-choice-right-button",
            hover : "hover"
          }
        }
      },
      feedback : {
        css : {
          identifier : "softchalk-slide-identification-activity-choice-feedback"
        }
      },
      feedbackIcon : {
        horizontalAlign : "right",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-slide-identification-activity-choice-feedback-icon"
        }
      },
      overlay : {
        css : {
          identifier : "softchalk-slide-identification-activity-choice-overlay"
        }
      }
    },
    image : {
      container : {
        references : null,
        css : {
          identifier : "softchalk-slide-identification-activity-image-container"
        }
      },
      image : {
        references : null,
        horizontalAlign : "center",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-slide-identification-activity-image"
        }
      },
      noImage : {
        css : {
          identifier : "softchalk-slide-identification-activity-no-image"
        }
      }
    }
  };
  $.fn.slideIdentificationActivity.defaults.data = {
    dataSets : [],
    calculateScore : function(setState) {
      var calculatedCorrect = 0;
      var calculatedIncorrect = 0;
      var calculatedPossible = 0;
      var choiceData = null;
      var correctSelected = 0;
      var incorrectSelected = 0;
      var totalCorrect = 0;
      var totalIncorrect = 0;
      for (var i = 0; i < setState.choices.length; i++) {
        choiceData = setState.choices[i];
        if (choiceData.correct == true) {
          totalCorrect++;
          calculatedPossible += choiceData.value;
        } else {
          totalIncorrect++;
        }
        if (choiceData.column == 1) {
          if (choiceData.correct == true) {
            calculatedCorrect += choiceData.value;
            correctSelected++;
          } else {
            calculatedIncorrect += choiceData.value;
            incorrectSelected++;
          }
        }
      }
      var calculatedScore = Math.max(0, calculatedCorrect - calculatedIncorrect);
      var calculatedScore = calculatedCorrect;
      return {
        calculatedScore : calculatedScore,
        calculatedPossible : calculatedPossible,
        totalCorrect : totalCorrect,
        totalIncorrect : totalIncorrect,
        correctSelected : correctSelected,
        incorrectSelected : incorrectSelected
      };
    },
    enabled : true,
    enableLogging : false,
    allowRetry : true,
    randomizeOnRetry : true,
    animate : true,
    gradeSetsIndividually : false,
    overridePoints : null,
    overrideImages : false
  };
  $.fn.slideIdentificationActivity.defaults.accessibility = {
    pseudoMouse : {
      allow : true,
      mice : []
    },
    keyboard : {
      allow : true
    },
    hasFocus : false
  };
  $.fn.slideIdentificationActivity.defaults.logging = {
    debug : false,
    info : true,
    warn : false,
    error : false
  };
})(jQuery);
(function($) {
  $.fn.slideShowActivity = function(action, options) {
    var shouldReturnResults = false;
    var results = [];
    var params = null;
    action = action || "initialize";
    if ( typeof (action) == "object") {
      options = action;
      action = "initialize";
    }
    if (action == "initialize") {
      if (!options) {
        options = $.fn.slideShowActivity.defaults;
      } else {
        options = $.extend(true, {}, $.fn.slideShowActivity.defaults, options);
      }
    } else {
      params = options;
    }
    var optionsReference = options;
    $(this).each(function() {
      switch(action) {
        case"initialize":
          log(this, optionsReference, "Action:Initializing Activity", "info");
          initialize(this, optionsReference);
          break;
        case"loadXMLAndBuildActivity":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Loading XML", "info");
          loadXMLAndBuildActivity(this, options, params);
          break;
        case"parseXMLAndBuildActivity":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Parsing XML", "info");
          parseXMLAndBuildActivity(this, options, params);
          break;
        case"showNextSet":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Showing Next Set", "info");
          showNextSet(this, options);
          break;
        case"showPreviousSet":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Showing Previous Set", "info");
          showPreviousSet(this, options);
          break;
        case"getState":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Getting Activity State", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getActivityState(this, options)
          });
          break;
        case"setState":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Setting Activity State", "info");
          setActivityState(this, options, params.state);
          break;
        case"getEnabled":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Getting Enabled", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.enabled
          });
          break;
        case"setEnabled":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Setting Enabled", "info");
          options.data.enabled = params;
          $(this).data("slideShowActivity:options", options);
          enableDisable(this, options);
          break;
        case"getSetIds":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Getting Set Ids", "info");
          var setContainers = getSetContainers(this, options);
          var setContainer = null;
          var setContainerData = null;
          var setIds = [];
          for (var i = 0; i < setContainers.length; i++) {
            setContainer = setContainers[i];
            setContainerData = $(setContainer).data("slideShowActivity:set");
            setIds.push(setContainerData.id);
          }
          shouldReturnResults = true;
          results.push({
            target : this,
            result : setIds
          });
          break;
        case"getNumberOfSets":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getSetContainers(this, options).length
          });
          break;
        case"showSet":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          showSet(this, options, params);
          break;
        case"toggleSetContent":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Toggling Set Content", "info");
          toggleSetContent(this, options);
          break;
        case"resize":
          var options = $(this).data("slideShowActivity:options");
          log(this, options, "Action:Resizing the activity", "info");
          handleResize(this, options);
          break;
      }
    });
    if (shouldReturnResults == true) {
      return results;
    }
    function log(target, options, data, level) {
      level = level || "debug";
      level = $.trim(level).toLowerCase();
      if (options.data.enableLogging && window.console) {
        if (level == "info" && window.console.info && options.logging.info) {
          if ($(target).attr("id")) {
            window.console.info("[slideShowActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
          } else {
            if ($(target).attr("name")) {
              window.console.info("[slideShowActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
            } else {
              window.console.info("[slideShowActivity][" + target + "]" + data);
            }
          }
        } else {
          if (level == "warn" && window.console.warn && options.logging.warn) {
            if ($(target).attr("id")) {
              window.console.warn("[slideShowActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
            } else {
              if ($(target).attr("name")) {
                window.console.warn("[slideShowActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
              } else {
                window.console.warn("[slideShowActivity][" + target + "]" + data);
              }
            }
          } else {
            if (level == "error" && window.console.error && options.logging.error) {
              if ($(target).attr("id")) {
                window.console.error("[slideShowActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
              } else {
                if ($(target).attr("name")) {
                  window.console.error("[slideShowActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                } else {
                  window.console.error("[slideShowActivity][" + target + "]" + data);
                }
              }
            } else {
              if (window.console.log && options.logging.debug) {
                if ($(target).attr("id")) {
                  window.console.log("[slideShowActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
                } else {
                  if ($(target).attr("name")) {
                    window.console.log("[slideShowActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                  } else {
                    window.console.log("[slideShowActivity][" + target + "]" + data);
                  }
                }
              }
            }
          }
        }
      }
    }

    function initialize(target, options) {
      options = $.extend(true, {}, options);
      options.containers.activity.reference = target;
      $(options.containers.activity.reference).addClass(options.containers.activity.css.identifier);
      options.containers.content.reference = target;
      $(options.containers.content.reference).addClass(options.containers.content.css.identifier);
      if (options.containers.choice.reference == null) {
        options.containers.choice.reference = $("<div />");
        $(options.containers.content.reference).append(options.containers.choice.reference);
      }
      options.containers.choice.reference.addClass(options.containers.choice.css.identifier);
      $(target).data("slideShowActivity:options", options);
    }

    function handleResize(target, options) {
      alignSets(target, options);
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var choices = null;
      var choiceDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("slideShowActivity:set");
        alignSetImage(target, options, setContainer);
      }
      log(target, options, "Activity Container Resized", "info");
    }

    function registerAccessibilityEvents(target, options, choices) {
      var handleMiceEvents = function(event) {
        var options = $(this).data("slideShowActivity:options");
        if (options.data.enabled && event.pageX && event.pageY) {
          var offset = $(this).offset();
          var width = $(this).outerWidth();
          var height = $(this).outerHeight();
          if (!options.accessibility.hasFocus && event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
            options.accessibility.hasFocus = true;
            $(this).data("slideShowActivity:options", options);
          } else {
            if (options.accessibility.hasFocus && (event.pageX < offset.left || event.pageX > offset.left + width || event.pageY < offset.top || event.pageY > offset.top + height)) {
              options.accessibility.hasFocus = false;
              $(this).data("slideShowActivity:options", options);
            }
          }
        }
      };
      $(target).bind("mouseover", handleMiceEvents).bind("mouseout", handleMiceEvents).bind("mousemove", handleMiceEvents);
      $(target).bind("focusin", function(event) {
        var options = $(this).data("slideShowActivity:options");
        if (options.data.enabled && !options.accessibility.hasFocus) {
          log(target, options, "Giving Focus", "info");
          options.accessibility.hasFocus = true;
          $(this).data("slideShowActivity:options", options);
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("slideShowActivity:set");
          if (activeSetData.focusedChoiceRow < 0 || activeSetData.focusedChoiceColumn < 0 || !activeSetData.focusedChoiceId) {
            focusChoiceInSet(target, options, activeSet, null, 0, 0, false);
          }
        }
      });
      $(target).bind("focusout", function(event) {
        var options = $(this).data("slideShowActivity:options");
        if (options.data.enabled && options.accessibility.hasFocus) {
          options.accessibility.hasFocus = false;
          $(this).data("slideShowActivity:options", options);
        }
      });
      if (options.accessibility.keyboard.allow) {
        registerKeyboardEvents(target, options, choices);
      }
      if (options.accessibility.pseudoMouse.allow) {
        registerPseudoMouseEvents(target, options, choices);
      }
    }

    function calculateChoiceDimensions(target, options, rows, columns) {
      var containerWidth = $(options.containers.choice.reference).width();
      var containerHeight = $(options.containers.choice.reference).height();
      var borderTestDiv = $("<div />").css("display", "none").addClass(options.containers.more.container.css.identifier).width(100).height(100);
      $(target).append(borderTestDiv);
      var borderWidthOffset = ($(borderTestDiv).outerWidth() - $(borderTestDiv).innerWidth()) / 2;
      var borderHeightOffset = ($(borderTestDiv).outerHeight() - $(borderTestDiv).innerHeight()) / 2;
      $(borderTestDiv).remove();
      containerWidth -= borderWidthOffset * (2 * columns);
      containerHeight -= borderHeightOffset * (2 * rows);
      var choiceMaxWidth = containerWidth + 20;
      var choiceMaxHeight = 50;
      return {
        width : choiceMaxWidth,
        height : choiceMaxHeight
      };
    }

    function calculateContainerPadding(target, options, container) {
      var paddingTestDiv = $('<div style="padding:0px 0px 0px 0px;"/>');
      paddingTestDiv.css("padding-top", $(container).css("padding-top"));
      var paddingTop = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-top", "0px");
      paddingTestDiv.css("padding-right", $(container).css("padding-right"));
      var paddingRight = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-right", "0px");
      paddingTestDiv.css("padding-bottom", $(container).css("padding-bottom"));
      var paddingBottom = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-bottom", "0px");
      paddingTestDiv.css("padding-left", $(container).css("padding-left"));
      var paddingLeft = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-left", "0px");
      return {
        top : paddingTop,
        right : paddingRight,
        bottom : paddingBottom,
        left : paddingLeft
      };
    }

    function createQuestionContainer(target, options, contentHtml) {
      var question = $("<div />").addClass(options.containers.question.css.identifier);
      var contentDiv = $("<div />").addClass(options.containers.question.content.css.identifier);
      alignToParent(target, options, "center", "middle", contentDiv);
      $(question).append(contentDiv);
      if (contentHtml) {
        $(contentDiv).html(contentHtml);
      }
      return question;
    }

    function createImageContainer(target, options, contentHtml, imageAlignDelay) {
      var imageContainer = $("<div />").addClass(options.containers.image.container.css.identifier);
      if (contentHtml) {
        var image = $("<div />").addClass(options.containers.image.image.css.identifier);
        $(image).html(contentHtml);
        $(imageContainer).append(image);
        setTimeout(function() {
          alignSetImage(target, options, $(image).parent().parent());
        }, imageAlignDelay);
      }
      return imageContainer;
    }

    function createChoiceContainer(target, options, contentHtml) {
      var choice = $("<div />").addClass(options.containers.more.container.css.identifier).css("position", "absolute");
      var backgroundDiv = $("<div />").addClass(options.containers.more.background.css.identifier);
      $(choice).append(backgroundDiv);
      var contentDiv = $("<div />").addClass(options.containers.more.content.css.identifier);
      $(choice).append(contentDiv);
      if (contentHtml) {
        $(contentDiv).html(contentHtml);
      }
      return choice;
    }

    function enableDisable(target, options, choices) {
      log(target, options, "Enabling/Disabling Activity:" + options.data.enabled, "info");
      choices = choices || getChoices(target, options);
      if (options.data.enabled) {
        $(options.containers.content.reference).removeClass(options.containers.content.css.disabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.enabled);
        $(target).trigger("enabled.slideShowActivity", [options.data.dataSets.length]);
      } else {
        $(options.containers.content.reference).removeClass(options.containers.content.css.enabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.disabled);
        clearChoicesHover(target, options, choices);
        $(target).trigger("disabled.slideShowActivity", [options.data.dataSets.length]);
      }
    }

    function toggleSetContent(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var setContainerData = $(setContainer).data("slideShowActivity:set");
      var setContentContainer = $(setContainer).find("." + options.containers.more.container.css.identifier).first();
      if (!$(setContentContainer).hasClass(options.containers.more.container.css.animating)) {
        if (setContainerData.contentShown) {
          setContainerData.contentShown = false;
          if (options.data.animate) {
            $(setContentContainer).stop(true, false);
            $(setContentContainer).addClass(options.containers.more.container.css.animating);
            $(setContentContainer).animate({
              top : "100%"
            }, "slow", null, function() {
              var reference = this;
              setTimeout(function() {
                $(reference).removeClass(options.containers.more.container.css.animating);
              }, 50);
            });
          } else {
            $(setContentContainer).css("top", "100%");
          }
          $(target).trigger("contentHidden.slideShowActivity");
        } else {
          setContainerData.contentShown = true;
          if (options.data.animate) {
            $(setContentContainer).stop(true, false);
            $(setContentContainer).addClass(options.containers.more.container.css.animating);
            $(setContentContainer).animate({
              top : "50%"
            }, "slow", null, function() {
              var reference = this;
              setTimeout(function() {
                $(reference).removeClass(options.containers.more.container.css.animating);
              }, 50);
            });
          } else {
            $(setContentContainer).css("top", "50%");
          }
          $(target).trigger("contentShown.slideShowActivity");
        }
      }
    }

    function resizeChoices(target, options, width, height, choices) {
      choices = choices || getChoices(target, options);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).width(width);
        $(choice).height(height);
      }
    }

    function getSetContainers(target, options) {
      return $(options.containers.choice.reference).children("." + options.containers.set.css.identifier) || [];
    }

    function getActiveSetContainer(target, options) {
      return $(options.containers.choice.reference).children("."+options.containers.set.css.identifier).filter("."+options.containers.set.css.selected)[0] || null;
    }

    function getChoices(target, options) {
      var activeSetContainer = getActiveSetContainer(target, options);
      return $(activeSetContainer).children("." + options.containers.more.container.css.identifier) || [];
    }

    function getChoicesInSet(target, options, setContainer) {
      return $(setContainer).children("." + options.containers.choices.container.css.identifier) || [];
    }

    function clearChoicesHover(target, options, choices) {
      if (!choices) {
        choices = getChoices(target, options);
      }
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.hover);
      }
    }

    function focusChoiceInSet(target, options, setContainer, id, row, column, selectChoice) {
      log(target, options, "Focusing Choice:{id:" + id + ",row:" + row + ",column:" + column + "}", "info");
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      selectChoice = selectChoice || false;
      clearChoicesHover(target, options, choices);
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceOptions = $(choice).data("slideShowActivity:choice");
        if (id == choiceOptions.id) {
          $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseover");
          if (selectChoice) {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("click");
          }
        } else {
          if (row == choiceOptions.row && column == choiceOptions.column) {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseover");
            if (selectChoice) {
              $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("click");
            }
          } else {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseout");
          }
        }
      }
    }

    function clearSelectedChoicesInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.selected);
      }
    }

    function clearSelectedChoices(target, options, choices) {
      choices = choices || getChoices(target, options);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.selected);
      }
    }

    function registerKeyboardEvents(target, options, choices) {
      $(document).keydown(function(event) {
        var options = $(target).data("slideShowActivity:options");
        if (options.data.enabled && options.accessibility.keyboard.allow && options.accessibility.hasFocus) {
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("slideShowActivity:set");
          switch(event.keyCode) {
            case 38:
              if (activeSetData.focusedChoiceRow - 1 >= 0) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow - 1, activeSetData.focusedChoiceColumn);
              }
              break;
            case 40:
              if (activeSetData.focusedChoiceRow + 1 < activeSetData.rows) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow + 1, activeSetData.focusedChoiceColumn);
              }
              break;
            case 37:
              if (activeSetData.focusedChoiceColumn - 1 >= 0) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn - 1);
              }
              break;
            case 39:
              if (activeSetData.focusedChoiceColumn + 1 < activeSetData.columns) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn + 1);
              }
              break;
            case 32:
              focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn, true);
              break;
          }
        }
      });
    }

    function registerPseudoMouseEvents(target, options, choices) {
      var pseudoMice = options.accessibility.pseudoMouse.mice;
      var mouse = null;
      var offset = null;
      var width = null;
      var height = null;
      var container = null;
      var found = false;
      for (var i = 0; i < pseudoMice.length; i++) {
        mouse = pseudoMice[i];
        $(mouse).bind("mousemove", function(event) {
          var options = $(target).data("slideShowActivity:options");
          if (options.data.enabled) {
            var event2 = new $.Event("mousemove");
            event2.pageX = event.pageX;
            event2.pageY = event.pageY;
            $(target).trigger(event2);
          }
          options = $(target).data("slideShowActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            var activeSet = getActiveSetContainer(target, options);
            var choices = getChoicesInSet(target, options, activeSet);
            for (var j = 0; j < choices.length; j++) {
              found = false;
              container = $(choices[j]).children("." + options.containers.choices.downarrow.css.identifier).first();
              offset = $(container).offset();
              if ($(container).hasClass(options.containers.choices.container.css.hover)) {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      found = true;
                    }
                  }
                }
                if (!found) {
                  $(container).trigger("mouseout");
                }
              } else {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      $(container).trigger("mouseover");
                    }
                  }
                }
              }
            }
          }
        });
        $(mouse).bind("mouseup", function(event) {
          var options = $(target).data("slideShowActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            container = null;
            for (var j = 0; j < choices.length; j++) {
              container = $(choices[j]).children("." + options.containers.choices.downarrow.css.identifier).first();
              offset = $(container).offset();
              width = $(container).width();
              height = $(container).height();
              if (event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
                $(container).trigger("click");
              }
            }
          }
        });
      }
    }

    function parseXMLAndBuildActivity(target, options, data) {
      log(target, options, "Parsing Activity XML", "info");
      try {
        if (window.ActiveXObject) {
          var doc = new ActiveXObject("Microsoft.XMLDOM");
          doc.loadXML(data);
          data = doc;
        } else {
          if (window.DOMParser) {
            data = (new DOMParser).parseFromString(data, "text/xml");
          }
        }
      } catch(error) {
        data = null;
        log(target, options, "XML Parse Error:{error:" + error + "}", "error");
      }
      if (data) {
        var activityData = {
          dataSets : []
        };
        var idIndex = 0;
        var dataSet = null;
        var choice = null;
        if ($(data).children("slideShowActivity").attr("retry")) {
          activityData.allowRetry = ($(data).children("slideShowActivity").attr("retry").toLowerCase() == "true") ? true : false;
        }
        if ($(data).children("slideShowActivity").attr("randomizeOnRetry")) {
          activityData.randomizeOnRetry = ($(data).children("slideShowActivity").attr("randomizeOnRetry").toLowerCase() == "true") ? true : false;
        }
        $(data).children("slideShowActivity").children("set").each(function() {
          dataSet = {
            id : $(this).attr("id"),
            title : $(this).children("title:first").text(),
            image : $(this).children("image:first").text(),
            allowImageScale : true,
            imageAlignDelay : 50,
            content : [],
            rows : 1,
            columns : 1
          };
          if ($(this).children("title:first").attr("encoding")) {
            dataSet.title = unescape(dataSet.title.replace(/\+/g, " "));
          }
          if ($(this).children("image:first").attr("encoding")) {
            dataSet.image = unescape(dataSet.image.replace(/\+/g, " "));
          }
          if ($(this).children("image:first").attr("allowScale") == "false") {
            dataSet.allowImageScale = false;
          }
          if ($(this).children("image:first").attr("imageAlignDelay")) {
            dataSet.imageAlignDelay = parseInt($(this).children("image:first").attr("imageAlignDelay"));
          }
          $(this).children("content").each(function() {
            var text = $(this).text();
            if ($(this).attr("encoding")) {
              text = unescape(text.replace(/\+/g, " "));
            }
            dataSet.content.push(text);
          });
          activityData.dataSets.push(dataSet);
        });
        buildActivity(target, options, activityData);
      } else {
        log(target, options, "XML Activity Build Error:{error:No data to build activity}", "error");
      }
    }

    function loadXMLAndBuildActivity(target, options, url) {
      log(target, options, "Loading XML", "info");
      $.ajax({
        url : url,
        dataType : "text",
        success : function(data, textStatus, xhr) {
          var options = $(target).data("slideShowActivity:options");
          log(target, options, "XML Loaded", "info");
          parseXMLAndBuildActivity(target, options, data);
        },
        error : function(xhr, textStatus, errorThrown) {
          log(target, options, "XML Load Error:{textStatus:" + textStatus + ",errorThrown:" + errorThrown + "}", "error");
        }
      });
    }

    function buildActivity(target, options, activityData) {
      var dataSet = null;
      var choiceDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      var currentChoice = null;
      var choices = [];
      var currentRow = 0;
      var currentColumn = 0;
      var choice = null;
      var setContainer = null;
      var imageContainer = null;
      var choiceContainer = null;
      for (var i = 0; i < activityData.dataSets.length; i++) {
        dataSet = $.extend({}, activityData.dataSets[i], {
          choices : [],
          attempts : 0,
          focusedChoiceId : null,
          focusedChoiceRow : -1,
          focusedChoiceColumn : -1,
          contentShown : false
        });
        options.data.dataSets.push(dataSet);
        choiceDimensions = calculateChoiceDimensions(target, options, dataSet.rows, dataSet.columns);
        currentRow = 0;
        currentColumn = 0;
        choice = null;
        setContainer = createSetContainer(target, options);
        options.containers.set.references.push(setContainer);
        $(setContainer).data("slideShowActivity:set", dataSet);
        imageContainer = createImageContainer(target, options, dataSet.image, dataSet.imageAlignDelay);
        $(setContainer).append(imageContainer);
        choiceContainer = createChoiceContainer(target, options, dataSet.content[0]);
        $(setContainer).append(choiceContainer);
        $(options.containers.choice.reference).append(setContainer);
        resizeChoices(target, options, choiceDimensions.width, choiceDimensions.height, dataSet.choices);
      }
      registerAccessibilityEvents(target, options, choices);
      enableDisable(target, options, choices);
      $(target).data("slideShowActivity:options", options);
      alignSets(target, options);
      showSet(target, options, activityData.dataSets[0].id);
      $(target).trigger("activityLoaded.slideIdentificationActivity", [options.data.dataSets.length, 0]);
    }

    function createSetContainer(target, options) {
      return $("<div />").addClass(options.containers.set.css.identifier);
    }

    function showSet(target, options, id, setContainers, reset, resetPosition) {
      setContainers = setContainers || getSetContainers(target, options);
      reset = reset || false;
      resetPosition = resetPosition || false;
      var setContainer = null;
      var setContainerData = null;
      var selectedSetContainerData = null;
      var selectedSetContainer = null;
      var setPosition = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("slideShowActivity:set");
        $(setContainer).removeClass(options.containers.set.css.selected);
        if (setContainerData.id == id) {
          setPosition = i;
          selectedSetContainerData = setContainerData;
          selectedSetContainer = setContainer;
          $(setContainer).addClass(options.containers.set.css.selected);
        }
      }
      var choices = getChoices(target, options);
      if (reset && selectedSetContainerData) {
        options.data.enabled = true;
        enableDisable(target, options, choices);
        $(target).data("slideShowActivity:data", options);
      }
      if (resetPosition) {
        var width = $(options.containers.choice.reference).outerWidth();
        var finalPosition = -(width * [id]);
        $(options.containers.choice.reference).css("left", finalPosition + "px");
      }
      $(target).trigger("titleChanged.slideShowActivity", [selectedSetContainerData.title]);
      $(target).trigger("setChanged.slideShowActivity", [setContainers.length, setPosition, selectedSetContainerData.content.length, selectedSetContainerData.contentShown, options.data.enabled]);
    }

    function showNextSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          if (setContainers[i] == currentSetContainer && i < setContainers.length - 1) {
            var width = $(options.containers.choice.reference).outerWidth();
            var finalPosition = -(width * [i + 1]);
            if (options.data.animate) {
              $(options.containers.choice.reference).stop(true, false).addClass(options.containers.choice.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.choice.css.animating);
              });
            } else {
              $(options.containers.choice.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i + 1]).data("slideShowActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function showPreviousSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          if (setContainers[i] == currentSetContainer && i > 0) {
            var width = $(options.containers.choice.reference).outerWidth();
            var finalPosition = -(width * [i - 1]);
            if (options.data.animate) {
              $(options.containers.choice.reference).stop(true, false).addClass(options.containers.choice.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.choice.css.animating);
              });
            } else {
              $(options.containers.choice.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i - 1]).data("slideShowActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function getSetState(target, options, setContainer) {
      var setContainerData = $(setContainer).data("slideShowActivity:set");
      var setState = {
        id : setContainerData.id,
        allowRetry : setContainerData.allowRetry,
        showFeedback : setContainerData.showFeedback,
        gradeIndividually : setContainerData.gradeIndividually,
        attempts : setContainerData.attempts,
        rows : setContainerData.rows
      };
      return setState;
    }

    function setSetState(target, options, setContainer, setState) {
      log(target, options, "Setting Set State:" + setState.id);
      var setContainerData = $(setContainer).data("slideShowActivity:set");
      setContainerData.allowRetry = setState.allowRetry;
      setContainerData.showFeedback = setState.showFeedback;
      setContainerData.gradeIndividually = setState.gradeIndividually;
      setContainerData.attempts = setState.attempts;
      $(setContainer).data("slideShowActivity:set", setContainerData);
    }

    function alignSetImage(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var setContainerData = $(setContainer).data("slideShowActivity:set");
      var imageContainer = $(setContainer).find("." + options.containers.image.container.css.identifier).first();
      var image = $(imageContainer).find("." + options.containers.image.image.css.identifier).first();
      if (setContainerData.allowImageScale) {
        $(image).transform({
          scale : [1, 1]
        });
      }
      var setWidth = $(setContainer).width();
      var setHeight = $(setContainer).height();
      $(imageContainer).height(setHeight);
      if (setContainerData.allowImageScale) {
        var imageContainerWidth = $(imageContainer).width();
        var imageContainerHeight = $(imageContainer).height();
        var imageWidth = $(image).outerWidth();
        var imageHeight = $(image).outerHeight();
        var imageNewWidth = null;
        var imageNewHeight = null;
        if ($(image).outerWidth() > imageContainerWidth) {
          imageNewWidth = imageContainerWidth;
        }
        if ($(image).outerHeight() > imageContainerHeight) {
          imageNewHeight = imageContainerHeight;
        }
        var scale = 1;
        if (imageNewWidth || imageNewHeight) {
          if (imageNewWidth && !imageNewHeight) {
            var scale = imageNewWidth / imageWidth;
          } else {
            if (imageNewHeight && !imageNewWidth) {
              scale = imageNewHeight / imageHeight;
            } else {
              scale = Math.min(imageNewWidth / imageWidth, imageNewHeight / imageHeight);
            }
          }
        }
        $(image).transform({
          scale : [scale, scale]
        });
      }
      alignToParent(target, options, options.containers.image.image.horizontalAlign, options.containers.image.image.verticalAlign, image);
    }

    function alignSets(target, options, setContainers) {
      setContainers = setContainers || getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var setWidth = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("slideShowActivity:set");
        setWidth = $(setContainer).width();
        $(setContainer).css("left", (setWidth * setContainerData.id) + "px");
      }
    }

    function alignToParent(target, options, horizontalAlign, verticalAlign, container) {
      $(container).css("position", "absolute");
      if (horizontalAlign) {
        switch(horizontalAlign.toLowerCase()) {
          case"left":
            $(container).css("right", null).css("left", "0px");
            break;
          case"right":
            $(container).css("left", null).css("right", "0px");
            break;
          case"center":
            $(container).css("right", null).css("left", ($(container).parent().innerWidth() / 2 - $(container).outerWidth() / 2) + "px");
            break;
        }
      }
      if (verticalAlign) {
        switch(verticalAlign.toLowerCase()) {
          case"top":
            $(container).css("bottom", null).css("top", "0px");
            break;
          case"bottom":
            $(container).css("top", null).css("bottom", "0px");
            break;
          case"middle":
            $(container).css("bottom", null).css("top", ($(container).parent().innerHeight() / 2 - $(container).outerHeight() / 2) + "px");
            break;
        }
      }
    }

    function getActiveSetContainerId(target, options) {
      return $(getActiveSetContainer(target, options)).data("slideShowActivity:set").id || null;
    }

    function getActivityState(target, options) {
      var activityState = {
        enabled : options.data.enabled,
        allowRetry : options.data.allowRetry,
        randomizeOnRetry : options.data.randomizeOnRetry,
        activeSetId : getActiveSetContainerId(target, options),
        sets : []
      };
      var setContainers = getSetContainers(target, options);
      for (var i = 0; i < setContainers.length; i++) {
        activityState.sets.push(getSetState(target, options, setContainers[i]));
      }
      return activityState;
    }

    function setActivityState(target, options, activityState) {
      log(target, options, "Setting Activity State");
      var setData = null;
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var choices = null;
      showSet(target, options, activityState.activeSetId, false, true);
      for (var i = 0; i < activityState.sets.length; i++) {
        setData = activityState.sets[i];
        for (var j = 0; j < setContainers.length; j++) {
          setContainer = setContainers[j];
          setContainerData = $(setContainer).data("slideShowActivity:set");
          choices = getChoicesInSet(target, options, setContainer);
          if (setData.id == setContainerData.id) {
            setSetState(target, options, setContainer, setData);
          }
        }
      }
      options.data.enabled = activityState.enabled;
      options.data.allowRetry = activityState.allowRetry;
      options.data.randomizeOnRetry = activityState.randomizeOnRetry;
      $(target).data("slideShowActivity:options", options);
      enableDisable(target, options);
    }
    return this;
  };
  $.fn.slideShowActivity.defaults = {};
  $.fn.slideShowActivity.defaults.containers = {
    activity : {
      reference : null,
      css : {
        identifier : "softchalk-slide-show-activity"
      }
    },
    content : {
      reference : null,
      css : {
        identifier : "softchalk-slide-show-activity-content",
        enabled : "enabled",
        disabled : "disabled"
      }
    },
    choice : {
      reference : null,
      css : {
        identifier : "softchalk-slide-show-activity-sets",
        animating : "animating"
      }
    },
    set : {
      references : [],
      css : {
        identifier : "softchalk-slide-show-activity-set",
        selected : "selected"
      }
    },
    more : {
      container : {
        css : {
          identifier : "softchalk-slide-show-activity-more-container",
          animating : "animating"
        }
      },
      background : {
        css : {
          identifier : "softchalk-slide-show-activity-more-background"
        }
      },
      content : {
        css : {
          identifier : "softchalk-slide-show-activity-more-content"
        }
      }
    },
    image : {
      container : {
        references : null,
        css : {
          identifier : "softchalk-slide-show-activity-image-container"
        }
      },
      image : {
        references : null,
        horizontalAlign : "center",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-slide-show-activity-image"
        }
      }
    }
  };
  $.fn.slideShowActivity.defaults.data = {
    dataSets : [],
    enabled : true,
    enableLogging : false,
    animate : true
  };
  $.fn.slideShowActivity.defaults.accessibility = {
    pseudoMouse : {
      allow : true,
      mice : []
    },
    keyboard : {
      allow : true
    },
    hasFocus : false
  };
  $.fn.slideShowActivity.defaults.logging = {
    debug : false,
    info : true,
    warn : false,
    error : false
  };
})(jQuery);
(function($) {
  $.fn.slideSlotActivity = function(action, options) {
    var shouldReturnResults = false;
    var results = [];
    var params = null;
    action = action || "initialize";
    if ( typeof (action) == "object") {
      options = action;
      action = "initialize";
    }
    if (action == "initialize") {
      if (!options) {
        options = $.fn.slideSlotActivity.defaults;
      } else {
        options = $.extend(true, {}, $.fn.slideSlotActivity.defaults, options);
      }
    } else {
      params = options;
    }
    var optionsReference = options;
    $(this).each(function() {
      switch(action) {
        case"initialize":
          log(this, optionsReference, "Action:Initializing Activity", "info");
          initialize(this, optionsReference);
          break;
        case"loadXMLAndBuildActivity":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Loading XML", "info");
          loadXMLAndBuildActivity(this, options, params);
          break;
        case"parseXMLAndBuildActivity":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Parsing XML", "info");
          parseXMLAndBuildActivity(this, options, params);
          break;
        case"calculateScore":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Calculating Score", "info");
          calculateScore(this, options);
          break;
        case"reset":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Resetting Activity", "info");
          resetActivity(this, options);
          break;
        case"finish":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Finishing Activity", "info");
          calculateActivityScore(this, options, true, true);
          break;
        case"showNextSet":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Showing Next Set", "info");
          showNextSet(this, options);
          break;
        case"showPreviousSet":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Showing Previous Set", "info");
          showPreviousSet(this, options);
          break;
        case"getState":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Getting Activity State", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getActivityState(this, options)
          });
          break;
        case"setState":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Setting Activity State", "info");
          setActivityState(this, options, params.state, params.completed);
          break;
        case"getEnabled":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Getting Enabled", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.enabled
          });
          break;
        case"setEnabled":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Setting Enabled", "info");
          options.data.enabled = params;
          $(this).data("slideSlotActivity:options", options);
          enableDisable(this, options);
          break;
        case"getSetIds":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Getting Set Ids", "info");
          var setContainers = getSetContainers(this, options);
          var setContainer = null;
          var setContainerData = null;
          var setIds = [];
          for (var i = 0; i < setContainers.length; i++) {
            setContainer = setContainers[i];
            setContainerData = $(setContainer).data("slideSlotActivity:set");
            setIds.push(setContainerData.id);
          }
          shouldReturnResults = true;
          results.push({
            target : this,
            result : setIds
          });
          break;
        case"getNumberOfSets":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : getSetContainers(this, options).length
          });
          break;
        case"showSet":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Getting number of sets", "info");
          showSet(this, options, params);
          break;
        case"getAllowReset":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Getting allow reset", "info");
          shouldReturnResults = true;
          results.push({
            target : this,
            result : options.data.allowRetry
          });
          break;
        case"resize":
          var options = $(this).data("slideSlotActivity:options");
          log(this, options, "Action:Resizing the activity", "info");
          handleResize(this, options);
          break;
      }
    });
    if (shouldReturnResults == true) {
      return results;
    }
    function log(target, options, data, level) {
      level = level || "debug";
      level = $.trim(level).toLowerCase();
      if (options.data.enableLogging && window.console) {
        if (level == "info" && window.console.info && options.logging.info) {
          if ($(target).attr("id")) {
            window.console.info("[slideSlotActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
          } else {
            if ($(target).attr("name")) {
              window.console.info("[slideSlotActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
            } else {
              window.console.info("[slideSlotActivity][" + target + "]" + data);
            }
          }
        } else {
          if (level == "warn" && window.console.warn && options.logging.warn) {
            if ($(target).attr("id")) {
              window.console.warn("[slideSlotActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
            } else {
              if ($(target).attr("name")) {
                window.console.warn("[slideSlotActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
              } else {
                window.console.warn("[slideSlotActivity][" + target + "]" + data);
              }
            }
          } else {
            if (level == "error" && window.console.error && options.logging.error) {
              if ($(target).attr("id")) {
                window.console.error("[slideSlotActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
              } else {
                if ($(target).attr("name")) {
                  window.console.error("[slideSlotActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                } else {
                  window.console.error("[slideSlotActivity][" + target + "]" + data);
                }
              }
            } else {
              if (window.console.log && options.logging.debug) {
                if ($(target).attr("id")) {
                  window.console.log("[slideSlotActivity][" + target + ", id=" + $(target).attr("id") + "]" + data);
                } else {
                  if ($(target).attr("name")) {
                    window.console.log("[slideSlotActivity][" + target + ", name=" + $(target).attr("name") + "]" + data);
                  } else {
                    window.console.log("[slideSlotActivity][" + target + "]" + data);
                  }
                }
              }
            }
          }
        }
      }
    }

    function initialize(target, options) {
      options = $.extend(true, {}, options);
      options.containers.activity.reference = target;
      $(options.containers.activity.reference).addClass(options.containers.activity.css.identifier);
      options.containers.content.reference = target;
      $(options.containers.content.reference).addClass(options.containers.content.css.identifier);
      if (options.containers.choice.reference == null) {
        options.containers.choice.reference = $("<div />");
        $(options.containers.content.reference).append(options.containers.choice.reference);
      }
      options.containers.choice.reference.addClass(options.containers.choice.css.identifier);
      $(target).data("slideSlotActivity:options", options);
    }

    function handleResize(target, options) {
      alignSets(target, options);
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var choices = null;
      var choiceDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("slideSlotActivity:set");
        choices = getChoicesInSet(target, options, setContainer);
        choiceDimensions = calculateChoiceDimensions(target, options, setContainerData.rows.length, setContainerData.columns);
        resizeChoices(target, options, choiceDimensions.width, choiceDimensions.height, choices);
        positionChoices(target, options, choices);
        alignChoices(target, options, choices);
      }
      log(target, options, "Activity Container Resized", "info");
    }

    function registerAccessibilityEvents(target, options, choices) {
      var handleMiceEvents = function(event) {
        var options = $(this).data("slideSlotActivity:options");
        if (options.data.enabled && event.pageX && event.pageY) {
          var offset = $(this).offset();
          var width = $(this).outerWidth();
          var height = $(this).outerHeight();
          if (!options.accessibility.hasFocus && event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
            options.accessibility.hasFocus = true;
            $(this).data("slideSlotActivity:options", options);
          } else {
            if (options.accessibility.hasFocus && (event.pageX < offset.left || event.pageX > offset.left + width || event.pageY < offset.top || event.pageY > offset.top + height)) {
              options.accessibility.hasFocus = false;
              $(this).data("slideSlotActivity:options", options);
            }
          }
        }
      };
      $(target).bind("mouseover", handleMiceEvents).bind("mouseout", handleMiceEvents).bind("mousemove", handleMiceEvents);
      $(target).bind("focusin", function(event) {
        var options = $(this).data("slideSlotActivity:options");
        if (options.data.enabled && !options.accessibility.hasFocus) {
          log(target, options, "Giving Focus", "info");
          options.accessibility.hasFocus = true;
          $(this).data("slideSlotActivity:options", options);
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("slideSlotActivity:set");
          if (activeSetData.focusedChoiceRow < 0 || activeSetData.focusedChoiceColumn < 0 || !activeSetData.focusedChoiceId) {
            focusChoiceInSet(target, options, activeSet, null, 0, 0, false);
          }
        }
      });
      $(target).bind("focusout", function(event) {
        var options = $(this).data("slideSlotActivity:options");
        if (options.data.enabled && options.accessibility.hasFocus) {
          options.accessibility.hasFocus = false;
          $(this).data("slideSlotActivity:options", options);
        }
      });
      if (options.accessibility.keyboard.allow) {
        registerKeyboardEvents(target, options, choices);
      }
      if (options.accessibility.pseudoMouse.allow) {
        registerPseudoMouseEvents(target, options, choices);
      }
    }

    function calculateChoiceDimensions(target, options, rows, columns) {
      var containerWidth = $(options.containers.choice.reference).width();
      var containerHeight = $(options.containers.choice.reference).height();
      var borderTestDiv = $("<div />").css("display", "none").addClass(options.containers.choices.container.css.identifier).width(100).height(100);
      $(target).append(borderTestDiv);
      var borderWidthOffset = ($(borderTestDiv).outerWidth() - $(borderTestDiv).innerWidth()) / 2;
      var borderHeightOffset = ($(borderTestDiv).outerHeight() - $(borderTestDiv).innerHeight()) / 2;
      containerWidth -= borderWidthOffset + 2;
      containerHeight -= borderHeightOffset * (2 * rows);
      $(borderTestDiv).remove();
      var choiceMaxWidth = containerWidth;
      var choiceMaxHeight = containerHeight / rows;
      return {
        width : choiceMaxWidth,
        height : choiceMaxHeight
      };
    }

    function calculateContainerPadding(target, options, container) {
      var paddingTestDiv = $('<div style="padding:0px 0px 0px 0px;"/>');
      paddingTestDiv.css("padding-top", $(container).css("padding-top"));
      var paddingTop = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-top", "0px");
      paddingTestDiv.css("padding-right", $(container).css("padding-right"));
      var paddingRight = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-right", "0px");
      paddingTestDiv.css("padding-bottom", $(container).css("padding-bottom"));
      var paddingBottom = $(paddingTestDiv).height();
      paddingTestDiv.css("padding-bottom", "0px");
      paddingTestDiv.css("padding-left", $(container).css("padding-left"));
      var paddingLeft = $(paddingTestDiv).width();
      paddingTestDiv.css("padding-left", "0px");
      return {
        top : paddingTop,
        right : paddingRight,
        bottom : paddingBottom,
        left : paddingLeft
      };
    }

    function createChoiceContainer(target, options, contentHtml) {
      var choice = $("<div />").addClass(options.containers.choices.container.css.identifier).css("position", "absolute");
      var contentDiv = $("<div />").addClass(options.containers.choices.content.css.identifier);
      $(choice).append(contentDiv);
      var feedbackDiv = $("<div />").addClass(options.containers.choices.feedback.css.identifier);
      $(choice).append(feedbackDiv);
      var feedbackIconDiv = $("<div />").addClass(options.containers.choices.feedbackIcon.css.identifier);
      $(choice).append(feedbackIconDiv);
      var overlayDiv = $("<div />").addClass(options.containers.choices.overlay.css.identifier);
      $(choice).append(overlayDiv);
      var leftButtonDiv = $("<div />").addClass(options.containers.choices.leftButton.container.css.identifier);
      $(choice).append(leftButtonDiv);
      var leftButton = $("<div />").addClass(options.containers.choices.leftButton.button.css.identifier);
      $(leftButtonDiv).append(leftButton);
      var rightButtonDiv = $("<div />").addClass(options.containers.choices.rightButton.container.css.identifier);
      $(choice).append(rightButtonDiv);
      var rightButton = $("<div />").addClass(options.containers.choices.rightButton.button.css.identifier);
      $(rightButtonDiv).append(rightButton);
      if (contentHtml) {
        $(contentDiv).html(contentHtml);
      }
      return choice;
    }

    function enableDisable(target, options, choices) {
      log(target, options, "Enabling/Disabling Activity:" + options.data.enabled, "info");
      choices = choices || getChoices(target, options);
      if (options.data.enabled) {
        $(options.containers.content.reference).removeClass(options.containers.content.css.disabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.enabled);
        $(target).trigger("enabled.slideSlotActivity", [options.data.dataSets.length]);
      } else {
        $(options.containers.content.reference).removeClass(options.containers.content.css.enabled);
        $(options.containers.content.reference).addClass(options.containers.content.css.disabled);
        clearChoicesHover(target, options, choices);
        $(target).trigger("disabled.slideSlotActivity", [options.data.dataSets.length]);
      }
    }

    function resizeChoices(target, options, width, height, choices) {
      choices = choices || getChoices(target, options);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).width(width);
        $(choice).height(height);
      }
    }

    function positionChoices(target, options, choices, containerPadding) {
      choices = choices || getChoices(target, options);
      containerPadding = containerPadding || calculateContainerPadding(target, options, options.containers.choice.reference);
      var choiceData = null;
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceData = $(choice).data("slideSlotActivity:choice");
        $(choice).css("left", (-containerPadding.left + $(choice).outerWidth() * (choiceData.column - 1)) + "px");
        $(choice).css("top", (-containerPadding.top + $(choice).outerHeight() * choiceData.row) + "px");
      }
    }

    function randomizeChoicePositionsInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var setData = $(setContainer).data("slideSlotActivity:set");
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceData = null;
      var unpositionedChoices = [];
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceData = $(choice).data("slideSlotActivity:choice");
        choiceData.column = null;
        $(choice).data("slideSlotActivity:choice", choiceData);
        unpositionedChoices.push(choice);
      }
      var choiceMatrix = [];
      var currentRow = 0;
      var currentColumn = 0;
      var currentRowArray = null;
      var rowData = null;
      for ( currentRow = 0; currentRow < setData.rows.length; currentRow++) {
        currentRowArray = [];
        rowData = setData.rows[currentRow];
        for ( currentColumn = 0; currentColumn < rowData.columns; currentColumn++) {
          currentRowArray.push(null);
        }
        choiceMatrix.push(currentRowArray);
      }
      var positioningChoice = null;
      var randomSelector = null;
      var found = false;
      while (unpositionedChoices.length > 0) {
        randomSelector = Math.floor(Math.random() * unpositionedChoices.length);
        choice = unpositionedChoices.splice(randomSelector, 1);
        choiceData = $(choice).data("slideSlotActivity:choice");
        found = false;
        currentRow = choiceData.row;
        rowData = null;
        $.each(setData.rows, function(i, data) {
          if (data.id == choiceData.row) {
            rowData = data;
            return true;
          }
        });
        for ( currentColumn = 0; currentColumn < rowData.columns; currentColumn++) {
          if (!choiceMatrix[currentRow][currentColumn] && !found) {
            found = true;
            choiceMatrix[currentRow][currentColumn] = choice;
          }
        }
        choice = null;
      }
      for ( currentRow = 0; currentRow < setData.rows.length; currentRow++) {
        rowData = setData.rows[currentRow];
        for ( currentColumn = 0; currentColumn < rowData.columns; currentColumn++) {
          choice = choiceMatrix[currentRow][currentColumn];
          choiceData = $(choice).data("slideSlotActivity:choice");
          choiceData.column = currentColumn;
          $(choice).data("slideSlotActivity:choice", choiceData);
        }
      }
    }

    function registerChoiceEvents(target, options, choice) {
      $(choice).children("." + options.containers.choices.rightButton.container.css.identifier).bind("mouseover", function() {
        var options = $(target).data("slideSlotActivity:options");
        var choiceOptions = $(choice).data("slideSlotActivity:choice");
        var setOptions = $(choice).parent().data("slideSlotActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if (!$(this).hasClass(options.containers.choices.rightButton.container.css.hover)) {
            clearChoicesHover(target, options);
            $(this).addClass(options.containers.choices.rightButton.container.css.hover);
            setOptions.focusedChoiceId = choiceOptions.id;
            setOptions.focusedChoiceRow = choiceOptions.row;
            setOptions.focusedChoiceColumn = choiceOptions.column;
            $(choice).parent().data("slideSlotActivity:set", setOptions);
            options.accessibility.hasFocus = true;
            $(target).data("slideSlotActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.rightButton.container.css.identifier).bind("mouseout", function() {
        var options = $(target).data("slideSlotActivity:options");
        var choiceOptions = $(choice).data("slideSlotActivity:choice");
        var setOptions = $(choice).parent().data("slideSlotActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if ($(this).hasClass(options.containers.choices.rightButton.container.css.hover)) {
            $(this).removeClass(options.containers.choices.rightButton.container.css.hover);
            options.accessibility.hasFocus = true;
            $(target).data("slideSlotActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.rightButton.container.css.identifier).bind("click", function(event) {
        var options = $(target).data("slideSlotActivity:options");
        var choiceOptions = $(choice).data("slideSlotActivity:choice");
        var setOptions = $(choice).parent().data("slideSlotActivity:set");
        if (options.data.enabled && !setOptions.completed && !$(choice).hasClass(options.containers.choices.container.css.animating)) {
          var shouldRecalculate = false;
          shiftRow(target, options, null, $(this).parent(), 1);
          if (setOptions.gradeIndividually) {
            shouldRecalculate = true;
          } else {
            if (setOptions.allowRetry || (!setOptions.allowRetry && setOptions.attempts == 0)) {
              shouldRecalculate = true;
            }
          }
          options.accessibility.hasFocus = true;
          $(target).data("slideSlotActivity:options", options);
          if (shouldRecalculate) {
            calculateActivityScore(target, options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.leftButton.container.css.identifier).bind("mouseover", function() {
        var options = $(target).data("slideSlotActivity:options");
        var choiceOptions = $(choice).data("slideSlotActivity:choice");
        var setOptions = $(choice).parent().data("slideSlotActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if (!$(this).hasClass(options.containers.choices.leftButton.container.css.hover)) {
            clearChoicesHover(target, options);
            $(this).addClass(options.containers.choices.leftButton.container.css.hover);
            setOptions.focusedChoiceId = choiceOptions.id;
            setOptions.focusedChoiceRow = choiceOptions.row;
            setOptions.focusedChoiceColumn = choiceOptions.column;
            $(choice).parent().data("slideSlotActivity:set", setOptions);
            options.accessibility.hasFocus = true;
            $(target).data("slideSlotActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.leftButton.container.css.identifier).bind("mouseout", function() {
        var options = $(target).data("slideSlotActivity:options");
        var choiceOptions = $(choice).data("slideSlotActivity:choice");
        var setOptions = $(choice).parent().data("slideSlotActivity:set");
        if (options.data.enabled && !setOptions.completed) {
          if ($(this).hasClass(options.containers.choices.leftButton.container.css.hover)) {
            $(this).removeClass(options.containers.choices.leftButton.container.css.hover);
            options.accessibility.hasFocus = true;
            $(target).data("slideSlotActivity:options", options);
          }
        }
      });
      $(choice).children("." + options.containers.choices.leftButton.container.css.identifier).bind("click", function(event) {
        var options = $(target).data("slideSlotActivity:options");
        var choiceOptions = $(choice).data("slideSlotActivity:choice");
        var setOptions = $(choice).parent().data("slideSlotActivity:set");
        if (options.data.enabled && !setOptions.completed && !$(choice).hasClass(options.containers.choices.container.css.animating)) {
          var shouldRecalculate = false;
          shiftRow(target, options, null, $(this).parent(), -1);
          if (setOptions.gradeIndividually) {
            shouldRecalculate = true;
          } else {
            if (setOptions.allowRetry || (!setOptions.allowRetry && setOptions.attempts == 0)) {
              shouldRecalculate = true;
            }
          }
          options.accessibility.hasFocus = true;
          $(target).data("slideSlotActivity:options", options);
          if (shouldRecalculate) {
            calculateActivityScore(target, options);
          }
        }
      });
    }

    function shiftRow(target, options, setContainer, choice, columnDelta, wrapAround) {
      log(target, options, choice, "info");
      setContainer = setContainer || getActiveSetContainer(target, options);
      columnDelta = columnDelta || 0;
      wrapAround = wrapAround || true;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      var choiceOptions = $(choice).data("slideSlotActivity:choice");
      var setOptions = $(setContainer).data("slideSlotActivity:set");
      var allChoicesInSet = getChoicesInSet(target, options, setContainer);
      var rowData = null;
      var workingChoice = null;
      var workingChoiceData = null;
      var originalColumn = null;
      if (options.data.animate) {
        for (var i = 0; i < allChoicesInSet.length; i++) {
          workingChoice = allChoicesInSet[i];
          workingChoiceData = $(workingChoice).data("slideSlotActivity:choice");
          if (workingChoiceData.row == choiceOptions.row) {
            $.each(setOptions.rows, function(index, data) {
              if (data.id == workingChoiceData.row) {
                rowData = data;
                return true;
              }
            });
            originalColumn = workingChoiceData.column;
            $(workingChoice).css("left", -containerPadding.left + $(workingChoice).outerWidth() * (workingChoiceData.column - 1));
            workingChoiceData.column += columnDelta;
            $(workingChoice).data("slideSlotActivity:choice", workingChoiceData);
            if (true) {
              $(workingChoice).addClass(options.containers.choices.container.css.animating);
              if (rowData.columns == 2 && columnDelta < 0) {
                if (workingChoiceData.column < 0) {
                  workingChoiceData.column += rowData.columns;
                } else {
                  if (workingChoiceData.column >= rowData.columns) {
                    workingChoiceData.column -= rowData.columns;
                  }
                }
                $(workingChoice).css("left", -containerPadding.left + $(workingChoice).outerWidth() * (workingChoiceData.column));
              }
              $(workingChoice).animate({
                left : -containerPadding.left + $(workingChoice).outerWidth() * (workingChoiceData.column - 1)
              }, "slow", null, function() {
                var reference = this;
                setTimeout(function() {
                  $(reference).removeClass(options.containers.choices.container.css.animating);
                  var data = $(reference).data("slideSlotActivity:choice");
                  if (data.column < 0) {
                    data.column += rowData.columns;
                  } else {
                    if (data.column >= rowData.columns) {
                      data.column -= rowData.columns;
                    }
                  }
                  $(reference).data("slideSlotActivity:choice", data);
                  $(reference).css("left", -containerPadding.left + $(reference).outerWidth() * (data.column - 1));
                }, 50);
              });
            } else {
              $(workingChoice).css("left", -containerPadding.left + $(workingChoice).outerWidth() * (workingChoiceData.column - 1));
            }
          }
        }
      } else {
        for (var i = 0; i < allChoicesInSet.length; i++) {
          workingChoice = allChoicesInSet[i];
          workingChoiceData = $(workingChoice).data("slideSlotActivity:choice");
          if (workingChoiceData.row == choiceOptions.row) {
            $.each(setOptions.rows, function(index, data) {
              if (data.id == workingChoiceData.row) {
                rowData = data;
                return true;
              }
            });
            workingChoiceData.column += columnDelta;
            if (workingChoiceData.column < 0) {
              workingChoiceData.column += rowData.columns;
            } else {
              if (workingChoiceData.column >= rowData.columns) {
                workingChoiceData.column -= rowData.columns;
              }
            }
            $(workingChoice).data("slideSlotActivity:choice", workingChoiceData);
          }
        }
        positionChoices(target, options);
      }
    }

    function getSetContainers(target, options) {
      return $(options.containers.choice.reference).children("." + options.containers.set.css.identifier) || [];
    }

    function getActiveSetContainer(target, options) {
      return $(options.containers.choice.reference).children("."+options.containers.set.css.identifier).filter("."+options.containers.set.css.selected)[0] || null;
    }

    function getChoices(target, options) {
      var activeSetContainer = getActiveSetContainer(target, options);
      return $(activeSetContainer).children("." + options.containers.choices.container.css.identifier) || [];
    }

    function getChoicesInSet(target, options, setContainer) {
      return $(setContainer).children("." + options.containers.choices.container.css.identifier) || [];
    }

    function clearChoicesHover(target, options, choices) {
      if (!choices) {
        choices = getChoices(target, options);
      }
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.hover);
      }
    }

    function focusChoiceInSet(target, options, setContainer, id, row, column, selectChoice) {
      log(target, options, "Focusing Choice:{id:" + id + ",row:" + row + ",column:" + column + "}", "info");
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      selectChoice = selectChoice || false;
      clearChoicesHover(target, options, choices);
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        choiceOptions = $(choice).data("slideSlotActivity:choice");
        if (id == choiceOptions.id) {
          $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseover");
          if (selectChoice) {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("click");
          }
        } else {
          if (row == choiceOptions.row && column == choiceOptions.column) {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseover");
            if (selectChoice) {
              $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("click");
            }
          } else {
            $(choice).children("." + options.containers.choices.downarrow.css.identifier).trigger("mouseout");
          }
        }
      }
    }

    function clearSelectedChoicesInSet(target, options, setContainer) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      var choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.selected);
      }
    }

    function clearSelectedChoices(target, options, choices) {
      choices = choices || getChoices(target, options);
      var choice = null;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.selected);
      }
    }

    function registerKeyboardEvents(target, options, choices) {
      $(document).keydown(function(event) {
        var options = $(target).data("slideSlotActivity:options");
        if (options.data.enabled && options.accessibility.keyboard.allow && options.accessibility.hasFocus) {
          var activeSet = getActiveSetContainer(target, options);
          var activeSetData = $(activeSet).data("slideSlotActivity:set");
          switch(event.keyCode) {
            case 38:
              if (activeSetData.focusedChoiceRow - 1 >= 0) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow - 1, activeSetData.focusedChoiceColumn);
              }
              break;
            case 40:
              if (activeSetData.focusedChoiceRow + 1 < activeSetData.rows) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow + 1, activeSetData.focusedChoiceColumn);
              }
              break;
            case 37:
              if (activeSetData.focusedChoiceColumn - 1 >= 0) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn - 1);
              }
              break;
            case 39:
              if (activeSetData.focusedChoiceColumn + 1 < activeSetData.columns) {
                focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn + 1);
              }
              break;
            case 32:
              focusChoiceInSet(target, options, activeSet, null, activeSetData.focusedChoiceRow, activeSetData.focusedChoiceColumn, true);
              break;
            case 13:
              calculateActivityScore(target, options);
              break;
          }
        }
      });
    }

    function registerPseudoMouseEvents(target, options, choices) {
      var pseudoMice = options.accessibility.pseudoMouse.mice;
      var mouse = null;
      var offset = null;
      var width = null;
      var height = null;
      var container = null;
      var found = false;
      for (var i = 0; i < pseudoMice.length; i++) {
        mouse = pseudoMice[i];
        $(mouse).bind("mousemove", function(event) {
          var options = $(target).data("slideSlotActivity:options");
          if (options.data.enabled) {
            var event2 = new $.Event("mousemove");
            event2.pageX = event.pageX;
            event2.pageY = event.pageY;
            $(target).trigger(event2);
          }
          options = $(target).data("slideSlotActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            var activeSet = getActiveSetContainer(target, options);
            var choices = getChoicesInSet(target, options, activeSet);
            for (var j = 0; j < choices.length; j++) {
              found = false;
              container = $(choices[j]).children("." + options.containers.choices.downarrow.css.identifier).first();
              offset = $(container).offset();
              if ($(container).hasClass(options.containers.choices.container.css.hover)) {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      found = true;
                    }
                  }
                }
                if (!found) {
                  $(container).trigger("mouseout");
                }
              } else {
                if (event.pageX >= offset.left) {
                  if (event.pageY >= offset.top) {
                    width = $(container).outerWidth();
                    height = $(container).outerHeight();
                    if (event.pageX <= offset.left + width && event.pageY <= offset.top + height) {
                      $(container).trigger("mouseover");
                    }
                  }
                }
              }
            }
          }
        });
        $(mouse).bind("mouseup", function(event) {
          var options = $(target).data("slideSlotActivity:options");
          if (options.data.enabled && options.accessibility.hasFocus) {
            container = null;
            for (var j = 0; j < choices.length; j++) {
              container = $(choices[j]).children("." + options.containers.choices.downarrow.css.identifier).first();
              offset = $(container).offset();
              width = $(container).width();
              height = $(container).height();
              if (event.pageX >= offset.left && event.pageX <= offset.left + width && event.pageY >= offset.top && event.pageY <= offset.top + height) {
                $(container).trigger("click");
              }
            }
          }
        });
      }
    }

    function parseXMLAndBuildActivity(target, options, data) {
      log(target, options, "Parsing Activity XML", "info");
      try {
        if (window.ActiveXObject) {
          var doc = new ActiveXObject("Microsoft.XMLDOM");
          doc.loadXML(data);
          data = doc;
        } else {
          if (window.DOMParser) {
            data = (new DOMParser).parseFromString(data, "text/xml");
          }
        }
      } catch(error) {
        data = null;
        log(target, options, "XML Parse Error:{error:" + error + "}", "error");
      }
      if (data) {
        var activityData = {
          allowRetry : true,
          randomizeOnRetry : true,
          gradeSetsIndividually : false,
          dataSets : []
        };
        var idIndex = 0;
        var dataSet = null;
        var choice = null;
        if ($(data).children("slideSlotActivity").attr("retry")) {
          activityData.allowRetry = ($(data).children("slideSlotActivity").attr("retry").toLowerCase() == "true") ? true : false;
        }
        if ($(data).children("slideSlotActivity").attr("randomizeOnRetry")) {
          activityData.randomizeOnRetry = ($(data).children("slideSlotActivity").attr("randomizeOnRetry").toLowerCase() == "true") ? true : false;
        }
        if ($(data).children("slideSlotActivity").attr("gradeSetsIndividually")) {
          activityData.gradeSetsIndividually = ($(data).children("slideSlotActivity").attr("gradeSetsIndividually").toLowerCase() == "true") ? true : false;
        }
        $(data).children("slideSlotActivity").children("set").each(function() {
          dataSet = {
            id : $(this).attr("id"),
            allowRetry : false,
            showFeedback : true,
            gradeIndividually : false,
            autoComplete : false,
            title : $(this).children("title:first").text(),
            rows : [],
            choices : []
          };
          if ($(this).children("title:first").attr("encoding")) {
            dataSet.title = unescape(dataSet.title.replace(/\+/g, " "));
          }
          $(this).children("choices").children("choice").each(function() {
            choice = {
              id : $(this).attr("id"),
              content : $(this).text(),
              value : parseFloat($(this).attr("value")),
              correct : (($(this).attr("correct").toLowerCase() == "true") ? true : false),
              row : parseFloat($(this).attr("row")),
              selectOnce : false
            };
            var rowDataFound = false;
            $.each(dataSet.rows, function(i, rowData) {
              if (rowData.id == choice.row) {
                rowDataFound = true;
                rowData.columns++;
                return true;
              }
            });
            if (!rowDataFound) {
              dataSet.rows.push({
                id : choice.row,
                columns : 1
              });
            }
            if ($(this).attr("encoding")) {
              choice.content = unescape(choice.content.replace(/\+/g, " "));
            }
            if ($(this).attr("selectOnce")) {
              choice.selectOnce = ($(this).attr("selectOnce").toLowerCase() == "true") ? true : false;
            }
            dataSet.choices.push(choice);
          });
          activityData.dataSets.push(dataSet);
        });
        buildActivity(target, options, activityData);
      } else {
        log(target, options, "XML Activity Build Error:{error:No data to build activity}", "error");
      }
    }

    function loadXMLAndBuildActivity(target, options, url) {
      log(target, options, "Loading XML", "info");
      $.ajax({
        url : url,
        dataType : "text",
        success : function(data, textStatus, xhr) {
          var options = $(target).data("slideSlotActivity:options");
          log(target, options, "XML Loaded", "info");
          parseXMLAndBuildActivity(target, options, data);
        },
        error : function(xhr, textStatus, errorThrown) {
          log(target, options, "XML Load Error:{textStatus:" + textStatus + ",errorThrown:" + errorThrown + "}", "error");
        }
      });
    }

    function buildActivity(target, options, activityData) {
      var dataSet = null;
      var choiceDimensions = null;
      var containerPadding = calculateContainerPadding(target, options, options.containers.choice.reference);
      var currentChoice = null;
      var choices = [];
      var choice = null;
      var setContainer = null;
      var columnsInRows = [];
      options.data.allowRetry = activityData.allowRetry;
      options.data.randomizeOnRetry = activityData.randomizeOnRetry;
      options.data.gradeSetsIndividually = activityData.gradeSetsIndividually;
      if (options.data.overridePoints || options.data.overridePoints == 0) {
        var totalCorrectPoints = 0;
        $.each(activityData.dataSets, function(i, dataSet) {
          $.each(dataSet.choices, function(j, choice) {
            if (choice.correct) {
              totalCorrectPoints += choice.value;
            }
          });
        });
        if (totalCorrectPoints == 0 || options.data.overridePoints == 0) {
          totalCorrectPoints = 0;
          $.each(activityData.dataSets, function(i, dataSet) {
            $.each(dataSet.choices, function(j, choice) {
              if (choice.correct) {
                if (options.data.overridePoints > 0) {
                  choice.value = 1;
                  totalCorrectPoints++;
                } else {
                  choice.value = 0;
                }
              }
            });
          });
        }
        var factor = options.data.overridePoints / totalCorrectPoints;
        $.each(activityData.dataSets, function(i, dataSet) {
          $.each(dataSet.choices, function(j, choice) {
            choice.value = choice.value * factor;
          });
        });
      }
      var rowData = null;
      for (var i = 0; i < activityData.dataSets.length; i++) {
        dataSet = $.extend({}, activityData.dataSets[i], {
          choices : [],
          attempts : 0,
          focusedChoiceId : null,
          focusedChoiceRow : -1,
          focusedChoiceColumn : -1,
          completed : false
        });
        options.data.dataSets.push(dataSet);
        choiceDimensions = calculateChoiceDimensions(target, options, dataSet.rows.length, 1);
        choice = null;
        for (var j = 0; j < activityData.dataSets[i].choices.length; j++) {
          choice = activityData.dataSets[i].choices[j];
          rowData = null;
          $.each(columnsInRows, function(k, data) {
            if (data.id == choice.row) {
              rowData = data;
            }
          });
          if (!rowData) {
            rowData = {
              id : choice.row,
              columns : 0
            };
            columnsInRows.push(rowData);
          }
          currentChoice = createChoiceContainer(target, options, choice.content);
          $(currentChoice).data("slideSlotActivity:choice", {
            id : choice.id,
            row : choice.row,
            column : rowData.columns,
            value : choice.value,
            correct : choice.correct,
            selectOnce : choice.selectOnce
          });
          registerChoiceEvents(target, options, currentChoice);
          dataSet.choices.push(currentChoice);
          choices.push(currentChoice);
          rowData.columns++;
        }
        setContainer = createSetContainer(target, options);
        options.containers.set.references.push(setContainer);
        $(setContainer).data("slideSlotActivity:set", dataSet);
        $(options.containers.choice.reference).append(setContainer);
        for (var j = 0; j < dataSet.choices.length; j++) {
          $(setContainer).append(dataSet.choices[j]);
        }
        resizeChoices(target, options, choiceDimensions.width, choiceDimensions.height, dataSet.choices);
        randomizeChoicePositionsInSet(target, options, setContainer);
        positionChoices(target, options, dataSet.choices);
        alignChoices(target, options, dataSet.choices);
      }
      registerAccessibilityEvents(target, options, choices);
      enableDisable(target, options, choices);
      $(target).data("slideSlotActivity:options", options);
      alignSets(target, options);
      showSet(target, options, activityData.dataSets[0].id);
      calculateActivityScore(target, options, false);
      $(target).trigger("activityLoaded.slideSlotActivity", [options.data.dataSets.length, 0, options.data.allowRetry, options.data.gradeSetsIndividually]);
    }

    function createSetContainer(target, options) {
      return $("<div />").addClass(options.containers.set.css.identifier);
    }

    function showSet(target, options, id, setContainers, reset, resetPosition) {
      setContainers = setContainers || getSetContainers(target, options);
      reset = reset || false;
      resetPosition = resetPosition || false;
      var setContainer = null;
      var setContainerData = null;
      var selectedSetContainerData = null;
      var selectedSetContainer = null;
      var setPosition = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("slideSlotActivity:set");
        $(setContainer).removeClass(options.containers.set.css.selected);
        if (setContainerData.id == id) {
          setPosition = i;
          selectedSetContainerData = setContainerData;
          selectedSetContainer = setContainer;
          $(setContainer).addClass(options.containers.set.css.selected);
        }
      }
      var choices = getChoices(target, options);
      positionChoices(target, options, choices);
      alignChoices(target, options, choices);
      if (reset && selectedSetContainerData) {
        options.data.enabled = true;
        enableDisable(target, options, choices);
        $(target).data("slideSlotActivity:data", options);
      }
      if (resetPosition) {
        var width = $(options.containers.choice.reference).outerWidth();
        var finalPosition = -(width * [id]);
        $(options.containers.choice.reference).css("left", finalPosition + "px");
      }
      $(target).trigger("titleChanged.slideSlotActivity", [selectedSetContainerData.title]);
      $(target).trigger("setChanged.slideSlotActivity", [setContainers.length, setPosition, options.data.gradeSetsIndividually, options.data.allowRetry, selectedSetContainerData.completed, options.data.enabled]);
    }

    function showNextSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          if (setContainers[i] == currentSetContainer && i < setContainers.length - 1) {
            var width = $(options.containers.choice.reference).outerWidth();
            var finalPosition = -(width * [i + 1]);
            if (options.data.animate) {
              $(options.containers.choice.reference).stop(true, false).addClass(options.containers.choice.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.choice.css.animating);
              });
            } else {
              $(options.containers.choice.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i + 1]).data("slideSlotActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function showPreviousSet(target, options) {
      var setContainers = getSetContainers(target, options);
      var currentSetContainer = getActiveSetContainer(target, options);
      var setData = null;
      if (currentSetContainer) {
        for (var i = 0; i < setContainers.length; i++) {
          if (setContainers[i] == currentSetContainer && i > 0) {
            var width = $(options.containers.choice.reference).outerWidth();
            var finalPosition = -(width * [i - 1]);
            if (options.data.animate) {
              $(options.containers.choice.reference).stop(true, false).addClass(options.containers.choice.css.animating).animate({
                left : finalPosition
              }, "slow", null, function() {
                $(this).removeClass(options.containers.choice.css.animating);
              });
            } else {
              $(options.containers.choice.reference).css("left", finalPosition + "px");
            }
            setData = $(setContainers[i - 1]).data("slideSlotActivity:set");
            showSet(target, options, setData.id, setContainers);
            break;
          }
        }
      }
    }

    function getSetState(target, options, setContainer) {
      var setContainerData = $(setContainer).data("slideSlotActivity:set");
      var setState = {
        id : setContainerData.id,
        allowRetry : setContainerData.allowRetry,
        showFeedback : setContainerData.showFeedback,
        gradeIndividually : setContainerData.gradeIndividually,
        attempts : setContainerData.attempts,
        completed : setContainerData.completed,
        rows : setContainerData.rows,
        choices : []
      };
      var setChoices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      var normalizedChoiceData = null;
      for (var i = 0; i < setChoices.length; i++) {
        choice = setChoices[i];
        choiceOptions = $(choice).data("slideSlotActivity:choice");
        normalizedChoiceData = {
          id : choiceOptions.id,
          row : choiceOptions.row,
          column : choiceOptions.column,
          correct : choiceOptions.correct,
          value : choiceOptions.value,
          selected : $(choice).hasClass(options.containers.choices.container.css.selected),
          finished : $(choice).hasClass(options.containers.choices.container.css.correct) || $(choice).hasClass(options.containers.choices.container.css.incorrect) || false
        };
        setState.choices.push(normalizedChoiceData);
      }
      return setState;
    }

    function setSetState(target, options, setContainer, setState) {
      log(target, options, "Setting Set State:" + setState.id);
      var setContainerData = $(setContainer).data("slideSlotActivity:set");
      setContainerData.allowRetry = setState.allowRetry;
      setContainerData.showFeedback = setState.showFeedback;
      setContainerData.gradeIndividually = setState.gradeIndividually;
      setContainerData.attempts = setState.attempts;
      setContainerData.completed = setState.completed;
      setContainerData.rows = setState.rows;
      $(setContainer).data("slideSlotActivity:set", setContainerData);
      if (setContainerData.completed && !$(setContainer).hasClass(options.containers.set.css.completed)) {
        $(setContainer).addClass(options.containers.set.css.completed);
      }
      var setChoices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var choiceOptions = null;
      var normalizedChoiceData = null;
      for (var i = 0; i < setChoices.length; i++) {
        choice = setChoices[i];
        choiceOptions = $(choice).data("slideSlotActivity:choice");
        for (var j = 0; j < setState.choices.length; j++) {
          normalizedChoiceData = setState.choices[j];
          if (normalizedChoiceData.id == choiceOptions.id) {
            choiceOptions.row = normalizedChoiceData.row;
            choiceOptions.column = normalizedChoiceData.column;
            choiceOptions.correct = normalizedChoiceData.correct;
            choiceOptions.value = normalizedChoiceData.value;
            $(choice).removeClass(options.containers.choices.container.css.selected);
            if (normalizedChoiceData.selected) {
              $(choice).addClass(options.containers.choices.container.css.selected);
            }
            if (normalizedChoiceData.finished) {
              if (normalizedChoiceData.correct) {
                $(choice).addClass(options.containers.choices.container.css.correct);
              } else {
                $(choice).addClass(options.containers.choices.container.css.incorrect);
              }
            }
          }
        }
        $(choice).data("slideSlotActivity:choice", choiceOptions);
      }
    }

    function calculateActivityScore(target, options, incrementAttempts, autoCompleteOverride, doNotUpdateExternalScore) {
      incrementAttempts = incrementAttempts || true;
      autoCompleteOverride = autoCompleteOverride || false;
      doNotUpdateExternalScore = doNotUpdateExternalScore || false;
      var choiceSets = getSetContainers(target, options);
      var activeSet = getActiveSetContainer(target, options);
      var activeSetPosition = 0;
      var setScore = null;
      var setScores = [];
      var calculatedScore = 0;
      var calculatedPossible = 0;
      var totalCorrect = 0;
      var totalIncorrect = 0;
      var correctSelected = 0;
      var incorrectSelected = 0;
      for (var i = 0; i < choiceSets.length; i++) {
        if (choiceSets[i] == activeSet) {
          activeSetPosition = i;
        }
        if (options.data.gradeSetsIndividually && choiceSets[i] == activeSet) {
          setScore = calculateSetScore(target, options, choiceSets[i], incrementAttempts, autoCompleteOverride);
        } else {
          if (options.data.gradeSetsIndividually && choiceSets[i] != activeSet) {
            setScore = calculateSetScore(target, options, choiceSets[i], false, false);
          } else {
            setScore = calculateSetScore(target, options, choiceSets[i], incrementAttempts, autoCompleteOverride);
          }
        }
        calculatedScore += setScore.calculatedScore;
        calculatedPossible += setScore.calculatedPossible;
        totalCorrect += setScore.totalCorrect;
        totalIncorrect += setScore.totalIncorrect;
        correctSelected += setScore.correctSelected;
        incorrectSelected += setScore.incorrectSelected;
        $(target).trigger("setScoreChanged.slideSlotActivity", [options.data.dataSets.length, i, options.data.allowRetry, options.data.gradeSetsIndividually, setScore.calculatedScore, setScore.calculatedPossible, $(choiceSets[i]).data("slideSlotActivity:set").completed, doNotUpdateExternalScore]);
      }
      log(target, options, "Score Recalculated:" + calculatedScore + "/" + calculatedPossible, "info");
      $(target).trigger("activityScoreChanged.slideSlotActivity", [options.data.dataSets.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually, calculatedScore, calculatedPossible, $(activeSet).data("slideSlotActivity:set").completed, doNotUpdateExternalScore]);
      if (!options.data.gradeSetsIndividually && autoCompleteOverride) {
        options.data.enabled = false;
        $(target).data("slideSlotActivity:options", options);
        enableDisable(target, options);
        log(target, options, "Activity Completed:" + calculatedScore + "/" + calculatedPossible, "info");
        $(target).trigger("activityComplete.slideSlotActivity", [options.data.dataSets.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually, calculatedScore, calculatedPossible, doNotUpdateExternalScore]);
      }
      return {
        calculatedScore : calculatedScore,
        calculatedPossible : calculatedPossible,
        totalCorrect : totalCorrect,
        totalIncorrect : totalIncorrect,
        correctSelected : correctSelected,
        incorrectSelected : incorrectSelected
      };
    }

    function calculateSetScore(target, options, setContainer, incrementAttempts, autoCompleteOverride) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      incrementAttempts = incrementAttempts || true;
      autoCompleteOverride = autoCompleteOverride || false;
      var setData = $(setContainer).data("slideSlotActivity:set");
      var setState = getSetState(target, options, setContainer);
      var scoreResults = options.data.calculateScore(setState);
      if (setData.gradeIndividually) {
        if (setData.showFeedback) {
          showCorrectAndIncorrect(target, options, setContainer, true);
        }
      } else {
        if (setData.autoComplete && scoreResults.totalCorrect == scoreResults.correctSelected || autoCompleteOverride == true) {
          setData.completed = true;
          if (!$(setContainer).hasClass(options.containers.set.css.completed)) {
            $(setContainer).addClass(options.containers.set.css.completed);
          }
          if (setData.showFeedback) {
            showCorrectAndIncorrect(target, options, setContainer, false);
          }
          if (incrementAttempts) {
            setData.attempts++;
          }
        } else {
          clearCorrectAndIncorrectInSet(target, options, setContainer);
          if (!setData.completed) {
            scoreResults.calculatedScore = 0;
          } else {
            if (setData.showFeedback) {
              showCorrectAndIncorrect(target, options, setContainer, false);
            }
          }
        }
      }
      $(setContainer).data("slideSlotActivity:set", setData);
      return scoreResults;
    }

    function showCorrectAndIncorrect(target, options, setContainer, showOnlySelected) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      showOnlySelected = showOnlySelected || true;
      if (options.data.enabled) {
        var choices = getChoicesInSet(target, options, setContainer);
        var choice = null;
        var choiceOptions = null;
        var showChoice = false;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          choiceOptions = $(choice).data("slideSlotActivity:choice");
          showChoice = true;
          if (showChoice) {
            if (choiceOptions.correct) {
              $(choice).removeClass(options.containers.choices.container.css.incorrect);
              if (!$(choice).hasClass(options.containers.choices.container.css.correct)) {
                $(choice).addClass(options.containers.choices.container.css.correct);
              }
            } else {
              $(choice).removeClass(options.containers.choices.container.css.correct);
              if (!$(choice).hasClass(options.containers.choices.container.css.incorrect)) {
                $(choice).addClass(options.containers.choices.container.css.incorrect);
              }
            }
          } else {
            $(choice).removeClass(options.containers.choices.container.css.correct);
            $(choice).removeClass(options.containers.choices.container.css.incorrect);
          }
        }
      }
    }

    function clearCorrectAndIncorrect(target, options, choices, showOnlySelected) {
      choices = choices || getChoices(target, options);
      showOnlySelected = showOnlySelected || true;
      if (options.data.enabled) {
        var choice = null;
        var showChoice = false;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          $(choice).removeClass(options.containers.choices.container.css.incorrect);
          $(choice).removeClass(options.containers.choices.container.css.correct);
        }
      }
    }

    function clearCorrectAndIncorrectInSet(target, options, setContainer, showOnlySelected) {
      setContainer = setContainer || getActiveSetContainer(target, options);
      showOnlySelected = showOnlySelected || true;
      choices = getChoicesInSet(target, options, setContainer);
      var choice = null;
      var showChoice = false;
      for (var i = 0; i < choices.length; i++) {
        choice = choices[i];
        $(choice).removeClass(options.containers.choices.container.css.incorrect);
        $(choice).removeClass(options.containers.choices.container.css.correct);
      }
    }

    function alignChoices(target, options, choices) {
      choices = choices || getChoices(target, options);
      if (choices) {
        var choice = null;
        var choiceContent = null;
        var choiceOptions = null;
        var leftContent = null;
        var rightContent = null;
        var feedbackIconContent = null;
        for (var i = 0; i < choices.length; i++) {
          choice = choices[i];
          choiceContent = $(choice).children("." + options.containers.choices.content.css.identifier + ":first");
          leftContent = $(choice).find("." + options.containers.choices.leftButton.button.css.identifier + ":first");
          rightContent = $(choice).find("." + options.containers.choices.rightButton.button.css.identifier + ":first");
          feedbackIconContent = $(choice).find("." + options.containers.choices.feedbackIcon.css.identifier + ":first");
          alignToParent(target, options, options.containers.choices.content.horizontalAlign, options.containers.choices.content.verticalAlign, choiceContent);
          alignToParent(target, options, "left", "middle", leftContent);
          alignToParent(target, options, "right", "middle", rightContent);
          alignToParent(target, options, options.containers.choices.feedbackIcon.horizontalAlign, options.containers.choices.feedbackIcon.verticalAlign, feedbackIconContent);
        }
      }
    }

    function alignSets(target, options, setContainers) {
      setContainers = setContainers || getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var setWidth = 0;
      for (var i = 0; i < setContainers.length; i++) {
        setContainer = setContainers[i];
        setContainerData = $(setContainer).data("slideSlotActivity:set");
        setWidth = $(setContainer).width();
        $(setContainer).css("left", (setWidth * setContainerData.id) + "px");
      }
    }

    function alignToParent(target, options, horizontalAlign, verticalAlign, container) {
      $(container).css("position", "absolute");
      if (horizontalAlign) {
        switch(horizontalAlign.toLowerCase()) {
          case"left":
            $(container).css("right", null).css("left", "0px");
            break;
          case"right":
            $(container).css("left", null).css("right", "0px");
            break;
          case"center":
            $(container).css("right", null).css("left", ($(container).parent().innerWidth() / 2 - $(container).outerWidth() / 2) + "px");
            break;
        }
      }
      if (verticalAlign) {
        switch(verticalAlign.toLowerCase()) {
          case"top":
            $(container).css("bottom", null).css("top", "0px");
            break;
          case"bottom":
            $(container).css("top", null).css("bottom", "0px");
            break;
          case"middle":
            $(container).css("bottom", null).css("top", ($(container).parent().innerHeight() / 2 - $(container).outerHeight() / 2) + "px");
            break;
        }
      }
    }

    function resetActivity(target, options) {
      if (options.data.allowRetry) {
        log(target, options, "Resetting Activity", "info");
        var setContainers = getSetContainers(target, options);
        var activeSet = getActiveSetContainer(target, options);
        var activeSetPosition = 0;
        var setContainer = null;
        var setContainerData = null;
        var choices = null;
        var calculatedScore = 0;
        var calculatedPossible = 0;
        var setScore = null;
        options.data.enabled = true;
        for (var i = 0; i < setContainers.length; i++) {
          setContainer = setContainers[i];
          setContainerData = $(setContainer).data("slideSlotActivity:set");
          if (setContainer == activeSet) {
            activeSetPosition = i;
          }
          if ((options.data.gradeSetsIndividually && setContainer == activeSet) || !options.data.gradeSetsIndividually) {
            setContainerData.attempts = 0;
            setContainerData.completed = false;
            setContainerData.focusedChoiceId = null;
            setContainerData.focusedChoiceRow = -1;
            setContainerData.focusedChoiceColumn = -1;
            $(setContainer).data("slideSlotActivity:set", setContainerData);
            choices = getChoicesInSet(target, options, setContainer);
            clearChoicesHover(target, options, choices);
            clearCorrectAndIncorrectInSet(target, options, setContainer);
            clearSelectedChoices(target, options, choices);
            setScore = calculateSetScore(target, options, setContainer);
            calculatedScore += setScore.calculatedScore;
            calculatedPossible += setScore.calculatedPossible;
            if (options.data.randomizeOnRetry) {
              randomizeChoicePositionsInSet(target, options, setContainer);
              positionChoices(target, options, choices);
            }
            if ($(setContainer).hasClass(options.containers.set.css.completed)) {
              $(setContainer).removeClass(options.containers.set.css.completed);
            }
          }
        }
        enableDisable(target, options);
        var setPosition = $(activeSet).data("slideSlotActivity:set").id;
        if (!options.data.gradeSetsIndividually && options.data.randomizeOnRetry) {
          setPosition = Math.floor(Math.random() * setContainers.length);
        }
        setContainer = setContainers[setPosition];
        setContainerData = $(setContainer).data("slideSlotActivity:set");
        showSet(target, options, setContainerData.id, setContainers, false, true);
        activeSet = getActiveSetContainer(target, options);
        for (var i = 0; i < setContainers.length; i++) {
          setContainer = setContainers[i];
          setContainerData = $(setContainer).data("slideSlotActivity:set");
          if (setContainer == activeSet) {
            activeSetPosition = i;
          }
        }
        $(target).data("slideSlotActivity:options", options);
        $(target).trigger("reset.slideSlotActivity", [setContainers.length, activeSetPosition, options.data.allowRetry, options.data.gradeSetsIndividually]);
        calculateActivityScore(target, options, false);
      }
    }

    function getActiveSetContainerId(target, options) {
      return $(getActiveSetContainer(target, options)).data("slideSlotActivity:set").id || null;
    }

    function getActivityState(target, options) {
      var activityState = {
        enabled : options.data.enabled,
        allowRetry : options.data.allowRetry,
        randomizeOnRetry : options.data.randomizeOnRetry,
        activeSetId : getActiveSetContainerId(target, options),
        sets : []
      };
      var setContainers = getSetContainers(target, options);
      for (var i = 0; i < setContainers.length; i++) {
        activityState.sets.push(getSetState(target, options, setContainers[i]));
      }
      return activityState;
    }

    function setActivityState(target, options, activityState, completed) {
      log(target, options, "Setting Activity State");
      var setData = null;
      var setContainers = getSetContainers(target, options);
      var setContainer = null;
      var setContainerData = null;
      var choices = null;
      showSet(target, options, activityState.activeSetId, false, true);
      for (var i = 0; i < activityState.sets.length; i++) {
        setData = activityState.sets[i];
        for (var j = 0; j < setContainers.length; j++) {
          setContainer = setContainers[j];
          setContainerData = $(setContainer).data("slideSlotActivity:set");
          choices = getChoicesInSet(target, options, setContainer);
          if (setData.id == setContainerData.id) {
            setSetState(target, options, setContainer, setData);
          }
          positionChoices(target, options, choices);
        }
      }
      options.data.enabled = activityState.enabled;
      options.data.allowRetry = activityState.allowRetry;
      options.data.randomizeOnRetry = activityState.randomizeOnRetry;
      $(target).data("slideSlotActivity:options", options);
      enableDisable(target, options);
      calculateActivityScore(target, options, false, completed, true);
    }
    return this;
  };
  $.fn.slideSlotActivity.defaults = {};
  $.fn.slideSlotActivity.defaults.containers = {
    activity : {
      reference : null,
      css : {
        identifier : "softchalk-slide-slot-activity"
      }
    },
    content : {
      reference : null,
      css : {
        identifier : "softchalk-slide-slot-activity-content",
        enabled : "enabled",
        disabled : "disabled"
      }
    },
    choice : {
      reference : null,
      css : {
        identifier : "softchalk-slide-slot-activity-sets",
        animating : "animating"
      }
    },
    set : {
      references : [],
      css : {
        identifier : "softchalk-slide-slot-activity-set",
        selected : "selected",
        completed : "completed"
      }
    },
    choices : {
      references : [],
      container : {
        css : {
          identifier : "softchalk-slide-slot-activity-choice",
          selected : "selected",
          correct : "correct",
          incorrect : "incorrect",
          hover : "hover",
          animating : "animating"
        }
      },
      content : {
        horizontalAlign : "center",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-slide-slot-activity-choice-content"
        }
      },
      leftButton : {
        container : {
          css : {
            identifier : "softchalk-slide-slot-activity-choice-left-button-container",
            hover : "hover"
          }
        },
        button : {
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-slide-slot-activity-choice-left-button",
            hover : "hover"
          }
        }
      },
      rightButton : {
        container : {
          css : {
            identifier : "softchalk-slide-slot-activity-choice-right-button-container",
            hover : "hover"
          }
        },
        button : {
          horizontalAlign : "center",
          verticalAlign : "middle",
          css : {
            identifier : "softchalk-slide-slot-activity-choice-right-button",
            hover : "hover"
          }
        }
      },
      feedback : {
        css : {
          identifier : "softchalk-slide-slot-activity-choice-feedback"
        }
      },
      feedbackIcon : {
        horizontalAlign : "right",
        verticalAlign : "middle",
        css : {
          identifier : "softchalk-slide-slot-activity-choice-feedback-icon"
        }
      },
      overlay : {
        css : {
          identifier : "softchalk-slide-slot-activity-choice-overlay"
        }
      }
    }
  };
  $.fn.slideSlotActivity.defaults.data = {
    dataSets : [],
    calculateScore : function(setState) {
      var calculatedCorrect = 0;
      var calculatedIncorrect = 0;
      var calculatedPossible = 0;
      var choiceData = null;
      var correctSelected = 0;
      var incorrectSelected = 0;
      var totalCorrect = 0;
      var totalIncorrect = 0;
      for (var i = 0; i < setState.choices.length; i++) {
        choiceData = setState.choices[i];
        if (choiceData.correct == true) {
          totalCorrect++;
          calculatedPossible += choiceData.value;
        } else {
          totalIncorrect++;
        }
        if (choiceData.column == 1) {
          if (choiceData.correct == true) {
            calculatedCorrect += choiceData.value;
            correctSelected++;
          } else {
            calculatedIncorrect += choiceData.value;
            incorrectSelected++;
          }
        }
      }
      var calculatedScore = Math.max(0, calculatedCorrect - calculatedIncorrect);
      var calculatedScore = calculatedCorrect;
      return {
        calculatedScore : calculatedScore,
        calculatedPossible : calculatedPossible,
        totalCorrect : totalCorrect,
        totalIncorrect : totalIncorrect,
        correctSelected : correctSelected,
        incorrectSelected : incorrectSelected
      };
    },
    enabled : true,
    enableLogging : false,
    allowRetry : true,
    randomizeOnRetry : true,
    animate : true,
    gradeSetsIndividually : false,
    overridePoints : null
  };
  $.fn.slideSlotActivity.defaults.accessibility = {
    pseudoMouse : {
      allow : true,
      mice : []
    },
    keyboard : {
      allow : true
    },
    hasFocus : false
  };
  $.fn.slideSlotActivity.defaults.logging = {
    debug : false,
    info : true,
    warn : false,
    error : false
  };
})(jQuery);
(function(jQuery) {
  var domfocus = false;
  var mousefocus = false;
  var zoomactive = false;
  var tabindexcounter = 5000;
  var ascrailcounter = 2000;
  var $ = jQuery;
  function getScriptPath() {
    var scripts = document.getElementsByTagName("script");
    var path = scripts[scripts.length-1].src.split("?")[0];
    return (path.split("/").length > 0) ? path.split("/").slice(0, -1).join("/") + "/" : "";
  }

  var scriptpath = getScriptPath();
  var setAnimationFrame = (function() {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || false;
  })();
  var clearAnimationFrame = (function() {
    return window.cancelRequestAnimationFrame || window.webkitCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || false;
  })();
  var NiceScrollClass = function(myopt, me) {
    var self = this;
    this.version = "3.0.0-PREVIEW1";
    this.name = "nicescroll";
    this.me = me;
    this.opt = {
      doc : $("body"),
      win : false,
      zindex : 9000,
      cursoropacitymin : 0,
      cursoropacitymax : 1,
      cursorcolor : "#424242",
      cursorwidth : "5px",
      cursorborder : "1px solid #fff",
      cursorborderradius : "5px",
      scrollspeed : 60,
      mousescrollstep : 8 * 5,
      touchbehavior : false,
      hwacceleration : true,
      usetransition : true,
      boxzoom : false,
      dblclickzoom : true,
      gesturezoom : true,
      grabcursorenabled : true,
      autohidemode : true,
      background : "",
      iframeautoresize : true,
      cursorminheight : 20,
      preservenativescrolling : true,
      railoffset : false,
      bouncescroll : false,
      spacebarenabled : true
    };
    if (myopt || false) {
      for (var a in self.opt) {
        if ( typeof myopt[a] != "undefined") {
          self.opt[a] = myopt[a];
        }
      }
    }
    this.doc = self.opt.doc;
    this.id = (this.doc && this.doc[0]) ? this.doc[0].id || "" : "";
    this.ispage = /BODY|HTML/.test((self.opt.win) ? self.opt.win[0].nodeName : this.doc[0].nodeName);
    this.haswrapper = (self.opt.win !== false);
    this.win = self.opt.win || (this.ispage ? $(window) : this.doc);
    this.docscroll = (this.ispage && !this.haswrapper) ? $(window) : this.win;
    this.body = $("body");
    this.iframe = false;
    this.isiframe = ((this.doc[0].nodeName == "IFRAME") && (this.win[0].nodeName == "IFRAME"));
    this.istextarea = (this.win[0].nodeName == "TEXTAREA");
    this.onmousedown = false;
    this.onmouseup = false;
    this.onmousemove = false;
    this.onmousewheel = false;
    this.onkeypress = false;
    this.ongesturezoom = false;
    this.onclick = false;
    this.view = false;
    this.page = false;
    this.scroll = {
      x : 0,
      y : 0
    };
    this.scrollratio = {
      x : 0,
      y : 0
    };
    this.cursorheight = 20;
    this.scrollvaluemax = 0;
    this.scrollmom = false;
    do {
      this.id = "ascrail" + (ascrailcounter++);
    } while(document.getElementById(this.id));
    this.rail = false;
    this.cursor = false;
    this.cursorfreezed = false;
    this.zoom = false;
    this.zoomactive = false;
    this.hasfocus = false;
    this.hasmousefocus = false;
    this.visibility = true;
    this.locked = false;
    self.nativescrollingarea = false;
    this.events = [];
    this.saved = {};
    this.delaylist = {};
    var domtest = document.createElement("DIV");
    this.isopera = ("opera" in window);
    this.isie = (("all" in document) && ("attachEvent" in domtest) && !this.isopera);
    this.isieold = (this.isie && !("msInterpolationMode" in domtest.style));
    this.isie7 = this.isie && !this.isieold && (!("documentMode" in document) || (document.documentMode == 7));
    this.isie8 = this.isie && ("documentMode" in document) && (document.documentMode == 8);
    this.isie9 = this.isie && ("performance" in window) && (document.documentMode >= 9);
    this.ismozilla = ("MozAppearance" in domtest.style);
    this.ischrome = ("chrome" in window);
    this.cantouch = ("ontouchstart" in document.documentElement);
    this.isios = (this.cantouch && /iphone|ipad|ipod/i.test(navigator.platform));
    this.isios4 = ((this.isios) && !("seal" in Object));
    if (self.opt.hwacceleration) {
      this.trstyle = (window.opera) ? "OTransform" : (document.all) ? "msTransform" : (domtest.style.webkitTransform !== undefined) ? "webkitTransform" : (domtest.style.MozTransform !== undefined) ? "MozTransform" : false;
      if (this.trstyle && typeof domtest.style[this.trstyle] == "undefined") {
        this.trstyle = false;
      }
      this.hastransform = (this.trstyle != false);
      if (this.hastransform) {
        domtest.style[this.trstyle] = "translate3d(1px,2px,3px)";
        this.hastranslate3d = /translate3d/.test(domtest.style[this.trstyle]);
      }
      this.transitionstyle = false;
      this.prefixstyle = "";
      this.transitionend = false;
      var check = ["transition", "webkitTransition", "MozTransition", "OTransition", "msTransition", "KhtmlTransition"];
      var prefix = ["", "-webkit-", "-moz-", "-o-", "-ms-", "-khtml-"];
      var evs = ["transitionEnd", "webkitTransitionEnd", "transitionend", "oTransitionEnd", "msTransitionEnd", "KhtmlTransitionEnd"];
      for (var a = 0; a < check.length; a++) {
        if (check[a] in domtest.style) {
          this.transitionstyle = check[a];
          this.prefixstyle = prefix[a];
          this.transitionend = evs[a];
          break;
        }
      }
      this.hastransition = (this.transitionstyle);
    } else {
      this.trstyle = false;
      this.hastransform = false;
      this.hastranslate3d = false;
      this.transitionstyle = false;
      this.hastransition = false;
      this.transitionend = false;
    }
    this.cursorgrabvalue = "";
    if (self.opt.grabcursorenabled && self.opt.touchbehavior) {
      function detectCursorGrab() {
        if (self.ischrome || (self.isie && !self.isie9)) {
          var lst = ["url(http://www.google.com/intl/en_ALL/mapfiles/openhand.cur)", "n-resize"];
        } else {
          var lst = ["grab", "-moz-grab", "-webkit-grab", "url(http://www.google.com/intl/en_ALL/mapfiles/openhand.cur)", "n-resize"];
        }
        for (var a = 0; a < lst.length; a++) {
          var p = lst[a];
          domtest.style.cursor = p;
          if (domtest.style.cursor == p) {
            return p;
          }
        }
        return "";
      }
      this.cursorgrabvalue = detectCursorGrab();
    }
    domtest = null;
    this.ishwscroll = (self.hastransform) && (self.opt.hwacceleration) && (self.haswrapper);
    this.delayed = function(name, fn, tm) {
      var dd = self.delaylist[name];
      var nw = (new Date()).getTime();
      if (dd && dd.tt) {
        return false;
      }
      if (dd && dd.last + tm > nw && !dd.tt) {
        self.delaylist[name] = {
          last : nw + tm,
          tt : setTimeout(function() {
            self.delaylist[name].tt = 0;
            fn.call();
          }, tm)
        };
      } else {
        if (!dd || !dd.tt) {
          self.delaylist[name] = {
            last : nw,
            tt : 0
          };
          setTimeout(function() {
            fn.call();
          }, 0);
        }
      }
    };
    this.css = function(el, pars) {
      for (var n in pars) {
        self.saved.css.push([el, n, el.css(n)]);
        el.css(n, pars[n]);
      }
    };
    this.scrollTop = function(val) {
      return ( typeof val == "undefined") ? self.getScrollTop() : self.setScrollTop(val);
    };
    BezierClass = function(st, ed, spd, p1, p2, p3, p4) {
      this.st = st;
      this.ed = ed;
      this.spd = spd;
      this.p1 = p1 || 0;
      this.p2 = p2 || 1;
      this.p3 = p3 || 0;
      this.p4 = p4 || 1;
      this.ts = (new Date()).getTime();
      this.df = this.ed - this.st;
    };
    BezierClass.prototype = {
      B2 : function(t) {
        return 3 * t * t * (1 - t);
      },
      B3 : function(t) {
        return 3 * t * (1 - t) * (1 - t);
      },
      B4 : function(t) {
        return (1 - t) * (1 - t) * (1 - t);
      },
      getNow : function() {
        var nw = (new Date()).getTime();
        var pc = 1 - ((nw - this.ts) / this.spd);
        var bz = this.B2(pc) + this.B3(pc) + this.B4(pc);
        return (pc < 0) ? this.ed : this.st + Math.round(this.df * bz);
      },
      update : function(ed, spd) {
        this.st = this.getNow();
        this.ed = ed;
        this.spd = spd;
        this.ts = (new Date()).getTime();
        this.df = this.ed - this.st;
        return this;
      }
    };
    if (this.ishwscroll) {
      this.doc.translate = {
        x : 0,
        y : 0
      };
      if (this.hastranslate3d) {
        this.doc.css(this.prefixstyle + "backface-visibility", "hidden");
      }
      this.getScrollTop = function(last) {
        if (self.timerscroll && !last) {
          return self.timerscroll.bz.getNow();
        } else {
          return self.doc.translate.y;
        }
      };
      if (document.createEvent) {
        this.notifyScrollEvent = function(el) {
          var e = document.createEvent("UIEvents");
          e.initUIEvent("scroll", false, true, window, 1);
          el.dispatchEvent(e);
        };
      } else {
        if (document.fireEvent) {
          this.notifyScrollEvent = function(el) {
            var e = document.createEventObject();
            el.fireEvent("onscroll");
            e.cancelBubble = true;
          };
        } else {
          this.notifyScrollEvent = function(el) {
          };
        }
      }
      if (this.hastranslate3d) {
        this.setScrollTop = function(val, silent) {
          self.doc.css(self.trstyle, "translate3d(0px," + (val * -1) + "px,0px)");
          self.doc.translate.y = val;
          if (!silent) {
            self.notifyScrollEvent(self.win[0]);
          }
        };
      } else {
        this.setScrollTop = function(val, silent) {
          self.doc.css(self.trstyle, "translate(0px," + (val * -1) + "px)");
          self.doc.translate.y = val;
          if (!silent) {
            self.notifyScrollEvent(self.win[0]);
          }
        };
      }
    } else {
      this.getScrollTop = function() {
        return self.docscroll.scrollTop();
      };
      this.setScrollTop = function(val) {
        return self.docscroll.scrollTop(val);
      };
      this.getScrollLeft = function() {
        return self.docscroll.scrollLeft();
      };
      this.setScrollLeft = function(val) {
        return self.docscroll.scrollLeft(val);
      };
    }
    this.getTarget = function(e) {
      if (!e) {
        return false;
      }
      if (e.target) {
        return e.target;
      }
      if (e.srcElement) {
        return e.srcElement;
      }
      return false;
    };
    this.hasParent = function(e, id) {
      if (!e) {
        return false;
      }
      var el = e.target || e.srcElement || e || false;
      while (el && el.id != id) {
        el = el.parentNode || false;
      }
      return (el !== false);
    };
    this.updateScrollBar = function(len) {
      if (self.ishwscroll) {
        self.rail.css({
          height : self.win.innerHeight()
        });
      } else {
        var wpos = self.win.offset();
        var pos = {
          top : wpos.top,
          left : wpos.left
        };
        pos.top += 2;
        var brd = (self.win.outerWidth() - self.win.innerWidth()) / 2;
        pos.left += self.win.innerWidth() + brd - self.rail.width - 1;
        var off = self.opt.railoffset;
        if (off) {
          if (off.top) {
            pos.top += off.top;
          }
          if (off.left) {
            pos.left += off.left;
          }
        }
        self.rail.css({
          top : pos.top,
          left : pos.left,
          height : (len) ? len.h : self.win.innerHeight()
        });
        if (self.zoom) {
          self.zoom.css({
            top : pos.top + 1,
            left : pos.left - 20
          });
        }
        if (self.railh) {
          var pos = {
            top : wpos.top,
            left : wpos.left
          };
          var y = pos.top + self.win.height() - self.railh.height;
          var x = pos.left;
          self.railh.css({
            top : y,
            left : x,
            width : self.railh.width
          });
        }
      }
    };
    self.hasanimationframe = (setAnimationFrame);
    self.hascancelanimationframe = (clearAnimationFrame);
    if (!self.hasanimationframe) {
      setAnimationFrame = function(fn) {
        return setTimeout(fn, Math.round(1000 / 60));
      };
      clearAnimationFrame = clearInterval;
    } else {
      if (!self.hascancelanimationframe) {
        clearAnimationFrame = function() {
          self.cancelAnimationFrame = true;
        };
      }
    }
    this.init = function() {
      self.saved.css = [];
      if (!self.ispage || (!self.cantouch && !self.isieold)) {
        var cont = self.docscroll;
        if (self.ispage) {
          cont = (self.haswrapper) ? self.win : self.doc;
        }
        self.css(cont, {
          "overflow-y" : "hidden"
        });
        if (self.ispage && self.isie7 && self.win[0].nodeName == "BODY") {
          self.css($("html"), {
            "overflow-y" : "hidden"
          });
        }
        var cursor = $(document.createElement("div"));
        cursor.css({
          position : "relative",
          top : 0,
          "float" : "right",
          width : self.opt.cursorwidth,
          height : "0px",
          "background-color" : self.opt.cursorcolor,
          border : self.opt.cursorborder,
          "background-clip" : "padding-box",
          "-webkit-border-radius" : self.opt.cursorborderradius,
          "-moz-border-radius" : self.opt.cursorborderradius,
          "border-radius" : self.opt.cursorborderradius
        });
        cursor.hborder = parseFloat(cursor.outerHeight() - cursor.innerHeight());
        self.cursor = cursor;
        var rail = $(document.createElement("div"));
        rail.attr("id", self.id);
        rail.width = 1 + Math.max(parseFloat(self.opt.cursorwidth), cursor.outerWidth());
        rail.css({
          "padding-left" : "0px",
          "padding-right" : "1px",
          width : rail.width + "px",
          zIndex : (self.ispage) ? self.opt.zindex : self.opt.zindex + 2,
          background : self.opt.background
        });
        rail.append(cursor);
        rail.visibility = true;
        self.rail = rail;
        self.rail.drag = false;
        var zoom = false;
        if (self.opt.boxzoom && !self.ispage && !self.isieold) {
          zoom = document.createElement("div");
          self.bind(zoom, "click", self.doZoom);
          self.zoom = $(zoom);
          self.zoom.css({
            cursor : "pointer",
            "z-index" : self.opt.zindex,
            backgroundImage : "url(" + scriptpath + "zoomico.png)",
            height : 18,
            width : 18,
            backgroundPosition : "0px 0px"
          });
          if (self.opt.dblclickzoom) {
            self.bind(self.win, "dblclick", self.doZoom);
          }
          if (self.cantouch && self.opt.gesturezoom) {
            self.ongesturezoom = function(e) {
              if (e.scale > 1.5) {
                self.doZoomIn(e);
              }
              if (e.scale < 0.8) {
                self.doZoomOut(e);
              }
              return self.cancelEvent(e);
            };
            self.bind(self.win, "gestureend", self.ongesturezoom);
          }
        }
        self.css(cont, {
          "overflow-x" : "hidden"
        });
        var cursor = $(document.createElement("div"));
        cursor.css({
          position : "relative",
          top : 0,
          height : self.opt.cursorwidth,
          width : "0px",
          "background-color" : self.opt.cursorcolor,
          border : self.opt.cursorborder,
          "background-clip" : "padding-box",
          "-webkit-border-radius" : self.opt.cursorborderradius,
          "-moz-border-radius" : self.opt.cursorborderradius,
          "border-radius" : self.opt.cursorborderradius
        });
        cursor.wborder = parseFloat(cursor.outerWidth() - cursor.innerWidth());
        self.cursorh = cursor;
        var railh = $(document.createElement("div"));
        railh.attr("id", self.id + "-h");
        railh.height = 1 + Math.max(parseFloat(self.opt.cursorwidth), cursor.outerHeight());
        railh.css({
          height : railh.height + "px",
          zIndex : (self.ispage) ? self.opt.zindex : self.opt.zindex + 2,
          background : self.opt.background
        });
        railh.append(cursor);
        railh.visibility = true;
        self.railh = railh;
        self.railh.drag = false;
        if (self.ispage) {
          rail.css({
            position : "fixed",
            top : "0px",
            right : "0px",
            height : "100%"
          });
          self.body.append(rail);
          if (self.railh) {
            railh.css({
              position : "fixed",
              bottom : "0px",
              left : "0px",
              width : "100%"
            });
            self.body.append(railh);
          }
        } else {
          if (self.ishwscroll) {
            if (self.win.css("position") == "static") {
              self.css(self.win, {
                position : "relative"
              });
            }
            var bd = (self.win[0].nodeName == "HTML") ? self.body : self.win;
            if (self.zoom) {
              self.zoom.css({
                position : "absolute",
                top : 1,
                right : 0,
                "margin-right" : rail.width + 4
              });
              bd.append(self.zoom);
            }
            rail.css({
              position : "absolute",
              top : 0,
              right : 0
            });
            bd.append(rail);
          } else {
            rail.css({
              position : "absolute"
            });
            if (self.zoom) {
              self.zoom.css({
                position : "absolute"
              });
            }
            self.updateScrollBar();
            self.body.append(rail);
            if (self.zoom) {
              self.body.append(self.zoom);
            }
            if (self.railh) {
              railh.css({
                position : "absolute"
              });
              self.body.append(railh);
            }
          }
        }
        if (self.opt.autohidemode === false) {
          self.autohidedom = false;
        } else {
          if (self.opt.autohidemode === true) {
            self.autohidedom = self.rail;
          } else {
            if (self.opt.autohidemode == "cursor") {
              self.autohidedom = self.cursor;
            }
          }
        }
        if (self.cantouch || self.opt.touchbehavior) {
          self.scrollmom = {
            y : new ScrollMomentumClass(self),
            x : (self.railh) ? new ScrollMomentumClass(self, true) : false
          };
          self.onmousedown = function(e) {
            if (!self.locked) {
              self.cancelScroll();
              self.rail.drag = {
                x : e.screenX,
                y : e.screenY,
                sx : self.scroll.x,
                sy : self.scroll.y,
                st : self.getScrollTop(),
                sl : self.getScrollLeft()
              };
              self.hasmoving = false;
              self.scrollmom.y.reset(e.screenY);
              if (!self.cantouch) {
                return self.cancelEvent(e);
              }
            }
          };
          self.onmouseup = function(e) {
            if (self.rail.drag) {
              self.scrollmom.y.doMomentum();
              if (self.scrollmom.x) {
                self.scrollmom.x.doMomentum();
              }
              self.rail.drag = false;
              if (self.hasmoving) {
                self.hideCursor();
                return self.cancelEvent(e);
              }
            }
          };
          self.onclick = function(e) {
            if (self.hasmoving) {
              return self.cancelEvent(e);
            }
          };
          self.onmousemove = function(e) {
            if (self.rail.drag) {
              self.hasmoving = true;
              var my = (e.screenY - self.rail.drag.y);
              var fy = e.screenY;
              var ny = self.rail.drag.st - my;
              if (self.ishwscroll) {
                if (ny < 0) {
                  ny = Math.round(ny / 2);
                  fy = 0;
                } else {
                  if (ny > self.page.maxh) {
                    ny = self.page.maxh + Math.round((ny - self.page.maxh) / 2);
                    fy = 0;
                  }
                }
              } else {
                if (ny < 0) {
                  ny = 0;
                }
                if (ny > self.page.maxh) {
                  ny = self.page.maxh;
                }
              }
              var nx = false;
              if (self.railh) {
                var mx = (e.screenX - self.rail.drag.x);
                var fx = e.screenX;
                nx = self.rail.drag.sl - mx;
                if (self.ishwscroll) {
                  if (nx < 0) {
                    nx = Math.round(nx / 2);
                    fx = 0;
                  } else {
                    if (nx > self.page.maxw) {
                      nx = self.page.maxw + Math.round((nx - self.page.maxw) / 2);
                      fx = 0;
                    }
                  }
                } else {
                  if (nx < 0) {
                    nx = 0;
                  }
                  if (nx > self.page.maxw) {
                    nx = self.page.maxw;
                  }
                }
                self.scroll.x = Math.round(nx * 1 / self.scrollratio.x);
              }
              self.showCursor(ny);
              if (self.prepareTransition) {
                self.prepareTransition(0);
              }
              self.setScrollTop(ny);
              self.scrollmom.y.update(fy);
              if (nx !== false) {
                self.setScrollLeft(nx);
                self.scrollmom.x.update(fx);
              }
              return self.cancelEvent(e);
            }
          };
          if (self.cursorgrabvalue) {
            self.css((self.ispage) ? self.doc : self.win, {
              cursor : self.cursorgrabvalue
            });
            self.css(self.rail, {
              cursor : self.cursorgrabvalue
            });
          }
        } else {
          self.onmousedown = function(e) {
            if (self.locked) {
              return self.cancelEvent(e);
            }
            self.cancelScroll();
            self.rail.drag = {
              x : e.screenX,
              y : e.screenY,
              sx : self.scroll.x,
              sy : self.scroll.y
            };
            return self.cancelEvent(e);
          };
          self.onmouseup = function(e) {
            if (self.rail.drag) {
              self.rail.drag = false;
              return self.cancelEvent(e);
            }
          };
          self.onmousemove = function(e) {
            if (self.rail.drag) {
              var py = false;
              if (!self.rail.drag.locked || self.rail.drag.locked == "v") {
                self.scroll.y = self.rail.drag.sy + (e.screenY - self.rail.drag.y);
                if (self.scroll.y < 0) {
                  self.scroll.y = 0;
                }
                var my = self.scrollvaluemax;
                if (self.scroll.y > my) {
                  self.scroll.y = my;
                }
                py = Math.round(self.scroll.y * self.scrollratio.y);
              }
              var px = false;
              if (self.cursorh) {
                if (!self.rail.drag.locked || self.rail.drag.locked == "h") {
                  self.scroll.x = self.rail.drag.sx + (e.screenX - self.rail.drag.x);
                  if (self.scroll.x < 0) {
                    self.scroll.x = 0;
                  }
                  var mx = self.scrollvaluemaxw;
                  if (self.scroll.x > mx) {
                    self.scroll.x = mx;
                  }
                  var px = Math.round(self.scroll.x * self.scrollratio.x);
                }
              }
              self.showCursor();
              self.cursorfreezed = true;
              if (py !== false) {
                self.doScroll(py);
              }
              if (px !== false) {
                self.doScrollLeft(px);
              }
              return self.cancelEvent(e);
            } else {
              self.checkarea = true;
            }
          };
        }
        if (self.cantouch || self.opt.touchbehavior) {
          self.bind(self.win, "mousedown", self.onmousedown);
        }
        self.bind(self.win, "mouseup", self.onmouseup);
        self.bind(self.cursor, "mousedown", function(e) {
          self.onmousedown(e);
          self.rail.drag.locked = "v";
        });
        self.bind(self.cursor, "mouseup", function(e) {
          self.rail.drag = false;
          self.hasmoving = false;
          self.hideCursor();
          return self.cancelEvent(e);
        });
        if (self.cursorh) {
          self.bind(self.cursorh, "mousedown", function(e) {
            self.onmousedown(e);
            self.rail.drag.locked = "h";
          });
          self.bind(self.cursorh, "mouseup", function(e) {
            self.rail.drag = false;
            self.hasmoving = false;
            self.hideCursor();
            return self.cancelEvent(e);
          });
        }
        self.bind(document, "mouseup", self.onmouseup);
        self.bind(document, "mousemove", self.onmousemove);
        if (self.onclick) {
          self.bind(document, "click", self.onclick);
        }
        if (!self.cantouch) {
          self.rail.mouseenter(function() {
            self.showCursor();
            self.rail.active = true;
          });
          self.rail.mouseleave(function() {
            self.rail.active = false;
            if (!self.rail.drag) {
              self.hideCursor();
            }
          });
          if (self.railh) {
            self.railh.mouseenter(function() {
              self.showCursor();
              self.railh.active = true;
            });
            self.railh.mouseleave(function() {
              self.railh.active = false;
              if (!self.railh.drag) {
                self.hideCursor();
              }
            });
          }
          if (!self.isiframe) {
            self.bind((self.isie && self.ispage) ? document : self.docscroll, "mousewheel", self.onmousewheel);
          }
          self.bind(self.rail, "mousewheel", self.onmousewheel);
          if (self.railh) {
            self.bind(self.railh, "mousewheel", self.onmousewheelhz);
          }
        }
        if (self.zoom) {
          self.zoom.mouseenter(function() {
            self.showCursor();
            self.rail.active = true;
          });
          self.zoom.mouseleave(function() {
            self.rail.active = false;
            if (!self.rail.drag) {
              self.hideCursor();
            }
          });
        }
        if (!self.ispage && !self.cantouch && !(/HTML|BODY/.test(self.win[0].nodeName))) {
          if (!self.win.attr("tabindex")) {
            self.win.attr({
              tabindex : tabindexcounter++
            });
          }
          self.win.focus(function(e) {
            domfocus = (self.getTarget(e)).id || true;
            self.hasfocus = true;
            self.noticeCursor();
          });
          self.win.blur(function(e) {
            domfocus = false;
            self.hasfocus = false;
          });
          self.win.mouseenter(function(e) {
            mousefocus = (self.getTarget(e)).id || true;
            self.hasmousefocus = true;
            self.noticeCursor();
          });
          self.win.mouseleave(function() {
            mousefocus = false;
            self.hasmousefocus = false;
          });
        }
        self.onkeypress = function(e) {
          if (self.locked && self.page.maxh == 0) {
            return true;
          }
          e = (e) ? e : window.e;
          var tg = self.getTarget(e);
          if (tg && /INPUT|TEXTAREA|SELECT|OPTION/.test(tg.nodeName)) {
            var tp = tg.getAttribute("type") || tg.type || false;
            if ((!tp) || !(/submit|button|cancel/i.tp)) {
              return true;
            }
          }
          if (self.hasfocus || (self.hasmousefocus && !domfocus) || (self.ispage && !domfocus && !mousefocus)) {
            var key = e.keyCode;
            var ctrl = e.ctrlKey || false;
            if (self.locked && key != 27) {
              return self.cancelEvent(e);
            }
            var ret = false;
            switch(key) {
              case 38:
              case 63233:
                (ctrl) ? self.doScroll(0) : self.doScrollBy(24 * 3);
                ret = true;
                break;
              case 40:
              case 63235:
                (ctrl) ? self.doScroll(self.page.maxh) : self.doScrollBy(-24 * 3);
                ret = true;
                break;
              case 37:
              case 63232:
                if (self.railh) {
                  (ctrl) ? self.doScrollLeft(0) : self.doScrollLeftBy(24 * 3);
                  ret = true;
                }
                break;
              case 39:
              case 63234:
                if (self.railh) {
                  (ctrl) ? self.doScrollLeft(self.page.maxw) : self.doScrollLeftBy(-24 * 3);
                  ret = true;
                }
                break;
              case 33:
              case 63276:
                self.doScrollBy(self.view.h);
                ret = true;
                break;
              case 34:
              case 63277:
                self.doScrollBy(-self.view.h);
                ret = true;
                break;
              case 36:
              case 63273:
                self.doScrollTo(0);
                if (self.railh && ctrl) {
                  self.doScrollLeft(0);
                }
                ret = true;
                break;
              case 35:
              case 63275:
                self.doScrollTo(self.page.maxh);
                if (self.railh && ctrl) {
                  self.doScrollLeft(self.page.maxw);
                }
                ret = true;
                break;
              case 32:
                if (self.opt.spacebarenabled) {
                  self.doScrollBy(-self.view.h);
                  ret = true;
                }
                break;
              case 27:
                if (self.zoomactive) {
                  self.doZoom();
                  ret = true;
                }
                break;
            }
            if (ret) {
              return self.cancelEvent(e);
            }
          }
        };
        self.bind(document, (self.isopera) ? "keypress" : "keydown", self.onkeypress);
        self.bind(window, "resize", self.resize);
        self.bind(window, "orientationchange", self.resize);
        self.bind(window, "load", self.resize);
        if (!self.ispage && self.opt.boxzoom) {
          self.bind(window, "resize", self.resizeZoom);
        }
        if (self.istextarea) {
          self.bind(self.win, "mouseup", self.resize);
        }
        self.resize();
      }
      if (this.doc[0].nodeName == "IFRAME") {
        function oniframeload(e) {
          self.iframexd = false;
          try {
            var doc = "contentDocument" in this ? this.contentDocument : this.contentWindow.document;
            var a = doc.domain;
          } catch(e) {
            self.iframexd = true;
            doc = false;
          }
          if (self.iframexd) {
            return true;
          }
          if (self.isiframe) {
            self.iframe = {
              html : self.doc.contents().find("html")[0],
              body : self.doc.contents().find("body")[0]
            };
            self.docscroll = $(this.contentWindow);
          }
          if (self.opt.iframeautoresize && !self.isiframe) {
            self.win.scrollTop(0);
            self.doc.height("");
            var hh = Math.max(doc.getElementsByTagName("html")[0].scrollHeight, doc.body.scrollHeight);
            self.doc.height(hh);
          }
          self.onResize();
          if (self.isie7) {
            self.css($(doc).find("html"), {
              "overflow-y" : "hidden"
            });
          }
          self.css($(doc.body), {
            "overflow-y" : "hidden"
          });
          if ("contentWindow" in this) {
            self.bind(this.contentWindow, "scroll", self.onscroll);
          } else {
            self.bind(doc, "scroll", self.onscroll);
          }
          self.bind(doc, "mouseup", self.onmouseup);
          self.bind(doc, "mousewheel", self.onmousewheel);
          if (self.railh) {
            self.bind(self.railh, "mousewheel", self.onmousewheelhz);
          }
          self.bind(doc, (self.isopera) ? "keypress" : "keydown", self.onkeypress);
          if (self.cantouch || self.opt.touchbehavior) {
            self.bind(doc, "mousedown", self.onmousedown);
            if (self.cursorgrabvalue) {
              self.css($(doc.body), {
                cursor : self.cursorgrabvalue
              });
            }
          }
          self.bind(doc, "mousemove", self.onmousemove);
          if (self.zoom) {
            if (self.opt.dblclickzoom) {
              self.bind(doc, "dblclick", self.doZoom);
            }
            if (self.ongesturezoom) {
              self.bind(doc, "gestureend", self.ongesturezoom);
            }
          }
        }

        if (this.doc[0].readyState && this.doc[0].readyState == "complete") {
          setTimeout(function() {
            oniframeload.call(self.doc[0], false);
          }, 500);
        }
        self.bind(this.doc, "load", oniframeload);
      }
    };
    this.showCursor = function(py) {
      if (self.cursortimeout) {
        clearTimeout(self.cursortimeout);
        self.cursortimeout = 0;
      }
      if (!self.rail) {
        return;
      }
      if (self.autohidedom) {
        self.autohidedom.stop().css({
          opacity : self.opt.cursoropacitymax
        });
        if (self.railh) {
          self.railh.stop().css({
            opacity : self.opt.cursoropacitymax
          });
        }
      }
      if ( typeof py != "undefined") {
        self.scroll.y = Math.round(py * 1 / self.scrollratio.y);
      }
      self.cursor.css({
        height : self.cursorheight,
        top : self.scroll.y
      });
      if (self.zoom) {
        self.zoom.stop().css({
          opacity : self.opt.cursoropacitymax
        });
      }
      if (self.cursorh) {
        self.cursorh.css({
          width : self.cursorwidth,
          left : self.scroll.x
        });
      }
    };
    this.hideCursor = function(tm) {
      if (self.cursortimeout) {
        return;
      }
      if (!self.rail) {
        return;
      }
      if (!self.autohidedom) {
        return;
      }
      self.cursortimeout = setTimeout(function() {
        if (!self.rail.active) {
          self.autohidedom.stop().animate({
            opacity : self.opt.cursoropacitymin
          });
          if (self.zoom) {
            self.zoom.stop().animate({
              opacity : self.opt.cursoropacitymin
            });
          }
          if (self.railh) {
            self.railh.stop().animate({
              opacity : self.opt.cursoropacitymin
            });
          }
        }
        self.cursortimeout = 0;
      }, tm || 400);
    };
    this.noticeCursor = function(tm, py) {
      self.showCursor(py);
      self.hideCursor(tm);
    };
    this.getContentSize = function() {
      var pg = (self.ispage) ? {
        w : Math.max(document.body.scrollWidth, document.documentElement.scrollWidth),
        h : Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
      } : (self.haswrapper) ? {
        w : self.doc.outerWidth() + parseInt(self.win.css("paddingLeft")) + parseInt(self.win.css("paddingRight")),
        h : self.doc.outerHeight() + parseInt(self.win.css("paddingTop")) + parseInt(self.win.css("paddingBottom"))
      } : (self.iframe) ? {
        w : Math.max(self.iframe.html.scrollWidth, self.iframe.body.scrollWidth),
        h : Math.max(self.iframe.html.scrollHeight, self.iframe.body.scrollHeight)
      } : {
        w : self.docscroll[0].scrollWidth,
        h : self.docscroll[0].scrollHeight
      };
      return pg;
    };
    this.onResize = function(e, page) {
      if (!self.haswrapper && !self.ispage) {
        var vis = (self.win.css("display") != "none");
        if (vis && !self.visibility) {
          self.show();
        }
        if (!vis && self.visibility) {
          self.hide();
        }
        if (!self.visibility) {
          return false;
        }
      }
      var premaxh = self.page.maxh;
      var premaxw = self.page.maxw;
      var preview = {
        h : self.view.h,
        w : self.view.w
      };
      self.view = {
        w : (self.ispage) ? self.win.width() : self.win.innerWidth(),
        h : (self.ispage) ? self.win.height() : self.win.innerHeight()
      };
      self.page = (page) ? page : self.getContentSize();
      self.page.maxh = Math.max(0, self.page.h - self.view.h);
      self.page.maxw = Math.max(0, self.page.w - self.view.w);
      if ((self.page.maxh == premaxh) && (self.page.maxw == premaxw) && (self.view.w == preview.w)) {
        return self;
      }
      if ((!self.rail.visibility) && (self.page.maxh >= 0)) {
        self.show(self.rail);
      }
      if ((self.railh) && (!self.railh.visibility) && (self.page.maxw >= 0)) {
        self.show(self.railh);
      }
      if (self.page.maxh == 0) {
        self.hide(self.rail);
        self.scrollvaluemax = 0;
        self.scroll.y = 0;
        self.scrollratio.y = 0;
        self.cursorheight = 0;
        self.setScrollTop(0);
      }
      if (self.page.maxw == 0) {
        self.hide(self.railh);
        self.scrollvaluemaxw = 0;
        self.scroll.x = 0;
        self.scrollratio.x = 0;
        self.cursorwidth = 0;
        self.setScrollLeft(0);
      }
      if ((self.page.maxh == 0) && (self.page.maxw == 0)) {
        self.hide();
        self.locked = true;
        return false;
      }
      self.locked = false;
      if (self.istextarea && self.win.css("resize") && self.win.css("resize") != "none") {
        self.view.h -= 20;
      }
      if (!self.ispage) {
        self.updateScrollBar(self.view);
      }
      self.cursorheight = Math.min(self.view.h, Math.round(self.view.h * (self.view.h / self.page.h)));
      self.cursorheight = Math.max(self.opt.cursorminheight, self.cursorheight);
      self.cursorwidth = Math.min(self.view.w, Math.round(self.view.w * (self.view.w / self.page.w)));
      self.cursorwidth = Math.max(self.opt.cursorminheight, self.cursorwidth);
      self.scrollvaluemax = self.view.h - self.cursorheight - self.cursor.hborder;
      self.railh.width = (self.page.maxh > 0) ? (self.view.w - self.rail.width) : self.view.w;
      self.scrollvaluemaxw = self.railh.width - self.cursorwidth - self.cursorh.wborder;
      self.scrollratio = {
        x : (self.page.maxw / self.scrollvaluemaxw),
        y : (self.page.maxh / self.scrollvaluemax)
      };
      var sy = self.getScrollTop();
      if (sy > self.page.maxh) {
        self.doScroll(self.page.maxh);
      } else {
        self.scroll.y = Math.round(self.getScrollTop() * (1 / self.scrollratio.y));
        self.scroll.x = Math.round(self.getScrollLeft() * (1 / self.scrollratio.x));
        self.noticeCursor();
      }
      return self;
    };
    this.resize = this.onResize;
    this._bind = function(el, name, fn, bubble) {
      self.events.push({
        e : el,
        n : name,
        f : fn
      });
      if (el.addEventListener) {
        el.addEventListener(name, fn, bubble || false);
      } else {
        if (el.attachEvent) {
          el.attachEvent("on" + name, fn);
        } else {
          el["on" + name] = fn;
        }
      }
    };
    this.bind = function(dom, name, fn, bubble) {
      var el = ("jquery" in dom) ? dom[0] : dom;
      if (el.addEventListener) {
        if (self.cantouch && /mouseup|mousedown|mousemove/.test(name)) {
          var tt = (name == "mousedown") ? "touchstart" : (name == "mouseup") ? "touchend" : "touchmove";
          self._bind(el, tt, function(e) {
            if (e.touches.length < 2) {
              var ev = (e.touches.length > 0) ? e.touches[0] : e;
              ev.original = e;
              fn.call(this, ev);
            }
          }, bubble || false);
        }
        self._bind(el, name, fn, bubble || false);
        if (name == "mousewheel") {
          self._bind(el, "DOMMouseScroll", fn, bubble || false);
        }
        if (self.cantouch && name == "mouseup") {
          self._bind(el, "touchcancel", fn, bubble || false);
        }
      } else {
        self._bind(el, name, function(e) {
          e = e || window.event || false;
          if (e) {
            if (e.srcElement) {
              e.target = e.srcElement;
            }
          }
          return ((fn.call(el, e) === false) || bubble === false) ? self.cancelEvent(e) : true;
        });
      }
    };
    this._unbind = function(el, name, fn) {
      if (el.removeEventListener) {
        el.removeEventListener(name, fn, false);
      } else {
        if (el.detachEvent) {
          el.detachEvent("on" + name, fn);
        } else {
          el["on" + name] = false;
        }
      }
    };
    this.unbindAll = function() {
      for (var a = 0; a < self.events.length; a++) {
        var r = self.events[a];
        self._unbind(r.e, r.n, r.f);
      }
    };
    this.cancelEvent = function(e) {
      if (self.cantouch) {
        e = e.original ? e.original : e || false;
      } else {
        e = e ? e : window.event || false;
      }
      if (!e) {
        return false;
      }
      if (e.stopPropagation) {
        e.stopPropagation();
      }
      if (e.preventDefault) {
        e.preventDefault();
      }
      e.cancelBubble = true;
      e.cancel = true;
      e.returnValue = false;
      return false;
    };
    this.show = function() {
      if (self.page.maxh != 0) {
        self.rail.visibility = true;
        self.rail.css("display", "block");
      }
      if (self.page.maxw != 0) {
        self.railh.visibility = true;
        self.railh.css("display", "block");
      }
      self.visibility = (self.rail.visibility || self.railh.visibility);
      return self;
    };
    this.hide = function(rr) {
      rr = (rr) ? rr : self.rail;
      rr.visibility = false;
      rr.css("display", "none");
      self.visibility = (self.rail.visibility || self.railh.visibility);
      return self;
    };
    this.remove = function() {
      self.doZoomOut();
      self.unbindAll();
      self.events = [];
      self.rail.remove();
      if (self.zoom) {
        self.zoom.remove();
      }
      self.cursor = false;
      self.rail = false;
      self.zoom = false;
      for (var a = 0; a < self.saved.css.length; a++) {
        var d = self.saved.css[a];
        d[0].css(d[1], ( typeof d[2] == "undefined") ? "" : d[2]);
      }
      self.saved = false;
      self.me.data("__nicescroll", "");
      return self;
    };
    this.isScrollable = function(e) {
      var dom = (e.target) ? e.target : e;
      while (dom && dom.nodeName && !(/BODY|HTML/.test(dom.nodeName))) {
        var dd = $(dom);
        var ov = dd.css("overflowY") || dd.css("overflowX") || dd.css("overflow") || "";
        if (/scroll|auto/.test(ov)) {
          return (dom.clientHeight != dom.scrollHeight);
        }
        dom = (dom.parentNode) ? dom.parentNode : false;
      }
      return false;
    };
    this.onmousewheel = function(e) {
      if (self.locked && self.page.maxh == 0) {
        return true;
      }
      if (self.opt.preservenativescrolling && self.checkarea) {
        self.checkarea = false;
        self.nativescrollingarea = self.isScrollable(e);
      }
      if (self.nativescrollingarea) {
        return true;
      }
      if (self.locked) {
        return self.cancelEvent(e);
      }
      if (self.rail.drag) {
        return self.cancelEvent(e);
      }
      var delta = 0;
      var delta = e.detail ? e.detail * -1 : e.wheelDelta / 40;
      if (delta) {
        if (self.scrollmom) {
          self.scrollmom.y.stop();
        }
        self.doScrollBy(delta * self.opt.mousescrollstep);
      }
      return self.cancelEvent(e);
    };
    this.onmousewheelhz = function(e) {
      if (self.locked && self.page.maxw == 0) {
        return true;
      }
      if (self.opt.preservenativescrolling && self.checkarea) {
        self.checkarea = false;
        self.nativescrollingarea = self.isScrollable(e);
      }
      if (self.nativescrollingarea) {
        return true;
      }
      if (self.locked) {
        return self.cancelEvent(e);
      }
      if (self.rail.drag) {
        return self.cancelEvent(e);
      }
      var delta = 0;
      var delta = e.detail ? e.detail * -1 : e.wheelDelta / 40;
      if (delta) {
        if (self.scrollmom) {
          self.scrollmom.x.stop();
        }
        self.doScrollLeftBy(delta * self.opt.mousescrollstep);
      }
      return self.cancelEvent(e);
    };
    this.stop = function() {
      self.cancelScroll();
      if (self.scrollmon) {
        self.scrollmon.stop();
      }
      self.cursorfreezed = false;
      self.scroll.y = Math.round(self.getScrollTop() * (1 / self.scrollratio.y));
      self.noticeCursor();
      return self;
    };
    if (self.ishwscroll && self.hastransition && self.opt.usetransition) {
      this.prepareTransition = function(dif, trend) {
        var sp = Math.round(self.opt.scrollspeed * 10);
        var ex = Math.min(sp, Math.round((dif / 20) * self.opt.scrollspeed));
        var trans = (ex > 20) ? self.prefixstyle + "transform " + ex + "ms ease-out 0s" : "";
        if (!self.lasttransitionstyle || self.lasttransitionstyle != trans) {
          self.lasttransitionstyle = trans;
          self.doc.css(self.transitionstyle, trans);
        }
        return ex;
      };
      this.doScroll = function(y, spd) {
        var sy = self.getScrollTop();
        if (y < 0 && sy <= 0) {
          return self.noticeCursor();
        } else {
          if (y > self.page.maxh && sy >= self.page.maxh) {
            self.checkContentSize();
            return self.noticeCursor();
          }
        }
        self.newscrolly = y;
        self.newscrollspeed = spd || false;
        if (self.timer) {
          return false;
        }
        if (!self.scrollendtrapped) {
          self.scrollendtrapped = true;
          self.bind(self.doc, self.transitionend, self.onScrollEnd, false);
        }
        self.timer = setTimeout(function() {
          var top = self.getScrollTop();
          var dif = (self.newscrollspeed) ? self.newscrollspeed : Math.abs(top - self.newscrolly);
          var ms = self.prepareTransition(dif);
          self.timer = setTimeout(function() {
            if (self.newscrolly < 0 && !self.opt.bouncescroll) {
              self.newscrolly = 0;
            } else {
              if (self.newscrolly > self.page.maxh && !self.opt.bouncescroll) {
                self.newscrolly = self.page.maxh;
              }
            }
            if (self.newscrolly == self.getScrollTop()) {
              self.timer = 0;
              self.onScrollEnd();
            } else {
              var py = self.getScrollTop();
              if (self.timerscroll && self.timerscroll.tm) {
                clearInterval(self.timerscroll.tm);
              }
              if (ms > 0) {
                self.timerscroll = {
                  ts : (new Date()).getTime(),
                  s : self.getScrollTop(),
                  e : self.newscrolly,
                  sp : ms,
                  bz : new BezierClass(py, self.newscrolly, ms, 0, 1, 0, 1)
                };
                if (!self.cursorfreezed) {
                  self.timerscroll.tm = setInterval(function() {
                    self.showCursor(self.getScrollTop());
                  }, 60);
                }
              }
              self.setScrollTop(self.newscrolly);
              self.timer = 0;
            }
          }, 15);
        }, self.opt.scrollspeed);
      };
      this.cancelScroll = function() {
        if (!self.scrollendtrapped) {
          return true;
        }
        var py = self.getScrollTop();
        self.scrollendtrapped = false;
        self._unbind(self.doc, self.transitionend, self.onScrollEnd);
        self.prepareTransition(0);
        self.setScrollTop(py);
        if (self.timerscroll && self.timerscroll.tm) {
          clearInterval(self.timerscroll.tm);
        }
        self.timerscroll = false;
        self.cursorfreezed = false;
        self.noticeCursor(false, py);
        return self;
      };
      this.onScrollEnd = function() {
        self.scrollendtrapped = false;
        self._unbind(self.doc, self.transitionend, self.onScrollEnd);
        if (self.timerscroll && self.timerscroll.tm) {
          clearInterval(self.timerscroll.tm);
        }
        self.timerscroll = false;
        self.cursorfreezed = false;
        var py = self.getScrollTop();
        self.setScrollTop(py);
        self.noticeCursor(false, py);
        if (py < 0) {
          self.doScroll(0, 60);
        } else {
          if (py > self.page.maxh) {
            self.doScroll(self.page.maxh, 60);
          }
        }
      };
    } else {
      this.doScroll = function(y) {
        var py = self.getScrollTop();
        self.newscrolly = y;
        if (!self.bouncescroll) {
          if (self.newscrolly < 0) {
            if (self.newspeedy) {
              self.newspeedy.x = 0;
            }
            self.newscrolly = 0;
          } else {
            if (self.newscrolly > self.page.maxh) {
              if (self.newspeedy) {
                self.newspeedy.x = self.page.maxh;
              }
              self.newscrolly = self.page.maxh;
            }
          }
        }
        var mg = Math.floor(Math.abs(y - py) / 40);
        if (mg > 0) {
          var ms = Math.min(10, mg) * 100;
          self.bzscroll = (self.bzscroll) ? self.bzscroll.update(y, ms) : new BezierClass(py, y, ms, 0, 1, 0, 1);
        } else {
          self.bzscroll = false;
        }
        if (self.timer) {
          return;
        }
        if (py == self.page.maxh && y >= self.page.maxh) {
          self.checkContentSize();
        }
        var sync = 1;
        function scrolling() {
          if (self.cancelAnimationFrame) {
            return true;
          }
          sync = 1 - sync;
          if (sync) {
            return (self.timer = setAnimationFrame(scrolling) || 1);
          }
          var sy = self.getScrollTop();
          var sc = (self.bzscroll) ? self.bzscroll.getNow() : self.newscrolly;
          var dr = sc - sy;
          if ((dr < 0 && sc < self.newscrolly) || (dr > 0 && sc > self.newscrolly)) {
            sc = self.newscrolly;
          }
          self.setScrollTop(sc);
          if (sc == self.newscrolly) {
            self.timer = 0;
            self.cursorfreezed = false;
            self.bzscroll = false;
            if (sc < 0) {
              self.doScroll(0);
            } else {
              if (sc > self.page.maxh) {
                self.doScroll(self.page.maxh);
              }
            }
          } else {
            self.timer = setAnimationFrame(scrolling) || 1;
          }
        }
        self.cancelAnimationFrame = false;
        self.timer = 1;
        scrolling();
        if (py == self.page.maxh && y >= py) {
          self.checkContentSize();
        }
        self.noticeCursor();
      };
      this.doScrollLeft = function(x) {
        var px = self.getScrollLeft();
        self.newscrollx = x;
        if (!self.bouncescroll) {
          if (self.newscrollx < 0) {
            if (self.newspeedy) {
              self.newspeedy.x = 0;
            }
            self.newscrollx = 0;
          } else {
            if (self.newscrollx > self.page.maxw) {
              if (self.newspeedy) {
                self.newspeedy.x = self.page.maxw;
              }
              self.newscrollx = self.page.maxw;
            }
          }
        }
        var mg = Math.floor(Math.abs(x - px) / 40);
        if (mg > 0) {
          var ms = Math.min(10, mg) * 100;
          self.bzscrollx = (self.bzscrollx) ? self.bzscrollx.update(x, ms) : new BezierClass(px, x, ms, 0, 1, 0, 1);
        } else {
          self.bzscrollx = false;
        }
        if (self.timerx) {
          return;
        }
        if (px == self.page.maxw && x >= self.page.maxw) {
          self.checkContentSize();
        }
        var sync = 1;
        function scrolling() {
          if (self.cancelAnimationFrameX) {
            return true;
          }
          sync = 1 - sync;
          if (sync) {
            return (self.timerx = setAnimationFrame(scrolling) || 1);
          }
          var sx = self.getScrollLeft();
          var sc = (self.bzscrollx) ? self.bzscrollx.getNow() : self.newscrollx;
          var dr = sc - sx;
          if ((dr < 0 && sc < self.newscrollx) || (dr > 0 && sc > self.newscrollx)) {
            sc = self.newscrollx;
          }
          self.setScrollLeft(sc);
          if (sc == self.newscrollx) {
            self.timerx = 0;
            self.cursorfreezed = false;
            self.bzscrollx = false;
            if (sc < 0) {
              self.doScrollLeft(0);
            } else {
              if (sc > self.page.maxw) {
                self.doScrollLeft(self.page.maxw);
              }
            }
          } else {
            self.timerx = setAnimationFrame(scrolling) || 1;
          }
        }
        self.cancelAnimationFrameX = false;
        self.timerx = 1;
        scrolling();
        if (px == self.page.maxw && x >= px) {
          self.checkContentSize();
        }
        self.noticeCursor();
      };
      this.cancelScroll = function() {
        if (self.timerx) {
          clearAnimationFrame(self.timerx);
        }
        self.timerx = 0;
        self.bzscrollx = false;
        return self;
      };
    }
    this.doScrollBy = function(stp, relative) {
      var ny = 0;
      if (relative) {
        ny = Math.floor((self.scroll.y - stp) * self.scrollratio.y);
      } else {
        var sy = (self.timer) ? self.newscrolly : self.getScrollTop(true);
        ny = sy - stp;
      }
      if (self.bouncescroll) {
        var haf = Math.round(self.view.h / 2);
        if (ny < -haf) {
          ny = -haf;
        } else {
          if (ny > (self.page.maxh + haf)) {
            ny = (self.page.maxh + haf);
          }
        }
      }
      self.cursorfreezed = false;
      self.doScroll(ny);
    };
    this.doScrollLeftBy = function(stp, relative) {
      var ny = 0;
      if (relative) {
        nx = Math.floor((self.scroll.x - stp) * self.scrollratio.x);
      } else {
        var sx = (self.timer) ? self.newscrollx : self.getScrollLeft(true);
        nx = sx - stp;
      }
      if (self.bouncescroll) {
        var haf = Math.round(self.view.w / 2);
        if (nx < -haf) {
          nx = -haf;
        } else {
          if (nx > (self.page.maxw + haf)) {
            nx = (self.page.maxw + haf);
          }
        }
      }
      self.cursorfreezed = false;
      self.doScrollLeft(nx);
    };
    this.doScrollTo = function(pos, relative) {
      var ny = (relative) ? Math.round(pos * self.scrollratio.y) : pos;
      if (ny < 0) {
        ny = 0;
      } else {
        if (ny > self.page.maxh) {
          ny = self.page.maxh;
        }
      }
      self.cursorfreezed = false;
      self.doScroll(pos);
    };
    this.checkContentSize = function() {
      var pg = self.getContentSize();
      if (pg.h != self.page.h) {
        self.resize(false, pg);
      }
    };
    self.onscroll = function(e) {
      if (self.rail.drag) {
        return;
      }
      if (!self.cursorfreezed) {
        self.delayed("onscroll", function() {
          self.scroll.y = Math.round(self.getScrollTop() * (1 / self.scrollratio.y));
          if (self.railh) {
            self.scroll.x = Math.round(self.getScrollLeft() * (1 / self.scrollratio.x));
          }
          self.noticeCursor();
        }, 30);
      }
    };
    self.bind(self.docscroll, "scroll", self.onscroll);
    this.doZoomIn = function(e) {
      if (self.zoomactive) {
        return;
      }
      self.zoomactive = true;
      self.zoomrestore = {
        style : {}
      };
      var lst = ["position", "top", "left", "zIndex", "backgroundColor", "marginTop", "marginBottom", "marginLeft", "marginRight"];
      var win = self.win[0].style;
      for (var a in lst) {
        var pp = lst[a];
        self.zoomrestore.style[pp] = ( typeof win[pp] != "undefined") ? win[pp] : "";
      }
      self.zoomrestore.style.width = self.win.css("width");
      self.zoomrestore.style.height = self.win.css("height");
      self.zoomrestore.padding = {
        w : self.win.outerWidth() - self.win.width(),
        h : self.win.outerHeight() - self.win.height()
      };
      if (self.isios4) {
        self.zoomrestore.scrollTop = $(window).scrollTop();
        $(window).scrollTop(0);
      }
      self.win.css({
        position : (self.isios4) ? "absolute" : "fixed",
        top : 0,
        left : 0,
        "z-index" : self.opt.zindex + 100,
        margin : "0px"
      });
      var bkg = self.win.css("backgroundColor");
      if (bkg == "" || /transparent|rgba\(0, 0, 0, 0\)|rgba\(0,0,0,0\)/.test(bkg)) {
        self.win.css("backgroundColor", "#fff");
      }
      self.rail.css({
        "z-index" : self.opt.zindex + 110
      });
      self.zoom.css({
        "z-index" : self.opt.zindex + 112
      });
      self.zoom.css("backgroundPosition", "0px -18px");
      self.resizeZoom();
      return self.cancelEvent(e);
    };
    this.doZoomOut = function(e) {
      if (!self.zoomactive) {
        return;
      }
      self.zoomactive = false;
      self.win.css("margin", "");
      self.win.css(self.zoomrestore.style);
      if (self.isios4) {
        $(window).scrollTop(self.zoomrestore.scrollTop);
      }
      self.rail.css({
        "z-index" : (self.ispage) ? self.opt.zindex : self.opt.zindex + 2
      });
      self.zoom.css({
        "z-index" : self.opt.zindex
      });
      self.zoomrestore = false;
      self.zoom.css("backgroundPosition", "0px 0px");
      self.onResize();
      return self.cancelEvent(e);
    };
    this.doZoom = function(e) {
      return (self.zoomactive) ? self.doZoomOut(e) : self.doZoomIn(e);
    };
    this.resizeZoom = function() {
      if (!self.zoomactive) {
        return;
      }
      var py = self.getScrollTop();
      self.win.css({
        width : $(window).width() - self.zoomrestore.padding.w + "px",
        height : $(window).height() - self.zoomrestore.padding.h + "px"
      });
      self.onResize();
      self.setScrollTop(Math.min(self.page.maxh, py));
    };
    this.init();
  };
  var ScrollMomentumClass = function(nc, hz) {
    var self = this;
    this.nc = nc;
    this.hz = hz || false;
    this.lasty = 0;
    this.speedy = 0;
    this.lasttime = 0;
    this.snapy = false;
    this.demuly = 0;
    this.timer = 0;
    this.time = function() {
      return (new Date()).getTime();
    };
    this.reset = function(py) {
      self.stop();
      self.lasttime = self.time();
      self.speedy = 0;
      self.lasty = py;
    };
    this.update = function(py) {
      self.lasttime = self.time();
      var dy = py - self.lasty;
      var sy = (self.hz) ? nc.getScrollLeft() : nc.getScrollTop();
      var newy = sy + dy;
      var mx = (self.hz) ? self.nc.page.maxw : self.nc.page.maxh;
      self.snapy = (newy < 0) || (newy > mx);
      self.speedy = dy;
      self.lasty = py;
    };
    this.stop = function() {
      if (self.timer) {
        clearTimeout(self.timer);
        self.timer = 0;
      }
    };
    if (this.hz) {
      this.doSnapy = function(nx) {
        if (nx < 0) {
          self.nc.doScrollLeft(0, 60);
        } else {
          if (nx > self.nc.page.maxw) {
            self.nc.doScrollLeft(self.nc.page.maxw, 60);
          }
        }
      };
    } else {
      this.doSnapy = function(ny) {
        if (ny < 0) {
          self.nc.doScroll(0, 60);
        } else {
          if (ny > self.nc.page.maxh) {
            self.nc.doScroll(self.nc.page.maxh, 60);
          }
        }
      };
    }
    this.getScroll = (this.hz) ? this.nc.getScrollLeft : this.nc.getScrollTop;
    this.setScroll = (this.hz) ? this.nc.setScrollLeft : this.nc.setScrollTop;
    this.doMomentum = function() {
      var l = self.lasttime;
      var t = self.time();
      self.speedy = Math.min(60, self.speedy);
      var chk = l && (t - l) <= 50;
      var sy = (self.speedy && chk) ? self.speedy : false;
      if (sy) {
        var tm = t - l;
        var pageh = (self.hz) ? self.nc.page.maxw : self.nc.page.maxh;
        self.demuly = 0;
        var onscroll = function() {
          var ny = Math.floor(self.getScroll() - (self.speedy * (1 - self.demuly)));
          if ((ny < 0) || (ny > pageh)) {
            self.demuly += 0.08;
          } else {
            self.demuly += 0.01;
          }
          self.setScroll(ny);
          if (self.hz) {
            self.nc.scroll.x = Math.round(ny * 1 / self.nc.scrollratio.x);
          } else {
            self.nc.scroll.y = Math.round(ny * 1 / self.nc.scrollratio.y);
          }
          self.nc.showCursor();
          if (self.demuly < 1) {
            self.timer = setTimeout(onscroll, tm);
          } else {
            self.timer = 0;
            self.nc.hideCursor();
            self.doSnapy(ny);
          }
        };
        onscroll();
      } else {
        if (self.snapy) {
          self.doSnapy(self.getScroll());
        }
      }
    };
  };
  var _scrollTop = jQuery.fn.scrollTop;
  $.cssHooks.scrollTop = {
    get : function(elem, computed, extra) {
      var nice = $.data(elem, "__nicescroll") || false;
      return (nice && nice.ishwscroll) ? nice.getScrollTop() : _scrollTop.call(elem);
    },
    set : function(elem, value) {
      var nice = $.data(elem, "__nicescroll") || false;
      (nice && nice.ishwscroll) ? nice.setScrollTop(parseInt(value)) : _scrollTop.call(elem, value);
      return this;
    }
  };
  jQuery.fn.scrollTop = function(value) {
    if ( typeof value == "undefined") {
      var nice = (this[0]) ? $.data(this[0], "__nicescroll") || false : false;
      return (nice && nice.ishwscroll) ? nice.getScrollTop() : _scrollTop.call(this);
    } else {
      return this.each(function() {
        var nice = $.data(this, "__nicescroll") || false;
        (nice && nice.ishwscroll) ? nice.setScrollTop(parseInt(value)) : _scrollTop.call($(this), value);
      });
    }
  };
  var NiceScrollArray = function(doms) {
    var self = this;
    this.length = 0;
    this.name = "nicescrollarray";
    this.each = function(fn) {
      for (var a = 0; a < self.length; a++) {
        fn.call(self[a]);
      }
      return self;
    };
    this.push = function(nice) {
      self[self.length] = nice;
      self.length++;
    };
    this.eq = function(idx) {
      return self[idx];
    };
    if (doms) {
      for ( a = 0; a < doms.length; a++) {
        var nice = $.data(doms[a], "__nicescroll") || false;
        if (nice) {
          this[this.length] = nice;
          this.length++;
        }
      }
    }
    return this;
  };
  function mplex(el, lst, fn) {
    for (var a = 0; a < lst.length; a++) {
      fn(el, lst[a]);
    }
  }

  mplex(NiceScrollArray.prototype, ["show", "hide", "onResize", "resize", "remove", "stop"], function(e, n) {
    e[n] = function() {
      return this.each(function() {
        this[n].call();
      });
    };
  });
  jQuery.fn.getNiceScroll = function(index) {
    if ( typeof index == "undefined") {
      return new NiceScrollArray(this);
    } else {
      var nice = $.data(this[index], "__nicescroll") || false;
      return nice;
    }
  };
  jQuery.extend(jQuery.expr[":"], {
    nicescroll : function(a) {
      return ($.data(a, "__nicescroll")) ? true : false;
    }
  });
  $.fn.niceScroll = function(wrapper, opt) {
    if ( typeof opt == "undefined") {
      if (( typeof wrapper == "object") && !("jquery" in wrapper)) {
        opt = wrapper;
        wrapper = false;
      }
    }
    var ret = new NiceScrollArray();
    if ( typeof opt == "undefined") {
      opt = {};
    }
    if (wrapper || false) {
      opt.doc = $(wrapper);
      opt.win = $(this);
    }
    var docundef = !("doc" in opt);
    if (!docundef && !("win" in opt)) {
      opt.win = $(this);
    }
    this.each(function() {
      var nice = $(this).data("__nicescroll") || false;
      if (!nice) {
        opt.doc = (docundef) ? $(this) : opt.doc;
        nice = new NiceScrollClass(opt, $(this));
        $(this).data("__nicescroll", nice);
      }
      ret.push(nice);
    });
    return (ret.length == 1) ? ret[0] : ret;
  };
  window.NiceScroll = {
    getjQuery : function() {
      return jQuery;
    }
  };
})(jQuery);
var DRAG_N_DROP_EJS = '<div class="sc-mainDiv" style="background-color: #<%= color %>;width:<%= width %>px;height:<%= height %>px">\n  <input type="button" id="inputf_<%= id %>" style="width:1px;height:1px;border:0;position:absolute;z-index:-1;"/>\n  <div style="height:<%= labels.length*45+35 %>px">\n    <%\n    var baseTopl=20;\n    var dyl=45;\n    %>\n    <% for(var i =0; i < labels.length ; i++){%>\n    <div class="sc-dnd-dndLeft" style="left:6px;top:<%= (dyl*i+baseTopl)+"px" %>">\n      <div class="sc-dnd-dndInner <%=bigText%>">\n        <div><%= labels[i].left %></div>\n      </div>\n    </div>\n    <div class="sc-dnd-dndTarget" id="dndTarget_<%= id %>_<%= i %>" data-id="<%= i %>" style="left:268px;top:<%= (dyl*i+baseTopl)+"px" %>"></div>\n    <% } %>\n  </div>\n  <div class="sc-labelContainerDiv" style="height:<%= height - labels.length*45 - 75%>px">\n    <%\n    var dx=35;\n    var dy=10;\n    %>\n    <% for(var i =0; i < labels.length ; i++){ %>\n    <%\n    var baseTop=labels.length*45+35;\n    var left=(dx*i+45)+"px";\n    var top=(dy*i+baseTop)+"px";\n    %>\n    <div id="dragndrop_<%= id %>_<%= randArr[i] %>" data-id="<%= randArr[i] %>" class="sc-dnd" style="left:<%= left %>;top:<%= top %>">\n      <div class="sc-dnd-dndInner <%=bigText%>">\n        <div>\n          <%= labels[randArr[i]].right %>\n        </div>\n      </div>\n    </div>\n    <% } %>\n  </div>\n  <div class="sc-statusDiv">    \n    <div id="jp_<%= id %>" style="width:0;height:0;position:absolute"></div>\n    <div style="padding-top:14px;padding-left:10px;font-size:11px;float:left;color:white;font-weight:bold;width:90px;" id="statusText_<%= id %>">\n      Score 0/8\n    </div>\n    <div id="hintText_<%= id %>" style="padding-top:14px;float:left;width:320px;color:white;text-align:center;font-size:11px;font-family:Verdana">\n      Press SPACE to switch between labels, ENTER to drop\n    </div>\n    <div id="restart_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:10px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;line-height:110%">Re-start</div>\n    </div>\n  </div>\n</div>';
var HOTSPOT_EJS = '<div class="sc-hp-mainDiv" style="background-color: #<%= color %>;width:<%= width %>px;">\n  <input type="text" id="inputf_<%= id %>" style="width:1px;height:1px;border:0;position:absolute;z-index:-1;"/>\n  <div class="sc-hp-workspace" id="hotspot_container_<%= id %>">\n		<div class="sc-hp-wrapper sc-hp-<%= mode %>"><div class="sc-hp-image"></div></div>\n    <div class="sc-hp-response sc-hp-<%= mode %>"></div>\n  </div>\n	<table class="sc-hp-question sc-hp-<%= mode %>"><tr>\n		<td class="sc-hp-questionText"><div></div></td>\n		<td class="sc-hp-questionCtrl">\n			<div class="sc-hp-button sc-hp-skip">Skip</div>\n			<div class="sc-hp-button sc-hp-hint">Hint</div>\n		</td>\n	</tr></table>\n<div class="sc-hp-question sc-hp-add"></div>\n  <% if(mode == \'quiz\' ) { %>\n	<table class="sc-statusDiv"><tr>\n		<td class="sc-hp-score">\n			<div id="jp_<%= id %>" style="width:0;height:0;position:absolute"></div>\n			<div style="padding-left:10px;padding-top:0px;font-size:11px;float:left;color:white;font-weight:bold;width:90px;font-family:Verdana" id="statusText_<%= id %>">\n				Score 0/8\n			</div>\n		</td>\n		<td class="sc-hp-ctrls" style="padding:0"><div id="restart_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:0px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;line-height:110%">Re-start</div>\n		</td>\n	</tr></table>\n  <% } %>\n</div>';
var LABELING_EJS = ' <div class="sc-mainDiv" style="background-color: #<%= color %>;width:<%= width %>px;height:<%= height %>px">\n   <input type="button" id="inputf_<%= id %>" style="width:0px;height:0px;border:0;position:absolute;z-index:-1;"/>\n   <div style="height:<%= height-40 %>px">\n    <div style="text-align:left">\n      <img src="<%= img %>" style="position:relative;left:<%=imgPos[0]%>px;top:<%=imgPos[1]%>px"/>\n    </div>\n    <div class="sc-labelContainerDiv" style="width:<%= width %>px;visibility:hidden">\n      <%               \n        var dx=60;\n        var dy=4;\n      %>\n      <% for(var i =0; i < labels.length ; i++){ %>\n        <%\n          var left=(dx*i+10)+"px";\n          var top=(dy*i+390)+"px";          \n        %>\n        <div id="labeling_<%= id %>_<%= randArr[i] %>" data-id="<%= randArr[i] %>" class="sc-labels <%=bigText%>" style="left:<%= left %>;top:<%= top %>">\n          <div><%= labels[randArr[i]].name[1] %></div>\n        </div>        \n        <div id="labelTarget_<%= id %>_<%= i %>" data-id="<%= i %>" class="sc-labelsTargets" style="left:<%= labels[i].labx %>px;top:<%= labels[i].laby %>px"></div>\n        <img src="sclb_extras/labelsrc.png" style="position:absolute;z-index:1;left:<%= labels[i].dotx-3 %>px;top:<%= labels[i].doty -3%>px"/>\n      <% } %>   \n    </div>\n    </div>\n    <div class="sc-statusDiv">   	  \n   	  <div id="jp_<%= id %>" style="width:0;height:0;position:absolute"></div>\n      <div style="padding-left:10px;padding-top:14px;font-size:11px;float:left;color:white;font-weight:bold;width:90px;font-family:Verdana" id="statusText_<%= id %>">Score 0/8</div>\n      <div id="hintText_<%= id %>" style="padding-top:14px;float:left;width:370px;color:white;text-align:center;font-size:11px;font-family:Verdana">Press SPACE to switch between labels, ENTER to drop</div>\n      <div id="restart_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:10px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;line-height:110%">Re-start</div>\n    </div>\n  </div>';
var ORDERING_EJS = '<div class="sc-mainDiv" style="background-color: #<%= color %>;width:<%= width %>px;height:<%= height %>px">\n  <input type="button" id="inputf_<%= id %>" style="width:1px;height:1px;border:0;position:absolute;z-index:-1;"/>\n  <div style="height: <%= height - 40 %>px">\n    <%\n    var baseTopl=13;\n    var dyl=50;\n    %>\n    <% for(var i =0; i < labels.length ; i++){%>\n    <div id="ordering_<%= id %>_<%= randArr[i] %>" class="sc-order <%=bigText%>" data-id="<%= randArr[i] %>" style="left:15px;top:<%= (dyl*i+baseTopl)+"px" %>">\n      <%= labels[randArr[i]].item %>\n    </div>\n    <div class="sc-orderTarget" id="orderTarget_<%= id %>_<%= i %>" data-id="<%= i %>" style="left:290px;top:<%= (dyl*i+baseTopl)+"px" %>"></div>\n    <% } %>\n  </div>\n  <div class="sc-statusDiv">    \n     <div id="jp_<%= id %>" style="width:0;height:0;position:absolute"></div>\n    <div style="padding-left:10px;padding-top:14px;font-size:11px;float:left;color:white;font-weight:bold;width:90px;font-family:Verdana" id="statusText_<%= id %>">\n      Score 0/8\n    </div>\n    <div id="hintText_<%= id %>" style="padding-top:14px;float:left;width:320px;color:white;text-align:center;font-size:11px;font-family:Verdana">\n      Press SPACE to switch between labels, ENTER to drop\n    </div>\n    <div id="restart_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:10px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;line-height:110%">Re-start</div>\n    </div>\n  </div>\n</div>';
var PUZZLE_EJS = '<div class="sc-mainDiv" style="background-color: #<%= color %>;width:<%= width %>px;height:<%= height %>px">\n  <input type="text" id="inputf_<%= id %>" style="width:1px;height:1px;border:0;position:absolute;z-index:-1;"/>\n  <div style="width:100%;height:<%= height - 40 %>px;" id="puzzle_container_<%= id %>">\n    \n  </div>\n  <div class="sc-statusDiv">    \n     <div id="jp_<%= id %>" style="width:0;height:0;position:absolute"></div>\n    <div style="padding-left:10px;padding-top:14px;font-size:11px;float:left;color:white;font-weight:bold;font-family:Verdana" id="statusText_<%= id %>">\n      Score 0/8\n    </div>\n    <div id="hintText_<%= id %>" style="padding-left:10px;;padding-top:14px;float:left;width:360px;color:white;text-align:center;font-size:11px;font-family:Verdana">Press SPACE to switch between parts, ENTER to release</div>\n    <div id="finish_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:10px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;line-height:110%">Finish</div>\n<div id="restart_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:10px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;line-height:110%">Re-start</div>\n      </div>\n</div>';
var SORTING_EJS = '<div class="sc-mainDiv" style="background-color: #<%= color %>;width:<%= width %>px;height:<%= height %>px;position:relative;">\n  <input type="button" id="inputf_<%= id %>" style="width:1px;height:1px;border:0;position:absolute;z-index:-1;"/>\n  <div style="height: <%= height - 40 %>px">\n    <table width="100%" height="100%" cellpadding="0" cellspacing="0" border="0">\n      <tr>\n        <td style="height:223px;text-align:center;" align="center">\n        <table align="center" cellpadding="0" cellspacing="0" border="0">\n          <tr>\n            <% for(var i =0; i < sortLabels.length ; i++){ %> <td>\n            <div class="sc-sort-sortLabelTitle <%=bigText%>">\n              <%= sortLabels[i] %>\n            </div><div id="sortTarget_<%= i+1 %>_<%= id %>" class="sc-sort-sortTarget sc-sort-sortCommon" data-id="<%= i+1 %>"></div></td>\n            <%  } %>\n          </tr>\n        </table></td>\n      </tr>\n      <tr>\n        <td style="height:100%">\n        <div style="position:absolute;top:230px;  left:60px;width:100px;">\n          <div id="sort_0_<%= id %>" class="sc-sort-sortCommon sc-sort-sortLast"></div>\n          <div id="sort_sub_<%= id %>" style="text-align: center;font-size: 10pt;font-family: Verdana;margin-top:8px;">\n            8/8\n          </div>\n        </div>\n        <div id="sort_1_<%= id %>" class="sc-sort-sortDeck" style="position:absolute;left:63px; top:233px;width:100px;z-index:1;cursor:pointer;"><img src="sclb_extras/cover.png"/>\n        </div>\n        <div id="sort_2_<%= id %>" class="sc-sort-sortDeck" style="position:absolute;left:66px; top:236px;width:100px;z-index:2;cursor:pointer;"><img src="sclb_extras/cover.png"/>\n        </div>\n        <div id="sort_3_<%= id %>" class="sc-sort-sortDeck" style="position:absolute;left:69px; top:239px;width:100px;z-index:3;cursor:pointer;"><img src="sclb_extras/cover.png"/>\n        </div> <% for(var i=0; i < labels.length ; i++){ %>\n        <div id="sorting_<%= id %>_<%= randArr[i] %>" data-id="<%= randArr[i] %>" target-id="<%= labels[randArr[i]].cat %>" class="sc-sort sc-sort-sortCommon <%=bigText%>" style="position:absolute;cursor:pointer;left:200px;top:230px;border:1px solid black;display:none;">\n          <div>\n            <div  class="sc-sort-image">\n              <% if(labels[randArr[i]].image + "" != "[object Object]") { %>\n              <img ondragstart="return false;" src="<%= labels[randArr[i]].image %>"/>\n              <% } %>\n            </div>\n            <% if (labels[randArr[i]].title!="" || labels[randArr[i]].title2!="") { %>\n            <div  class="sc-sort-title"  style="padding:0 2px;">\n              <%=labels[randArr[i]].title %>\n            </div>\n            <div  class="sc-sort-title"  style="padding:0px 2px 0px 2px;">\n              <%=labels[randArr[i]].title2 %>\n            </div>\n            <% } %>\n            <div class="sc-sort-text"  style="margin:3px;">\n              <% if(labels[randArr[i]].text + "" != "[object Object]") { %>\n              <%=labels[randArr[i]].text %>\n              <% } %>\n            </div>\n          </div>\n        </div> <% } %> </td>\n      </tr>\n    </table>\n  </div>\n  <div class="sc-statusDiv">\n    <div id="jp_<%= id %>" style="width:0;height:0;position:absolute"></div>\n    <div style="padding-left:10px;padding-top:14px;font-size:11px;float:left;color:white;font-weight:bold;width:90px;font-family:Verdana" id="statusText_<%= id %>">\n      Score 0/8\n    </div>\n    <div id="hintText_<%= id %>" style="padding-top:14px;float:left;width:320px;color:white;text-align:center;font-size:11px;font-family:Verdana">\n      Press SPACE to show next card, ENTER to drop\n    </div>\n    <div id="restart_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:10px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;line-height:110%">Re-start</div>\n    </div>\n  </div>\n</div>';
var SEEK_A_WORD_EJS = '<div class="sc-mainDiv" style="background-color: #<%= color %>;">\n  <input type="button" id="inputf_<%= id %>" style="width:0px;height:0px;border:0;position:absolute;z-index:-1;"/>\n  <div style="width:<%= width %>px ;height: <%= height - 40 %>px">\n    <div id="seekAWord_BackPaper_<%= id %>" class="seekAWord seekAWordSheet" style="z-index:0:"></div>\n    <div class="seekAWord seekAWordSheet"id="seekAWord_Sheet_<%= id %>" style="z-index:1:cursor:pointer;background:transparent;">\n <table width="100%" height="100%"><tr><td align="center" valign="middle">     <table width="<%=sheetSize-20%>" height="<%=sheetSize-20%>" cellpadding="0" cellspacing="0" style="margin:0"  id="seekAWord_Table_<%= id %>">\n        <% for(var i=0;i\n        <state.length;i++) { %>\n          <tr height="<%= (sheetSize-20)/state.length%>px">\n            <% for(var j=0;j\n            <state[i].length;j++) { %>\n              <td width="<%= (sheetSize-20)/state[i].length%>" align="center"><span><%=state[i][j].letter%></span></td>\n              <% } %>\n          </tr>\n          <% } %>\n      </table>\n  </td></tr></table>  </div>\n    <div id="seekAWord_Paper_<%= id %>" class="seekAWord seekAWordSheet" style="z-index:2:cursor:pointer;background:transparent;"></div>\n    <div class="seekAWord seekAWordWords" style="padding:0px;">\n      <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">\n        <% for(var i=0;i<state.answer_key.length;i++) { %>\n          <tr>\n            <td align="center">\n            <div style="width:100%;position:relative;" id="word_<%=i%>_<%= id %>">\n              <%= state.answer_key[i].word %>\n              <hr style="position:absolute;width:85%;border-color:red;color:red;top:0;text-align: bottom;left:12px;display:none;>"/>\n            </div>\n            </td>\n          </tr>\n          <% } %>\n      </table>\n    </div>\n    <div class="seekAWord seekAWordHint">\n      <% if(isHint){ %>\n      <%=inst%>\n      <% } %>\n    </div>\n  </div>\n  <div class="sc-statusDiv">\n    <div id="jp_<%= id %>" style="width:0;height:0;position:absolute"></div>\n    <div style="padding-left:10px;padding-top:14px;font-size:11px;float:left;color:white;font-weight:bold;width:90px;font-family:Verdana" id="statusText_<%= id %>">\n      Score 0/8\n    </div>\n    <div id="hintText_<%= id %>" style="padding-top:14px;float:left;width:270px;color:white;text-align:center;font-size:11px;font-family:Verdana"></div>\n        <div id="finish_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:10px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;line-height:120%">\n      Finish\n    </div>\n  <div id="restart_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:10px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;line-height:120%">\n      Restart\n    </div>\n</div>\n</div>\n';
var CROSSWORD_EJS = '<div class="sc-mainDiv" style="background-color: #<%= color %>;">\n  <input type="button" id="inputf_<%= id %>" style="width:0px;height:0px;border:0;position:absolute;z-index:-1;"/>\n  <div style="width:<%= width %>px ;height: <%= height - 40 %>px">\n    <div style="float:left;width:<%= width - 180%>px;height: <%= height - 40 %>px">\n      <!--% var dx=parseInt((width - 180)/dimensions[0]),dy=parseInt((height- 180)/dimensions[1]);-->\n      <%\n      var usedIndexes={};\n      var dx = 30;\n      var fs = "16pt"; \n      var padd = "0 0 4px 0";\n      if(state.length>20){\n        dx=18;\n        var fs = "12pt";\n      } else if(state.length>15) {\n        dx=22;\n        var fs = "14pt";\n      } else {\n        padd = "4px 0 0 0";\n      }\n      var dy = dx;\n      for(var i=0;i < state.length;i++){\n      for(var j=0;j < state[i].length;j++){\n      if(state[i][j]!=-1) {\n      %> <div class="crosswordCell"  style="padding:<%=padd%>;width:<%=dx-1%>px;height:<%=dy-1-4%>px;left:<%=(i)*dx%>px;top:<%=(j)*dy%>px;font-size:<%=fs%>"><div style="display: table-cell; vertical-align: middle;width:29px;height:21px"><div id="cell_<%= id %>_<%= i %>_<%= j %>" data-correct="0"></div></div></div>\n      <input class="crosswordCellInput" id="cellinput_<%= id %>_<%= i %>_<%= j %>" style="padding:<%=padd%>;width:<%=dx-1%>px;height:<%=dy-1-4%>px;left:<%=(i)*dx%>px;top:<%=(j)*dy%>px;z-index:2">\n      </input>\n      <%   }}} %>\n    </div>\n    <div style="float:left;width:<%= 180%>px;height: <%= height - 40 %>px">\n      <div style="height:23px;padding:10px 0 5px 10px" class="crosswordLable">\n        <%= acrossText %>\n      </div>\n      <div class="crosswordDefs">\n        <% for(var i=0;i < across.length;i++){%>\n        <div class="crosswordDef" id="def_<%= id %>_<%= across[i].index %>a" data-cell="<%=across[i].x_pos%>#<%=across[i].y_pos%>">\n          <div style="margin:3px;margin-right:13px;">\n            <%= across[i].index+".) " + across[i].clue %>\n          </div>\n        </div>\n        <div class="crosswordWordNumber" style="left:<%=dx*(across[i].x_pos)+2%>px;top:<%=dy*across[i].y_pos+3%>px;z-index:1">\n          <%= across[i].index %>\n        </div>\n        <%\n        usedIndexes[across[i].index]=1;\n        } %>\n      </div>\n      <div style="height:7px;padding:21px 0 22px 10px;" class="crosswordLable">\n        <%= downText %>\n      </div>\n      <div class="crosswordDefs">\n        <% for(var i=0;i < down.length;i++){\n        %>\n        <div class="crosswordDef"  id="def_<%=id%>_<%=down[i].index%>d" data-cell="<%=down[i].x_pos%>#<%=down[i].y_pos%>">\n          <div style="margin:3px;">\n            <%= down[i].index+".) " + down[i].clue %>\n          </div>\n        </div>\n        <% if(!usedIndexes[down[i].index]) { %>\n        <div class="crosswordWordNumber" style="left:<%=dx*(down[i].x_pos)+1%>px;top:<%=dy*down[i].y_pos+3%>px;">\n          <%= down[i].index %>\n        </div>\n        <% }} %>\n      </div>\n    </div>\n  </div>\n  <div class="sc-statusDiv">\n    <div id="jp_<%= id %>" style="width:0;height:0;position:absolute"></div>\n    <div style="padding-top:14px;padding-left:10px;font-size:11px;float:left;color:white;font-weight:bold;width:90px;font-family:Verdana" id="statusText_<%= id %>">\n      Score 0/8\n    </div>\n    <div id="hintText_<%= id %>" style="padding-top:14px;float:left;width:280px;color:white;text-align:center;font-size:11px;font-family:Verdana"></div>\n    <div id="finish_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:10px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;">\n      Finish\n    </div>\n    <div id="restart_<%= id %>" style="margin-right:20px;font-family:Verdana;vertical-align:middle;background-color:#f8f8f8;font-size: 11px;margin-top:10px;height:14px;width:100px;text-align:center;float:right;padding-left:0px;cursor:pointer;border: 3px double #919191;border-radius: 5px;">\n      Restart\n    </div>\n  </div>\n</div>\n';
var TIMELINE_EJS = '<div class="sc-mainDiv" style="border-color: #<%= color %>;width:<%= width %>px;height:<%= height %>px;position:relative;visibility:hidden;">\n  <input type="button" id="inputf_<%= id %>" style="width:1px;height:1px;border:0;position:absolute;z-index:-1;"/>\n  <div style="height: 25px;width:100%;background-color:#e2e2e2;font-family:Verdana;text-align:center;padding-top:10px;font-size:14pt;" id="timeline_title_<%=id%>">\n    <%=title%>\n  </div>\n  <div class="timelinePopup" id="timeline_popup_<%=id%>" style="display:none;text-align:center;">\n    <div class="timelinePopupText">\n      <img style="float:left;margin:0 10px 10px 0;" src="" id="timeline_popupImg_<%=id%>"/>\n      <div id="timeline_popupTitle_<%=id%>" style="text-align:left;"></div>\n      <div>&nbsp;</div>\n      <div id="timeline_popupText_<%=id%>" style="text-align: left"></div>\n    </div>\n    <div id="timeline_closeButton_<%=id%>" class="tlquestionSkip" style="display:inline-block;background-color:#f8f8f8;border-color:#9ca2a2;margin:4px 0px 0 0;float:none;width:76px;">\n      <%=closeTxt%>\n    </div>\n  </div>\n  <div class="timeline scroll" id="timeline_sc_<%=id%>">    \n    <div class="timeline leftArrow" id="timeline_la_<%=id%>"></div>    \n    <div class="timeline scrollerBack" id="timeline_sb_<%=id%>"></div>\n    <div class="timeline rightArrow" id="timeline_ra_<%=id%>"></div>\n    <div class="timeline scroller" id="timeline_sm_<%=id%>"></div>      \n  </div>\n  <div class="timeline container" id="timeline_container_<%=id%>" style="overflow:hidden;">    \n    <table border="0" cellpadding="0" cellspacing="0">\n      <tr>\n        <td><div class="timeline container first"></div></td>\n        <% for(var i=0;i<visualContainers.length; i++) { %>\n          <td>\n          <div class="timeline container part" style="width:<%=partWidth%>px;">\n            <div class="timeline partLabel">\n              <div style="padding-top:3px;padding-left:3px;">\n                <%= visualContainers[i] %>\n              </div>\n            </div>\n          </div></td>\n          <% } %>\n      </tr>\n    </table>\n    <% for(var i=0;i<events.length; i++) {\n      var left = events[i].visPosition*partWidth+3;\n      if(ordermethod=="numbered") {\n        left+=10;\n      }\n     %>\n      <div id="timeline_label_<%=i%>_<%=id%>" class="timelineLabels" style="position:absolute;left:<%=left%>px;top:<%=20*(i+1)%>px;z-index:1;">\n        <table border="0" cellpadding="0" cellspacing="0">\n          <tr>\n            <td width="10px"><img src="sclb_extras/tlpoint.png"/></td>\n            <td align="left" style="padding:0 4px;white-space:nowrap;"><%=events[i].title%></td>\n          </tr>\n          <tr>\n            <td colspan="2" style="padding-left:3px;"> <% if(events[i].visWidth!=0) { %> <div style="border-left:2px solid #071c71;border-bottom:2px solid #071c71;position:relative;top:-4px;height:5px;width:<%=events[i].visWidth*partWidth%>px"></div> <% } %> </td>\n          </tr>\n        </table>\n      </div>\n      <% } %>\n  </div>\n</div>';
if (!$.browser.msie || ($.browser.msie && parseInt($.browser.version.split(".")[0]) >= 9)) {
  (function(b, f) {
    b.fn.jPlayer = function(a) {
      var c = typeof a === "string", d = Array.prototype.slice.call(arguments, 1), e = this, a = !c && d.length ? b.extend.apply(null, [!0, a].concat(d)) : a;
      if (c && a.charAt(0) === "_") {
        return e;
      }
      c ? this.each(function() {
        var c = b.data(this, "jPlayer"), h = c && b.isFunction(c[a]) ? c[a].apply(c, d) : c;
        if (h !== c && h !== f) {
          return e = h, !1;
        }
      }) : this.each(function() {
        var c = b.data(this, "jPlayer");
        c ? c.option(a || {}) : b.data(this, "jPlayer", new b.jPlayer(a, this));
      });
      return e;
    };
    b.jPlayer = function(a, c) {
      if (arguments.length) {
        this.element = b(c);
        this.options = b.extend(!0, {}, this.options, a);
        var d = this;
        this.element.bind("remove.jPlayer", function() {
          d.destroy();
        });
        this._init();
      }
    };
    b.jPlayer.emulateMethods = "load play pause";
    b.jPlayer.emulateStatus = "src readyState networkState currentTime duration paused ended playbackRate";
    b.jPlayer.emulateOptions = "muted volume";
    b.jPlayer.reservedEvent = "ready flashreset resize repeat error warning";
    b.jPlayer.event = {
      ready : "jPlayer_ready",
      flashreset : "jPlayer_flashreset",
      resize : "jPlayer_resize",
      repeat : "jPlayer_repeat",
      click : "jPlayer_click",
      error : "jPlayer_error",
      warning : "jPlayer_warning",
      loadstart : "jPlayer_loadstart",
      progress : "jPlayer_progress",
      suspend : "jPlayer_suspend",
      abort : "jPlayer_abort",
      emptied : "jPlayer_emptied",
      stalled : "jPlayer_stalled",
      play : "jPlayer_play",
      pause : "jPlayer_pause",
      loadedmetadata : "jPlayer_loadedmetadata",
      loadeddata : "jPlayer_loadeddata",
      waiting : "jPlayer_waiting",
      playing : "jPlayer_playing",
      canplay : "jPlayer_canplay",
      canplaythrough : "jPlayer_canplaythrough",
      seeking : "jPlayer_seeking",
      seeked : "jPlayer_seeked",
      timeupdate : "jPlayer_timeupdate",
      ended : "jPlayer_ended",
      ratechange : "jPlayer_ratechange",
      durationchange : "jPlayer_durationchange",
      volumechange : "jPlayer_volumechange"
    };
    b.jPlayer.htmlEvent = "loadstart,abort,emptied,stalled,loadedmetadata,loadeddata,canplay,canplaythrough,ratechange".split(",");
    b.jPlayer.pause = function() {
      b.each(b.jPlayer.prototype.instances, function(a, b) {
        b.data("jPlayer").status.srcSet && b.jPlayer("pause");
      });
    };
    b.jPlayer.timeFormat = {
      showHour : !1,
      showMin : !0,
      showSec : !0,
      padHour : !1,
      padMin : !0,
      padSec : !0,
      sepHour : ":",
      sepMin : ":",
      sepSec : ""
    };
    b.jPlayer.convertTime = function(a) {
      var c = new Date(a * 1000), d = c.getUTCHours(), a = c.getUTCMinutes(), c = c.getUTCSeconds(), d = b.jPlayer.timeFormat.padHour && d < 10 ? "0" + d : d, a = b.jPlayer.timeFormat.padMin && a < 10 ? "0" + a : a, c = b.jPlayer.timeFormat.padSec && c < 10 ? "0" + c : c;
      return (b.jPlayer.timeFormat.showHour ? d + b.jPlayer.timeFormat.sepHour : "") + (b.jPlayer.timeFormat.showMin ? a + b.jPlayer.timeFormat.sepMin : "") + (b.jPlayer.timeFormat.showSec ? c + b.jPlayer.timeFormat.sepSec : "");
    };
    b.jPlayer.uaBrowser = function(a) {
      var a = a.toLowerCase(), b = /(opera)(?:.*version)?[ \/]([\w.]+)/, d = /(msie) ([\w.]+)/, e = /(mozilla)(?:.*? rv:([\w.]+))?/, a = /(webkit)[ \/]([\w.]+)/.exec(a) || b.exec(a) || d.exec(a) || a.indexOf("compatible") < 0 && e.exec(a) || [];
      return {
        browser : a[1] || "",
        version : a[2] || "0"
      };
    };
    b.jPlayer.uaPlatform = function(a) {
      var b = a.toLowerCase(), d = /(android)/, e = /(mobile)/, a = /(ipad|iphone|ipod|android|blackberry|playbook|windows ce|webos)/.exec(b) || [], b = /(ipad|playbook)/.exec(b) || !e.exec(b) && d.exec(b) || [];
      a[1] && (a[1] = a[1].replace(/\s/g, "_"));
      return {
        platform : a[1] || "",
        tablet : b[1] || ""
      };
    };
    b.jPlayer.browser = {};
    b.jPlayer.platform = {};
    var i = b.jPlayer.uaBrowser(navigator.userAgent);
    if (i.browser) {
      b.jPlayer.browser[i.browser] = !0, b.jPlayer.browser.version = i.version;
    }
    i = b.jPlayer.uaPlatform(navigator.userAgent);
    if (i.platform) {
      b.jPlayer.platform[i.platform] = !0, b.jPlayer.platform.mobile = !i.tablet, b.jPlayer.platform.tablet = !!i.tablet;
    }
    b.jPlayer.prototype = {
      count : 0,
      version : {
        script : "2.1.0",
        needFlash : "2.1.0",
        flash : "unknown"
      },
      options : {
        swfPath : "js",
        solution : "html, flash",
        supplied : "mp3",
        preload : "metadata",
        volume : 0.8,
        muted : !1,
        wmode : "opaque",
        backgroundColor : "#000000",
        cssSelectorAncestor : "#jp_container_1",
        cssSelector : {
          videoPlay : ".jp-video-play",
          play : ".jp-play",
          pause : ".jp-pause",
          stop : ".jp-stop",
          seekBar : ".jp-seek-bar",
          playBar : ".jp-play-bar",
          mute : ".jp-mute",
          unmute : ".jp-unmute",
          volumeBar : ".jp-volume-bar",
          volumeBarValue : ".jp-volume-bar-value",
          volumeMax : ".jp-volume-max",
          currentTime : ".jp-current-time",
          duration : ".jp-duration",
          fullScreen : ".jp-full-screen",
          restoreScreen : ".jp-restore-screen",
          repeat : ".jp-repeat",
          repeatOff : ".jp-repeat-off",
          gui : ".jp-gui",
          noSolution : ".jp-no-solution"
        },
        fullScreen : !1,
        autohide : {
          restored : !1,
          full : !0,
          fadeIn : 200,
          fadeOut : 600,
          hold : 1000
        },
        loop : !1,
        repeat : function(a) {
          a.jPlayer.options.loop ? b(this).unbind(".jPlayerRepeat").bind(b.jPlayer.event.ended + ".jPlayer.jPlayerRepeat", function() {
            b(this).jPlayer("play");
          }) : b(this).unbind(".jPlayerRepeat");
        },
        nativeVideoControls : {},
        noFullScreen : {
          msie : /msie [0-6]/,
          ipad : /ipad.*?os [0-4]/,
          iphone : /iphone/,
          ipod : /ipod/,
          android_pad : /android [0-3](?!.*?mobile)/,
          android_phone : /android.*?mobile/,
          blackberry : /blackberry/,
          windows_ce : /windows ce/,
          webos : /webos/
        },
        noVolume : {
          ipad : /ipad/,
          iphone : /iphone/,
          ipod : /ipod/,
          android_pad : /android(?!.*?mobile)/,
          android_phone : /android.*?mobile/,
          blackberry : /blackberry/,
          windows_ce : /windows ce/,
          webos : /webos/,
          playbook : /playbook/
        },
        verticalVolume : !1,
        idPrefix : "jp",
        noConflict : "jQuery",
        emulateHtml : !1,
        errorAlerts : !1,
        warningAlerts : !1
      },
      optionsAudio : {
        size : {
          width : "0px",
          height : "0px",
          cssClass : ""
        },
        sizeFull : {
          width : "0px",
          height : "0px",
          cssClass : ""
        }
      },
      optionsVideo : {
        size : {
          width : "480px",
          height : "270px",
          cssClass : "jp-video-270p"
        },
        sizeFull : {
          width : "100%",
          height : "100%",
          cssClass : "jp-video-full"
        }
      },
      instances : {},
      status : {
        src : "",
        media : {},
        paused : !0,
        format : {},
        formatType : "",
        waitForPlay : !0,
        waitForLoad : !0,
        srcSet : !1,
        video : !1,
        seekPercent : 0,
        currentPercentRelative : 0,
        currentPercentAbsolute : 0,
        currentTime : 0,
        duration : 0,
        readyState : 0,
        networkState : 0,
        playbackRate : 1,
        ended : 0
      },
      internal : {
        ready : !1
      },
      solution : {
        html : !0,
        flash : !0
      },
      format : {
        mp3 : {
          codec : 'audio/mpeg; codecs="mp3"',
          flashCanPlay : !0,
          media : "audio"
        },
        m4a : {
          codec : 'audio/mp4; codecs="mp4a.40.2"',
          flashCanPlay : !0,
          media : "audio"
        },
        oga : {
          codec : 'audio/ogg; codecs="vorbis"',
          flashCanPlay : !1,
          media : "audio"
        },
        wav : {
          codec : 'audio/wav; codecs="1"',
          flashCanPlay : !1,
          media : "audio"
        },
        webma : {
          codec : 'audio/webm; codecs="vorbis"',
          flashCanPlay : !1,
          media : "audio"
        },
        fla : {
          codec : "audio/x-flv",
          flashCanPlay : !0,
          media : "audio"
        },
        m4v : {
          codec : 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',
          flashCanPlay : !0,
          media : "video"
        },
        ogv : {
          codec : 'video/ogg; codecs="theora, vorbis"',
          flashCanPlay : !1,
          media : "video"
        },
        webmv : {
          codec : 'video/webm; codecs="vorbis, vp8"',
          flashCanPlay : !1,
          media : "video"
        },
        flv : {
          codec : "video/x-flv",
          flashCanPlay : !0,
          media : "video"
        }
      },
      _init : function() {
        var a = this;
        this.element.empty();
        this.status = b.extend({}, this.status);
        this.internal = b.extend({}, this.internal);
        this.internal.domNode = this.element.get(0);
        this.formats = [];
        this.solutions = [];
        this.require = {};
        this.htmlElement = {};
        this.html = {};
        this.html.audio = {};
        this.html.video = {};
        this.flash = {};
        this.css = {};
        this.css.cs = {};
        this.css.jq = {};
        this.ancestorJq = [];
        this.options.volume = this._limitValue(this.options.volume, 0, 1);
        b.each(this.options.supplied.toLowerCase().split(","), function(c, d) {
          var e = d.replace(/^\s+|\s+$/g, "");
          if (a.format[e]) {
            var f = !1;
            b.each(a.formats, function(a, b) {
              if (e === b) {
                return f = !0, !1;
              }
            });
            f || a.formats.push(e);
          }
        });
        b.each(this.options.solution.toLowerCase().split(","), function(c, d) {
          var e = d.replace(/^\s+|\s+$/g, "");
          if (a.solution[e]) {
            var f = !1;
            b.each(a.solutions, function(a, b) {
              if (e === b) {
                return f = !0, !1;
              }
            });
            f || a.solutions.push(e);
          }
        });
        this.internal.instance = "jp_" + this.count;
        this.instances[this.internal.instance] = this.element;
        this.element.attr("id") || this.element.attr("id", this.options.idPrefix + "_jplayer_" + this.count);
        this.internal.self = b.extend({}, {
          id : this.element.attr("id"),
          jq : this.element
        });
        this.internal.audio = b.extend({}, {
          id : this.options.idPrefix + "_audio_" + this.count,
          jq : f
        });
        this.internal.video = b.extend({}, {
          id : this.options.idPrefix + "_video_" + this.count,
          jq : f
        });
        this.internal.flash = b.extend({}, {
          id : this.options.idPrefix + "_flash_" + this.count,
          jq : f,
          swf : this.options.swfPath + (this.options.swfPath.toLowerCase().slice(-4) !== ".swf" ? (this.options.swfPath && this.options.swfPath.slice(-1) !== "/" ? "/" : "") + "Jplayer.swf" : "")
        });
        this.internal.poster = b.extend({}, {
          id : this.options.idPrefix + "_poster_" + this.count,
          jq : f
        });
        b.each(b.jPlayer.event, function(b, c) {
          a.options[b] !== f && (a.element.bind(c + ".jPlayer", a.options[b]), a.options[b] = f);
        });
        this.require.audio = !1;
        this.require.video = !1;
        b.each(this.formats, function(b, c) {
          a.require[a.format[c].media] = !0;
        });
        this.options = this.require.video ? b.extend(!0, {}, this.optionsVideo, this.options) : b.extend(!0, {}, this.optionsAudio, this.options);
        this._setSize();
        this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls);
        this.status.noFullScreen = this._uaBlocklist(this.options.noFullScreen);
        this.status.noVolume = this._uaBlocklist(this.options.noVolume);
        this._restrictNativeVideoControls();
        this.htmlElement.poster = document.createElement("img");
        this.htmlElement.poster.id = this.internal.poster.id;
        this.htmlElement.poster.onload = function() {
          (!a.status.video || a.status.waitForPlay) && a.internal.poster.jq.show();
        };
        this.element.append(this.htmlElement.poster);
        this.internal.poster.jq = b("#" + this.internal.poster.id);
        this.internal.poster.jq.css({
          width : this.status.width,
          height : this.status.height
        });
        this.internal.poster.jq.hide();
        this.internal.poster.jq.bind("click.jPlayer", function() {
          a._trigger(b.jPlayer.event.click);
        });
        this.html.audio.available = !1;
        if (this.require.audio) {
          this.htmlElement.audio = document.createElement("audio"), this.htmlElement.audio.id = this.internal.audio.id, this.html.audio.available = !!this.htmlElement.audio.canPlayType && this._testCanPlayType(this.htmlElement.audio);
        }
        this.html.video.available = !1;
        if (this.require.video) {
          this.htmlElement.video = document.createElement("video"), this.htmlElement.video.id = this.internal.video.id, this.html.video.available = !!this.htmlElement.video.canPlayType && this._testCanPlayType(this.htmlElement.video);
        }
        this.flash.available = this._checkForFlash(10);
        this.html.canPlay = {};
        this.flash.canPlay = {};
        b.each(this.formats, function(b, c) {
          a.html.canPlay[c] = a.html[a.format[c].media].available && "" !== a.htmlElement[a.format[c].media].canPlayType(a.format[c].codec);
          a.flash.canPlay[c] = a.format[c].flashCanPlay && a.flash.available;
        });
        this.html.desired = !1;
        this.flash.desired = !1;
        b.each(this.solutions, function(c, d) {
          if (c === 0) {
            a[d].desired = !0;
          } else {
            var e = !1, f = !1;
            b.each(a.formats, function(b, c) {
              a[a.solutions[0]].canPlay[c] && (a.format[c].media === "video" ? f = !0 : e = !0);
            });
            a[d].desired = a.require.audio && !e || a.require.video && !f;
          }
        });
        this.html.support = {};
        this.flash.support = {};
        b.each(this.formats, function(b, c) {
          a.html.support[c] = a.html.canPlay[c] && a.html.desired;
          a.flash.support[c] = a.flash.canPlay[c] && a.flash.desired;
        });
        this.html.used = !1;
        this.flash.used = !1;
        b.each(this.solutions, function(c, d) {
          b.each(a.formats, function(b, c) {
            if (a[d].support[c]) {
              return a[d].used = !0, !1;
            }
          });
        });
        this._resetActive();
        this._resetGate();
        this._cssSelectorAncestor(this.options.cssSelectorAncestor);
        !this.html.used && !this.flash.used ? (this._error({
          type : b.jPlayer.error.NO_SOLUTION,
          context : "{solution:'" + this.options.solution + "', supplied:'" + this.options.supplied + "'}",
          message : b.jPlayer.errorMsg.NO_SOLUTION,
          hint : b.jPlayer.errorHint.NO_SOLUTION
        }), this.css.jq.noSolution.length && this.css.jq.noSolution.show()) : this.css.jq.noSolution.length && this.css.jq.noSolution.hide();
        if (this.flash.used) {
          var c, d = "jQuery=" + encodeURI(this.options.noConflict) + "&id=" + encodeURI(this.internal.self.id) + "&vol=" + this.options.volume + "&muted=" + this.options.muted;
          if (b.browser.msie && Number(b.browser.version) <= 8) {
            d = ['<param name="movie" value="' + this.internal.flash.swf + '" />', '<param name="FlashVars" value="' + d + '" />', '<param name="allowScriptAccess" value="always" />', '<param name="bgcolor" value="' + this.options.backgroundColor + '" />', '<param name="wmode" value="' + this.options.wmode + '" />'];
            c = document.createElement('<object id="' + this.internal.flash.id + '" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="0" height="0"></object>');
            for (var e = 0; e < d.length; e++) {
              c.appendChild(document.createElement(d[e]));
            }
          } else {
            e = function(a, b, c) {
              var d = document.createElement("param");
              d.setAttribute("name", b);
              d.setAttribute("value", c);
              a.appendChild(d);
            }, c = document.createElement("object"), c.setAttribute("id", this.internal.flash.id), c.setAttribute("data", this.internal.flash.swf), c.setAttribute("type", "application/x-shockwave-flash"), c.setAttribute("width", "1"), c.setAttribute("height", "1"), e(c, "flashvars", d), e(c, "allowscriptaccess", "always"), e(c, "bgcolor", this.options.backgroundColor), e(c, "wmode", this.options.wmode);
          }
          this.element.append(c);
          this.internal.flash.jq = b(c);
        }
        if (this.html.used) {
          if (this.html.audio.available) {
            this._addHtmlEventListeners(this.htmlElement.audio, this.html.audio), this.element.append(this.htmlElement.audio), this.internal.audio.jq = b("#" + this.internal.audio.id);
          }
          if (this.html.video.available) {
            this._addHtmlEventListeners(this.htmlElement.video, this.html.video), this.element.append(this.htmlElement.video), this.internal.video.jq = b("#" + this.internal.video.id), this.status.nativeVideoControls ? this.internal.video.jq.css({
              width : this.status.width,
              height : this.status.height
            }) : this.internal.video.jq.css({
              width : "0px",
              height : "0px"
            }), this.internal.video.jq.bind("click.jPlayer", function() {
              a._trigger(b.jPlayer.event.click);
            });
          }
        }
        this.options.emulateHtml && this._emulateHtmlBridge();
        this.html.used && !this.flash.used && setTimeout(function() {
          a.internal.ready = !0;
          a.version.flash = "n/a";
          a._trigger(b.jPlayer.event.repeat);
          a._trigger(b.jPlayer.event.ready);
        }, 100);
        this._updateNativeVideoControls();
        this._updateInterface();
        this._updateButtons(!1);
        this._updateAutohide();
        this._updateVolume(this.options.volume);
        this._updateMute(this.options.muted);
        this.css.jq.videoPlay.length && this.css.jq.videoPlay.hide();
        b.jPlayer.prototype.count++;
      },
      destroy : function() {
        this.clearMedia();
        this._removeUiClass();
        this.css.jq.currentTime.length && this.css.jq.currentTime.text("");
        this.css.jq.duration.length && this.css.jq.duration.text("");
        b.each(this.css.jq, function(a, b) {
          b.length && b.unbind(".jPlayer");
        });
        this.internal.poster.jq.unbind(".jPlayer");
        this.internal.video.jq && this.internal.video.jq.unbind(".jPlayer");
        this.options.emulateHtml && this._destroyHtmlBridge();
        this.element.removeData("jPlayer");
        this.element.unbind(".jPlayer");
        this.element.empty();
        delete this.instances[this.internal.instance];
      },
      enable : function() {
      },
      disable : function() {
      },
      _testCanPlayType : function(a) {
        try {
          return a.canPlayType(this.format.mp3.codec), !0;
        } catch(b) {
          return !1;
        }
      },
      _uaBlocklist : function(a) {
        var c = navigator.userAgent.toLowerCase(), d = !1;
        b.each(a, function(a, b) {
          if (b && b.test(c)) {
            return d = !0, !1;
          }
        });
        return d;
      },
      _restrictNativeVideoControls : function() {
        if (this.require.audio && this.status.nativeVideoControls) {
          this.status.nativeVideoControls = !1, this.status.noFullScreen = !0;
        }
      },
      _updateNativeVideoControls : function() {
        if (this.html.video.available && this.html.used) {
          this.htmlElement.video.controls = this.status.nativeVideoControls, this._updateAutohide(), this.status.nativeVideoControls && this.require.video ? (this.internal.poster.jq.hide(), this.internal.video.jq.css({
            width : this.status.width,
            height : this.status.height
          })) : this.status.waitForPlay && this.status.video && (this.internal.poster.jq.show(), this.internal.video.jq.css({
            width : "0px",
            height : "0px"
          }));
        }
      },
      _addHtmlEventListeners : function(a, c) {
        var d = this;
        a.preload = this.options.preload;
        a.muted = this.options.muted;
        a.volume = this.options.volume;
        a.addEventListener("progress", function() {
          c.gate && (d._getHtmlStatus(a), d._updateInterface(), d._trigger(b.jPlayer.event.progress));
        }, !1);
        a.addEventListener("timeupdate", function() {
          c.gate && (d._getHtmlStatus(a), d._updateInterface(), d._trigger(b.jPlayer.event.timeupdate));
        }, !1);
        a.addEventListener("durationchange", function() {
          if (c.gate) {
            d.status.duration = this.duration, d._getHtmlStatus(a), d._updateInterface(), d._trigger(b.jPlayer.event.durationchange);
          }
        }, !1);
        a.addEventListener("play", function() {
          c.gate && (d._updateButtons(!0), d._html_checkWaitForPlay(), d._trigger(b.jPlayer.event.play));
        }, !1);
        a.addEventListener("playing", function() {
          c.gate && (d._updateButtons(!0), d._seeked(), d._trigger(b.jPlayer.event.playing));
        }, !1);
        a.addEventListener("pause", function() {
          c.gate && (d._updateButtons(!1), d._trigger(b.jPlayer.event.pause));
        }, !1);
        a.addEventListener("waiting", function() {
          c.gate && (d._seeking(), d._trigger(b.jPlayer.event.waiting));
        }, !1);
        a.addEventListener("seeking", function() {
          c.gate && (d._seeking(), d._trigger(b.jPlayer.event.seeking));
        }, !1);
        a.addEventListener("seeked", function() {
          c.gate && (d._seeked(), d._trigger(b.jPlayer.event.seeked));
        }, !1);
        a.addEventListener("volumechange", function() {
          if (c.gate) {
            d.options.volume = a.volume, d.options.muted = a.muted, d._updateMute(), d._updateVolume(), d._trigger(b.jPlayer.event.volumechange);
          }
        }, !1);
        a.addEventListener("suspend", function() {
          c.gate && (d._seeked(), d._trigger(b.jPlayer.event.suspend));
        }, !1);
        a.addEventListener("ended", function() {
          if (c.gate) {
            if (!b.jPlayer.browser.webkit) {
              d.htmlElement.media.currentTime = 0;
            }
            d.htmlElement.media.pause();
            d._updateButtons(!1);
            d._getHtmlStatus(a, !0);
            d._updateInterface();
            d._trigger(b.jPlayer.event.ended);
          }
        }, !1);
        a.addEventListener("error", function() {
          if (c.gate && (d._updateButtons(!1), d._seeked(), d.status.srcSet)) {
            clearTimeout(d.internal.htmlDlyCmdId), d.status.waitForLoad = !0, d.status.waitForPlay = !0, d.status.video && !d.status.nativeVideoControls && d.internal.video.jq.css({
              width : "0px",
              height : "0px"
            }), d._validString(d.status.media.poster) && !d.status.nativeVideoControls && d.internal.poster.jq.show(), d.css.jq.videoPlay.length && d.css.jq.videoPlay.show(), d._error({
              type : b.jPlayer.error.URL,
              context : d.status.src,
              message : b.jPlayer.errorMsg.URL,
              hint : b.jPlayer.errorHint.URL
            });
          }
        }, !1);
        b.each(b.jPlayer.htmlEvent, function(e, g) {
          a.addEventListener(this, function() {
            c.gate && d._trigger(b.jPlayer.event[g]);
          }, !1);
        });
      },
      _getHtmlStatus : function(a, b) {
        var d = 0, e = 0, g = 0, f = 0;
        if (a.duration) {
          this.status.duration = a.duration;
        }
        d = a.currentTime;
        e = this.status.duration > 0 ? 100 * d / this.status.duration : 0;
        typeof a.seekable === "object" && a.seekable.length > 0 ? ( g = this.status.duration > 0 ? 100 * a.seekable.end(a.seekable.length - 1) / this.status.duration : 100, f = 100 * a.currentTime / a.seekable.end(a.seekable.length - 1)) : ( g = 100, f = e);
        b && ( e = f = d = 0);
        this.status.seekPercent = g;
        this.status.currentPercentRelative = f;
        this.status.currentPercentAbsolute = e;
        this.status.currentTime = d;
        this.status.readyState = a.readyState;
        this.status.networkState = a.networkState;
        this.status.playbackRate = a.playbackRate;
        this.status.ended = a.ended;
      },
      _resetStatus : function() {
        this.status = b.extend({}, this.status, b.jPlayer.prototype.status);
      },
      _trigger : function(a, c, d) {
        a = b.Event(a);
        a.jPlayer = {};
        a.jPlayer.version = b.extend({}, this.version);
        a.jPlayer.options = b.extend(!0, {}, this.options);
        a.jPlayer.status = b.extend(!0, {}, this.status);
        a.jPlayer.html = b.extend(!0, {}, this.html);
        a.jPlayer.flash = b.extend(!0, {}, this.flash);
        if (c) {
          a.jPlayer.error = b.extend({}, c);
        }
        if (d) {
          a.jPlayer.warning = b.extend({}, d);
        }
        this.element.trigger(a);
      },
      jPlayerFlashEvent : function(a, c) {
        if (a === b.jPlayer.event.ready) {
          if (this.internal.ready) {
            if (this.flash.gate) {
              if (this.status.srcSet) {
                var d = this.status.currentTime, e = this.status.paused;
                this.setMedia(this.status.media);
                d > 0 && ( e ? this.pause(d) : this.play(d));
              }
              this._trigger(b.jPlayer.event.flashreset);
            }
          } else {
            this.internal.ready = !0, this.internal.flash.jq.css({
              width : "0px",
              height : "0px"
            }), this.version.flash = c.version, this.version.needFlash !== this.version.flash && this._error({
              type : b.jPlayer.error.VERSION,
              context : this.version.flash,
              message : b.jPlayer.errorMsg.VERSION + this.version.flash,
              hint : b.jPlayer.errorHint.VERSION
            }), this._trigger(b.jPlayer.event.repeat), this._trigger(a);
          }
        }
        if (this.flash.gate) {
          switch(a) {
            case b.jPlayer.event.progress:
              this._getFlashStatus(c);
              this._updateInterface();
              this._trigger(a);
              break;
            case b.jPlayer.event.timeupdate:
              this._getFlashStatus(c);
              this._updateInterface();
              this._trigger(a);
              break;
            case b.jPlayer.event.play:
              this._seeked();
              this._updateButtons(!0);
              this._trigger(a);
              break;
            case b.jPlayer.event.pause:
              this._updateButtons(!1);
              this._trigger(a);
              break;
            case b.jPlayer.event.ended:
              this._updateButtons(!1);
              this._trigger(a);
              break;
            case b.jPlayer.event.click:
              this._trigger(a);
              break;
            case b.jPlayer.event.error:
              this.status.waitForLoad = !0;
              this.status.waitForPlay = !0;
              this.status.video && this.internal.flash.jq.css({
                width : "0px",
                height : "0px"
              });
              this._validString(this.status.media.poster) && this.internal.poster.jq.show();
              this.css.jq.videoPlay.length && this.status.video && this.css.jq.videoPlay.show();
              this.status.video ? this._flash_setVideo(this.status.media) : this._flash_setAudio(this.status.media);
              this._updateButtons(!1);
              this._error({
                type : b.jPlayer.error.URL,
                context : c.src,
                message : b.jPlayer.errorMsg.URL,
                hint : b.jPlayer.errorHint.URL
              });
              break;
            case b.jPlayer.event.seeking:
              this._seeking();
              this._trigger(a);
              break;
            case b.jPlayer.event.seeked:
              this._seeked();
              this._trigger(a);
              break;
            case b.jPlayer.event.ready:
              break;
            default:
              this._trigger(a);
          }
        }
        return !1;
      },
      _getFlashStatus : function(a) {
        this.status.seekPercent = a.seekPercent;
        this.status.currentPercentRelative = a.currentPercentRelative;
        this.status.currentPercentAbsolute = a.currentPercentAbsolute;
        this.status.currentTime = a.currentTime;
        this.status.duration = a.duration;
        this.status.readyState = 4;
        this.status.networkState = 0;
        this.status.playbackRate = 1;
        this.status.ended = !1;
      },
      _updateButtons : function(a) {
        if (a !== f) {
          this.status.paused = !a, this.css.jq.play.length && this.css.jq.pause.length && ( a ? (this.css.jq.play.hide(), this.css.jq.pause.show()) : (this.css.jq.play.show(), this.css.jq.pause.hide()));
        }
        this.css.jq.restoreScreen.length && this.css.jq.fullScreen.length && (this.status.noFullScreen ? (this.css.jq.fullScreen.hide(), this.css.jq.restoreScreen.hide()) : this.options.fullScreen ? (this.css.jq.fullScreen.hide(), this.css.jq.restoreScreen.show()) : (this.css.jq.fullScreen.show(), this.css.jq.restoreScreen.hide()));
        this.css.jq.repeat.length && this.css.jq.repeatOff.length && (this.options.loop ? (this.css.jq.repeat.hide(), this.css.jq.repeatOff.show()) : (this.css.jq.repeat.show(), this.css.jq.repeatOff.hide()));
      },
      _updateInterface : function() {
        this.css.jq.seekBar.length && this.css.jq.seekBar.width(this.status.seekPercent + "%");
        this.css.jq.playBar.length && this.css.jq.playBar.width(this.status.currentPercentRelative + "%");
        this.css.jq.currentTime.length && this.css.jq.currentTime.text(b.jPlayer.convertTime(this.status.currentTime));
        this.css.jq.duration.length && this.css.jq.duration.text(b.jPlayer.convertTime(this.status.duration));
      },
      _seeking : function() {
        this.css.jq.seekBar.length && this.css.jq.seekBar.addClass("jp-seeking-bg");
      },
      _seeked : function() {
        this.css.jq.seekBar.length && this.css.jq.seekBar.removeClass("jp-seeking-bg");
      },
      _resetGate : function() {
        this.html.audio.gate = !1;
        this.html.video.gate = !1;
        this.flash.gate = !1;
      },
      _resetActive : function() {
        this.html.active = !1;
        this.flash.active = !1;
      },
      setMedia : function(a) {
        var c = this, d = !1, e = this.status.media.poster !== a.poster;
        this._resetMedia();
        this._resetGate();
        this._resetActive();
        b.each(this.formats, function(e, f) {
          var i = c.format[f].media === "video";
          b.each(c.solutions, function(b, e) {
            if (c[e].support[f] && c._validString(a[f])) {
              var g = e === "html";
              i ? ( g ? (c.html.video.gate = !0, c._html_setVideo(a), c.html.active = !0) : (c.flash.gate = !0, c._flash_setVideo(a), c.flash.active = !0), c.css.jq.videoPlay.length && c.css.jq.videoPlay.show(), c.status.video = !0) : ( g ? (c.html.audio.gate = !0, c._html_setAudio(a), c.html.active = !0) : (c.flash.gate = !0, c._flash_setAudio(a), c.flash.active = !0), c.css.jq.videoPlay.length && c.css.jq.videoPlay.hide(), c.status.video = !1);
              d = !0;
              return !1;
            }
          });
          if (d) {
            return !1;
          }
        });
        if (d) {
          if ((!this.status.nativeVideoControls || !this.html.video.gate) && this._validString(a.poster)) {
            e ? this.htmlElement.poster.src = a.poster : this.internal.poster.jq.show();
          }
          this.status.srcSet = !0;
          this.status.media = b.extend({}, a);
          this._updateButtons(!1);
          this._updateInterface();
        } else {
          this._error({
            type : b.jPlayer.error.NO_SUPPORT,
            context : "{supplied:'" + this.options.supplied + "'}",
            message : b.jPlayer.errorMsg.NO_SUPPORT,
            hint : b.jPlayer.errorHint.NO_SUPPORT
          });
        }
      },
      _resetMedia : function() {
        this._resetStatus();
        this._updateButtons(!1);
        this._updateInterface();
        this._seeked();
        this.internal.poster.jq.hide();
        clearTimeout(this.internal.htmlDlyCmdId);
        this.html.active ? this._html_resetMedia() : this.flash.active && this._flash_resetMedia();
      },
      clearMedia : function() {
        this._resetMedia();
        this.html.active ? this._html_clearMedia() : this.flash.active && this._flash_clearMedia();
        this._resetGate();
        this._resetActive();
      },
      load : function() {
        this.status.srcSet ? this.html.active ? this._html_load() : this.flash.active && this._flash_load() : this._urlNotSetError("load");
      },
      play : function(a) {
        a = typeof a === "number" ? a : NaN;
        this.status.srcSet ? this.html.active ? this._html_play(a) : this.flash.active && this._flash_play(a) : this._urlNotSetError("play");
      },
      videoPlay : function() {
        this.play();
      },
      pause : function(a) {
        a = typeof a === "number" ? a : NaN;
        this.status.srcSet ? this.html.active ? this._html_pause(a) : this.flash.active && this._flash_pause(a) : this._urlNotSetError("pause");
      },
      pauseOthers : function() {
        var a = this;
        b.each(this.instances, function(b, d) {
          a.element !== d && d.data("jPlayer").status.srcSet && d.jPlayer("pause");
        });
      },
      stop : function() {
        this.status.srcSet ? this.html.active ? this._html_pause(0) : this.flash.active && this._flash_pause(0) : this._urlNotSetError("stop");
      },
      playHead : function(a) {
        a = this._limitValue(a, 0, 100);
        this.status.srcSet ? this.html.active ? this._html_playHead(a) : this.flash.active && this._flash_playHead(a) : this._urlNotSetError("playHead");
      },
      _muted : function(a) {
        this.options.muted = a;
        this.html.used && this._html_mute(a);
        this.flash.used && this._flash_mute(a);
        !this.html.video.gate && !this.html.audio.gate && (this._updateMute(a), this._updateVolume(this.options.volume), this._trigger(b.jPlayer.event.volumechange));
      },
      mute : function(a) {
        a = a === f ? !0 : !!a;
        this._muted(a);
      },
      unmute : function(a) {
        a = a === f ? !0 : !!a;
        this._muted(!a);
      },
      _updateMute : function(a) {
        if (a === f) {
          a = this.options.muted;
        }
        this.css.jq.mute.length && this.css.jq.unmute.length && (this.status.noVolume ? (this.css.jq.mute.hide(), this.css.jq.unmute.hide()) : a ? (this.css.jq.mute.hide(), this.css.jq.unmute.show()) : (this.css.jq.mute.show(), this.css.jq.unmute.hide()));
      },
      volume : function(a) {
        a = this._limitValue(a, 0, 1);
        this.options.volume = a;
        this.html.used && this._html_volume(a);
        this.flash.used && this._flash_volume(a);
        !this.html.video.gate && !this.html.audio.gate && (this._updateVolume(a), this._trigger(b.jPlayer.event.volumechange));
      },
      volumeBar : function(a) {
        if (this.css.jq.volumeBar.length) {
          var b = this.css.jq.volumeBar.offset(), d = a.pageX - b.left, e = this.css.jq.volumeBar.width(), a = this.css.jq.volumeBar.height() - a.pageY + b.top, b = this.css.jq.volumeBar.height();
          this.options.verticalVolume ? this.volume(a / b) : this.volume(d / e);
        }
        this.options.muted && this._muted(!1);
      },
      volumeBarValue : function(a) {
        this.volumeBar(a);
      },
      _updateVolume : function(a) {
        if (a === f) {
          a = this.options.volume;
        }
        a = this.options.muted ? 0 : a;
        this.status.noVolume ? (this.css.jq.volumeBar.length && this.css.jq.volumeBar.hide(), this.css.jq.volumeBarValue.length && this.css.jq.volumeBarValue.hide(), this.css.jq.volumeMax.length && this.css.jq.volumeMax.hide()) : (this.css.jq.volumeBar.length && this.css.jq.volumeBar.show(), this.css.jq.volumeBarValue.length && (this.css.jq.volumeBarValue.show(), this.css.jq.volumeBarValue[this.options.verticalVolume?"height":"width"](a * 100 + "%")), this.css.jq.volumeMax.length && this.css.jq.volumeMax.show());
      },
      volumeMax : function() {
        this.volume(1);
        this.options.muted && this._muted(!1);
      },
      _cssSelectorAncestor : function(a) {
        var c = this;
        this.options.cssSelectorAncestor = a;
        this._removeUiClass();
        this.ancestorJq = a ? b(a) : [];
        a && this.ancestorJq.length !== 1 && this._warning({
          type : b.jPlayer.warning.CSS_SELECTOR_COUNT,
          context : a,
          message : b.jPlayer.warningMsg.CSS_SELECTOR_COUNT + this.ancestorJq.length + " found for cssSelectorAncestor.",
          hint : b.jPlayer.warningHint.CSS_SELECTOR_COUNT
        });
        this._addUiClass();
        b.each(this.options.cssSelector, function(a, b) {
          c._cssSelector(a, b);
        });
      },
      _cssSelector : function(a, c) {
        var d = this;
        typeof c === "string" ? b.jPlayer.prototype.options.cssSelector[a] ? (this.css.jq[a] && this.css.jq[a].length && this.css.jq[a].unbind(".jPlayer"), this.options.cssSelector[a] = c, this.css.cs[a] = this.options.cssSelectorAncestor + " " + c, this.css.jq[a] = c ? b(this.css.cs[a]) : [], this.css.jq[a].length && this.css.jq[a].bind("click.jPlayer", function(c) {
          d[a](c);
          b(this).blur();
          return !1;
        }), c && this.css.jq[a].length !== 1 && this._warning({
          type : b.jPlayer.warning.CSS_SELECTOR_COUNT,
          context : this.css.cs[a],
          message : b.jPlayer.warningMsg.CSS_SELECTOR_COUNT + this.css.jq[a].length + " found for " + a + " method.",
          hint : b.jPlayer.warningHint.CSS_SELECTOR_COUNT
        })) : this._warning({
          type : b.jPlayer.warning.CSS_SELECTOR_METHOD,
          context : a,
          message : b.jPlayer.warningMsg.CSS_SELECTOR_METHOD,
          hint : b.jPlayer.warningHint.CSS_SELECTOR_METHOD
        }) : this._warning({
          type : b.jPlayer.warning.CSS_SELECTOR_STRING,
          context : c,
          message : b.jPlayer.warningMsg.CSS_SELECTOR_STRING,
          hint : b.jPlayer.warningHint.CSS_SELECTOR_STRING
        });
      },
      seekBar : function(a) {
        if (this.css.jq.seekBar) {
          var b = this.css.jq.seekBar.offset(), a = a.pageX - b.left, b = this.css.jq.seekBar.width();
          this.playHead(100 * a / b);
        }
      },
      playBar : function(a) {
        this.seekBar(a);
      },
      repeat : function() {
        this._loop(!0);
      },
      repeatOff : function() {
        this._loop(!1);
      },
      _loop : function(a) {
        if (this.options.loop !== a) {
          this.options.loop = a, this._updateButtons(), this._trigger(b.jPlayer.event.repeat);
        }
      },
      currentTime : function() {
      },
      duration : function() {
      },
      gui : function() {
      },
      noSolution : function() {
      },
      option : function(a, c) {
        var d = a;
        if (arguments.length === 0) {
          return b.extend(!0, {}, this.options);
        }
        if ( typeof a === "string") {
          var e = a.split(".");
          if (c === f) {
            for (var d = b.extend(!0, {}, this.options), g = 0; g < e.length; g++) {
              if (d[e[g]] !== f) {
                d = d[e[g]];
              } else {
                return this._warning({
                  type : b.jPlayer.warning.OPTION_KEY,
                  context : a,
                  message : b.jPlayer.warningMsg.OPTION_KEY,
                  hint : b.jPlayer.warningHint.OPTION_KEY
                }), f;
              }
            }
            return d;
          }
          for (var g = d = {}, h = 0; h < e.length; h++) {
            h < e.length - 1 ? (g[e[h]] = {}, g = g[e[h]]) : g[e[h]] = c;
          }
        }
        this._setOptions(d);
        return this;
      },
      _setOptions : function(a) {
        var c = this;
        b.each(a, function(a, b) {
          c._setOption(a, b);
        });
        return this;
      },
      _setOption : function(a, c) {
        var d = this;
        switch(a) {
          case"volume":
            this.volume(c);
            break;
          case"muted":
            this._muted(c);
            break;
          case"cssSelectorAncestor":
            this._cssSelectorAncestor(c);
            break;
          case"cssSelector":
            b.each(c, function(a, b) {
              d._cssSelector(a, b);
            });
            break;
          case"fullScreen":
            this.options[a] !== c && (this._removeUiClass(), this.options[a] = c, this._refreshSize());
            break;
          case"size":
            !this.options.fullScreen && this.options[a].cssClass !== c.cssClass && this._removeUiClass();
            this.options[a] = b.extend({}, this.options[a], c);
            this._refreshSize();
            break;
          case"sizeFull":
            this.options.fullScreen && this.options[a].cssClass !== c.cssClass && this._removeUiClass();
            this.options[a] = b.extend({}, this.options[a], c);
            this._refreshSize();
            break;
          case"autohide":
            this.options[a] = b.extend({}, this.options[a], c);
            this._updateAutohide();
            break;
          case"loop":
            this._loop(c);
            break;
          case"nativeVideoControls":
            this.options[a] = b.extend({}, this.options[a], c);
            this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls);
            this._restrictNativeVideoControls();
            this._updateNativeVideoControls();
            break;
          case"noFullScreen":
            this.options[a] = b.extend({}, this.options[a], c);
            this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls);
            this.status.noFullScreen = this._uaBlocklist(this.options.noFullScreen);
            this._restrictNativeVideoControls();
            this._updateButtons();
            break;
          case"noVolume":
            this.options[a] = b.extend({}, this.options[a], c);
            this.status.noVolume = this._uaBlocklist(this.options.noVolume);
            this._updateVolume();
            this._updateMute();
            break;
          case"emulateHtml":
            this.options[a] !== c && ((this.options[a] = c) ? this._emulateHtmlBridge() : this._destroyHtmlBridge());
        }
        return this;
      },
      _refreshSize : function() {
        this._setSize();
        this._addUiClass();
        this._updateSize();
        this._updateButtons();
        this._updateAutohide();
        this._trigger(b.jPlayer.event.resize);
      },
      _setSize : function() {
        this.options.fullScreen ? (this.status.width = this.options.sizeFull.width, this.status.height = this.options.sizeFull.height, this.status.cssClass = this.options.sizeFull.cssClass) : (this.status.width = this.options.size.width, this.status.height = this.options.size.height, this.status.cssClass = this.options.size.cssClass);
        this.element.css({
          width : this.status.width,
          height : this.status.height
        });
      },
      _addUiClass : function() {
        this.ancestorJq.length && this.ancestorJq.addClass(this.status.cssClass);
      },
      _removeUiClass : function() {
        this.ancestorJq.length && this.ancestorJq.removeClass(this.status.cssClass);
      },
      _updateSize : function() {
        this.internal.poster.jq.css({
          width : this.status.width,
          height : this.status.height
        });
        !this.status.waitForPlay && this.html.active && this.status.video || this.html.video.available && this.html.used && this.status.nativeVideoControls ? this.internal.video.jq.css({
          width : this.status.width,
          height : this.status.height
        }) : !this.status.waitForPlay && this.flash.active && this.status.video && this.internal.flash.jq.css({
          width : this.status.width,
          height : this.status.height
        });
      },
      _updateAutohide : function() {
        var a = this, b = function() {
          a.css.jq.gui.fadeIn(a.options.autohide.fadeIn, function() {
            clearTimeout(a.internal.autohideId);
            a.internal.autohideId = setTimeout(function() {
              a.css.jq.gui.fadeOut(a.options.autohide.fadeOut);
            }, a.options.autohide.hold);
          });
        };
        this.css.jq.gui.length && (this.css.jq.gui.stop(!0, !0), clearTimeout(this.internal.autohideId), this.element.unbind(".jPlayerAutohide"), this.css.jq.gui.unbind(".jPlayerAutohide"), this.status.nativeVideoControls ? this.css.jq.gui.hide() : this.options.fullScreen && this.options.autohide.full || !this.options.fullScreen && this.options.autohide.restored ? (this.element.bind("mousemove.jPlayer.jPlayerAutohide", b), this.css.jq.gui.bind("mousemove.jPlayer.jPlayerAutohide", b), this.css.jq.gui.hide()) : this.css.jq.gui.show());
      },
      fullScreen : function() {
        this._setOption("fullScreen", !0);
      },
      restoreScreen : function() {
        this._setOption("fullScreen", !1);
      },
      _html_initMedia : function() {
        this.htmlElement.media.src = this.status.src;
        this.options.preload !== "none" && this._html_load();
        this._trigger(b.jPlayer.event.timeupdate);
      },
      _html_setAudio : function(a) {
        var c = this;
        b.each(this.formats, function(b, e) {
          if (c.html.support[e] && a[e]) {
            return c.status.src = a[e], c.status.format[e] = !0, c.status.formatType = e, !1;
          }
        });
        this.htmlElement.media = this.htmlElement.audio;
        this._html_initMedia();
      },
      _html_setVideo : function(a) {
        var c = this;
        b.each(this.formats, function(b, e) {
          if (c.html.support[e] && a[e]) {
            return c.status.src = a[e], c.status.format[e] = !0, c.status.formatType = e, !1;
          }
        });
        if (this.status.nativeVideoControls) {
          this.htmlElement.video.poster = this._validString(a.poster) ? a.poster : "";
        }
        this.htmlElement.media = this.htmlElement.video;
        this._html_initMedia();
      },
      _html_resetMedia : function() {
        this.htmlElement.media && (this.htmlElement.media.id === this.internal.video.id && !this.status.nativeVideoControls && this.internal.video.jq.css({
          width : "0px",
          height : "0px"
        }), this.htmlElement.media.pause());
      },
      _html_clearMedia : function() {
        if (this.htmlElement.media) {
          this.htmlElement.media.src = "", this.htmlElement.media.load();
        }
      },
      _html_load : function() {
        if (this.status.waitForLoad) {
          this.status.waitForLoad = !1, this.htmlElement.media.load();
        }
        clearTimeout(this.internal.htmlDlyCmdId);
      },
      _html_play : function(a) {
        var b = this;
        this._html_load();
        this.htmlElement.media.play();
        if (!isNaN(a)) {
          try {
            this.htmlElement.media.currentTime = a;
          } catch(d) {
            this.internal.htmlDlyCmdId = setTimeout(function() {
              b.play(a);
            }, 100);
            return;
          }
        }
        this._html_checkWaitForPlay();
      },
      _html_pause : function(a) {
        var b = this;
        a > 0 ? this._html_load() : clearTimeout(this.internal.htmlDlyCmdId);
        this.htmlElement.media.pause();
        if (!isNaN(a)) {
          try {
            this.htmlElement.media.currentTime = a;
          } catch(d) {
            this.internal.htmlDlyCmdId = setTimeout(function() {
              b.pause(a);
            }, 100);
            return;
          }
        }
        a > 0 && this._html_checkWaitForPlay();
      },
      _html_playHead : function(a) {
        var b = this;
        this._html_load();
        try {
          if ( typeof this.htmlElement.media.seekable === "object" && this.htmlElement.media.seekable.length > 0) {
            this.htmlElement.media.currentTime = a * this.htmlElement.media.seekable.end(this.htmlElement.media.seekable.length - 1) / 100;
          } else {
            if (this.htmlElement.media.duration > 0 && !isNaN(this.htmlElement.media.duration)) {
              this.htmlElement.media.currentTime = a * this.htmlElement.media.duration / 100;
            } else {
              throw "e";
            }
          }
        } catch(d) {
          this.internal.htmlDlyCmdId = setTimeout(function() {
            b.playHead(a);
          }, 100);
          return;
        }
        this.status.waitForLoad || this._html_checkWaitForPlay();
      },
      _html_checkWaitForPlay : function() {
        if (this.status.waitForPlay) {
          this.status.waitForPlay = !1, this.css.jq.videoPlay.length && this.css.jq.videoPlay.hide(), this.status.video && (this.internal.poster.jq.hide(), this.internal.video.jq.css({
            width : this.status.width,
            height : this.status.height
          }));
        }
      },
      _html_volume : function(a) {
        if (this.html.audio.available) {
          this.htmlElement.audio.volume = a;
        }
        if (this.html.video.available) {
          this.htmlElement.video.volume = a;
        }
      },
      _html_mute : function(a) {
        if (this.html.audio.available) {
          this.htmlElement.audio.muted = a;
        }
        if (this.html.video.available) {
          this.htmlElement.video.muted = a;
        }
      },
      _flash_setAudio : function(a) {
        var c = this;
        try {
          if (b.each(this.formats, function(b, d) {
            if (c.flash.support[d] && a[d]) {
              switch(d) {
                case"m4a":
                case"fla":
                  c._getMovie().fl_setAudio_m4a(a[d]);
                  break;
                case"mp3":
                  c._getMovie().fl_setAudio_mp3(a[d]);
              }
              c.status.src = a[d];
              c.status.format[d] = !0;
              c.status.formatType = d;
              return !1;
            }
          }), this.options.preload === "auto") {
            this._flash_load(), this.status.waitForLoad = !1;
          }
        } catch(d) {
          this._flashError(d);
        }
      },
      _flash_setVideo : function(a) {
        var c = this;
        try {
          if (b.each(this.formats, function(b, d) {
            if (c.flash.support[d] && a[d]) {
              switch(d) {
                case"m4v":
                case"flv":
                  c._getMovie().fl_setVideo_m4v(a[d]);
              }
              c.status.src = a[d];
              c.status.format[d] = !0;
              c.status.formatType = d;
              return !1;
            }
          }), this.options.preload === "auto") {
            this._flash_load(), this.status.waitForLoad = !1;
          }
        } catch(d) {
          this._flashError(d);
        }
      },
      _flash_resetMedia : function() {
        this.internal.flash.jq.css({
          width : "0px",
          height : "0px"
        });
        this._flash_pause(NaN);
      },
      _flash_clearMedia : function() {
        try {
          this._getMovie().fl_clearMedia();
        } catch(a) {
          this._flashError(a);
        }
      },
      _flash_load : function() {
        try {
          this._getMovie().fl_load();
        } catch(a) {
          this._flashError(a);
        }
        this.status.waitForLoad = !1;
      },
      _flash_play : function(a) {
        try {
          this._getMovie().fl_play(a);
        } catch(b) {
          this._flashError(b);
        }
        this.status.waitForLoad = !1;
        this._flash_checkWaitForPlay();
      },
      _flash_pause : function(a) {
        try {
          this._getMovie().fl_pause(a);
        } catch(b) {
          this._flashError(b);
        }
        if (a > 0) {
          this.status.waitForLoad = !1, this._flash_checkWaitForPlay();
        }
      },
      _flash_playHead : function(a) {
        try {
          this._getMovie().fl_play_head(a);
        } catch(b) {
          this._flashError(b);
        }
        this.status.waitForLoad || this._flash_checkWaitForPlay();
      },
      _flash_checkWaitForPlay : function() {
        if (this.status.waitForPlay) {
          this.status.waitForPlay = !1, this.css.jq.videoPlay.length && this.css.jq.videoPlay.hide(), this.status.video && (this.internal.poster.jq.hide(), this.internal.flash.jq.css({
            width : this.status.width,
            height : this.status.height
          }));
        }
      },
      _flash_volume : function(a) {
        try {
          this._getMovie().fl_volume(a);
        } catch(b) {
          this._flashError(b);
        }
      },
      _flash_mute : function(a) {
        try {
          this._getMovie().fl_mute(a);
        } catch(b) {
          this._flashError(b);
        }
      },
      _getMovie : function() {
        return document[this.internal.flash.id];
      },
      _checkForFlash : function(a) {
        var b = !1, d;
        if (window.ActiveXObject) {
          try {
            new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + a), b = !0;
          } catch(e) {
          }
        } else {
          navigator.plugins && navigator.mimeTypes.length > 0 && ( d = navigator.plugins["Shockwave Flash"]) && navigator.plugins["Shockwave Flash"].description.replace(/.*\s(\d+\.\d+).*/, "$1") >= a && ( b = !0);
        }
        return b;
      },
      _validString : function(a) {
        return a && typeof a === "string";
      },
      _limitValue : function(a, b, d) {
        return a < b ? b : a > d ? d : a;
      },
      _urlNotSetError : function(a) {
        this._error({
          type : b.jPlayer.error.URL_NOT_SET,
          context : a,
          message : b.jPlayer.errorMsg.URL_NOT_SET,
          hint : b.jPlayer.errorHint.URL_NOT_SET
        });
      },
      _flashError : function(a) {
        var c;
        c = this.internal.ready ? "FLASH_DISABLED" : "FLASH";
        this._error({
          type : b.jPlayer.error[c],
          context : this.internal.flash.swf,
          message : b.jPlayer.errorMsg[c] + a.message,
          hint : b.jPlayer.errorHint[c]
        });
        this.internal.flash.jq.css({
          width : "1px",
          height : "1px"
        });
      },
      _error : function(a) {
        this._trigger(b.jPlayer.event.error, a);
        this.options.errorAlerts && this._alert("Error!" + (a.message ? "\n\n" + a.message : "") + (a.hint ? "\n\n" + a.hint : "") + "\n\nContext: " + a.context);
      },
      _warning : function(a) {
        this._trigger(b.jPlayer.event.warning, f, a);
        this.options.warningAlerts && this._alert("Warning!" + (a.message ? "\n\n" + a.message : "") + (a.hint ? "\n\n" + a.hint : "") + "\n\nContext: " + a.context);
      },
      _alert : function(a) {
        alert("jPlayer " + this.version.script + " : id='" + this.internal.self.id + "' : " + a);
      },
      _emulateHtmlBridge : function() {
        var a = this;
        b.each(b.jPlayer.emulateMethods.split(/\s+/g), function(b, d) {
          a.internal.domNode[d] = function(b) {
            a[d](b);
          };
        });
        b.each(b.jPlayer.event, function(c, d) {
          var e = !0;
          b.each(b.jPlayer.reservedEvent.split(/\s+/g), function(a, b) {
            if (b === c) {
              return e = !1;
            }
          });
          e && a.element.bind(d + ".jPlayer.jPlayerHtml", function() {
            a._emulateHtmlUpdate();
            var b = document.createEvent("Event");
            b.initEvent(c, !1, !0);
            a.internal.domNode.dispatchEvent(b);
          });
        });
      },
      _emulateHtmlUpdate : function() {
        var a = this;
        b.each(b.jPlayer.emulateStatus.split(/\s+/g), function(b, d) {
          a.internal.domNode[d] = a.status[d];
        });
        b.each(b.jPlayer.emulateOptions.split(/\s+/g), function(b, d) {
          a.internal.domNode[d] = a.options[d];
        });
      },
      _destroyHtmlBridge : function() {
        var a = this;
        this.element.unbind(".jPlayerHtml");
        b.each((b.jPlayer.emulateMethods + " " + b.jPlayer.emulateStatus + " " + b.jPlayer.emulateOptions).split(/\s+/g), function(b, d) {
          delete a.internal.domNode[d];
        });
      }
    };
    b.jPlayer.error = {
      FLASH : "e_flash",
      FLASH_DISABLED : "e_flash_disabled",
      NO_SOLUTION : "e_no_solution",
      NO_SUPPORT : "e_no_support",
      URL : "e_url",
      URL_NOT_SET : "e_url_not_set",
      VERSION : "e_version"
    };
    b.jPlayer.errorMsg = {
      FLASH : "jPlayer's Flash fallback is not configured correctly, or a command was issued before the jPlayer Ready event. Details: ",
      FLASH_DISABLED : "jPlayer's Flash fallback has been disabled by the browser due to the CSS rules you have used. Details: ",
      NO_SOLUTION : "No solution can be found by jPlayer in this browser. Neither HTML nor Flash can be used.",
      NO_SUPPORT : "It is not possible to play any media format provided in setMedia() on this browser using your current options.",
      URL : "Media URL could not be loaded.",
      URL_NOT_SET : "Attempt to issue media playback commands, while no media url is set.",
      VERSION : "jPlayer " + b.jPlayer.prototype.version.script + " needs Jplayer.swf version " + b.jPlayer.prototype.version.needFlash + " but found "
    };
    b.jPlayer.errorHint = {
      FLASH : "Check your swfPath option and that Jplayer.swf is there.",
      FLASH_DISABLED : "Check that you have not display:none; the jPlayer entity or any ancestor.",
      NO_SOLUTION : "Review the jPlayer options: support and supplied.",
      NO_SUPPORT : "Video or audio formats defined in the supplied option are missing.",
      URL : "Check media URL is valid.",
      URL_NOT_SET : "Use setMedia() to set the media URL.",
      VERSION : "Update jPlayer files."
    };
    b.jPlayer.warning = {
      CSS_SELECTOR_COUNT : "e_css_selector_count",
      CSS_SELECTOR_METHOD : "e_css_selector_method",
      CSS_SELECTOR_STRING : "e_css_selector_string",
      OPTION_KEY : "e_option_key"
    };
    b.jPlayer.warningMsg = {
      CSS_SELECTOR_COUNT : "The number of css selectors found did not equal one: ",
      CSS_SELECTOR_METHOD : "The methodName given in jPlayer('cssSelector') is not a valid jPlayer method.",
      CSS_SELECTOR_STRING : "The methodCssSelector given in jPlayer('cssSelector') is not a String or is empty.",
      OPTION_KEY : "The option requested in jPlayer('option') is undefined."
    };
    b.jPlayer.warningHint = {
      CSS_SELECTOR_COUNT : "Check your css selector and the ancestor.",
      CSS_SELECTOR_METHOD : "Check your method name.",
      CSS_SELECTOR_STRING : "Check your css selector is a string.",
      OPTION_KEY : "Check your option name."
    };
  })(jQuery);
  (function($) {
    var regs = {
      undHash : /_|-/,
      colons : /::/,
      words : /([A-Z]+)([A-Z][a-z])/g,
      lowUp : /([a-z\d])([A-Z])/g,
      dash : /([a-z\d])([A-Z])/g,
      replacer : /\{([^\}]+)\}/g,
      dot : /\./
    }, getNext = function(current, nextPart, add) {
      return current[nextPart] !== undefined ? current[nextPart] : (add && (current[nextPart] = {}));
    }, isContainer = function(current) {
      var type = typeof current;
      return type && (type == "function" || type == "object");
    }, getObject = function(objectName, roots, add) {
      var parts = objectName ? objectName.split(regs.dot) : [], length = parts.length, currents = $.isArray(roots) ? roots : [roots || window], current, ret, i, c = 0, type;
      if (length == 0) {
        return currents[0];
      }
      while ( current = currents[c++]) {
        for ( i = 0; i < length - 1 && isContainer(current); i++) {
          current = getNext(current, parts[i], add);
        }
        if (isContainer(current)) {
          ret = getNext(current, parts[i], add);
          if (ret !== undefined) {
            if (add === false) {
              delete current[parts[i]];
            }
            return ret;
          }
        }
      }
    }, str = $.String = $.extend($.String || {}, {
      getObject : getObject,
      capitalize : function(s, cache) {
        return s.charAt(0).toUpperCase() + s.substr(1);
      },
      camelize : function(s) {
        s = str.classize(s);
        return s.charAt(0).toLowerCase() + s.substr(1);
      },
      classize : function(s, join) {
        var parts = s.split(regs.undHash), i = 0;
        for (; i < parts.length; i++) {
          parts[i] = str.capitalize(parts[i]);
        }
        return parts.join(join || "");
      },
      niceName : function(s) {
        return str.classize(s, " ");
      },
      underscore : function(s) {
        return s.replace(regs.colons, "/").replace(regs.words, "$1_$2").replace(regs.lowUp, "$1_$2").replace(regs.dash, "_").toLowerCase();
      },
      sub : function(s, data, remove) {
        var obs = [];
        obs.push(s.replace(regs.replacer, function(whole, inside) {
          var ob = getObject(inside, data, typeof remove == "boolean" ? !remove : remove), type = typeof ob;
          if ((type === "object" || type === "function") && type !== null) {
            obs.push(ob);
            return "";
          } else {
            return "" + ob;
          }
        }));
        return obs.length <= 1 ? obs[0] : obs;
      },
      _regs : regs
    });
  })(jQuery);
  (function($) {
    var initializing = false, makeArray = $.makeArray, isFunction = $.isFunction, isArray = $.isArray, extend = $.extend, getObject = $.String.getObject, concatArgs = function(arr, args) {
      return arr.concat(makeArray(args));
    }, fnTest = /xyz/.test(function() { xyz;
    }) ? /\b_super\b/ : /.*/, inheritProps = function(newProps, oldProps, addTo) {
      addTo = addTo || newProps;
      for (var name in newProps) {
        addTo[name] = isFunction(newProps[name]) && isFunction(oldProps[name]) && fnTest.test(newProps[name]) ? (function(name, fn) {
          return function() {
            var tmp = this._super, ret;
            this._super = oldProps[name];
            ret = fn.apply(this, arguments);
            this._super = tmp;
            return ret;
          };
        })(name, newProps[name]) : newProps[name];
      }
    }, STR_PROTOTYPE = "prototype";
    clss = $.Class = function() {
      if (arguments.length) {
        clss.extend.apply(clss, arguments);
      }
    };
    extend(clss, {
      proxy : function(funcs) {
        var args = makeArray(arguments), self;
        funcs = args.shift();
        if (!isArray(funcs)) {
          funcs = [funcs];
        }
        self = this;
        return function class_cb() {
          var cur = concatArgs(args, arguments), isString, length = funcs.length, f = 0, func;
          for (; f < length; f++) {
            func = funcs[f];
            if (!func) {
              continue;
            }
            isString = typeof func == "string";
            if (isString && self._set_called) {
              self.called = func;
            }
            cur = ( isString ? self[func] : func).apply(self, cur || []);
            if (f < length - 1) {
              cur = !isArray(cur) || cur._use_call ? [cur] : cur;
            }
          }
          return cur;
        };
      },
      newInstance : function() {
        var inst = this.rawInstance(), args;
        if (inst.setup) {
          args = inst.setup.apply(inst, arguments);
        }
        if (inst.init) {
          inst.init.apply(inst, isArray(args) ? args : arguments);
        }
        return inst;
      },
      setup : function(baseClass, fullName) {
        this.defaults = extend(true, {}, baseClass.defaults, this.defaults);
        return arguments;
      },
      rawInstance : function() {
        initializing = true;
        var inst = new this();
        initializing = false;
        return inst;
      },
      extend : function(fullName, klass, proto) {
        if ( typeof fullName != "string") {
          proto = klass;
          klass = fullName;
          fullName = null;
        }
        if (!proto) {
          proto = klass;
          klass = null;
        }
        proto = proto || {};
        var _super_class = this, _super = this[STR_PROTOTYPE], name, shortName, namespace, prototype;
        initializing = true;
        prototype = new this();
        initializing = false;
        inheritProps(proto, _super, prototype);
        function Class() {
          if (initializing) {
            return;
          }
          if (this.constructor !== Class && arguments.length) {
            return arguments.callee.extend.apply(arguments.callee, arguments);
          } else {
            return this.Class.newInstance.apply(this.Class, arguments);
          }
        }

        for (name in this) {
          if (this.hasOwnProperty(name)) {
            Class[name] = this[name];
          }
        }
        inheritProps(klass, this, Class);
        if (fullName) {
          var parts = fullName.split(/\./), shortName = parts.pop(), current = getObject(parts.join("."), window, true), namespace = current;
          current[shortName] = Class;
        }
        extend(Class, {
          prototype : prototype,
          namespace : namespace,
          shortName : shortName,
          constructor : Class,
          fullName : fullName
        });
        Class[STR_PROTOTYPE].Class = Class[STR_PROTOTYPE].constructor = Class;
        var args = Class.setup.apply(Class, concatArgs([_super_class], arguments));
        if (Class.init) {
          Class.init.apply(Class, args || []);
        }
        return Class;
      }
    });
    clss.callback = clss[STR_PROTOTYPE].callback = clss[STR_PROTOTYPE].proxy = clss.proxy;
  })(jQuery);
  (function($) {
    var oldClean = jQuery.cleanData;
    $.cleanData = function(elems) {
      for (var i = 0, elem; ( elem = elems[i]) !== undefined; i++) {
        $(elem).triggerHandler("destroyed");
      }
      oldClean(elems);
    };
  })(jQuery);
  (function($) {
    var bind = function(el, ev, callback) {
      var wrappedCallback, binder = el.bind && el.unbind ? el : $(isFunction(el) ? [el] : el);
      if (ev.indexOf(">") === 0) {
        ev = ev.substr(1);
        wrappedCallback = function(event) {
          if (event.target === el) {
            callback.apply(this, arguments);
          }
        };
      }
      binder.bind(ev, wrappedCallback || callback);
      return function() {
        binder.unbind(ev, wrappedCallback || callback);
        el = ev = callback = wrappedCallback = null;
      };
    }, makeArray = $.makeArray, isArray = $.isArray, isFunction = $.isFunction, extend = $.extend, Str = $.String, each = $.each, STR_PROTOTYPE = "prototype", STR_CONSTRUCTOR = "constructor", slice = Array[STR_PROTOTYPE].slice, delegate = function(el, selector, ev, callback) {
      var binder = el.delegate && el.undelegate ? el : $(isFunction(el) ? [el] : el);
      binder.delegate(selector, ev, callback);
      return function() {
        binder.undelegate(selector, ev, callback);
        binder = el = ev = callback = selector = null;
      };
    }, binder = function(el, ev, callback, selector) {
      return selector ? delegate(el, selector, ev, callback) : bind(el, ev, callback);
    }, shifter = function shifter(context, name) {
      var method = typeof name == "string" ? context[name] : name;
      return function() {
        context.called = name;
        return method.apply(context, [this.nodeName ? $(this) : this].concat(slice.call(arguments, 0)));
      };
    }, dotsReg = /\./g, controllersReg = /_?controllers?/ig, underscoreAndRemoveController = function(className) {
      return Str.underscore(className.replace("jQuery.", "").replace(dotsReg, "_").replace(controllersReg, ""));
    }, actionMatcher = /[^\w]/, parameterReplacer = /\{([^\}]+)\}/g, breaker = /^(?:(.*?)\s)?([\w\.\:>]+)$/, basicProcessor, data = function(el, data) {
      return $.data(el, "controllers", data);
    };
    $.Class("jQuery.Controller", {
      setup : function() {
        this._super.apply(this, arguments);
        if (!this.shortName || this.fullName == "jQuery.Controller") {
          return;
        }
        this._fullName = underscoreAndRemoveController(this.fullName);
        this._shortName = underscoreAndRemoveController(this.shortName);
        var controller = this, pluginname = this.pluginName || this._fullName, funcName, forLint;
        if (!$.fn[pluginname]) {
          $.fn[pluginname] = function(options) {
            var args = makeArray(arguments), isMethod = typeof options == "string" && isFunction(controller[STR_PROTOTYPE][options]), meth = args[0];
            return this.each(function() {
              var controllers = data(this), plugin = controllers && controllers[pluginname];
              if (plugin) {
                if (isMethod) {
                  plugin[meth].apply(plugin, args.slice(1));
                } else {
                  plugin.update.apply(plugin, args);
                }
              } else {
                controller.newInstance.apply(controller, [this].concat(args));
              }
            });
          };
        }
        this.actions = {};
        for (funcName in this[STR_PROTOTYPE]) {
          if (funcName == "constructor" || !isFunction(this[STR_PROTOTYPE][funcName])) {
            continue;
          }
          if (this._isAction(funcName)) {
            this.actions[funcName] = this._action(funcName);
          }
        }
      },
      hookup : function(el) {
        return new this(el);
      },
      _isAction : function(methodName) {
        if (actionMatcher.test(methodName)) {
          return true;
        } else {
          return $.inArray(methodName, this.listensTo) > -1 || $.event.special[methodName] || processors[methodName];
        }
      },
      _action : function(methodName, options) {
        parameterReplacer.lastIndex = 0;
        if (!options && parameterReplacer.test(methodName)) {
          return null;
        }
        var convertedName = options ? Str.sub(methodName, [options, window]) : methodName, arr = isArray(convertedName), parts = ( arr ? convertedName[1] : convertedName).match(breaker), event = parts[2], processor = processors[event] || basicProcessor;
        return {
          processor : processor,
          parts : parts,
          delegate : arr ? convertedName[0] : undefined
        };
      },
      processors : {},
      listensTo : [],
      defaults : {}
    }, {
      setup : function(element, options) {
        var funcName, ready, cls = this[STR_CONSTRUCTOR];
        element = element.jquery ? element[0] : element;
        var pluginname = cls.pluginName || cls._fullName;
        this.element = $(element).addClass(pluginname);
        (data(element)||data(element,{}))[pluginname] = this;
        this.options = extend(extend(true, {}, cls.defaults), options);
        this.called = "init";
        this.bind();
        return this.element;
      },
      bind : function(el, eventName, func) {
        if (el === undefined) {
          this._bindings = [];
          var cls = this[STR_CONSTRUCTOR], bindings = this._bindings, actions = cls.actions, element = this.element;
          for (funcName in actions) {
            if (actions.hasOwnProperty(funcName)) {
              ready = actions[funcName] || cls._action(funcName, this.options);
              bindings.push(ready.processor(ready.delegate || element, ready.parts[2], ready.parts[1], funcName, this));
            }
          }
          var destroyCB = shifter(this, "destroy");
          element.bind("destroyed", destroyCB);
          bindings.push(function(el) {
            $(el).unbind("destroyed", destroyCB);
          });
          return bindings.length;
        }
        if ( typeof el == "string") {
          func = eventName;
          eventName = el;
          el = this.element;
        }
        return this._binder(el, eventName, func);
      },
      _binder : function(el, eventName, func, selector) {
        if ( typeof func == "string") {
          func = shifter(this, func);
        }
        this._bindings.push(binder(el, eventName, func, selector));
        return this._bindings.length;
      },
      _unbind : function() {
        var el = this.element[0];
        each(this._bindings, function(key, value) {
          value(el);
        });
        this._bindings = [];
      },
      delegate : function(element, selector, eventName, func) {
        if ( typeof element == "string") {
          func = eventName;
          eventName = selector;
          selector = element;
          element = this.element;
        }
        return this._binder(element, eventName, func, selector);
      },
      update : function(options) {
        extend(this.options, options);
        this._unbind();
        this.bind();
      },
      destroy : function() {
        if (this._destroyed) {
          throw this[STR_CONSTRUCTOR].shortName + " controller already deleted";
        }
        var self = this, fname = this[STR_CONSTRUCTOR].pluginName || this[STR_CONSTRUCTOR]._fullName, controllers;
        this._destroyed = true;
        this.element.removeClass(fname);
        this._unbind();
        delete this._actions;
        delete this.element.data("controllers")[fname];
        $(this).triggerHandler("destroyed");
        this.element = null;
      },
      find : function(selector) {
        return this.element.find(selector);
      },
      _set_called : true
    });
    var processors = $.Controller.processors, basicProcessor = function(el, event, selector, methodName, controller) {
      return binder(el, event, shifter(controller, methodName), selector);
    };
    each("change click contextmenu dblclick keydown keyup keypress mousedown mousemove mouseout mouseover mouseup reset resize scroll select submit focusin focusout mouseenter mouseleave".split(" "), function(i, v) {
      processors[v] = basicProcessor;
    });
    var i, isAControllerOf = function(instance, controllers) {
      for ( i = 0; i < controllers.length; i++) {
        if ( typeof controllers[i] == "string" ? instance[STR_CONSTRUCTOR]._shortName == controllers[i] : instance instanceof controllers[i]) {
          return true;
        }
      }
      return false;
    };
    $.fn.extend({
      controllers : function() {
        var controllerNames = makeArray(arguments), instances = [], controllers, c, cname;
        this.each(function() {
          controllers = $.data(this, "controllers");
          for (cname in controllers) {
            if (controllers.hasOwnProperty(cname)) {
              c = controllers[cname];
              if (!controllerNames.length || isAControllerOf(c, controllerNames)) {
                instances.push(c);
              }
            }
          }
        });
        return instances;
      },
      controller : function(controller) {
        return this.controllers.apply(this,arguments)[0];
      }
    });
  })(jQuery);
  (function() {
    var underscore = $.String.underscore, classize = $.String.classize, isArray = $.isArray, makeArray = $.makeArray, extend = $.extend, each = $.each, reqType = /GET|POST|PUT|DELETE/i, ajax = function(ajaxOb, attrs, success, error, fixture, type, dataType) {
      var dataType = dataType || "json", src = "", tmp;
      if ( typeof ajaxOb == "string") {
        var sp = ajaxOb.indexOf(" ");
        if (sp > 2 && sp < 7) {
          tmp = ajaxOb.substr(0, sp);
          if (reqType.test(tmp)) {
            type = tmp;
          } else {
            dataType = tmp;
          }
          src = ajaxOb.substr(sp + 1);
        } else {
          src = ajaxOb;
        }
      }
      typeof attrs == "object" && (!isArray(attrs)) && ( attrs = extend({}, attrs));
      var url = $.String.sub(src, attrs, true);
      return $.ajax({
        url : url,
        data : attrs,
        success : success,
        error : error,
        type : type || "post",
        dataType : dataType,
        fixture : fixture
      });
    }, fixture = function(extra, or) {
      var u = underscore(this.shortName), f = "-" + u + (extra || "");
      return $.fixture && $.fixture[f] ? f : or || "//" + underscore(this.fullName).replace(/\.models\..*/, "").replace(/\./g, "/") + "/fixtures/" + u + (extra || "") + ".json";
    }, addId = function(attrs, id) {
      attrs = attrs || {};
      var identity = this.id;
      if (attrs[identity] && attrs[identity] !== id) {
        attrs["new" + $.String.capitalize(id)] = attrs[identity];
        delete attrs[identity];
      }
      attrs[identity] = id;
      return attrs;
    }, getList = function(type) {
      var listType = type || $.Model.List || Array;
      return new listType();
    }, getId = function(inst) {
      return inst[inst.constructor.id];
    }, unique = function(items) {
      var collect = [];
      for (var i = 0; i < items.length; i++) {
        if (!items[i]["__u Nique"]) {
          collect.push(items[i]);
          items[i]["__u Nique"] = true;
        }
      }
      for ( i = 0; i < collect.length; i++) {
        delete collect[i]["__u Nique"];
      }
      return collect;
    }, makeRequest = function(self, type, success, error, method) {
      var deferred = $.Deferred(), resolve = function(data) {
        self[method||type+"d"](data);
        deferred.resolveWith(self, [self, data, type]);
      }, reject = function(data) {
        deferred.rejectWith(self, [data]);
      }, args = [self.serialize(), resolve, reject], constructor = self.constructor;
      if (type == "destroy") {
        args.shift();
      }
      if (type !== "create") {
        args.unshift(getId(self));
      }
      deferred.then(success);
      deferred.fail(error);
      constructor[type].apply(constructor, args);
      return deferred.promise();
    }, isObject = function(obj) {
      return typeof obj === "object" && obj !== null && obj;
    }, $method = function(name) {
      return function(eventType, handler) {
        $.fn[name].apply($([this]), arguments);
        return this;
      };
    }, bind = $method("bind"), unbind = $method("unbind"), STR_CONSTRUCTOR = "constructor";
    ajaxMethods = {
      create : function(str) {
        return function(attrs, success, error) {
          return ajax(str, attrs, success, error, fixture.call(this, "Create", "-restCreate"));
        };
      },
      update : function(str) {
        return function(id, attrs, success, error) {
          return ajax(str, addId.call(this, attrs, id), success, error, fixture.call(this, "Update", "-restUpdate"), "put");
        };
      },
      destroy : function(str) {
        return function(id, success, error) {
          var attrs = {};
          attrs[this.id] = id;
          return ajax(str, attrs, success, error, fixture.call(this, "Destroy", "-restDestroy"), "delete");
        };
      },
      findAll : function(str) {
        return function(params, success, error) {
          return ajax(str || this.shortName + "s.json", params, success, error, fixture.call(this, "s"), "get", "json " + this._shortName + ".models");
        };
      },
      findOne : function(str) {
        return function(params, success, error) {
          return ajax(str, params, success, error, fixture.call(this), "get", "json " + this._shortName + ".model");
        };
      }
    };
    jQuery.Class("jQuery.Model", {
      setup : function(superClass, stat, proto) {
        var self = this;
        each(["attributes", "associations", "validations"], function(i, name) {
          if (!self[name] || superClass[name] === self[name]) {
            self[name] = {};
          }
        });
        each(["convert", "serialize"], function(i, name) {
          if (superClass[name] != self[name]) {
            self[name] = extend({}, superClass[name], self[name]);
          }
        });
        this._fullName = underscore(this.fullName.replace(/\./g, "_"));
        this._shortName = underscore(this.shortName);
        if (this.fullName.substr(0, 7) == "jQuery.") {
          return;
        }
        if (this.listType) {
          this.list = new this.listType([]);
        }
        for (var name in ajaxMethods) {
          if ( typeof this[name] !== "function") {
            this[name] = ajaxMethods[name](this[name]);
          }
        }
        var converters = {}, convertName = "* " + this._shortName + ".model";
        converters[convertName + "s"] = this.proxy("models");
        converters[convertName] = this.proxy("model");
        $.ajaxSetup({
          converters : converters
        });
      },
      attributes : {},
      model : function(attributes) {
        if (!attributes) {
          return null;
        }
        if ( attributes instanceof this) {
          attributes = attributes.serialize();
        }
        return new this(isObject(attributes[this._shortName]) || isObject(attributes.data) || isObject(attributes.attributes) || attributes);
      },
      models : function(instancesRawData) {
        if (!instancesRawData) {
          return null;
        }
        var res = getList(this.List), arr = isArray(instancesRawData), ml = ($.Model.List && instancesRawData instanceof $.Model.List), raw = arr ? instancesRawData : ( ml ? instancesRawData.serialize() : instancesRawData.data), length = raw.length, i = 0;
        res._use_call = true;
        for (; i < length; i++) {
          res.push(this.model(raw[i]));
        }
        if (!arr) {
          for (var prop in instancesRawData) {
            if (prop !== "data") {
              res[prop] = instancesRawData[prop];
            }
          }
        }
        return res;
      },
      id : "id",
      addAttr : function(property, type) {
        var stub;
        if (this.associations[property]) {
          return;
        }
        stub = this.attributes[property] || (this.attributes[property] = type);
        return type;
      },
      _models : {},
      publish : function(event, data) {
        if (window.OpenAjax) {
          OpenAjax.hub.publish(this._shortName + "." + event, data);
        }
      },
      guessType : function() {
        return "string";
      },
      convert : {
        date : function(str) {
          var type = typeof str;
          if (type === "string") {
            return isNaN(Date.parse(str)) ? null : Date.parse(str);
          } else {
            if (type === "number") {
              return new Date(str);
            } else {
              return str;
            }
          }
        },
        number : function(val) {
          return parseFloat(val);
        },
        "boolean" : function(val) {
          return Boolean(val);
        },
        "default" : function(val, error, type) {
          var construct = $.String.getObject(type), context = window, realType;
          if (type.indexOf(".") >= 0) {
            realType = type.substring(0, type.lastIndexOf("."));
            context = $.String.getObject(realType);
          }
          return typeof construct == "function" ? construct.call(context, val) : val;
        }
      },
      serialize : {
        "default" : function(val, type) {
          return isObject(val) && val.serialize ? val.serialize() : val;
        }
      },
      bind : bind,
      unbind : unbind,
      _ajax : ajax
    }, {
      setup : function(attributes) {
        this._init = true;
        this.attrs(extend({}, this.constructor.defaults, attributes));
        delete this._init;
      },
      update : function(attrs, success, error) {
        this.attrs(attrs);
        return this.save(success, error);
      },
      errors : function(attrs) {
        if (attrs) {
          attrs = isArray(attrs) ? attrs : makeArray(arguments);
        }
        var errors = {}, self = this, addErrors = function(attr, funcs) {
          each(funcs, function(i, func) {
            var res = func.call(self);
            if (res) {
              if (!errors.hasOwnProperty(attr)) {
                errors[attr] = [];
              }
              errors[attr].push(res);
            }
          });
        }, validations = this.constructor.validations;
        each(attrs || validations || {}, function(attr, funcs) {
          if ( typeof attr == "number") {
            attr = funcs;
            funcs = validations[attr];
          }
          addErrors(attr, funcs || []);
        });
        for (var attr in errors) {
          if (errors.hasOwnProperty(attr)) {
            return errors;
          }
        }
        return null;
      },
      attr : function(attribute, value, success, error) {
        var cap = classize(attribute), get = "get" + cap;
        if (value !== undefined) {
          this._setProperty(attribute, value, success, error, cap);
          return this;
        }
        return this[get] ? this[get]() : this[attribute];
      },
      bind : bind,
      unbind : unbind,
      _setProperty : function(property, value, success, error, capitalized) {
        var setName = "set" + capitalized, old = this[property], self = this, errorCallback = function(errors) {
          var stub;
          stub = error && error.call(self, errors);
          $(self).triggerHandler("error." + property, errors);
        };
        if (this[setName] && ( value = this[setName](value, this.proxy("_updateProperty", property, value, old, success, errorCallback), errorCallback)) === undefined) {
          return;
        }
        this._updateProperty(property, value, old, success, errorCallback);
      },
      _updateProperty : function(property, value, old, success, errorCallback) {
        var Class = this.constructor, val, type = Class.attributes[property] || Class.addAttr(property, Class.guessType(value)), converter = Class.convert[type] || Class.convert["default"], errors = null, prefix = "", global = "updated.", args, globalArgs, callback = success, list = Class.list;
        val = this[property] = (value === null ? null : converter.call(Class, value, function() {
        }, type));
        if (!this._init) {
          errors = this.errors(property);
        }
        args = [val];
        globalArgs = [property, val, old];
        if (errors) {
          prefix = global = "error.";
          callback = errorCallback;
          globalArgs.splice(1, 0, errors);
          args.unshift(errors);
        }
        if (old !== val && !this._init) {
          !errors && $(this).triggerHandler(prefix + property, args);
          $(this).triggerHandler(global + "attr", globalArgs);
        }
        callback && callback.apply(this, args);
        if (property === Class.id && val !== null && list) {
          if (!old) {
            list.push(this);
          } else {
            if (old != val) {
              list.remove(old);
              list.push(this);
            }
          }
        }
      },
      removeAttr : function(attr) {
        var old = this[attr], deleted = false, attrs = this.constructor.attributes;
        if (this[attr]) {
          delete this[attr];
        }
        if (attrs[attr]) {
          delete attrs[attr];
          deleted = true;
        }
        if (!this._init && deleted && old) {
          $(this).triggerHandler("updated.attr", [attr, null, old]);
        }
      },
      attrs : function(attributes) {
        var key, constructor = this.constructor, attrs = constructor.attributes;
        if (!attributes) {
          attributes = {};
          for (key in attrs) {
            if (attrs.hasOwnProperty(key)) {
              attributes[key] = this.attr(key);
            }
          }
        } else {
          var idName = constructor.id;
          for (key in attributes) {
            if (key != idName) {
              this.attr(key, attributes[key]);
            }
          }
          if ( idName in attributes) {
            this.attr(idName, attributes[idName]);
          }
        }
        return attributes;
      },
      serialize : function() {
        var Class = this.constructor, attrs = Class.attributes, type, converter, data = {}, attr;
        attributes = {};
        for (attr in attrs) {
          if (attrs.hasOwnProperty(attr)) {
            type = attrs[attr];
            converter = Class.serialize[type] || Class.serialize["default"];
            data[attr] = converter(this[attr], type);
          }
        }
        return data;
      },
      isNew : function() {
        var id = getId(this);
        return (id === undefined || id === null);
      },
      save : function(success, error) {
        return makeRequest(this, this.isNew() ? "create" : "update", success, error);
      },
      destroy : function(success, error) {
        return makeRequest(this, "destroy", success, error, "destroyed");
      },
      identity : function() {
        var id = getId(this), constructor = this.constructor;
        return (constructor._fullName + "_" + (constructor.escapeIdentity ? encodeURIComponent(id) : id)).replace(/ /g, "_");
      },
      elements : function(context) {
        return $("." + this.identity(), context);
      },
      publish : function(event, data) {
        this.constructor.publish(event, data || this);
      },
      hookup : function(el) {
        var shortName = this.constructor._shortName, models = $.data(el, "models") || $.data(el, "models", {});
        $(el).addClass(shortName + " " + this.identity());
        models[shortName] = this;
      }
    });
    each(["created", "updated", "destroyed"], function(i, funcName) {
      $.Model.prototype[funcName] = function(attrs) {
        var stub, constructor = this.constructor;
        if (funcName === "destroyed" && constructor.list) {
          constructor.list.remove(getId(this));
        }
        stub = attrs && typeof attrs == "object" && this.attrs(attrs.attrs ? attrs.attrs() : attrs);
        $(this).triggerHandler(funcName);
        this.publish(funcName, this);
        $([constructor]).triggerHandler(funcName, this);
        return [this].concat(makeArray(arguments));
      };
    });
    $.fn.models = function(type) {
      var collection = [], kind, ret, retType;
      this.each(function() {
        each($.data(this, "models") || {}, function(name, instance) {
          kind = kind === undefined ? instance.constructor.List || null : (instance.constructor.List === kind ? kind : null);
          collection.push(instance);
        });
      });
      ret = getList(kind);
      ret.push.apply(ret, unique(collection));
      return ret;
    };
    $.fn.model = function(type) {
      if (type && type instanceof $.Model) {
        type.hookup(this[0]);
        return this;
      } else {
        return this.models.apply(this,arguments)[0];
      }
    };
  })(jQuery);
  (function($) {
    var getArgs = function(args) {
      if (args[0] && ($.isArray(args[0]))) {
        return args[0];
      } else {
        if (args[0] instanceof $.Model.List) {
          return $.makeArray(args[0]);
        } else {
          return $.makeArray(args);
        }
      }
    }, id = 0, getIds = function(item) {
      return item[item.constructor.id];
    }, expando = jQuery.expando, each = $.each, ajax = $.Model._ajax, ajaxMethods = {
      update : function(str) {
        return function(ids, attrs, success, error) {
          return ajax(str, {
            ids : ids,
            attrs : attrs
          }, success, error, "-updateAll", "put");
        };
      },
      destroy : function(str) {
        return function(ids, success, error) {
          return ajax(str, ids, success, error, "-destroyAll", "post");
        };
      }
    };
    $.Class("jQuery.Model.List", {
      setup : function() {
        for (var name in ajaxMethods) {
          if ( typeof this[name] !== "function") {
            this[name] = ajaxMethods[name](this[name]);
          }
        }
      }
    }, {
      init : function(instances, noEvents) {
        this.length = 0;
        this._data = {};
        this._namespace = ".list" + (++id), this.push.apply(this, $.makeArray(instances || []));
      },
      slice : function() {
        return new this.Class(Array.prototype.slice.apply(this, arguments));
      },
      match : function(property, value) {
        return this.grep(function(inst) {
          return inst[property] == value;
        });
      },
      grep : function(callback, args) {
        return new this.Class($.grep(this, callback, args));
      },
      _makeData : function() {
        var data = this._data = {};
        this.each(function(i, inst) {
          data[inst[inst.constructor.id]] = inst;
        });
      },
      get : function() {
        if (!this.length) {
          return new this.Class([]);
        }
        if (this._changed) {
          this._makeData();
        }
        var list = [], constructor = this[0].constructor, underscored = constructor._fullName, idName = constructor.id, test = new RegExp(underscored + "_([^ ]+)"), matches, val, args = getArgs(arguments);
        for (var i = 0; i < args.length; i++) {
          if (args[i].nodeName && ( matches = args[i].className.match(test))) {
            val = this._data[matches[1]];
          } else {
            val = this._data[ typeof args[i] == "string" || typeof args[i] == "number" ? args[i] : args[i][idName]];
          }
          val && list.push(val);
        }
        return new this.Class(list);
      },
      remove : function(args) {
        if (!this.length) {
          return [];
        }
        var list = [], constructor = this[0].constructor, underscored = constructor._fullName, idName = constructor.id, test = new RegExp(underscored + "_([^ ]+)"), matches, val;
        args = getArgs(arguments);
        var i = 0;
        while (i < this.length) {
          var inst = this[i], found = false;
          for (var a = 0; a < args.length; a++) {
            var id = (args[a].nodeName && ( matches = args[a].className.match(test)) && matches[1]) || ( typeof args[a] == "string" || typeof args[a] == "number" ? args[a] : args[a][idName]);
            if (inst[idName] == id) {
              list.push.apply(list, this.splice(i, 1));
              args.splice(a, 1);
              found = true;
              break;
            }
          }
          if (!found) {
            i++;
          }
        }
        var ret = new this.Class(list);
        if (ret.length) {
          $([this]).trigger("remove", [ret]);
        }
        return ret;
      },
      elements : function(context) {
        return $(this.map(function(item) {
          return "." + item.identity();
        }).join(","), context);
      },
      model : function() {
        return this.constructor.namespace;
      },
      findAll : function(params, success, error) {
        var self = this;
        this.model().findAll(params, function(items) {
          self.push(items);
          success && success(self);
        }, error);
      },
      destroy : function(success, error) {
        var ids = this.map(getIds), items = this.slice(0, this.length);
        if (ids.length) {
          this.constructor.destroy(ids, function() {
            each(items, function() {
              this.destroyed();
            });
            success && success(items);
          }, error);
        } else {
          success && success(this);
        }
        return this;
      },
      update : function(attrs, success, error) {
        var ids = this.map(getIds), items = this.slice(0, this.length);
        if (ids.length) {
          this.constructor.update(ids, attrs, function(newAttrs) {
            var attributes = $.extend(attrs, newAttrs || {});
            each(items, function() {
              this.updated(attributes);
            });
            success && success(items);
          }, error);
        } else {
          success && success(this);
        }
        return this;
      },
      bind : function() {
        if (this[expando] === undefined) {
          this.bindings(this);
        }
        $.fn.bind.apply($([this]), arguments);
        return this;
      },
      unbind : function() {
        $.fn.unbind.apply($([this]), arguments);
        if (this[expando] === undefined) {
          $(this).unbind(this._namespace);
        }
        return this;
      },
      bindings : function(items) {
        var self = this;
        $(items).bind("destroyed" + this._namespace, function() {
          self.remove(this);
        }).bind("updated" + this._namespace, function() {
          $([self]).trigger("updated", this);
        });
      },
      push : function() {
        var args = getArgs(arguments), self = this;
        if (this[expando] !== undefined) {
          this.bindings(args);
        }
        this._changed = true;
        var res = push.apply(this, args);
        if (this[expando] && args.length) {
          $([this]).trigger("add", [args]);
        }
        return res;
      },
      serialize : function() {
        return this.map(function(item) {
          return item.serialize();
        });
      }
    });
    var push = [].push, modifiers = {
      pop : [].pop,
      shift : [].shift,
      unshift : [].unshift,
      splice : [].splice,
      sort : [].sort
    };
    each(modifiers, function(name, func) {
      $.Model.List.prototype[name] = function() {
        this._changed = true;
        return func.apply(this, arguments);
      };
    });
    each(["each", "map"], function(i, name) {
      $.Model.List.prototype[name] = function(callback, args) {
        return $[name](this, callback, args);
      };
    });
  })(jQuery);
  (function($) {
    var validate = function(attrNames, options, proc) {
      if (!proc) {
        proc = options;
        options = {};
      }
      options = options || {};
      attrNames = $.makeArray(attrNames);
      if (options.testIf && !options.testIf.call(this)) {
        return;
      }
      var self = this;
      $.each(attrNames, function(i, attrName) {
        if (!self.validations[attrName]) {
          self.validations[attrName] = [];
        }
        self.validations[attrName].push(function() {
          var res = proc.call(this, this[attrName]);
          return res === undefined ? undefined : (options.message || res);
        });
      });
    };
    $.extend($.Model, {
      validate : validate,
      validationMessages : {
        format : "is invalid",
        inclusion : "is not a valid option (perhaps out of range)",
        lengthShort : "is too short",
        lengthLong : "is too long",
        presence : "can't be empty",
        range : "is out of range"
      },
      validateFormatOf : function(attrNames, regexp, options) {
        validate.call(this, attrNames, options, function(value) {
          if (( typeof value != "undefined" && value != "") && String(value).match(regexp) == null) {
            return this.Class.validationMessages.format;
          }
        });
      },
      validateInclusionOf : function(attrNames, inArray, options) {
        validate.call(this, attrNames, options, function(value) {
          if ( typeof value == "undefined") {
            return;
          }
          if ($.grep(inArray, function(elm) {
            return (elm == value);
          }).length == 0) {
            return this.Class.validationMessages.inclusion;
          }
        });
      },
      validateLengthOf : function(attrNames, min, max, options) {
        validate.call(this, attrNames, options, function(value) {
          if (( typeof value == "undefined" && min > 0) || value.length < min) {
            return this.Class.validationMessages.lengthShort + " (min=" + min + ")";
          } else {
            if ( typeof value != "undefined" && value.length > max) {
              return this.Class.validationMessages.lengthLong + " (max=" + max + ")";
            }
          }
        });
      },
      validatePresenceOf : function(attrNames, options) {
        validate.call(this, attrNames, options, function(value) {
          if ( typeof value == "undefined" || value == "" || value === null) {
            return this.Class.validationMessages.presence;
          }
        });
      },
      validateRangeOf : function(attrNames, low, hi, options) {
        validate.call(this, attrNames, options, function(value) {
          if ( typeof value != "undefined" && value < low || value > hi) {
            return this.Class.validationMessages.range + " [" + low + "," + hi + "]";
          }
        });
      }
    });
  })(jQuery);
  (function($) {
    var fake_onhashchange, jq_event_special = $.event.special, str_location = "location", str_hashchange = "hashchange", str_href = "href", browser = $.browser, mode = document.documentMode, is_old_ie = browser.msie && (mode === undefined || mode < 8), supports_onhashchange = "on" + str_hashchange in window && !is_old_ie;
    function get_fragment(url) {
      url = url || window[str_location][str_href];
      return url.replace(/^[^#]*#?(.*)$/, "$1");
    }
    $[str_hashchange + "Delay"] = 100;
    jq_event_special[str_hashchange] = $.extend(jq_event_special[str_hashchange], {
      setup : function() {
        if (supports_onhashchange) {
          return false;
        }
        $(fake_onhashchange.start);
      },
      teardown : function() {
        if (supports_onhashchange) {
          return false;
        }
        $(fake_onhashchange.stop);
      }
    });
    fake_onhashchange = (function() {
      var self = {}, timeout_id, iframe, set_history, get_history;
      function init() {
        set_history = get_history = function(val) {
          return val;
        };
        if (is_old_ie) {
          iframe = $('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;
          get_history = function() {
            return get_fragment(iframe.document[str_location][str_href]);
          };
          set_history = function(hash, history_hash) {
            if (hash !== history_hash) {
              var doc = iframe.document;
              doc.open().close();
              doc[str_location].hash = "#" + hash;
            }
          };
          set_history(get_fragment());
        }
      }
      self.start = function() {
        if (timeout_id) {
          return;
        }
        var last_hash = get_fragment();
        set_history || init();
        if (!navigator.userAgent.match(/Rhino/)) {
          (function loopy() {
            var hash = get_fragment(), history_hash = get_history(last_hash);
            if (hash !== last_hash) {
              set_history( last_hash = hash, history_hash);
              $(window).trigger(str_hashchange);
            } else {
              if (history_hash !== last_hash) {
                window[str_location][str_href] = window[str_location][str_href].replace(/#.*/, "") + "#" + history_hash;
              }
            }
            timeout_id = setTimeout(loopy, $[str_hashchange + "Delay"]);
          })();
        }
      };
      self.stop = function() {
        if (!iframe) {
          timeout_id && clearTimeout(timeout_id);
          timeout_id = 0;
        }
      };
      return self;
    })();
  })(jQuery);
  (function() {
    var $event = $.event, oldTrigger = $event.trigger, isElement = function(o) {
      return ( typeof HTMLElement === "object" ? o instanceof HTMLElement : typeof o === "object" && o.nodeType === 1 && typeof o.nodeName === "string") || (o === window) || (o === document);
    };
    $.event.trigger = function(event, data, elem, onlyHandlers) {
      var type = event.type || event, namespaces = [], exclusive;
      if (type.indexOf("!") >= 0) {
        type = type.slice(0, -1);
        exclusive = true;
      }
      if (type.indexOf(".") >= 0) {
        namespaces = type.split(".");
        type = namespaces.shift();
        namespaces.sort();
      }
      if ((!elem || jQuery.event.customEvent[type]) && !jQuery.event.global[type]) {
        return;
      }
      event = typeof event === "object" ? event[jQuery.expando] ? event : new jQuery.Event(type, event) : new jQuery.Event(type);
      event.type = type;
      event.exclusive = exclusive;
      event.namespace = namespaces.join(".");
      event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
      if (onlyHandlers || !elem) {
        event.preventDefault();
        event.stopPropagation();
      }
      if (!elem) {
        jQuery.each(jQuery.cache, function() {
          var internalKey = jQuery.expando, internalCache = this[internalKey];
          if (internalCache && internalCache.events && internalCache.events[type]) {
            jQuery.event.trigger(event, data, internalCache.handle.elem);
          }
        });
        return;
      }
      if (elem.nodeType === 3 || elem.nodeType === 8) {
        return;
      }
      event.result = undefined;
      event.target = elem;
      data = data ? jQuery.makeArray(data) : [];
      data.unshift(event);
      var cur = elem, ontype = type.indexOf(":") < 0 ? "on" + type : "";
      do {
        var handle = jQuery._data(cur, "handle");
        event.currentTarget = cur;
        if (handle) {
          handle.apply(cur, data);
        }
        if (ontype && jQuery.acceptData(cur) && cur[ontype] && cur[ontype].apply(cur, data) === false) {
          event.result = false;
          event.preventDefault();
        }
        cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window;
      } while(cur&&!event.isPropagationStopped());
      if (!event.isDefaultPrevented()) {
        var old, special = jQuery.event.special[type] || {};
        if ((!special._default || special._default.call(elem.ownerDocument, event) === false) && !(type === "click" && jQuery.nodeName(elem, "a")) && jQuery.acceptData(elem)) {
          try {
            if (ontype && elem[type]) {
              old = elem[ontype];
              if (old) {
                elem[ontype] = null;
              }
              jQuery.event.triggered = type;
              elem[type]();
            }
          } catch(ieError) {
          }
          if (old) {
            elem[ontype] = old;
          }
          jQuery.event.triggered = undefined;
        }
      }
      return event.result;
    };
    $.event.handle = function(event) {
      event = jQuery.event.fix(event || window.event);
      var handlers = ((jQuery._data(this,"events")||{})[event.type] || []).slice(0), run_all = !event.exclusive && !event.namespace, args = Array.prototype.slice.call(arguments, 0);
      args[0] = event;
      event.currentTarget = this;
      var oldType = event.type, runDefault = event.type !== "default" && $event.special["default"] && !event.originalEvent && isElement(event.target);
      if (runDefault) {
        $event.special["default"].triggerDefault(event, this, args[1]);
      }
      event.type = oldType;
      for (var j = 0, l = handlers.length; j < l; j++) {
        var handleObj = handlers[j];
        if (event.firstPass) {
          event.firstPass = false;
          continue;
        }
        if (run_all || event.namespace_re.test(handleObj.namespace)) {
          event.handler = handleObj.handler;
          event.data = handleObj.data;
          event.handleObj = handleObj;
          var ret = handleObj.handler.apply(this, args);
          if (ret !== undefined) {
            event.result = ret;
            if (ret === false) {
              event.preventDefault();
              event.stopPropagation();
            }
          }
          if (event.isImmediatePropagationStopped()) {
            break;
          }
        }
      }
      if (runDefault) {
        $event.special["default"].checkAndRunDefaults(event, this);
      }
      return event.result;
    };
  })(jQuery);
  (function($) {
    $.fn.triggerAsync = function(type, data, success, prevented) {
      if ( typeof data == "function") {
        success = data;
        data = undefined;
      }
      if (this[0]) {
        var event = $.Event(type), old = event.preventDefault;
        event.preventDefault = function() {
          old.apply(this, arguments);
          prevented && prevented(this);
        };
        jQuery.event.trigger({
          type : type,
          _success : success
        }, data, this[0]);
      } else {
        success.call(this);
      }
      return this;
    };
    var types = {}, rnamespaces = /\.(.*)$/, $event = $.event;
    $event.special["default"] = {
      add : function(handleObj) {
        types[handleObj.namespace.replace(rnamespaces, "")] = true;
        var origHandler = handleObj.handler;
        handleObj.origHandler = origHandler;
        handleObj.handler = function(ev, data) {
          if (!ev._defaultActions) {
            ev._defaultActions = [];
          }
          ev._defaultActions.push({
            element : this,
            handler : origHandler,
            event : ev,
            data : data,
            currentTarget : ev.currentTarget
          });
        };
      },
      setup : function() {
        return true;
      },
      triggerDefault : function(event, elem, data) {
        var defaultGetter = jQuery.Event("default." + event.type);
        $.extend(defaultGetter, {
          target : elem,
          _defaultActions : event._defaultActions,
          exclusive : true
        });
        defaultGetter.stopPropagation();
        if (elem) {
          var type = defaultGetter.type || event, namespaces = [], exclusive;
          if (type.indexOf("!") >= 0) {
            type = type.slice(0, -1);
            exclusive = true;
          }
          if (type.indexOf(".") >= 0) {
            namespaces = type.split(".");
            type = namespaces.shift();
            namespaces.sort();
          }
          defaultGetter.type = type;
          defaultGetter.exclusive = exclusive;
          $event.handle.call(elem, defaultGetter, data);
        }
      },
      checkAndRunDefaults : function(event, elem) {
        if (!event.isDefaultPrevented() && (!event.isPaused || !event.isPaused()) && event._defaultActions && ((event.isPropagationStopped()) || (!elem.parentNode && !elem.ownerDocument))) {
          var origNamespace = event.namespace, origType = event.type, origLiveFired = event.liveFired;
          event.namespace = event.type;
          event.type = "default";
          event.liveFired = null;
          for (var i = 0; i < event._defaultActions.length; i++) {
            var a = event._defaultActions[i], oldHandle = event.handled;
            event.currentTarget = a.currentTarget;
            a.handler.call(a.element, event, a.data);
            event.handled = event.handled === null ? oldHandle : true;
          }
          event._defaultActions = null;
          if (event._success) {
            event._success(event);
          }
          event.namespace = origNamespace;
          event.type = origType;
          event.liveFired = origLiveFired;
        }
      }
    };
    var oldTrigger = $event.trigger, triggerDefault = $event.special["default"].triggerDefault, checkAndRunDefaults = $event.special["default"].checkAndRunDefaults, oldData = jQuery._data;
    $._data = function(elem, name, data) {
      if (!data && name === "handle") {
        var func = oldData.apply(this, arguments);
        return function(e) {
          return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.handle.apply(this, arguments) : undefined;
        };
      }
      return oldData.apply(this, arguments);
    };
    $event.trigger = function defaultTriggerer(event, data, elem, onlyHandlers) {
      var type = event.type || event, namespaces = [], event = typeof event === "object" ? event[jQuery.expando] ? event : new jQuery.Event(type, event) : new jQuery.Event(type);
      event._defaultActions = [];
      oldTrigger.call($.event, event, data, elem, onlyHandlers);
    };
  })(jQuery);
  (function($) {
    var getSetZero = function(v) {
      return v !== undefined ? (this.array[0] = v) : this.array[0];
    }, getSetOne = function(v) {
      return v !== undefined ? (this.array[1] = v) : this.array[1];
    };
    $.Vector = function() {
      this.update($.makeArray(arguments));
    };
    $.Vector.prototype = {
      app : function(f) {
        var i, vec, newArr = [];
        for ( i = 0; i < this.array.length; i++) {
          newArr.push(f(this.array[i]));
        }
        vec = new $.Vector();
        return vec.update(newArr);
      },
      plus : function() {
        var i, args = arguments[0] instanceof $.Vector ? arguments[0].array : $.makeArray(arguments), arr = this.array.slice(0), vec = new $.Vector();
        for ( i = 0; i < args.length; i++) {
          arr[i] = (arr[i] ? arr[i] : 0) + args[i];
        }
        return vec.update(arr);
      },
      minus : function() {
        var i, args = arguments[0] instanceof $.Vector ? arguments[0].array : $.makeArray(arguments), arr = this.array.slice(0), vec = new $.Vector();
        for ( i = 0; i < args.length; i++) {
          arr[i] = (arr[i] ? arr[i] : 0) - args[i];
        }
        return vec.update(arr);
      },
      equals : function() {
        var i, args = arguments[0] instanceof $.Vector ? arguments[0].array : $.makeArray(arguments), arr = this.array.slice(0), vec = new $.Vector();
        for ( i = 0; i < args.length; i++) {
          if (arr[i] != args[i]) {
            return null;
          }
        }
        return vec.update(arr);
      },
      x : getSetZero,
      width : getSetZero,
      y : getSetOne,
      height : getSetOne,
      top : getSetOne,
      left : getSetZero,
      toString : function() {
        return "(" + this.array[0] + "," + this.array[1] + ")";
      },
      update : function(array) {
        var i;
        if (this.array) {
          for ( i = 0; i < this.array.length; i++) {
            delete this.array[i];
          }
        }
        this.array = array;
        for ( i = 0; i < array.length; i++) {
          this[i] = this.array[i];
        }
        return this;
      }
    };
    $.Event.prototype.vector = function() {
      if (this.originalEvent.synthetic) {
        var doc = document.documentElement, body = document.body;
        return new $.Vector(this.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0), this.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0));
      } else {
        return new $.Vector(this.pageX, this.pageY);
      }
    };
    $.fn.offsetv = function() {
      if (this[0] == window) {
        return new $.Vector(window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft, window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop);
      } else {
        var offset = this.offset();
        return new $.Vector(offset.left, offset.top);
      }
    };
    $.fn.dimensionsv = function(which) {
      if (this[0] == window || !which) {
        return new $.Vector(this.width(), this.height());
      } else {
        return new $.Vector(this[which+"Width"](), this[which+"Height"]());
      }
    };
  })(jQuery);
  (function() {
    var event = jQuery.event, findHelper = function(events, types, callback) {
      var t, type, typeHandlers, all, h, handle, namespaces, namespace;
      for ( t = 0; t < types.length; t++) {
        type = types[t];
        all = type.indexOf(".") < 0;
        if (!all) {
          namespaces = type.split(".");
          type = namespaces.shift();
          namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)");
        }
        typeHandlers = (events[type] || []).slice(0);
        for ( h = 0; h < typeHandlers.length; h++) {
          handle = typeHandlers[h];
          if (!handle.selector && (all || namespace.test(handle.namespace))) {
            callback(type, handle.origHandler || handle.handler);
          }
        }
      }
    };
    event.find = function(el, types, selector) {
      var events = $.data(el, "events"), handlers = [], t, liver, live;
      if (!events) {
        return handlers;
      }
      if (selector) {
        if (!events.live) {
          return [];
        }
        live = events.live;
        for ( t = 0; t < live.length; t++) {
          liver = live[t];
          if (liver.selector === selector && $.inArray(liver.origType, types) !== -1) {
            handlers.push(liver.origHandler || liver.handler);
          }
        }
      } else {
        findHelper(events, types, function(type, handler) {
          handlers.push(handler);
        });
      }
      return handlers;
    };
    event.findBySelector = function(el, types) {
      var events = $.data(el, "events"), selectors = {}, add = function(selector, event, handler) {
        var select = selectors[selector] || (selectors[selector] = {}), events = select[event] || (select[event] = []);
        events.push(handler);
      };
      if (!events) {
        return selectors;
      }
      $.each(events.live || [], function(i, live) {
        if ($.inArray(live.origType, types) !== -1) {
          add(live.selector, live.origType, live.origHandler || live.handler);
        }
      });
      findHelper(events, types, function(type, handler) {
        add("", type, handler);
      });
      return selectors;
    };
    event.supportTouch = "ontouchend" in document;
    $.fn.respondsTo = function(events) {
      if (!this.length) {
        return false;
      } else {
        return event.find(this[0], $.isArray(events) ? events : [events]).length > 0;
      }
    };
    $.fn.triggerHandled = function(event, data) {
      event = ( typeof event == "string" ? $.Event(event) : event);
      this.trigger(event, data);
      return event.handled;
    };
    event.setupHelper = function(types, startingEvent, onFirst) {
      if (!onFirst) {
        onFirst = startingEvent;
        startingEvent = null;
      }
      var add = function(handleObj) {
        var bySelector, selector = handleObj.selector || "";
        if (selector) {
          bySelector = event.find(this, types, selector);
          if (!bySelector.length) {
            $(this).delegate(selector, startingEvent, onFirst);
          }
        } else {
          if (!event.find(this, types, selector).length) {
            event.add(this, startingEvent, onFirst, {
              selector : selector,
              delegate : this
            });
          }
        }
      }, remove = function(handleObj) {
        var bySelector, selector = handleObj.selector || "";
        if (selector) {
          bySelector = event.find(this, types, selector);
          if (!bySelector.length) {
            $(this).undelegate(selector, startingEvent, onFirst);
          }
        } else {
          if (!event.find(this, types, selector).length) {
            event.remove(this, startingEvent, onFirst, {
              selector : selector,
              delegate : this
            });
          }
        }
      };
      $.each(types, function() {
        event.special[this] = {
          add : add,
          remove : remove,
          setup : function() {
          },
          teardown : function() {
          }
        };
      });
    };
  })(jQuery);
  (function($) {
    var bind = function(object, method) {
      var args = Array.prototype.slice.call(arguments, 2);
      return function() {
        var args2 = [this].concat(args, $.makeArray(arguments));
        return method.apply(object, args2);
      };
    }, event = $.event, clearSelection = window.getSelection ? function() {
      window.getSelection().removeAllRanges();
    } : function() {
    };
    $.Drag = function() {
    };
    $.extend($.Drag, {
      lowerName : "drag",
      current : null,
      distance : 0,
      mousedown : function(ev, element) {
        var isLeftButton = ev.button === 0 || ev.button == 1;
        if (!isLeftButton || this.current) {
          return;
        }
        var drag = new $.Drag(), delegate = ev.liveFired || element, selector = ev.handleObj.selector, self = this;
        this.current = drag;
        drag.setup({
          element : element,
          delegate : ev.liveFired || element,
          selector : ev.handleObj.selector,
          moved : false,
          _distance : this.distance,
          callbacks : {
            dragdown : event.find(delegate, ["dragdown"], selector),
            draginit : event.find(delegate, ["draginit"], selector),
            dragover : event.find(delegate, ["dragover"], selector),
            dragmove : event.find(delegate, ["dragmove"], selector),
            dragout : event.find(delegate, ["dragout"], selector),
            dragend : event.find(delegate, ["dragend"], selector)
          },
          destroyed : function() {
            self.current = null;
          }
        }, ev);
      }
    });
    $.extend($.Drag.prototype, {
      setup : function(options, ev) {
        $.extend(this, options);
        this.element = $(this.element);
        this.event = ev;
        this.moved = false;
        this.allowOtherDrags = false;
        var mousemove = bind(this, this.mousemove), mouseup = bind(this, this.mouseup);
        this._mousemove = mousemove;
        this._mouseup = mouseup;
        this._distance = options.distance ? options.distance : 0;
        this.mouseStartPosition = ev.vector();
        $(document).bind("mousemove", mousemove);
        $(document).bind("mouseup", mouseup);
        if (!this.callEvents("down", this.element, ev)) {
          this.noSelection(this.delegate);
          clearSelection();
        }
      },
      destroy : function() {
        $(document).unbind("mousemove", this._mousemove);
        $(document).unbind("mouseup", this._mouseup);
        if (!this.moved) {
          this.event = this.element = null;
        }
        this.selection(this.delegate);
        this.destroyed();
      },
      mousemove : function(docEl, ev) {
        if (!this.moved) {
          var dist = Math.sqrt(Math.pow(ev.pageX - this.event.pageX, 2) + Math.pow(ev.pageY - this.event.pageY, 2));
          if (dist < this._distance) {
            return false;
          }
          this.init(this.element, ev);
          this.moved = true;
        }
        var pointer = ev.vector();
        if (this._start_position && this._start_position.equals(pointer)) {
          return;
        }
        this.draw(pointer, ev);
      },
      mouseup : function(docEl, event) {
        if (this.moved) {
          this.end(event);
        }
        this.destroy();
      },
      noSelection : function(elm) {
        elm = elm || this.delegate;
        document.documentElement.onselectstart = function() {
          return false;
        };
        document.documentElement.unselectable = "on";
        this.selectionDisabled = (this.selectionDisabled ? this.selectionDisabled.add(elm) : $(elm));
        this.selectionDisabled.css("-moz-user-select", "-moz-none");
      },
      selection : function(elm) {
        if (this.selectionDisabled) {
          document.documentElement.onselectstart = function() {
          };
          document.documentElement.unselectable = "off";
          this.selectionDisabled.css("-moz-user-select", "");
        }
      },
      init : function(element, event) {
        element = $(element);
        var startElement = (this.movingElement = (this.element = $(element)));
        this._cancelled = false;
        this.event = event;
        this.mouseElementPosition = this.mouseStartPosition.minus(this.element.offsetv());
        this.callEvents("init", element, event);
        if (this._cancelled === true) {
          return;
        }
        this.startPosition = startElement != this.movingElement ? this.movingElement.offsetv() : this.currentDelta();
        this.makePositioned(this.movingElement);
        this.oldZIndex = this.movingElement.css("zIndex");
        this.movingElement.css("zIndex", 1000);
        if (!this._only && this.constructor.responder) {
          this.constructor.responder.compile(event, this);
        }
      },
      makePositioned : function(that) {
        var style, pos = that.css("position");
        if (!pos || pos == "static") {
          style = {
            position : "relative"
          };
          if (window.opera) {
            style.top = "0px";
            style.left = "0px";
          }
          that.css(style);
        }
      },
      callEvents : function(type, element, event, drop) {
        var i, cbs = this.callbacks[this.constructor.lowerName + type];
        for ( i = 0; i < cbs.length; i++) {
          cbs[i].call(element, event, this, drop);
        }
        return cbs.length;
      },
      currentDelta : function() {
        return new $.Vector(parseInt(this.movingElement.css("left"), 10) || 0, parseInt(this.movingElement.css("top"), 10) || 0);
      },
      draw : function(pointer, event) {
        if (this._cancelled) {
          return;
        }
        clearSelection();
        this.location = pointer.minus(this.mouseElementPosition);
        this.move(event);
        if (this._cancelled) {
          return;
        }
        if (!event.isDefaultPrevented()) {
          this.position(this.location);
        }
        if (!this._only && this.constructor.responder) {
          this.constructor.responder.show(pointer, this, event);
        }
      },
      position : function(newOffsetv) {
        var style, dragged_element_css_offset = this.currentDelta(), dragged_element_position_vector = this.movingElement.offsetv().minus(dragged_element_css_offset);
        this.required_css_position = newOffsetv.minus(dragged_element_position_vector);
        this.offsetv = newOffsetv;
        style = this.movingElement[0].style;
        if (!this._cancelled && !this._horizontal) {
          style.top = this.required_css_position.top() + "px";
        }
        if (!this._cancelled && !this._vertical) {
          style.left = this.required_css_position.left() + "px";
        }
      },
      move : function(event) {
        this.callEvents("move", this.element, event);
      },
      over : function(event, drop) {
        this.callEvents("over", this.element, event, drop);
      },
      out : function(event, drop) {
        this.callEvents("out", this.element, event, drop);
      },
      end : function(event) {
        if (this._cancelled) {
          return;
        }
        if (!this._only && this.constructor.responder) {
          this.constructor.responder.end(event, this);
        }
        this.callEvents("end", this.element, event);
        if (this._revert) {
          var self = this;
          this.movingElement.animate({
            top : this.startPosition.top() + "px",
            left : this.startPosition.left() + "px"
          }, function() {
            self.cleanup.apply(self, arguments);
          });
        } else {
          this.cleanup();
        }
        this.event = null;
      },
      cleanup : function() {
        this.movingElement.css({
          zIndex : this.oldZIndex
        });
        if (this.movingElement[0] !== this.element[0] && !this.movingElement.has(this.element[0]).length && !this.element.has(this.movingElement[0]).length) {
          this.movingElement.css({
            display : "none"
          });
        }
        if (this._removeMovingElement) {
          this.movingElement.remove();
        }
        this.movingElement = this.element = this.event = null;
      },
      cancel : function() {
        this._cancelled = true;
        if (!this._only && this.constructor.responder) {
          this.constructor.responder.clear(this.event.vector(), this, this.event);
        }
        this.destroy();
      },
      ghost : function(loc) {
        var ghost = this.movingElement.clone().css("position", "absolute");
        ( loc ? $(loc) : this.movingElement).after(ghost);
        ghost.width(this.movingElement.width()).height(this.movingElement.height());
        ghost.offset(this.movingElement.offset());
        this.movingElement = ghost;
        this.noSelection(ghost);
        this._removeMovingElement = true;
        return ghost;
      },
      representative : function(element, offsetX, offsetY) {
        this._offsetX = offsetX || 0;
        this._offsetY = offsetY || 0;
        var p = this.mouseStartPosition;
        this.movingElement = $(element);
        this.movingElement.css({
          top : (p.y() - this._offsetY) + "px",
          left : (p.x() - this._offsetX) + "px",
          display : "block",
          position : "absolute"
        }).show();
        this.noSelection(this.movingElement);
        this.mouseElementPosition = new $.Vector(this._offsetX, this._offsetY);
      },
      revert : function(val) {
        this._revert = val === undefined ? true : val;
        return this;
      },
      vertical : function() {
        this._vertical = true;
        return this;
      },
      horizontal : function() {
        this._horizontal = true;
        return true;
      },
      only : function(only) {
        return (this._only = (only === undefined ? true : only));
      },
      distance : function(val) {
        if (val !== undefined) {
          this._distance = val;
          return this;
        } else {
          return this._distance;
        }
      }
    });
    event.setupHelper(["dragdown", "draginit", "dragover", "dragmove", "dragout", "dragend"], "mousedown", function(e) {
      $.Drag.mousedown.call($.Drag, e, this);
    });
  })(jQuery);
  (function($) {
    var getComputedStyle = document.defaultView && document.defaultView.getComputedStyle, rupper = /([A-Z])/g, rdashAlpha = /-([a-z])/ig, fcamelCase = function(all, letter) {
      return letter.toUpperCase();
    }, getStyle = function(elem) {
      if (getComputedStyle) {
        return getComputedStyle(elem, null);
      } else {
        if (elem.currentStyle) {
          return elem.currentStyle;
        }
      }
    }, rfloat = /float/i, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/;
    $.curStyles = function(el, styles) {
      if (!el) {
        return null;
      }
      var currentS = getStyle(el), oldName, val, style = el.style, results = {}, i = 0, left, rsLeft, camelCase, name;
      for (; i < styles.length; i++) {
        name = styles[i];
        oldName = name.replace(rdashAlpha, fcamelCase);
        if (rfloat.test(name)) {
          name = jQuery.support.cssFloat ? "float" : "styleFloat";
          oldName = "cssFloat";
        }
        if (getComputedStyle) {
          name = name.replace(rupper, "-$1").toLowerCase();
          val = currentS.getPropertyValue(name);
          if (name === "opacity" && val === "") {
            val = "1";
          }
          results[oldName] = val;
        } else {
          camelCase = name.replace(rdashAlpha, fcamelCase);
          results[oldName] = currentS[name] || currentS[camelCase];
          if (!rnumpx.test(results[oldName]) && rnum.test(results[oldName])) {
            left = style.left;
            rsLeft = el.runtimeStyle.left;
            el.runtimeStyle.left = el.currentStyle.left;
            style.left = camelCase === "fontSize" ? "1em" : (results[oldName] || 0);
            results[oldName] = style.pixelLeft + "px";
            style.left = left;
            el.runtimeStyle.left = rsLeft;
          }
        }
      }
      return results;
    };
    $.fn.curStyles = function() {
      return $.curStyles(this[0], $.makeArray(arguments));
    };
  })(jQuery);
  (function($) {
    $.Drag.prototype.limit = function(container, center) {
      var styles = container.curStyles("borderTopWidth", "paddingTop", "borderLeftWidth", "paddingLeft"), paddingBorder = new $.Vector(parseInt(styles.borderLeftWidth, 10) + parseInt(styles.paddingLeft, 10) || 0, parseInt(styles.borderTopWidth, 10) + parseInt(styles.paddingTop, 10) || 0);
      this._limit = {
        offset : container.offsetv().plus(paddingBorder),
        size : container.dimensionsv(),
        center : center === true ? "both" : center
      };
      return this;
    };
    var oldPosition = $.Drag.prototype.position;
    $.Drag.prototype.position = function(offsetPositionv) {
      if (this._limit) {
        var limit = this._limit, center = limit.center && limit.center.toLowerCase(), movingSize = this.movingElement.dimensionsv("outer"), halfHeight = center && center != "x" ? movingSize.height() / 2 : 0, halfWidth = center && center != "y" ? movingSize.width() / 2 : 0, lot = limit.offset.top(), lof = limit.offset.left(), height = limit.size.height(), width = limit.size.width();
        if (offsetPositionv.top() + halfHeight < lot) {
          offsetPositionv.top(lot - halfHeight);
        }
        if (offsetPositionv.top() + movingSize.height() - halfHeight > lot + height) {
          offsetPositionv.top(lot + height - movingSize.height() + halfHeight);
        }
        if (offsetPositionv.left() + halfWidth < lof) {
          offsetPositionv.left(lof - halfWidth);
        }
        if (offsetPositionv.left() + movingSize.width() - halfWidth > lof + width) {
          offsetPositionv.left(lof + width - movingSize.left() + halfWidth);
        }
      }
      oldPosition.call(this, offsetPositionv);
    };
  })(jQuery);
  (function($) {
    var withinBox = function(x, y, left, top, width, height) {
      return (y >= top && y < top + height && x >= left && x < left + width);
    };
    $.fn.within = function(left, top, useOffsetCache) {
      var ret = [];
      this.each(function() {
        var q = jQuery(this);
        if (this == document.documentElement) {
          return ret.push(this);
        }
        var offset = useOffsetCache ? jQuery.data(this, "offsetCache") || jQuery.data(this, "offsetCache", q.offset()) : q.offset();
        var res = withinBox(left, top, offset.left, offset.top, this.offsetWidth, this.offsetHeight);
        if (res) {
          ret.push(this);
        }
      });
      return this.pushStack(jQuery.unique(ret), "within", left + "," + top);
    };
    $.fn.withinBox = function(left, top, width, height, cache) {
      var ret = [];
      this.each(function() {
        var q = jQuery(this);
        if (this == document.documentElement) {
          return this.ret.push(this);
        }
        var offset = cache ? jQuery.data(this, "offset", q.offset()) : q.offset();
        var ew = q.width(), eh = q.height();
        res = !((offset.top > top + height) || (offset.top + eh < top) || (offset.left > left + width) || (offset.left + ew < left));
        if (res) {
          ret.push(this);
        }
      });
      return this.pushStack(jQuery.unique(ret), "withinBox", jQuery.makeArray(arguments).join(","));
    };
  })(jQuery);
  (function($) {
    jQuery.fn.compare = function(element) {
      try {
        element = element.jquery ? element[0] : element;
      } catch(e) {
        return null;
      }
      if (window.HTMLElement) {
        var s = HTMLElement.prototype.toString.call(element);
        if (s == "[xpconnect wrapped native prototype]" || s == "[object XULElement]" || s === "[object Window]") {
          return null;
        }
      }
      if (this[0].compareDocumentPosition) {
        return this[0].compareDocumentPosition(element);
      }
      if (this[0] == document && element != document) {
        return 8;
      }
      var number = (this[0] !== element && this[0].contains(element) && 16) + (this[0] != element && element.contains(this[0]) && 8), docEl = document.documentElement;
      if (this[0].sourceIndex) {
        number += (this[0].sourceIndex < element.sourceIndex && 4);
        number += (this[0].sourceIndex > element.sourceIndex && 2);
        number += (this[0].ownerDocument !== element.ownerDocument || (this[0] != docEl && this[0].sourceIndex <= 0) || (element != docEl && element.sourceIndex <= 0)) && 1;
      } else {
        var range = document.createRange(), sourceRange = document.createRange(), compare;
        range.selectNode(this[0]);
        sourceRange.selectNode(element);
        compare = range.compareBoundaryPoints(Range.START_TO_START, sourceRange);
      }
      return number;
    };
  })(jQuery);
  (function($) {
    var event = $.event, callHanders = function() {
    };
    var eventNames = ["dropover", "dropon", "dropout", "dropinit", "dropmove", "dropend"];
    $.Drop = function(callbacks, element) {
      jQuery.extend(this, callbacks);
      this.element = $(element);
    };
    $.each(eventNames, function() {
      event.special[this] = {
        add : function(handleObj) {
          var el = $(this), current = (el.data("dropEventCount") || 0);
          el.data("dropEventCount", current + 1);
          if (current == 0) {
            $.Drop.addElement(this);
          }
        },
        remove : function() {
          var el = $(this), current = (el.data("dropEventCount") || 0);
          el.data("dropEventCount", current - 1);
          if (current <= 1) {
            $.Drop.removeElement(this);
          }
        }
      };
    });
    $.extend($.Drop, {
      lowerName : "drop",
      _rootElements : [],
      _elements : $(),
      last_active : [],
      endName : "dropon",
      addElement : function(el) {
        for (var i = 0; i < this._rootElements.length; i++) {
          if (el == this._rootElements[i]) {
            return;
          }
        }
        this._rootElements.push(el);
      },
      removeElement : function(el) {
        for (var i = 0; i < this._rootElements.length; i++) {
          if (el == this._rootElements[i]) {
            this._rootElements.splice(i, 1);
            return;
          }
        }
      },
      sortByDeepestChild : function(a, b) {
        var compare = a.element.compare(b.element);
        if (compare & 16 || compare & 4) {
          return 1;
        }
        if (compare & 8 || compare & 2) {
          return -1;
        }
        return 0;
      },
      isAffected : function(point, moveable, responder) {
        return ((responder.element != moveable.element) && (responder.element.within(point[0], point[1], responder._cache).length == 1));
      },
      deactivate : function(responder, mover, event) {
        mover.out(event, responder);
        responder.callHandlers(this.lowerName + "out", responder.element[0], event, mover);
      },
      activate : function(responder, mover, event) {
        mover.over(event, responder);
        responder.callHandlers(this.lowerName + "over", responder.element[0], event, mover);
      },
      move : function(responder, mover, event) {
        responder.callHandlers(this.lowerName + "move", responder.element[0], event, mover);
      },
      compile : function(event, drag) {
        if (!this.dragging && !drag) {
          return;
        } else {
          if (!this.dragging) {
            this.dragging = drag;
            this.last_active = [];
          }
        }
        var el, drops, selector, dropResponders, newEls = [], dragging = this.dragging;
        for (var i = 0; i < this._rootElements.length; i++) {
          el = this._rootElements[i];
          var drops = $.event.findBySelector(el, eventNames);
          for (selector in drops) {
            dropResponders = selector ? jQuery(selector, el) : [el];
            for (var e = 0; e < dropResponders.length; e++) {
              if (this.addCallbacks(dropResponders[e], drops[selector], dragging)) {
                newEls.push(dropResponders[e]);
              }
            }
          }
        }
        this.add(newEls, event, dragging);
      },
      addCallbacks : function(el, callbacks, onlyNew) {
        var origData = $.data(el, "_dropData");
        if (!origData) {
          $.data(el, "_dropData", new $.Drop(callbacks, el));
          return true;
        } else {
          if (!onlyNew) {
            var origCbs = origData;
            for (var eventName in callbacks) {
              origCbs[eventName] = origCbs[eventName] ? origCbs[eventName].concat(callbacks[eventName]) : callbacks[eventName];
            }
            return false;
          }
        }
      },
      add : function(newEls, event, drag, dragging) {
        var i = 0, drop;
        while (i < newEls.length) {
          drop = $.data(newEls[i], "_dropData");
          drop.callHandlers(this.lowerName + "init", newEls[i], event, drag);
          if (drop._canceled) {
            newEls.splice(i, 1);
          } else {
            i++;
          }
        }
        this._elements.push.apply(this._elements, newEls);
      },
      show : function(point, moveable, event) {
        var element = moveable.element;
        if (!this._elements.length) {
          return;
        }
        var respondable, affected = [], propagate = true, i = 0, j, la, toBeActivated, aff, oldLastActive = this.last_active, responders = [], self = this, drag;
        while (i < this._elements.length) {
          drag = $.data(this._elements[i], "_dropData");
          if (!drag) {
            this._elements.splice(i, 1);
          } else {
            i++;
            if (self.isAffected(point, moveable, drag)) {
              affected.push(drag);
            }
          }
        }
        affected.sort(this.sortByDeepestChild);
        event.stopRespondPropagate = function() {
          propagate = false;
        };
        toBeActivated = affected.slice();
        this.last_active = affected;
        for ( j = 0; j < oldLastActive.length; j++) {
          la = oldLastActive[j];
          i = 0;
          while (( aff = toBeActivated[i])) {
            if (la == aff) {
              toBeActivated.splice(i, 1);
              break;
            } else {
              i++;
            }
          }
          if (!aff) {
            this.deactivate(la, moveable, event);
          }
          if (!propagate) {
            return;
          }
        }
        for (var i = 0; i < toBeActivated.length; i++) {
          this.activate(toBeActivated[i], moveable, event);
          if (!propagate) {
            return;
          }
        }
        for ( i = 0; i < affected.length; i++) {
          this.move(affected[i], moveable, event);
          if (!propagate) {
            return;
          }
        }
      },
      end : function(event, moveable) {
        var responder, la, endName = this.lowerName + "end";
        for (var i = 0; i < this.last_active.length; i++) {
          la = this.last_active[i];
          if (this.isAffected(event.vector(), moveable, la) && la[this.endName]) {
            la.callHandlers(this.endName, null, event, moveable);
          }
        }
        for (var r = 0; r < this._elements.length; r++) {
          $.data(this._elements[r], "_dropData").callHandlers(endName, null, event, moveable);
        }
        this.clear();
      },
      clear : function() {
        this._elements.each(function() {
          $.removeData(this, "_dropData");
        });
        this._elements = $();
        delete this.dragging;
      }
    });
    $.Drag.responder = $.Drop;
    $.extend($.Drop.prototype, {
      callHandlers : function(method, el, ev, drag) {
        var length = this[method] ? this[method].length : 0;
        for (var i = 0; i < length; i++) {
          this[method][i].call(el || this.element[0], ev, this, drag);
        }
      },
      cache : function(value) {
        this._cache = value != null ? value : true;
      },
      cancel : function() {
        this._canceled = true;
      }
    });
  })(jQuery);
  (function($) {
    $.Drag.prototype.scrolls = function(elements, options) {
      var elements = $(elements);
      for (var i = 0; i < elements.length; i++) {
        this.constructor.responder._elements.push(elements.eq(i).data("_dropData",new $.Scrollable(elements[i],options))[0]);
      }
    }, $.Scrollable = function(element, options) {
      this.element = jQuery(element);
      this.options = $.extend({
        distance : 30,
        delta : function(diff, distance) {
          return (distance - diff) / 2;
        },
        direction : "xy"
      }, options);
      this.x = this.options.direction.indexOf("x") != -1;
      this.y = this.options.direction.indexOf("y") != -1;
    };
    $.extend($.Scrollable.prototype, {
      init : function(element) {
        this.element = jQuery(element);
      },
      callHandlers : function(method, el, ev, drag) {
        this[method](el || this.element[0], ev, this, drag);
      },
      dropover : function() {
      },
      dropon : function() {
        this.clear_timeout();
      },
      dropout : function() {
        this.clear_timeout();
      },
      dropinit : function() {
      },
      dropend : function() {
      },
      clear_timeout : function() {
        if (this.interval) {
          clearTimeout(this.interval);
          this.interval = null;
        }
      },
      distance : function(diff) {
        return (30 - diff) / 2;
      },
      dropmove : function(el, ev, drop, drag) {
        this.clear_timeout();
        var mouse = ev.vector(), location_object = $(el == document.documentElement ? window : el), dimensions = location_object.dimensionsv("outer"), position = location_object.offsetv(), bottom = position.y() + dimensions.y() - mouse.y(), top = mouse.y() - position.y(), right = position.x() + dimensions.x() - mouse.x(), left = mouse.x() - position.x(), dx = 0, dy = 0, distance = this.options.distance;
        if (bottom < distance && this.y) {
          dy = this.options.delta(bottom, distance);
        } else {
          if (top < distance && this.y) {
            dy = -this.options.delta(top, distance);
          }
        }
        if (right < distance && this.options && this.x) {
          dx = this.options.delta(right, distance);
        } else {
          if (left < distance && this.x) {
            dx = -this.options.delta(left, distance);
          }
        }
        if (dx || dy) {
          var self = this;
          this.interval = setTimeout(function() {
            self.move($(el), drag.movingElement, dx, dy, ev, ev.clientX, ev.clientY, ev.screenX, ev.screenY);
          }, 15);
        }
      },
      move : function(scroll_element, drag_element, dx, dy, ev) {
        scroll_element.scrollTop(scroll_element.scrollTop() + dy);
        scroll_element.scrollLeft(scroll_element.scrollLeft() + dx);
        drag_element.trigger($.event.fix({
          type : "mousemove",
          clientX : ev.clientX,
          clientY : ev.clientY,
          screenX : ev.screenX,
          screenY : ev.screenY,
          pageX : ev.pageX,
          pageY : ev.pageY
        }));
      }
    });
  })(jQuery);
  (function($) {
    var round = function(x, m) {
      return Math.round(x / m) * m;
    };
    $.Drag.prototype.step = function(amount, container, center) {
      if ( typeof amount == "number") {
        amount = {
          x : amount,
          y : amount
        };
      }
      container = container || $(document.body);
      this._step = amount;
      var styles = container.curStyles("borderTopWidth", "paddingTop", "borderLeftWidth", "paddingLeft");
      var top = parseInt(styles.borderTopWidth) + parseInt(styles.paddingTop), left = parseInt(styles.borderLeftWidth) + parseInt(styles.paddingLeft);
      this._step.offset = container.offsetv().plus(left, top);
      this._step.center = center;
      return this;
    };
    var oldPosition = $.Drag.prototype.position;
    $.Drag.prototype.position = function(offsetPositionv) {
      if (this._step) {
        var step = this._step, center = step.center && step.center.toLowerCase(), movingSize = this.movingElement.dimensionsv("outer"), lot = step.offset.top() - (center && center != "x" ? movingSize.height() / 2 : 0), lof = step.offset.left() - (center && center != "y" ? movingSize.width() / 2 : 0);
        if (this._step.x) {
          offsetPositionv.left(Math.round(lof + round(offsetPositionv.left() - lof, this._step.x)));
        }
        if (this._step.y) {
          offsetPositionv.top(Math.round(lot + round(offsetPositionv.top() - lot, this._step.y)));
        }
      }
      oldPosition.call(this, offsetPositionv);
    };
  })(jQuery);
  (function($) {
    $.Hover = function() {
      this._delay = $.Hover.delay;
      this._distance = $.Hover.distance;
      this._leave = $.Hover.leave;
    };
    $.extend($.Hover, {
      delay : 100,
      distance : 10,
      leave : 0
    });
    $.extend($.Hover.prototype, {
      delay : function(delay) {
        this._delay = delay;
        return this;
      },
      distance : function(distance) {
        this._distance = distance;
        return this;
      },
      leave : function(leave) {
        this._leave = leave;
        return this;
      }
    });
    var event = $.event, handle = event.handle, onmouseenter = function(ev) {
      var delegate = ev.liveFired || ev.currentTarget;
      var selector = ev.handleObj.selector;
      if ($.data(delegate, "_hover" + selector)) {
        return;
      }
      $.data(delegate, "_hover" + selector, true);
      var loc = {
        pageX : ev.pageX,
        pageY : ev.pageY
      }, dist = 0, timer, enteredEl = this, hovered = false, lastEv = ev, hover = new $.Hover(), leaveTimer, callHoverLeave = function() {
        $.each(event.find(delegate, ["hoverleave"], selector), function() {
          this.call(enteredEl, ev, hover);
        });
        cleanUp();
      }, mouseenter = function(ev) {
        clearTimeout(leaveTimer);
        dist += Math.pow(ev.pageX - loc.pageX, 2) + Math.pow(ev.pageY - loc.pageY, 2);
        loc = {
          pageX : ev.pageX,
          pageY : ev.pageY
        };
        lastEv = ev;
      }, mouseleave = function(ev) {
        clearTimeout(timer);
        if (hovered) {
          if (hover._leave === 0) {
            callHoverLeave();
          } else {
            clearTimeout(leaveTimer);
            leaveTimer = setTimeout(function() {
              callHoverLeave();
            }, hover._leave);
          }
        } else {
          cleanUp();
        }
      }, cleanUp = function() {
        $(enteredEl).unbind("mouseleave", mouseleave);
        $(enteredEl).unbind("mousemove", mouseenter);
        $.removeData(delegate, "_hover" + selector);
      };
      $(enteredEl).bind("mousemove", mouseenter).bind("mouseleave", mouseleave);
      $.each(event.find(delegate, ["hoverinit"], selector), function() {
        this.call(enteredEl, ev, hover);
      });
      timer = setTimeout(function() {
        if (dist < hover._distance && $(enteredEl).queue().length == 0) {
          $.each(event.find(delegate, ["hoverenter"], selector), function() {
            this.call(enteredEl, lastEv, hover);
          });
          hovered = true;
          return;
        } else {
          dist = 0;
          timer = setTimeout(arguments.callee, hover._delay);
        }
      }, hover._delay);
    };
    event.setupHelper(["hoverinit", "hoverenter", "hoverleave", "hovermove"], "mouseenter", onmouseenter);
  })(jQuery);
  (function($) {
    var resizers = $(), resizeCount = 0, win = $(window), windowWidth = 0, windowHeight = 0, timer;
    $(function() {
      windowWidth = win.width();
      windowHeight = win.height();
    });
    $.event.special.resize = {
      setup : function(handleObj) {
        if (this !== window) {
          resizers.push(this);
          $.unique(resizers);
        }
        return this !== window;
      },
      teardown : function() {
        resizers = resizers.not(this);
        return this !== window;
      },
      add : function(handleObj) {
        var origHandler = handleObj.handler;
        handleObj.origHandler = origHandler;
        handleObj.handler = function(ev, data) {
          var isWindow = this === window;
          if (isWindow && ev.originalEvent) {
            var width = win.width(), height = win.height();
            if ((width != windowWidth || height != windowHeight)) {
              windowWidth = width;
              windowHeight = height;
              clearTimeout(timer);
              timer = setTimeout(function() {
                win.trigger("resize");
              }, 1);
            }
            return;
          }
          if (resizeCount === 0) {
            resizeCount++;
            var where = data === false ? ev.target : this;
            $.event.handle.call(where, ev);
            if (ev.isPropagationStopped()) {
              resizeCount--;
              return;
            }
            var index = resizers.index(this), length = resizers.length, child, sub;
            while (++index < length && ( child = resizers[index]) && (isWindow || $.contains(where, child))) {
              $.event.handle.call(child, ev);
              if (ev.isPropagationStopped()) {
                while (++index < length && ( sub = resizers[index])) {
                  if (!$.contains(child, sub)) {
                    index--;
                    break;
                  }
                }
              }
            }
            ev.stopImmediatePropagation();
            resizeCount--;
          } else {
            handleObj.origHandler.call(this, ev, data);
          }
        };
      }
    };
    $([document, window]).bind("resize", function() {
    });
  })(jQuery);
  (function($) {
    var current, rnamespaces = /\.(.*)$/, returnFalse = function() {
      return false;
    }, returnTrue = function() {
      return true;
    };
    $.Event.prototype.isPaused = returnFalse;
    $.Event.prototype.pause = function() {
      current = this;
      this.stopImmediatePropagation();
      this.isPaused = returnTrue;
    };
    $.Event.prototype.resume = function() {
      this.isPaused = this.isImmediatePropagationStopped = this.isPropagationStopped = returnFalse;
      var el = this.liveFired || this.currentTarget || this.target, defult = $.event.special["default"], oldType = this.type;
      if (this.handleObj.origHandler) {
        var cur = this.currentTarget;
        this.currentTarget = this.liveFired;
        this.liveFired = undefined;
        liveHandler.call(el, this, cur);
        el = cur;
      }
      if (this.isImmediatePropagationStopped()) {
        return false;
      }
      this.firstPass = true;
      if (!this.isPropagationStopped()) {
        $.event.trigger(this, [this.handleObj], el, false);
      }
    };
    function liveHandler(event, after) {
      var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery._data(this, "events");
      if (event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click") {
        return;
      }
      if (event.namespace) {
        namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
      }
      event.liveFired = this;
      var live = events.live.slice(0);
      for ( j = 0; j < live.length; j++) {
        handleObj = live[j];
        if (handleObj.origType.replace(rnamespaces, "") === event.type) {
          selectors.push(handleObj.selector);
        } else {
          live.splice(j--, 1);
        }
      }
      match = jQuery(event.target).closest(selectors, event.currentTarget);
      for ( i = 0, l = match.length; i < l; i++) {
        close = match[i];
        for ( j = 0; j < live.length; j++) {
          handleObj = live[j];
          if (close.selector === handleObj.selector && (!namespace || namespace.test(handleObj.namespace)) && !close.elem.disabled) {
            elem = close.elem;
            related = null;
            if (handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave") {
              event.type = handleObj.preType;
              related = jQuery(event.relatedTarget).closest(handleObj.selector)[0];
              if (related && jQuery.contains(elem, related)) {
                related = elem;
              }
            }
            if (!related || related !== elem) {
              elems.push({
                elem : elem,
                handleObj : handleObj,
                level : close.level
              });
            }
          }
        }
      }
      for ( i = 0, l = elems.length; i < l; i++) {
        match = elems[i];
        if (after) {
          if (after === match.elem) {
            after = undefined;
          }
          continue;
        }
        if (maxLevel && match.level > maxLevel) {
          break;
        }
        event.currentTarget = match.elem;
        event.data = match.handleObj.data;
        event.handleObj = match.handleObj;
        ret = match.handleObj.origHandler.apply(match.elem, arguments);
        if (ret === false || event.isPropagationStopped()) {
          maxLevel = match.level;
          if (ret === false) {
            stop = false;
          }
          if (event.isImmediatePropagationStopped()) {
            break;
          }
        }
      }
      return stop;
    }

  })(jQuery);
  (function($) {
    var toId = function(src) {
      return src.replace(/^\/\//, "").replace(/[\/\.]/g, "_");
    }, id = 1;
    var $view, render, checkText, get, getRenderer, isDeferred = function(obj) {
      return obj && $.isFunction(obj.always);
    }, getDeferreds = function(data) {
      var deferreds = [];
      if (isDeferred(data)) {
        return [data];
      } else {
        for (var prop in data) {
          if (isDeferred(data[prop])) {
            deferreds.push(data[prop]);
          }
        }
      }
      return deferreds;
    }, usefulPart = function(resolved) {
      return $.isArray(resolved) && resolved.length === 3 && resolved[1] === "success" ? resolved[0] : resolved;
    };
    $view = $.View = function(view, data, helpers, callback) {
      if ( typeof helpers === "function") {
        callback = helpers;
        helpers = undefined;
      }
      var deferreds = getDeferreds(data);
      if (deferreds.length) {
        var deferred = $.Deferred();
        deferreds.push(get(view, true));
        $.when.apply($, deferreds).then(function(resolved) {
          var objs = $.makeArray(arguments), renderer = objs.pop()[0], result;
          if (isDeferred(data)) {
            data = usefulPart(resolved);
          } else {
            for (var prop in data) {
              if (isDeferred(data[prop])) {
                data[prop] = usefulPart(objs.shift());
              }
            }
          }
          result = renderer(data, helpers);
          deferred.resolve(result);
          callback && callback(result);
        });
        return deferred.promise();
      } else {
        var response, async = typeof callback === "function", deferred = get(view, async);
        if (async) {
          response = deferred;
          deferred.done(function(renderer) {
            callback(renderer(data, helpers));
          });
        } else {
          deferred.done(function(renderer) {
            response = renderer(data, helpers);
          });
        }
        return response;
      }
    };
    checkText = function(text, url) {
      if (!text.match(/[^\s]/)) {
        throw "$.View ERROR: There is no template or an empty template at " + url;
      }
    };
    get = function(url, async) {
      return $.ajax({
        url : url,
        dataType : "view",
        async : async
      });
    };
    $.ajaxTransport("view", function(options, orig) {
      var view = orig.url, suffix = view.match(/\.[\w\d]+$/), type, el, id, renderer, url = view, jqXHR, response = function(text) {
        var func = type.renderer(id, text);
        if ($view.cache) {
          $view.cached[id] = func;
        }
        return {
          view : func
        };
      };
      if ( el = document.getElementById(view)) {
        suffix = el.type.match(/\/[\d\w]+$/)[0].replace(/^\//, ".");
      }
      if (!suffix) {
        suffix = $view.ext;
        url = url + $view.ext;
      }
      id = toId(url);
      if (url.match(/^\/\//)) {
        if ( typeof steal === "undefined") {
          url = "/" + url.substr(2);
        } else {
          url = steal.root.mapJoin(url.substr(2));
        }
      }
      type = $view.types[suffix];
      return {
        send : function(headers, callback) {
          if ($view.cached[id]) {
            return callback(200, "success", {
              view : $view.cached[id]
            });
          } else {
            if (el) {
              callback(200, "success", response(el.innerHTML));
            } else {
              jqXHR = $.ajax({
                async : orig.async,
                url : url,
                dataType : "text",
                error : function() {
                  checkText("", url);
                  callback(404);
                },
                success : function(text) {
                  checkText(text, url);
                  callback(200, "success", response(text));
                }
              });
            }
          }
        },
        abort : function() {
          jqXHR && jqXHR.abort();
        }
      };
    });
    $.extend($view, {
      hookups : {},
      hookup : function(cb) {
        var myid = ++id;
        $view.hookups[myid] = cb;
        return myid;
      },
      cached : {},
      cache : true,
      register : function(info) {
        this.types["." + info.suffix] = info;
        if (window.steal) {
          steal.type(info.suffix + " view js", function(options, orig, success, error) {
            var type = $view.types["." + options.type], id = toId(options.rootSrc);
            options.text = type.script(id, options.text);
            success();
          });
        }
      },
      types : {},
      ext : ".ejs",
      registerScript : function(type, id, src) {
        return "$.View.preload('" + id + "'," + $view.types["." + type].script(id, src) + ");";
      },
      preload : function(id, renderer) {
        $view.cached[id] = function(data, helpers) {
          return renderer.call(data, data, helpers);
        };
      }
    });
    if (window.steal) {
      steal.type("view js", function(options, orig, success, error) {
        var type = $view.types["." + options.type], id = toId(options.rootSrc);
        options.text = "steal('" + (type.plugin || "jquery/view/" + options.type) + "').then(function($){$.View.preload('" + id + "'," + options.text + ");\n})";
        success();
      });
    }
    var convert, modify, isTemplate, isHTML, getCallback, hookupView, funcs;
    convert = function(func_name) {
      var old = $.fn[func_name];
      $.fn[func_name] = function() {
        var args = $.makeArray(arguments), callbackNum, callback, self = this, result;
        if (isDeferred(args[0])) {
          args[0].done(function(res) {
            modify.call(self, [res], old);
          });
          return this;
        } else {
          if (isTemplate(args)) {
            if (( callbackNum = getCallback(args))) {
              callback = args[callbackNum];
              args[callbackNum] = function(result) {
                modify.call(self, [result], old);
                callback.call(self, result);
              };
              $view.apply($view, args);
              return this;
            }
            result = $view.apply($view, args);
            if (!isDeferred(result)) {
              args = [result];
            } else {
              result.done(function(res) {
                modify.call(self, [res], old);
              });
              return this;
            }
          }
        }
        return modify.call(this, args, old);
      };
    };
    modify = function(args, old) {
      var res, stub, hooks;
      for (var hasHookups in $view.hookups) {
        break;
      }
      if (hasHookups && args[0] && isHTML(args[0])) {
        hooks = $view.hookups;
        $view.hookups = {};
        args[0] = $(args[0]);
      }
      res = old.apply(this, args);
      if (hooks) {
        hookupView(args[0], hooks);
      }
      return res;
    };
    isTemplate = function(args) {
      var secArgType = typeof args[1];
      return typeof args[0] == "string" && (secArgType == "object" || secArgType == "function") && !args[1].nodeType && !args[1].jquery;
    };
    isHTML = function(arg) {
      if (arg.jquery || arg.nodeType === 1) {
        return true;
      } else {
        if ( typeof arg === "string") {
          arg = $.trim(arg);
          return arg.substr(0, 1) === "<" && arg.substr(arg.length - 1, 1) === ">" && arg.length >= 3;
        } else {
          return false;
        }
      }
    };
    getCallback = function(args) {
      return typeof args[3] === "function" ? 3 : typeof args[2] === "function" && 2;
    };
    hookupView = function(els, hooks) {
      var hookupEls, len, i = 0, id, func;
      els = els.filter(function() {
        return this.nodeType != 3;
      });
      hookupEls = els.add("[data-view-id]", els);
      len = hookupEls.length;
      for (; i < len; i++) {
        if (hookupEls[i].getAttribute && ( id = hookupEls[i].getAttribute("data-view-id")) && ( func = hooks[id])) {
          func(hookupEls[i], id);
          delete hooks[id];
          hookupEls[i].removeAttribute("data-view-id");
        }
      }
      $.extend($view.hookups, hooks);
    };
    $.fn.hookup = function() {
      var hooks = $view.hookups;
      $view.hookups = {};
      hookupView(this, hooks);
      return this;
    };
    funcs = ["prepend", "append", "after", "before", "text", "html", "replaceWith", "val"];
    for (var i = 0; i < funcs.length; i++) {
      convert(funcs[i]);
    }
  })(jQuery);
  (function($) {
    $.String.rsplit = function(string, regex) {
      var result = regex.exec(string), retArr = [], first_idx, last_idx;
      while (result !== null) {
        first_idx = result.index;
        last_idx = regex.lastIndex;
        if (first_idx !== 0) {
          retArr.push(string.substring(0, first_idx));
          string = string.slice(first_idx);
        }
        retArr.push(result[0]);
        string = string.slice(result[0].length);
        result = regex.exec(string);
      }
      if (string !== "") {
        retArr.push(string);
      }
      return retArr;
    };
  })(jQuery);
  (function($) {
    var myEval = function(script) {
      eval(script);
    }, chop = function(string) {
      return string.substr(0, string.length - 1);
    }, rSplit = $.String.rsplit, extend = $.extend, isArray = $.isArray, clean = function(content) {
      var converted = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/"/g, '\\"').replace(/\t/g, "\\t");
      return converted;
    }, escapeHTML = function(content) {
      return content.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&#34;").replace(/'/g, "&#39;");
    }, EJS = function(options) {
      if (this.constructor != EJS) {
        var ejs = new EJS(options);
        return function(data, helpers) {
          return ejs.render(data, helpers);
        };
      }
      if ( typeof options == "function") {
        this.template = {};
        this.template.process = options;
        return;
      }
      extend(this, EJS.options, options);
      this.template = compile(this.text, this.type, this.name);
    };
    $.EJS = EJS;
    EJS.prototype = {
      constructor : EJS,
      render : function(object, extraHelpers) {
        object = object || {};
        this._extra_helpers = extraHelpers;
        var v = new EJS.Helpers(object, extraHelpers || {});
        return this.template.process.call(object, object, v);
      }
    };
    EJS.text = function(input) {
      if ( typeof input == "string") {
        return input;
      }
      if (input === null || input === undefined) {
        return "";
      }
      var hook = (input.hookup &&
      function(el, id) {
        input.hookup.call(input, el, id);
      }) || ( typeof input == "function" && input) || (isArray(input) &&
      function(el, id) {
        for (var i = 0; i < input.length; i++) {
          var stub;
          stub = input[i].hookup ? input[i].hookup(el, id) : input[i](el, id);
        }
      });
      if (hook) {
        return "data-view-id='" + $.View.hookup(hook) + "'";
      }
      return input.toString ? input.toString() : "";
    };
    EJS.clean = function(text) {
      if ( typeof text == "string") {
        return escapeHTML(text);
      } else {
        if ( typeof text == "number") {
          return text;
        } else {
          return EJS.text(text);
        }
      }
    };
    var scan = function(scanner, source, block) {
      var source_split = rSplit(source, /\n/), i = 0;
      for (; i < source_split.length; i++) {
        scanline(scanner, source_split[i], block);
      }
    }, scanline = function(scanner, line, block) {
      scanner.lines++;
      var line_split = rSplit(line, scanner.splitter), token;
      for (var i = 0; i < line_split.length; i++) {
        token = line_split[i];
        if (token !== null) {
          block(token, scanner);
        }
      }
    }, makeScanner = function(left, right) {
      var scanner = {};
      extend(scanner, {
        left : left + "%",
        right : "%" + right,
        dLeft : left + "%%",
        dRight : "%%" + right,
        eeLeft : left + "%==",
        eLeft : left + "%=",
        cmnt : left + "%#",
        scan : scan,
        lines : 0
      });
      scanner.splitter = new RegExp("(" + [scanner.dLeft, scanner.dRight, scanner.eeLeft, scanner.eLeft, scanner.cmnt, scanner.left, scanner.right + "\n", scanner.right, "\n"].join(")|(").replace(/\[/g, "\\[").replace(/\]/g, "\\]") + ")");
      return scanner;
    }, compile = function(source, left, name) {
      source = source.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
      left = left || "<";
      var put_cmd = "___v1ew.push(", insert_cmd = put_cmd, buff = new EJS.Buffer(["var ___v1ew = [];"], []), content = "", put = function(content) {
        buff.push(put_cmd, '"', clean(content), '");');
      }, startTag = null, empty = function() {
        content = "";
      };
      scan(makeScanner(left, left === "[" ? "]" : ">"), source || "", function(token, scanner) {
        if (startTag === null) {
          switch(token) {
            case"\n":
              content = content + "\n";
              put(content);
              buff.cr();
              empty();
              break;
            case scanner.left:
            case scanner.eLeft:
            case scanner.eeLeft:
            case scanner.cmnt:
              startTag = token;
              if (content.length > 0) {
                put(content);
              }empty();
              break;
            case scanner.dLeft:
              content += scanner.left;
              break;
            default:
              content += token;
              break;
          }
        } else {
          switch(token) {
            case scanner.right:
              switch(startTag) {
                case scanner.left:
                  if (content[content.length - 1] == "\n") {
                    content = chop(content);
                    buff.push(content, ";");
                    buff.cr();
                  } else {
                    buff.push(content, ";");
                  }
                  break;
                case scanner.eLeft:
                  buff.push(insert_cmd, "(jQuery.EJS.clean(", content, ")));");
                  break;
                case scanner.eeLeft:
                  buff.push(insert_cmd, "(jQuery.EJS.text(", content, ")));");
                  break;
              }
              startTag = null;
              empty();
              break;
            case scanner.dRight:
              content += scanner.right;
              break;
            default:
              content += token;
              break;
          }
        }
      });
      if (content.length > 0) {
        buff.push(put_cmd, '"', clean(content) + '");');
      }
      var template = buff.close(), out = {
        out : "try { with(_VIEW) { with (_CONTEXT) {" + template + " return ___v1ew.join('');}}}catch(e){e.lineNumber=null;throw e;}"
      };
      myEval.call(out, "this.process = (function(_CONTEXT,_VIEW){" + out.out + "});\r\n//@ sourceURL=" + name + ".js");
      return out;
    };
    EJS.Buffer = function(pre_cmd, post) {
      this.line = [];
      this.script = [];
      this.post = post;
      this.push.apply(this, pre_cmd);
    };
    EJS.Buffer.prototype = {
      push : function() {
        this.line.push.apply(this.line, arguments);
      },
      cr : function() {
        this.script.push(this.line.join(""), "\n");
        this.line = [];
      },
      close : function() {
        var stub;
        if (this.line.length > 0) {
          this.script.push(this.line.join(""));
          this.line = [];
        }
        stub = this.post.length && this.push.apply(this, this.post);
        this.script.push(";");
        return this.script.join("");
      }
    };
    EJS.options = {
      type : "<",
      ext : ".ejs"
    };
    EJS.Helpers = function(data, extras) {
      this._data = data;
      this._extras = extras;
      extend(this, extras);
    };
    EJS.Helpers.prototype = {
      plugin : function(name) {
        var args = $.makeArray(arguments), widget = args.shift();
        return function(el) {
          var jq = $(el);
          jq[widget].apply(jq, args);
        };
      },
      view : function(url, data, helpers) {
        helpers = helpers || this._extras;
        data = data || this._data;
        return $.View(url, data, helpers);
      }
    };
    $.View.register({
      suffix : "ejs",
      script : function(id, src) {
        return "jQuery.EJS(function(_CONTEXT,_VIEW) { " + new EJS({
          text : src,
          name : id
        }).template.out + " })";
      },
      renderer : function(id, text) {
        var ejs = new EJS({
          text : text,
          name : id
        });
        return function(data, helpers) {
          return ejs.render.call(ejs, data, helpers);
        };
      }
    });
  })(jQuery);
  (function($) {
    var radioCheck = /radio|checkbox/i, keyBreaker = /[^\[\]]+/g, numberMatcher = /^[\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?$/;
    var isNumber = function(value) {
      if ( typeof value == "number") {
        return true;
      }
      if ( typeof value != "string") {
        return false;
      }
      return value.match(numberMatcher);
    };
    $.fn.extend({
      formParams : function(convert) {
        if (this[0].nodeName.toLowerCase() == "form" && this[0].elements) {
          return jQuery(jQuery.makeArray(this[0].elements)).getParams(convert);
        }
        return jQuery("input[name], textarea[name], select[name]", this[0]).getParams(convert);
      },
      getParams : function(convert) {
        var data = {}, current;
        convert = convert === undefined ? false : convert;
        this.each(function() {
          var el = this, type = el.type && el.type.toLowerCase();
          if ((type == "submit") || !el.name) {
            return;
          }
          var key = el.name, value = $.data(el, "value") || $.fn.val.call([el]), isRadioCheck = radioCheck.test(el.type), parts = key.match(keyBreaker), write = !isRadioCheck || !!el.checked, lastPart;
          if (convert) {
            if (isNumber(value)) {
              value = parseFloat(value);
            } else {
              if (value === "true") {
                value = true;
              } else {
                if (value === "false") {
                  value = false;
                }
              }
            }
            if (value === "") {
              value = undefined;
            }
          }
          current = data;
          for (var i = 0; i < parts.length - 1; i++) {
            if (!current[parts[i]]) {
              current[parts[i]] = {};
            }
            current = current[parts[i]];
          }
          lastPart = parts[parts.length - 1];
          if ( lastPart in current && type === "checkbox") {
            if (!$.isArray(current[lastPart])) {
              current[lastPart] = current[lastPart] === undefined ? [] : [current[lastPart]];
            }
            if (write) {
              current[lastPart].push(value);
            }
          } else {
            if (write || !current[lastPart]) {
              current[lastPart] = write ? value : undefined;
            }
          }
        });
        return data;
      }
    });
  })(jQuery);
  var Kinetic = {};
  Kinetic.GlobalObject = {
    stages : [],
    idCounter : 0,
    extend : function(c, b) {
      for (var a in b.prototype) {
        if (b.prototype.hasOwnProperty(a)) {
          c.prototype[a] = b.prototype[a];
        }
      }
    }
  };
  Kinetic.Node = function(a) {
    this.visible = true;
    this.isListening = true;
    this.name = a;
    this.x = 0;
    this.y = 0;
    this.scale = {
      x : 1,
      y : 1
    };
    this.rotation = 0;
    this.eventListeners = {};
    this.drag = {
      x : false,
      y : false,
      moving : false
    };
    this.alpha = 1;
  };
  Kinetic.Node.prototype = {
    on : function(c, i) {
      var g = c.split(" ");
      for (var d = 0; d < g.length; d++) {
        var h = g[d];
        var b = (h.indexOf("touch") === -1) ? "on" + h : h;
        var f = b.split(".");
        var e = f[0];
        var a = f.length > 1 ? f[1] : "";
        if (!this.eventListeners[e]) {
          this.eventListeners[e] = [];
        }
        this.eventListeners[e].push({
          name : a,
          handler : i
        });
      }
    },
    off : function(b) {
      var h = b.split(" ");
      for (var d = 0; d < h.length; d++) {
        var j = h[d];
        var a = (j.indexOf("touch") === -1) ? "on" + j : j;
        var f = a.split(".");
        var e = f[0];
        if (this.eventListeners[e] && f.length > 1) {
          var c = f[1];
          for (var g = 0; g < this.eventListeners[e].length; g++) {
            if (this.eventListeners[e][g].name === c) {
              this.eventListeners[e].splice(g, 1);
              if (this.eventListeners[e].length === 0) {
                this.eventListeners[e] = undefined;
              }
              break;
            }
          }
        } else {
          this.eventListeners[e] = undefined;
        }
      }
    },
    show : function() {
      this.visible = true;
    },
    hide : function() {
      this.visible = false;
    },
    getZIndex : function() {
      return this.index;
    },
    setScale : function(b, a) {
      if (a) {
        this.scale.x = b;
        this.scale.y = a;
      } else {
        this.scale.x = b;
        this.scale.y = b;
      }
    },
    getScale : function() {
      return this.scale;
    },
    setPosition : function(a, b) {
      this.x = a;
      this.y = b;
    },
    getPosition : function() {
      return {
        x : this.x,
        y : this.y
      };
    },
    getAbsolutePosition : function() {
      var a = this.x;
      var c = this.y;
      var b = this.getParent();
      while (b.className !== "Stage") {
        a += b.x;
        c += b.y;
        b = b.parent;
      }
      return {
        x : a,
        y : c
      };
    },
    move : function(a, b) {
      this.x += a;
      this.y += b;
    },
    setRotation : function(a) {
      this.rotation = a;
    },
    getRotation : function() {
      return this.rotation;
    },
    rotate : function(a) {
      this.rotation += a;
    },
    listen : function(a) {
      this.isListening = a;
    },
    moveToTop : function() {
      var a = this.index;
      this.parent.children.splice(a, 1);
      this.parent.children.push(this);
      this.parent._setChildrenIndices();
    },
    moveUp : function() {
      var a = this.index;
      this.parent.children.splice(a, 1);
      this.parent.children.splice(a + 1, 0, this);
      this.parent._setChildrenIndices();
    },
    moveDown : function() {
      var a = this.index;
      if (a > 0) {
        this.parent.children.splice(a, 1);
        this.parent.children.splice(a - 1, 0, this);
        this.parent._setChildrenIndices();
      }
    },
    moveToBottom : function() {
      var a = this.index;
      this.parent.children.splice(a, 1);
      this.parent.children.unshift(this);
      this.parent._setChildrenIndices();
    },
    setZIndex : function(b) {
      var a = this.index;
      this.parent.children.splice(a, 1);
      this.parent.children.splice(b, 0, this);
      this.parent._setChildrenIndices();
    },
    setAlpha : function(a) {
      this.alpha = a;
    },
    getAlpha : function() {
      return this.alpha;
    },
    getAbsoluteAlpha : function() {
      var b = 1;
      var a = this;
      while (a.className !== "Stage") {
        b *= a.alpha;
        a = a.parent;
      }
      return b;
    },
    _initDrag : function() {
      var a = this;
      this.on("mousedown.initdrag touchstart.initdrag", function(b) {
        var c = a.getStage();
        var d = c.getUserPosition();
        if (d) {
          c.nodeDragging = a;
          c.nodeDragging.offset = {};
          c.nodeDragging.offset.x = d.x - a.x;
          c.nodeDragging.offset.y = d.y - a.y;
        }
      });
    },
    _dragCleanup : function() {
      if (!this.drag.x && !this.drag.y) {
        this.off("mousedown.initdrag");
        this.off("touchstart.initdrag");
      }
    },
    draggable : function(b) {
      if (b) {
        var a = !this.drag.x && !this.drag.y;
        this.drag.x = true;
        this.drag.y = true;
        if (a) {
          this._initDrag();
        }
      } else {
        this.drag.x = false;
        this.drag.y = false;
        this._dragCleanup();
      }
    },
    draggableX : function(b) {
      if (b) {
        var a = !this.drag.x && !this.drag.y;
        this.drag.x = true;
        if (a) {
          this._initDrag();
        }
      } else {
        this.drag.x = false;
        this._dragCleanup();
      }
    },
    draggableY : function(b) {
      if (b) {
        var a = !this.drag.x && !this.drag.y;
        this.drag.y = true;
        if (a) {
          this._initDrag();
        }
      } else {
        this.drag.y = false;
        this._dragCleanup();
      }
    },
    isDragging : function() {
      return this.drag.moving;
    },
    _handleEvents : function(b, a) {
      function c(g) {
        var f = g.eventListeners;
        if (f[b]) {
          var e = f[b];
          for (var d = 0; d < e.length; d++) {
            e[d].handler.apply(g, [a]);
          }
        }
        if (g.parent.className !== "Stage") {
          c(g.parent);
        }
      }

      c(this);
    },
    moveTo : function(b) {
      var a = this.parent;
      a.children.splice(this.index, 1);
      a._setChildrenIndices();
      b.children.push(this);
      this.index = b.children.length - 1;
      this.parent = b;
      b._setChildrenIndices();
      if (this.name) {
        a.childrenNames[this.name] = undefined;
        b.childrenNames[this.name] = this;
      }
    },
    getParent : function() {
      return this.parent;
    },
    getLayer : function() {
      if (this.className === "Layer") {
        return this;
      } else {
        return this.getParent().getLayer();
      }
    },
    getStage : function() {
      return this.getParent().getStage();
    },
    getName : function() {
      return this.name;
    }
  };
  Kinetic.Container = function() {
    this.children = [];
    this.childrenNames = {};
  };
  Kinetic.Container.prototype = {
    _setChildrenIndices : function() {
      if (this.className === "Stage") {
        var c = this.container.childNodes;
        var a = c[0];
        var b = c[1];
        this.container.innerHTML = "";
        this.container.appendChild(a);
        this.container.appendChild(b);
      }
      for (var d = 0; d < this.children.length; d++) {
        this.children[d].index = d;
        if (this.className === "Stage") {
          this.container.appendChild(this.children[d].canvas);
        }
      }
    },
    _drawChildren : function() {
      var a = this.children;
      for (var c = 0; c < a.length; c++) {
        var b = a[c];
        if (b.className === "Shape") {
          b._draw(b.getLayer());
        } else {
          b._draw();
        }
      }
    },
    getChildren : function() {
      return this.children;
    },
    getChild : function(a) {
      return this.childrenNames[a];
    },
    _add : function(a) {
      if (a.name) {
        this.childrenNames[a.name] = a;
      }
      a.id = Kinetic.GlobalObject.idCounter++;
      a.index = this.children.length;
      a.parent = this;
      this.children.push(a);
    },
    _remove : function(a) {
      if (a.name !== undefined) {
        this.childrenNames[a.name] = undefined;
      }
      this.children.splice(a.index, 1);
      this._setChildrenIndices();
      a = undefined;
    }
  };
  Kinetic.Stage = function(b, c, a) {
    this.className = "Stage";
    this.container = typeof b === "string" ? document.getElementById(b) : b;
    this.width = c;
    this.height = a;
    this.scale = {
      x : 1,
      y : 1
    };
    this.dblClickWindow = 400;
    this.targetShape = undefined;
    this.clickStart = false;
    this.mousePos = undefined;
    this.mouseDown = false;
    this.mouseUp = false;
    this.touchPos = undefined;
    this.touchStart = false;
    this.touchEnd = false;
    this.bufferLayer = new Kinetic.Layer();
    this.backstageLayer = new Kinetic.Layer();
    this.bufferLayer.parent = this;
    this.backstageLayer.parent = this;
    var e = this.backstageLayer;
    this._stripLayer(e);
    this.bufferLayer.getCanvas().style.display = "none";
    this.backstageLayer.getCanvas().style.display = "none";
    this.bufferLayer.canvas.width = this.width;
    this.bufferLayer.canvas.height = this.height;
    this.container.appendChild(this.bufferLayer.canvas);
    this.backstageLayer.canvas.width = this.width;
    this.backstageLayer.canvas.height = this.height;
    this.container.appendChild(this.backstageLayer.canvas);
    this._listen();
    this._prepareDrag();
    var d = Kinetic.GlobalObject.stages;
    d.push(this);
    this.id = Kinetic.GlobalObject.idCounter++;
    Kinetic.Container.apply(this, []);
  };
  Kinetic.Stage.prototype = {
    draw : function() {
      this._drawChildren();
    },
    _stripLayer : function(a) {
      a.context.stroke = function() {
      };
      a.context.fill = function() {
      };
      a.context.fillRect = function(c, e, d, b) {
        a.context.rect(c, e, d, b);
      };
      a.context.strokeRect = function(c, e, d, b) {
        a.context.rect(c, e, d, b);
      };
      a.context.drawImage = function() {
      };
      a.context.fillText = function() {
      };
      a.context.strokeText = function() {
      };
    },
    _endDrag : function(a) {
      if (this.nodeDragging) {
        if (this.nodeDragging.drag.moving) {
          this.nodeDragging.drag.moving = false;
          this.nodeDragging._handleEvents("ondragend", a);
        }
      }
      this.nodeDragging = undefined;
    },
    _prepareDrag : function() {
      var a = this;
      this.on("mousemove touchmove", function(b) {
        if (a.nodeDragging) {
          var c = a.getUserPosition();
          if (a.nodeDragging.drag.x) {
            a.nodeDragging.x = c.x - a.nodeDragging.offset.x;
          }
          if (a.nodeDragging.drag.y) {
            a.nodeDragging.y = c.y - a.nodeDragging.offset.y;
          }
          a.nodeDragging.getLayer().draw();
          if (!a.nodeDragging.drag.moving) {
            a.nodeDragging.drag.moving = true;
            a.nodeDragging._handleEvents("ondragstart", b);
          }
          a.nodeDragging._handleEvents("ondragmove", b);
        }
      }, false);
      this.on("mouseup touchend mouseout", function(b) {
        a._endDrag(b);
      });
    },
    setSize : function(c, a) {
      var d = this.children;
      for (var e = 0; e < d.length; e++) {
        var b = d[e];
        b.getCanvas().width = c;
        b.getCanvas().height = a;
        b.draw();
      }
      this.width = c;
      this.height = a;
      this.bufferLayer.getCanvas().width = c;
      this.bufferLayer.getCanvas().height = a;
      this.backstageLayer.getCanvas().width = c;
      this.backstageLayer.getCanvas().height = a;
    },
    setScale : function(d, c) {
      var b = this.scale.x;
      var a = this.scale.y;
      if (c) {
        this.scale.x = d;
        this.scale.y = c;
      } else {
        this.scale.x = d;
        this.scale.y = d;
      }
      var f = this.children;
      var e = this;
      function g(j) {
        for (var h = 0; h < j.length; h++) {
          var k = j[h];
          k.x *= e.scale.x / b;
          k.y *= e.scale.y / a;
          if (k.children) {
            g(k.children);
          }
        }
      }

      g(f);
    },
    getScale : function() {
      return this.scale;
    },
    clear : function() {
      var a = this.children;
      for (var b = 0; b < a.length; b++) {
        a[b].clear();
      }
    },
    toDataURL : function(e) {
      var b = this.bufferLayer;
      var a = b.getContext();
      var d = this.children;
      function c(h) {
        var g = d[h].getCanvas().toDataURL();
        var f = new Image();
        f.onload = function() {
          a.drawImage(this, 0, 0);
          h++;
          if (h < d.length) {
            c(h);
          } else {
            e(b.getCanvas().toDataURL());
          }
        };
        f.src = g;
      }
      b.clear();
      c(0);
    },
    remove : function(a) {
      this.container.removeChild(a.canvas);
      this._remove(a);
    },
    on : function(b, d) {
      var c = b.split(" ");
      for (var e = 0; e < c.length; e++) {
        var a = c[e];
        this.container.addEventListener(a, d, false);
      }
    },
    add : function(a) {
      if (a.name) {
        this.childrenNames[a.name] = a;
      }
      a.canvas.width = this.width;
      a.canvas.height = this.height;
      this._add(a);
      a.draw();
      this.container.appendChild(a.canvas);
    },
    _handleEvent : function(i) {
      if (!i) {
        i = window.event;
      }
      this._setMousePosition(i);
      this._setTouchPosition(i);
      var c = this.backstageLayer;
      var f = c.getContext();
      var g = this;
      c.clear();
      var h = 0;
      function d(j) {
        j._draw(c);
        var o = g.getUserPosition();
        var n = j.eventListeners;
        if (j.visible && o !== undefined && f.isPointInPath(o.x, o.y)) {
          if (g.mouseDown) {
            g.mouseDown = false;
            g.clickStart = true;
            j._handleEvents("onmousedown", i);
            return true;
          } else {
            if (g.mouseUp) {
              g.mouseUp = false;
              j._handleEvents("onmouseup", i);
              if (g.clickStart) {
                if ((g.nodeDragging && !g.nodeDragging.drag.moving) || !g.nodeDragging) {
                  j._handleEvents("onclick", i);
                  if (j.inDoubleClickWindow) {
                    j._handleEvents("ondblclick", i);
                  }
                  j.inDoubleClickWindow = true;
                  setTimeout(function() {
                    j.inDoubleClickWindow = false;
                  }, g.dblClickWindow);
                }
              }
              return true;
            } else {
              if (g.touchStart) {
                g.touchStart = false;
                j._handleEvents("touchstart", i);
                if (n.ondbltap && j.inDoubleClickWindow) {
                  var m = n.ondbltap;
                  for (var l = 0; l < m.length; l++) {
                    m[l].handler.apply(j, [i]);
                  }
                }
                j.inDoubleClickWindow = true;
                setTimeout(function() {
                  j.inDoubleClickWindow = false;
                }, g.dblClickWindow);
                return true;
              } else {
                if (g.touchEnd) {
                  g.touchEnd = false;
                  j._handleEvents("touchend", i);
                  return true;
                } else {
                  if (n.touchmove) {
                    j._handleEvents("touchmove", i);
                    return true;
                  } else {
                    if (!g.targetShape || (g.targetShape && g.targetShape.id !== j.id && g.targetShape.getZIndex() < j.getZIndex())) {
                      if (g.targetShape) {
                        var k = g.targetShape.eventListeners;
                        if (k) {
                          g.targetShape._handleEvents("onmouseout", i);
                        }
                      }
                      g.targetShape = j;
                      j._handleEvents("onmouseover", i);
                      return true;
                    } else {
                      j._handleEvents("onmousemove", i);
                      return true;
                    }
                  }
                }
              }
            }
          }
        } else {
          if (g.targetShape && g.targetShape.id === j.id) {
            g.targetShape = undefined;
            j._handleEvents("onmouseout", i);
            return true;
          }
        }
        return false;
      }

      function b(m) {
        var l = m.children;
        for (var k = l.length - 1; k >= 0; k--) {
          h++;
          var n = l[k];
          if (n.className === "Shape") {
            var j = d(n);
            if (j) {
              return true;
            }
          } else {
            b(n);
          }
        }
        return false;
      }

      for (var a = this.children.length - 1; a >= 0; a--) {
        var e = this.children[a];
        if (e.visible && a >= 0 && e.isListening) {
          if (b(e)) {
            a = -1;
          }
        }
      }
    },
    _listen : function() {
      var a = this;
      this.container.addEventListener("mousedown", function(b) {
        a.mouseDown = true;
        a._handleEvent(b);
      }, false);
      this.container.addEventListener("mousemove", function(b) {
        a.mouseUp = false;
        a.mouseDown = false;
        a._handleEvent(b);
      }, false);
      this.container.addEventListener("mouseup", function(b) {
        a.mouseUp = true;
        a.mouseDown = false;
        a._handleEvent(b);
        a.clickStart = false;
      }, false);
      this.container.addEventListener("mouseover", function(b) {
        a._handleEvent(b);
      }, false);
      this.container.addEventListener("mouseout", function(b) {
        a.mousePos = undefined;
      }, false);
      this.container.addEventListener("touchstart", function(b) {
        b.preventDefault();
        a.touchStart = true;
        a._handleEvent(b);
      }, false);
      this.container.addEventListener("touchmove", function(b) {
        b.preventDefault();
        a._handleEvent(b);
      }, false);
      this.container.addEventListener("touchend", function(b) {
        b.preventDefault();
        a.touchEnd = true;
        a._handleEvent(b);
      }, false);
    },
    getMousePosition : function(a) {
      return this.mousePos;
    },
    getTouchPosition : function(a) {
      return this.touchPos;
    },
    getUserPosition : function(a) {
      return this.getTouchPosition() || this.getMousePosition();
    },
    _setMousePosition : function(a) {
      var c = a.clientX - this._getContainerPosition().left + window.pageXOffset;
      var b = a.clientY - this._getContainerPosition().top + window.pageYOffset;
      this.mousePos = {
        x : c,
        y : b
      };
    },
    _setTouchPosition : function(c) {
      if (c.touches !== undefined && c.touches.length === 1) {
        var d = c.touches[0];
        var b = d.clientX - this._getContainerPosition().left + window.pageXOffset;
        var a = d.clientY - this._getContainerPosition().top + window.pageYOffset;
        this.touchPos = {
          x : b,
          y : a
        };
      }
    },
    _getContainerPosition : function() {
      var c = this.container;
      var b = 0;
      var a = 0;
      while (c && c.tagName !== "BODY") {
        b += c.offsetTop;
        a += c.offsetLeft;
        c = c.offsetParent;
      }
      return {
        top : b,
        left : a
      };
    },
    getContainer : function() {
      return this.container;
    },
    getStage : function() {
      return this;
    },
    getTargetShape : function() {
      return this.targetShape;
    }
  };
  Kinetic.GlobalObject.extend(Kinetic.Stage, Kinetic.Container);
  Kinetic.Layer = function(a) {
    this.className = "Layer";
    this.canvas = document.createElement("canvas");
    this.context = this.canvas.getContext("2d");
    this.canvas.style.position = "absolute";
    Kinetic.Container.apply(this, []);
    Kinetic.Node.apply(this, [a]);
  };
  Kinetic.Layer.prototype = {
    draw : function() {
      this._draw();
    },
    _draw : function() {
      this.clear();
      if (this.visible) {
        this._drawChildren();
      }
    },
    clear : function() {
      var b = this.getContext();
      var a = this.getCanvas();
      b.clearRect(0, 0, a.width, a.height);
    },
    getCanvas : function() {
      return this.canvas;
    },
    getContext : function() {
      return this.context;
    },
    add : function(a) {
      this._add(a);
    },
    remove : function(a) {
      this._remove(a);
    }
  };
  Kinetic.GlobalObject.extend(Kinetic.Layer, Kinetic.Container);
  Kinetic.GlobalObject.extend(Kinetic.Layer, Kinetic.Node);
  Kinetic.Group = function(a) {
    this.className = "Group";
    Kinetic.Container.apply(this, []);
    Kinetic.Node.apply(this, [a]);
  };
  Kinetic.Group.prototype = {
    _draw : function() {
      if (this.visible) {
        this._drawChildren();
      }
    },
    add : function(a) {
      this._add(a);
    },
    remove : function(a) {
      this._remove(a);
    }
  };
  Kinetic.GlobalObject.extend(Kinetic.Group, Kinetic.Container);
  Kinetic.GlobalObject.extend(Kinetic.Group, Kinetic.Node);
  Kinetic.Shape = function(b, a) {
    this.className = "Shape";
    this.drawFunc = b;
    Kinetic.Node.apply(this, [a]);
  };
  Kinetic.Shape.prototype = {
    getContext : function() {
      return this.tempLayer.getContext();
    },
    getCanvas : function() {
      return this.tempLayer.getCanvas();
    },
    _draw : function(d) {
      if (this.visible) {
        var a = d.getStage();
        var c = d.getContext();
        var f = [];
        f.unshift(this);
        var e = this.parent;
        while (e.className !== "Stage") {
          f.unshift(e);
          e = e.parent;
        }
        for (var h = 0; h < f.length; h++) {
          var g = f[h];
          c.save();
          if (g.x !== 0 || g.y !== 0) {
            c.translate(g.x, g.y);
          }
          if (g.rotation !== 0) {
            c.rotate(g.rotation);
          }
          if (g.scale.x !== 1 || g.scale.y !== 1) {
            c.scale(g.scale.x, g.scale.y);
          }
          if (g.getAbsoluteAlpha() !== 1) {
            c.globalAlpha = g.getAbsoluteAlpha();
          }
        }
        c.save();
        if (a && (a.scale.x !== 1 || a.scale.y !== 1)) {
          c.scale(a.scale.x, a.scale.y);
        }
        this.tempLayer = d;
        this.drawFunc.call(this);
        for (var b = 0; b < f.length; b++) {
          c.restore();
        }
        c.restore();
      }
    }
  };
  Kinetic.GlobalObject.extend(Kinetic.Shape, Kinetic.Node);
  xml2json = {
    parser : function(xmlcode, ignoretags, debug) {
      if (!xmlcode.replace) {
        if (xmlcode.xml) {
          xmlcode = xmlcode.xml;
        } else {
          xmlcode = (new XMLSerializer()).serializeToString(xmlcode);
        }
      }
      if (!ignoretags) {
        ignoretags = "";
      }
      xmlcode = xmlcode.replace(/\s*\/>/g, "/>");
      xmlcode = xmlcode.replace(/<\?[^>]*>/g, "").replace(/<\![^>]*>/g, "");
      if (!ignoretags.sort) {
        ignoretags = ignoretags.split(",");
      }
      var x = this.no_fast_endings(xmlcode);
      x = this.attris_to_tags(x);
      x = escape(x);
      x = x.split("%3C").join("<").split("%3E").join(">").split("%3D").join("=").split("%22").join('"');
      for (var i = 0; i < ignoretags.length; i++) {
        x = x.replace(new RegExp("<" + ignoretags[i] + ">", "g"), "*$**" + ignoretags[i] + "**$*");
        x = x.replace(new RegExp("</" + ignoretags[i] + ">", "g"), "*$***" + ignoretags[i] + "**$*");
      }
      x = "<JSONTAGWRAPPER>" + x + "</JSONTAGWRAPPER>";
      this.xmlobject = {};
      var y = this.xml_to_object(x).jsontagwrapper;
      if (debug) {
        y = this.show_json_structure(y, debug);
      }
      return y;
    },
    xml_to_object : function(xmlcode) {
      var x = xmlcode.replace(/<\//g, "�");
      x = x.split("<");
      var y = [];
      var level = 0;
      var opentags = [];
      for (var i = 1; i < x.length; i++) {
        var tagname = x[i].split(">")[0];
        opentags.push(tagname);
        level++;
        y.push(level + "<" + x[i].split("�")[0]);
        while (x[i].indexOf("�" + opentags[opentags.length - 1] + ">") >= 0) {
          level--;
          opentags.pop();
        }
      }
      var oldniva = -1;
      var objname = "this.xmlobject";
      for (var i = 0; i < y.length; i++) {
        var preeval = "";
        var niva = y[i].split("<")[0];
        var tagnamn = y[i].split("<")[1].split(">")[0];
        tagnamn = tagnamn.toLowerCase();
        var rest = y[i].split(">")[1];
        if (niva <= oldniva) {
          var tabort = oldniva - niva + 1;
          for (var j = 0; j < tabort; j++) {
            objname = objname.substring(0, objname.lastIndexOf("."));
          }
        }
        objname += "." + tagnamn;
        var pobject = objname.substring(0, objname.lastIndexOf("."));
        if (eval("typeof " + pobject) != "object") {
          preeval += pobject + "={value:" + pobject + "};\n";
        }
        var objlast = objname.substring(objname.lastIndexOf(".") + 1);
        var already = false;
        for (k in eval(pobject)) {
          if (k == objlast) {
            already = true;
          }
        }
        var onlywhites = true;
        for (var s = 0; s < rest.length; s += 3) {
          if (rest.charAt(s) != "%") {
            onlywhites = false;
          }
        }
        if (rest != "" && !onlywhites) {
          if (rest / 1 != rest) {
            rest = "'" + rest.replace(/\'/g, "\\'") + "'";
            rest = rest.replace(/\*\$\*\*\*/g, "</");
            rest = rest.replace(/\*\$\*\*/g, "<");
            rest = rest.replace(/\*\*\$\*/g, ">");
          }
        } else {
          rest = "{}";
        }
        if (rest.charAt(0) == "'") {
          rest = "unescape(" + rest + ")";
        }
        if (already && !eval(objname + ".sort")) {
          preeval += objname + "=[" + objname + "];\n";
        }
        var before = "=";
        after = "";
        if (already) {
          before = ".push(";
          after = ")";
        }
        var toeval = preeval + objname + before + rest + after;
        eval(toeval);
        if (eval(objname + ".sort")) {
          objname += "[" + eval(objname + ".length-1") + "]";
        }
        oldniva = niva;
      }
      return this.xmlobject;
    },
    show_json_structure : function(obj, debug, l) {
      var x = "";
      if (obj.sort) {
        x += "[\n";
      } else {
        x += "{\n";
      }
      for (var i in obj) {
        if (!obj.sort) {
          x += i + ":";
        }
        if ( typeof obj[i] == "object") {
          x += this.show_json_structure(obj[i], false, 1);
        } else {
          if ( typeof obj[i] == "function") {
            var v = obj[i] + "";
            x += v;
          } else {
            if ( typeof obj[i] != "string") {
              x += obj[i] + ",\n";
            } else {
              x += "'" + obj[i].replace(/\'/g, "\\'").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r") + "',\n";
            }
          }
        }
      }
      if (obj.sort) {
        x += "],\n";
      } else {
        x += "},\n";
      }
      if (!l) {
        x = x.substring(0, x.lastIndexOf(","));
        x = x.replace(new RegExp(",\n}", "g"), "\n}");
        x = x.replace(new RegExp(",\n]", "g"), "\n]");
        var y = x.split("\n");
        x = "";
        var lvl = 0;
        for (var i = 0; i < y.length; i++) {
          if (y[i].indexOf("}") >= 0 || y[i].indexOf("]") >= 0) {
            lvl--;
          }
          tabs = "";
          for (var j = 0; j < lvl; j++) {
            tabs += "\t";
          }
          x += tabs + y[i] + "\n";
          if (y[i].indexOf("{") >= 0 || y[i].indexOf("[") >= 0) {
            lvl++;
          }
        }
        if (debug == "html") {
          x = x.replace(/</g, "&lt;").replace(/>/g, "&gt;");
          x = x.replace(/\n/g, "<BR>").replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
        }
        if (debug == "compact") {
          x = x.replace(/\n/g, "").replace(/\t/g, "");
        }
      }
      return x;
    },
    no_fast_endings : function(x) {
      x = x.split("/>");
      for (var i = 1; i < x.length; i++) {
        var t = x[i-1].substring(x[i-1].lastIndexOf("<")+1).split(" ")[0];
        x[i] = "></" + t + ">" + x[i];
      }
      x = x.join("");
      return x;
    },
    attris_to_tags : function(x) {
      var d = " =\"'".split("");
      x = x.split(">");
      for (var i = 0; i < x.length; i++) {
        var temp = x[i].split("<");
        for (var r = 0; r < 4; r++) {
          temp[0] = temp[0].replace(new RegExp(d[r], "g"), "_jsonconvtemp" + r + "_");
        }
        if (temp[1]) {
          temp[1] = temp[1].replace(/'/g, '"');
          temp[1] = temp[1].split('"');
          for (var j = 1; j < temp[1].length; j += 2) {
            for (var r = 0; r < 4; r++) {
              temp[1][j] = temp[1][j].replace(new RegExp(d[r], "g"), "_jsonconvtemp" + r + "_");
            }
          }
          temp[1] = temp[1].join('"');
        }
        x[i] = temp.join("<");
      }
      x = x.join(">");
      x = x.replace(/ ([^=]*)=([^ |>]*)/g, "><$1>$2</$1");
      x = x.replace(/>"/g, ">").replace(/"</g, "<");
      for (var r = 0; r < 4; r++) {
        x = x.replace(new RegExp("_jsonconvtemp" + r + "_", "g"), d[r]);
      }
      return x;
    }
  };
  if (!Array.prototype.push) {
    Array.prototype.push = function(x) {
      this[this.length] = x;
      return true;
    };
  }
  if (!Array.prototype.pop) {
    Array.prototype.pop = function() {
      var response = this[this.length - 1];
      this.length--;
      return response;
    };
  }
  (function($) {
    var lastTap = null;
    var tapValid = false;
    var tapTimeout = null;
    var rightClickPending = false;
    var rightClickEvent = null;
    var holdTimeout = null;
    var cancelMouseUp = false;
    cancelTap = function() {
      tapValid = false;
    };
    cancelHold = function() {
      if (rightClickPending) {
        window.clearTimeout(holdTimeout);
        rightClickPending = false;
        rightClickEvent = null;
      }
    };
    startHold = function(event) {
      if (rightClickPending) {
        return;
      }
      rightClickPending = true;
      rightClickEvent = (event.changedTouches)[0];
      holdTimeout = window.setTimeout("doRightClick();", 800);
    };
    doRightClick = function() {
      rightClickPending = false;
      var first = rightClickEvent, simulatedEvent = document.createEvent("MouseEvent");
      simulatedEvent.initMouseEvent("mouseup", true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0, null);
      first.target.dispatchEvent(simulatedEvent);
      simulatedEvent = document.createEvent("MouseEvent");
      simulatedEvent.initMouseEvent("mousedown", true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 2, null);
      first.target.dispatchEvent(simulatedEvent);
      simulatedEvent = document.createEvent("MouseEvent");
      simulatedEvent.initMouseEvent("contextmenu", true, true, window, 1, first.screenX + 50, first.screenY + 5, first.clientX + 50, first.clientY + 5, false, false, false, false, 2, null);
      first.target.dispatchEvent(simulatedEvent);
      cancelMouseUp = true;
      rightClickEvent = null;
    };
    iPadTouchStart = function(event) {
      var touches = event.changedTouches, first = touches[0], type = "mouseover", simulatedEvent = document.createEvent("MouseEvent");
      simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0, null);
      first.target.dispatchEvent(simulatedEvent);
      type = "mousedown";
      simulatedEvent = document.createEvent("MouseEvent");
      simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0, null);
      first.target.dispatchEvent(simulatedEvent);
      if (!tapValid) {
        lastTap = first.target;
        tapValid = true;
        tapTimeout = window.setTimeout("cancelTap();", 600);
        startHold(event);
      } else {
        window.clearTimeout(tapTimeout);
        if (first.target == lastTap) {
          lastTap = null;
          tapValid = false;
          type = "click";
          simulatedEvent = document.createEvent("MouseEvent");
          simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0, null);
          first.target.dispatchEvent(simulatedEvent);
          type = "dblclick";
          simulatedEvent = document.createEvent("MouseEvent");
          simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0, null);
          first.target.dispatchEvent(simulatedEvent);
        } else {
          lastTap = first.target;
          tapValid = true;
          tapTimeout = window.setTimeout("cancelTap();", 600);
          startHold(event);
        }
      }
    };
    iPadTouchHandler = function(event) {
      var type = "", button = 0;
      if (event.touches.length > 1) {
        return;
      }
      switch(event.type) {
        case"touchstart":
          if ($(event.changedTouches[0].target).is("select") || $(event.changedTouches[0].target).is("input")) {
            return;
          }iPadTouchStart(event);
          event.preventDefault();
          return false;
          break;
        case"touchmove":
          cancelHold();
          type = "mousemove";
          event.preventDefault();
          break;
        case"touchend":
          if (cancelMouseUp) {
            cancelMouseUp = false;
            event.preventDefault();
            return false;
          }cancelHold();
          type = "mouseup";
          break;
        default:
          return;
      }
      var touches = event.changedTouches, first = touches[0], simulatedEvent = document.createEvent("MouseEvent");
      simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, button, null);
      first.target.dispatchEvent(simulatedEvent);
      if (type == "mouseup" && tapValid && first.target == lastTap) {
        simulatedEvent = document.createEvent("MouseEvent");
        simulatedEvent.initMouseEvent("click", true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, button, null);
        first.target.dispatchEvent(simulatedEvent);
      }
    };
    $.extend($.support, {
      touch : "ontouchend" in document
    });
    $.fn.addTouch = function() {
      if ($.support.touch) {
        this.each(function(i, el) {
          el.addEventListener("touchstart", iPadTouchHandler, false);
          el.addEventListener("touchmove", iPadTouchHandler, false);
          el.addEventListener("touchend", iPadTouchHandler, false);
          el.addEventListener("touchcancel", iPadTouchHandler, false);
        });
      }
    };
  })(jQuery);
  (function(a) {
    var b = "0.3.4", c = "hasOwnProperty", d = /[\.\/]/, e = "*", f = function() {
    }, g = function(a, b) {
      return a - b;
    }, h, i, j = {
      n : {}
    }, k = function(a, b) {
      var c = j, d = i, e = Array.prototype.slice.call(arguments, 2), f = k.listeners(a), l = 0, m = !1, n, o = [], p = {}, q = [], r = h, s = [];
      h = a, i = 0;
      for (var t = 0, u = f.length; t < u; t++) {
        "zIndex" in f[t] && (o.push(f[t].zIndex), f[t].zIndex < 0 && (p[f[t].zIndex] = f[t]));
      }
      o.sort(g);
      while (o[l] < 0) {
        n = p[o[l++]], q.push(n.apply(b, e));
        if (i) {
          i = d;
          return q;
        }
      }
      for ( t = 0; t < u; t++) {
        n = f[t];
        if ("zIndex" in n) {
          if (n.zIndex == o[l]) {
            q.push(n.apply(b, e));
            if (i) {
              break;
            }
            do {
              l++, n = p[o[l]], n && q.push(n.apply(b, e));
              if (i) {
                break;
              }
            } while(n);
          } else {
            p[n.zIndex] = n;
          }
        } else {
          q.push(n.apply(b, e));
          if (i) {
            break;
          }
        }
      }
      i = d, h = r;
      return q.length ? q : null;
    };
    k.listeners = function(a) {
      var b = a.split(d), c = j, f, g, h, i, k, l, m, n, o = [c], p = [];
      for ( i = 0, k = b.length; i < k; i++) {
        n = [];
        for ( l = 0, m = o.length; l < m; l++) {
          c = o[l].n, g = [c[b[i]], c[e]], h = 2;
          while (h--) {
            f = g[h], f && (n.push(f), p = p.concat(f.f || []));
          }
        }
        o = n;
      }
      return p;
    }, k.on = function(a, b) {
      var c = a.split(d), e = j;
      for (var g = 0, h = c.length; g < h; g++) {
        e = e.n, !e[c[g]] && (e[c[g]] = {
          n : {}
        }), e = e[c[g]];
      }
      e.f = e.f || [];
      for ( g = 0, h = e.f.length; g < h; g++) {
        if (e.f[g] == b) {
          return f;
        }
      }
      e.f.push(b);
      return function(a) {
        +a == +a && (b.zIndex = +a);
      };
    }, k.stop = function() {
      i = 1;
    }, k.nt = function(a) {
      if (a) {
        return (new RegExp("(?:\\.|\\/|^)" + a + "(?:\\.|\\/|$)")).test(h);
      }
      return h;
    }, k.off = k.unbind = function(a, b) {
      var f = a.split(d), g, h, i, k, l, m, n, o = [j];
      for ( k = 0, l = f.length; k < l; k++) {
        for ( m = 0; m < o.length; m += i.length - 2) {
          i = [m, 1], g = o[m].n;
          if (f[k] != e) {
            g[f[k]] && i.push(g[f[k]]);
          } else {
            for (h in g) {
              g[c](h) && i.push(g[h]);
            }
          }
          o.splice.apply(o, i);
        }
      }
      for ( k = 0, l = o.length; k < l; k++) {
        g = o[k];
        while (g.n) {
          if (b) {
            if (g.f) {
              for ( m = 0, n = g.f.length; m < n; m++) {
                if (g.f[m] == b) {
                  g.f.splice(m, 1);
                  break;
                }
              }
              !g.f.length &&
              delete g.f;
            }
            for (h in g.n) {
              if (g.n[c](h) && g.n[h].f) {
                var p = g.n[h].f;
                for ( m = 0, n = p.length; m < n; m++) {
                  if (p[m] == b) {
                    p.splice(m, 1);
                    break;
                  }
                }
                !p.length &&
                delete g.n[h].f;
              }
            }
          } else {
            delete g.f;
            for (h in g.n) {
              g.n[c](h) && g.n[h].f &&
              delete g.n[h].f;
            }
          }
          g = g.n;
        }
      }
    }, k.once = function(a, b) {
      var c = function() {
        var d = b.apply(this, arguments);
        k.unbind(a, c);
        return d;
      };
      return k.on(a, c);
    }, k.version = b, k.toString = function() {
      return "You are running Eve " + b;
    }, typeof module != "undefined" && module.exports ? module.exports = k : typeof define != "undefined" ? define("eve", [], function() {
      return k;
    }) : a.eve = k;
  })(this), function() {
    function cF(a) {
      for (var b = 0; b < cy.length; b++) {
        cy[b].el.paper == a && cy.splice(b--, 1);
      }
    }

    function cE(b, d, e, f, h, i) {
      e = Q(e);
      var j, k, l, m = [], o, p, q, t = b.ms, u = {}, v = {}, w = {};
      if (f) {
        for ( y = 0, z = cy.length; y < z; y++) {
          var x = cy[y];
          if (x.el.id == d.id && x.anim == b) {
            x.percent != e ? (cy.splice(y, 1), l = 1) : k = x, d.attr(x.totalOrigin);
            break;
          }
        }
      } else {
        f = +v;
      }
      for (var y = 0, z = b.percents.length; y < z; y++) {
        if (b.percents[y] == e || b.percents[y] > f * b.top) {
          e = b.percents[y], p = b.percents[y - 1] || 0, t = t / b.top * (e - p), o = b.percents[y + 1], j = b.anim[e];
          break;
        }
        f && d.attr(b.anim[b.percents[y]]);
      }
      if (!!j) {
        if (!k) {
          for (var A in j) {
            if (j[g](A)) {
              if (U[g](A) || d.paper.customAttributes[g](A)) {
                u[A] = d.attr(A), u[A] == null && (u[A] = T[A]), v[A] = j[A];
                switch(U[A]) {
                  case C:
                    w[A] = (v[A] - u[A]) / t;
                    break;
                  case"colour":
                    u[A] = a.getRGB(u[A]);
                    var B = a.getRGB(v[A]);
                    w[A] = {
                      r : (B.r - u[A].r) / t,
                      g : (B.g - u[A].g) / t,
                      b : (B.b - u[A].b) / t
                    };
                    break;
                  case"path":
                    var D = bR(u[A], v[A]), E = D[1];
                    u[A] = D[0], w[A] = [];
                    for ( y = 0, z = u[A].length; y < z; y++) {
                      w[A][y] = [0];
                      for (var F = 1, G = u[A][y].length; F < G; F++) {
                        w[A][y][F] = (E[y][F] - u[A][y][F]) / t;
                      }
                    }
                    break;
                  case"transform":
                    var H = d._, I = ca(H[A], v[A]);
                    if (I) {
                      u[A] = I.from, v[A] = I.to, w[A] = [], w[A].real = !0;
                      for ( y = 0, z = u[A].length; y < z; y++) {
                        w[A][y] = [u[A][y][0]];
                        for ( F = 1, G = u[A][y].length; F < G; F++) {
                          w[A][y][F] = (v[A][y][F] - u[A][y][F]) / t;
                        }
                      }
                    } else {
                      var J = d.matrix || new cb, K = {
                        _ : {
                          transform : H.transform
                        },
                        getBBox : function() {
                          return d.getBBox(1);
                        }
                      };
                      u[A] = [J.a, J.b, J.c, J.d, J.e, J.f], b$(K, v[A]), v[A] = K._.transform, w[A] = [(K.matrix.a - J.a) / t, (K.matrix.b - J.b) / t, (K.matrix.c - J.c) / t, (K.matrix.d - J.d) / t, (K.matrix.e - J.e) / t, (K.matrix.f - J.f) / t];
                    }
                    break;
                  case"csv":
                    var L = r(j[A])[s](c), M = r(u[A])[s](c);
                    if (A == "clip-rect") {
                      u[A] = M, w[A] = [], y = M.length;
                      while (y--) {
                        w[A][y] = (L[y] - u[A][y]) / t;
                      }
                    }
                    v[A] = L;
                    break;
                  default:
                    L = [][n](j[A]), M = [][n](u[A]), w[A] = [], y = d.paper.customAttributes[A].length;
                    while (y--) {
                      w[A][y] = ((L[y] || 0) - (M[y] || 0)) / t;
                    }
                }
              }
            }
          }
          var O = j.easing, P = a.easing_formulas[O];
          if (!P) {
            P = r(O).match(N);
            if (P && P.length == 5) {
              var R = P;
              P = function(a) {
                return cC(a, +R[1], +R[2], +R[3], +R[4], t);
              };
            } else {
              P = bf;
            }
          }
          q = j.start || b.start || +(new Date), x = {
            anim : b,
            percent : e,
            timestamp : q,
            start : q + (b.del || 0),
            status : 0,
            initstatus : f || 0,
            stop : !1,
            ms : t,
            easing : P,
            from : u,
            diff : w,
            to : v,
            el : d,
            callback : j.callback,
            prev : p,
            next : o,
            repeat : i || b.times,
            origin : d.attr(),
            totalOrigin : h
          }, cy.push(x);
          if (f && !k && !l) {
            x.stop = !0, x.start = new Date - t * f;
            if (cy.length == 1) {
              return cA();
            }
          }
          l && (x.start = new Date - x.ms * f), cy.length == 1 && cz(cA);
        } else {
          k.initstatus = f, k.start = new Date - k.ms * f;
        }
        eve("raphael.anim.start." + d.id, d, b);
      }
    }

    function cD(a, b) {
      var c = [], d = {};
      this.ms = b, this.times = 1;
      if (a) {
        for (var e in a) {
          a[g](e) && (d[Q(e)] = a[e], c.push(Q(e)));
        }
        c.sort(bd);
      }
      this.anim = d, this.top = c[c.length - 1], this.percents = c;
    }

    function cC(a, b, c, d, e, f) {
      function o(a, b) {
        var c, d, e, f, j, k;
        for ( e = a, k = 0; k < 8; k++) {
          f = m(e) - a;
          if (z(f) < b) {
            return e;
          }
          j = (3 * i * e + 2 * h) * e + g;
          if (z(j) < 0.000001) {
            break;
          }
          e = e - f / j;
        }
        c = 0, d = 1, e = a;
        if (e < c) {
          return c;
        }
        if (e > d) {
          return d;
        }
        while (c < d) {
          f = m(e);
          if (z(f - a) < b) {
            return e;
          }
          a > f ? c = e : d = e, e = (d - c) / 2 + c;
        }
        return e;
      }

      function n(a, b) {
        var c = o(a, b);
        return ((l * c + k) * c + j) * c;
      }

      function m(a) {
        return ((i * a + h) * a + g) * a;
      }

      var g = 3 * b, h = 3 * (d - b) - g, i = 1 - g - h, j = 3 * c, k = 3 * (e - c) - j, l = 1 - j - k;
      return n(a, 1 / (200 * f));
    }

    function cq() {
      return this.x + q + this.y + q + this.width + " × " + this.height;
    }

    function cp() {
      return this.x + q + this.y;
    }

    function cb(a, b, c, d, e, f) {
      a != null ? (this.a = +a, this.b = +b, this.c = +c, this.d = +d, this.e = +e, this.f = +f) : (this.a = 1, this.b = 0, this.c = 0, this.d = 1, this.e = 0, this.f = 0);
    }

    function bH(b, c, d) {
      b = a._path2curve(b), c = a._path2curve(c);
      var e, f, g, h, i, j, k, l, m, n, o = d ? 0 : [];
      for (var p = 0, q = b.length; p < q; p++) {
        var r = b[p];
        if (r[0] == "M") {
          e = i = r[1], f = j = r[2];
        } else {
          r[0] == "C" ? ( m = [e, f].concat(r.slice(1)), e = m[6], f = m[7]) : ( m = [e, f, e, f, i, j, i, j], e = i, f = j);
          for (var s = 0, t = c.length; s < t; s++) {
            var u = c[s];
            if (u[0] == "M") {
              g = k = u[1], h = l = u[2];
            } else {
              u[0] == "C" ? ( n = [g, h].concat(u.slice(1)), g = n[6], h = n[7]) : ( n = [g, h, g, h, k, l, k, l], g = k, h = l);
              var v = bG(m, n, d);
              if (d) {
                o += v;
              } else {
                for (var w = 0, x = v.length; w < x; w++) {
                  v[w].segment1 = p, v[w].segment2 = s, v[w].bez1 = m, v[w].bez2 = n;
                }
                o = o.concat(v);
              }
            }
          }
        }
      }
      return o;
    }

    function bG(b, c, d) {
      var e = a.bezierBBox(b), f = a.bezierBBox(c);
      if (!a.isBBoxIntersect(e, f)) {
        return d ? 0 : [];
      }
      var g = bB.apply(0, b), h = bB.apply(0, c), i = ~~(g / 5), j = ~~(h / 5), k = [], l = [], m = {}, n = d ? 0 : [];
      for (var o = 0; o < i + 1; o++) {
        var p = a.findDotsAtSegment.apply(a, b.concat(o / i));
        k.push({
          x : p.x,
          y : p.y,
          t : o / i
        });
      }
      for ( o = 0; o < j + 1; o++) {
        p = a.findDotsAtSegment.apply(a, c.concat(o / j)), l.push({
          x : p.x,
          y : p.y,
          t : o / j
        });
      }
      for ( o = 0; o < i; o++) {
        for (var q = 0; q < j; q++) {
          var r = k[o], s = k[o + 1], t = l[q], u = l[q + 1], v = z(s.x - r.x) < 0.001 ? "y" : "x", w = z(u.x - t.x) < 0.001 ? "y" : "x", x = bD(r.x, r.y, s.x, s.y, t.x, t.y, u.x, u.y);
          if (x) {
            if (m[x.x.toFixed(4)] == x.y.toFixed(4)) {
              continue;
            }
            m[x.x.toFixed(4)] = x.y.toFixed(4);
            var y = r.t + z((x[v] - r[v]) / (s[v] - r[v])) * (s.t - r.t), A = t.t + z((x[w] - t[w]) / (u[w] - t[w])) * (u.t - t.t);
            y >= 0 && y <= 1 && A >= 0 && A <= 1 && ( d ? n++ : n.push({
              x : x.x,
              y : x.y,
              t1 : y,
              t2 : A
            }));
          }
        }
      }
      return n;
    }

    function bF(a, b) {
      return bG(a, b, 1);
    }

    function bE(a, b) {
      return bG(a, b);
    }

    function bD(a, b, c, d, e, f, g, h) {
      if (!(x(a, c) < y(e, g) || y(a, c) > x(e, g) || x(b, d) < y(f, h) || y(b, d) > x(f, h))) {
        var i = (a * d - b * c) * (e - g) - (a - c) * (e * h - f * g), j = (a * d - b * c) * (f - h) - (b - d) * (e * h - f * g), k = (a - c) * (f - h) - (b - d) * (e - g);
        if (!k) {
          return;
        }
        var l = i / k, m = j / k, n = +l.toFixed(2), o = +m.toFixed(2);
        if (n < +y(a, c).toFixed(2) || n > +x(a, c).toFixed(2) || n < +y(e, g).toFixed(2) || n > +x(e, g).toFixed(2) || o < +y(b, d).toFixed(2) || o > +x(b, d).toFixed(2) || o < +y(f, h).toFixed(2) || o > +x(f, h).toFixed(2)) {
          return;
        }
        return {
          x : l,
          y : m
        };
      }
    }

    function bC(a, b, c, d, e, f, g, h, i) {
      if (!(i < 0 || bB(a, b, c, d, e, f, g, h) < i)) {
        var j = 1, k = j / 2, l = j - k, m, n = 0.01;
        m = bB(a, b, c, d, e, f, g, h, l);
        while (z(m - i) > n) {
          k /= 2, l += (m < i ? 1 : -1) * k, m = bB(a, b, c, d, e, f, g, h, l);
        }
        return l;
      }
    }

    function bB(a, b, c, d, e, f, g, h, i) {
      i == null && ( i = 1), i = i > 1 ? 1 : i < 0 ? 0 : i;
      var j = i / 2, k = 12, l = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816], m = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472], n = 0;
      for (var o = 0; o < k; o++) {
        var p = j * l[o] + j, q = bA(p, a, c, e, g), r = bA(p, b, d, f, h), s = q * q + r * r;
        n += m[o] * w.sqrt(s);
      }
      return j * n;
    }

    function bA(a, b, c, d, e) {
      var f = -3 * b + 9 * c - 9 * d + 3 * e, g = a * f + 6 * b - 12 * c + 6 * d;
      return a * g - 3 * b + 3 * c;
    }

    function by(a, b) {
      var c = [];
      for (var d = 0, e = a.length; e - 2 * !b > d; d += 2) {
        var f = [{
          x : +a[d - 2],
          y : +a[d - 1]
        }, {
          x : +a[d],
          y : +a[d + 1]
        }, {
          x : +a[d + 2],
          y : +a[d + 3]
        }, {
          x : +a[d + 4],
          y : +a[d + 5]
        }];
        b ? d ? e - 4 == d ? f[3] = {
          x : +a[0],
          y : +a[1]
        } : e - 2 == d && (f[2] = {
          x : +a[0],
          y : +a[1]
        }, f[3] = {
          x : +a[2],
          y : +a[3]
        }) : f[0] = {
          x : +a[e - 2],
          y : +a[e - 1]
        } : e - 4 == d ? f[3] = f[2] : d || (f[0] = {
          x : +a[d],
          y : +a[d + 1]
        }), c.push(["C", (-f[0].x + 6 * f[1].x + f[2].x) / 6, (-f[0].y + 6 * f[1].y + f[2].y) / 6, (f[1].x + 6 * f[2].x - f[3].x) / 6, (f[1].y + 6 * f[2].y - f[3].y) / 6, f[2].x, f[2].y]);
      }
      return c;
    }

    function bx() {
      return this.hex;
    }

    function bv(a, b, c) {
      function d() {
        var e = Array.prototype.slice.call(arguments, 0), f = e.join("�?�"), h = d.cache = d.cache || {}, i = d.count = d.count || [];
        if (h[g](f)) {
          bu(i, f);
          return c ? c(h[f]) : h[f];
        }
        i.length >= 1000 &&
        delete h[i.shift()], i.push(f), h[f] = a[m](b, e);
        return c ? c(h[f]) : h[f];
      }
      return d;
    }

    function bu(a, b) {
      for (var c = 0, d = a.length; c < d; c++) {
        if (a[c] === b) {
          return a.push(a.splice(c,1)[0]);
        }
      }
    }

    function bm(a) {
      if (Object(a) !== a) {
        return a;
      }
      var b = new a.constructor;
      for (var c in a) {
        a[g](c) && (b[c] = bm(a[c]));
      }
      return b;
    }

    function a(c) {
      if (a.is(c, "function")) {
        return b ? c() : eve.on("raphael.DOMload", c);
      }
      if (a.is(c, E)) {
        return a._engine.create[m](a, c.splice(0, 3 + a.is(c[0], C))).add(c);
      }
      var d = Array.prototype.slice.call(arguments, 0);
      if (a.is(d[d.length - 1], "function")) {
        var e = d.pop();
        return b ? e.call(a._engine.create[m](a, d)) : eve.on("raphael.DOMload", function() {
          e.call(a._engine.create[m](a, d));
        });
      }
      return a._engine.create[m](a, arguments);
    }
    a.version = "2.1.0", a.eve = eve;
    var b, c = /[, ]+/, d = {
      circle : 1,
      rect : 1,
      path : 1,
      ellipse : 1,
      text : 1,
      image : 1
    }, e = /\{(\d+)\}/g, f = "prototype", g = "hasOwnProperty", h = {
      doc : document,
      win : window
    }, i = {
      was : Object.prototype[g].call(h.win, "Raphael"),
      is : h.win.Raphael
    }, j = function() {
      this.ca = this.customAttributes = {};
    }, k, l = "appendChild", m = "apply", n = "concat", o = "createTouch" in h.doc, p = "", q = " ", r = String, s = "split", t = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[s](q), u = {
      mousedown : "touchstart",
      mousemove : "touchmove",
      mouseup : "touchend"
    }, v = r.prototype.toLowerCase, w = Math, x = w.max, y = w.min, z = w.abs, A = w.pow, B = w.PI, C = "number", D = "string", E = "array", F = "toString", G = "fill", H = Object.prototype.toString, I = {}, J = "push", K = a._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i, L = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i, M = {
      NaN : 1,
      Infinity : 1,
      "-Infinity" : 1
    }, N = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/, O = w.round, P = "setAttribute", Q = parseFloat, R = parseInt, S = r.prototype.toUpperCase, T = a._availableAttrs = {
      "arrow-end" : "none",
      "arrow-start" : "none",
      blur : 0,
      "clip-rect" : "0 0 1e9 1e9",
      cursor : "default",
      cx : 0,
      cy : 0,
      fill : "#fff",
      "fill-opacity" : 1,
      font : '10px "Arial"',
      "font-family" : '"Arial"',
      "font-size" : "10",
      "font-style" : "normal",
      "font-weight" : 400,
      gradient : 0,
      height : 0,
      href : "http://raphaeljs.com/",
      "letter-spacing" : 0,
      opacity : 1,
      path : "M0,0",
      r : 0,
      rx : 0,
      ry : 0,
      src : "",
      stroke : "#000",
      "stroke-dasharray" : "",
      "stroke-linecap" : "butt",
      "stroke-linejoin" : "butt",
      "stroke-miterlimit" : 0,
      "stroke-opacity" : 1,
      "stroke-width" : 1,
      target : "_blank",
      "text-anchor" : "middle",
      title : "Raphael",
      transform : "",
      width : 0,
      x : 0,
      y : 0
    }, U = a._availableAnimAttrs = {
      blur : C,
      "clip-rect" : "csv",
      cx : C,
      cy : C,
      fill : "colour",
      "fill-opacity" : C,
      "font-size" : C,
      height : C,
      opacity : C,
      path : "path",
      r : C,
      rx : C,
      ry : C,
      stroke : "colour",
      "stroke-opacity" : C,
      "stroke-width" : C,
      transform : "transform",
      width : C,
      x : C,
      y : C
    }, V = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]/g, W = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/, X = {
      hs : 1,
      rg : 1
    }, Y = /,?([achlmqrstvxz]),?/gi, Z = /([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig, $ = /([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig, _ = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/ig, ba = a._radial_gradient = /^r(?:\(([^,]+?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*([^\)]+?)\))?/, bb = {}, bc = function(a, b) {
      return a.key - b.key;
    }, bd = function(a, b) {
      return Q(a) - Q(b);
    }, be = function() {
    }, bf = function(a) {
      return a;
    }, bg = a._rectPath = function(a, b, c, d, e) {
      if (e) {
        return [["M", a + e, b], ["l", c - e * 2, 0], ["a", e, e, 0, 0, 1, e, e], ["l", 0, d - e * 2], ["a", e, e, 0, 0, 1, -e, e], ["l", e * 2 - c, 0], ["a", e, e, 0, 0, 1, -e, -e], ["l", 0, e * 2 - d], ["a", e, e, 0, 0, 1, e, -e], ["z"]];
      }
      return [["M", a, b], ["l", c, 0], ["l", 0, d], ["l", -c, 0], ["z"]];
    }, bh = function(a, b, c, d) {
      d == null && ( d = c);
      return [["M", a, b], ["m", 0, -d], ["a", c, d, 0, 1, 1, 0, 2 * d], ["a", c, d, 0, 1, 1, 0, -2 * d], ["z"]];
    }, bi = a._getPath = {
      path : function(a) {
        return a.attr("path");
      },
      circle : function(a) {
        var b = a.attrs;
        return bh(b.cx, b.cy, b.r);
      },
      ellipse : function(a) {
        var b = a.attrs;
        return bh(b.cx, b.cy, b.rx, b.ry);
      },
      rect : function(a) {
        var b = a.attrs;
        return bg(b.x, b.y, b.width, b.height, b.r);
      },
      image : function(a) {
        var b = a.attrs;
        return bg(b.x, b.y, b.width, b.height);
      },
      text : function(a) {
        var b = a._getBBox();
        return bg(b.x, b.y, b.width, b.height);
      }
    }, bj = a.mapPath = function(a, b) {
      if (!b) {
        return a;
      }
      var c, d, e, f, g, h, i;
      a = bR(a);
      for ( e = 0, g = a.length; e < g; e++) {
        i = a[e];
        for ( f = 1, h = i.length; f < h; f += 2) {
          c = b.x(i[f], i[f + 1]), d = b.y(i[f], i[f + 1]), i[f] = c, i[f + 1] = d;
        }
      }
      return a;
    };
    a._g = h, a.type = h.win.SVGAngle || h.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML";
    if (a.type == "VML") {
      var bk = h.doc.createElement("div"), bl;
      bk.innerHTML = '<v:shape adj="1"/>', bl = bk.firstChild, bl.style.behavior = "url(#default#VML)";
      if (!bl || typeof bl.adj != "object") {
        return a.type = p;
      }
      bk = null;
    }
    a.svg = !(a.vml = a.type == "VML"), a._Paper = j, a.fn = k = j.prototype = a.prototype, a._id = 0, a._oid = 0, a.is = function(a, b) {
      b = v.call(b);
      if (b == "finite") {
        return !M[g](+a);
      }
      if (b == "array") {
        return a instanceof Array;
      }
      return b == "null" && a === null || b == typeof a && a !== null || b == "object" && a === Object(a) || b == "array" && Array.isArray && Array.isArray(a) || H.call(a).slice(8, -1).toLowerCase() == b;
    }, a.angle = function(b, c, d, e, f, g) {
      if (f == null) {
        var h = b - d, i = c - e;
        if (!h && !i) {
          return 0;
        }
        return (180 + w.atan2(-i, -h) * 180 / B + 360) % 360;
      }
      return a.angle(b, c, f, g) - a.angle(d, e, f, g);
    }, a.rad = function(a) {
      return a % 360 * B / 180;
    }, a.deg = function(a) {
      return a * 180 / B % 360;
    }, a.snapTo = function(b, c, d) {
      d = a.is(d, "finite") ? d : 10;
      if (a.is(b, E)) {
        var e = b.length;
        while (e--) {
          if (z(b[e] - c) <= d) {
            return b[e];
          }
        }
      } else {
        b = +b;
        var f = c % b;
        if (f < d) {
          return c - f;
        }
        if (f > b - d) {
          return c - f + b;
        }
      }
      return c;
    };
    var bn = a.createUUID = function(a, b) {
      return function() {
        return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(a, b).toUpperCase();
      };
    }(/[xy]/g, function(a) {
      var b = w.random() * 16 | 0, c = a == "x" ? b : b & 3 | 8;
      return c.toString(16);
    });
    a.setWindow = function(b) {
      eve("raphael.setWindow", a, h.win, b), h.win = b, h.doc = h.win.document, a._engine.initWin && a._engine.initWin(h.win);
    };
    var bo = function(b) {
      if (a.vml) {
        var c = /^\s+|\s+$/g, d;
        try {
          var e = new ActiveXObject("htmlfile");
          e.write("<body>"), e.close(), d = e.body;
        } catch(f) {
          d = createPopup().document.body;
        }
        var g = d.createTextRange();
        bo = bv(function(a) {
          try {
            d.style.color = r(a).replace(c, p);
            var b = g.queryCommandValue("ForeColor");
            b = (b & 255) << 16 | b & 65280 | (b & 16711680) >>> 16;
            return "#" + ("000000" + b.toString(16)).slice(-6);
          } catch(e) {
            return "none";
          }
        });
      } else {
        var i = h.doc.createElement("i");
        i.title = "Raphaël Colour Picker", i.style.display = "none", h.doc.body.appendChild(i), bo = bv(function(a) {
          i.style.color = a;
          return h.doc.defaultView.getComputedStyle(i, p).getPropertyValue("color");
        });
      }
      return bo(b);
    }, bp = function() {
      return "hsb(" + [this.h, this.s, this.b] + ")";
    }, bq = function() {
      return "hsl(" + [this.h, this.s, this.l] + ")";
    }, br = function() {
      return this.hex;
    }, bs = function(b, c, d) {
      c == null && a.is(b, "object") && "r" in b && "g" in b && "b" in b && ( d = b.b, c = b.g, b = b.r);
      if (c == null && a.is(b, D)) {
        var e = a.getRGB(b);
        b = e.r, c = e.g, d = e.b;
      }
      if (b > 1 || c > 1 || d > 1) {
        b /= 255, c /= 255, d /= 255;
      }
      return [b, c, d];
    }, bt = function(b, c, d, e) {
      b *= 255, c *= 255, d *= 255;
      var f = {
        r : b,
        g : c,
        b : d,
        hex : a.rgb(b, c, d),
        toString : br
      };
      a.is(e, "finite") && (f.opacity = e);
      return f;
    };
    a.color = function(b) {
      var c;
      a.is(b, "object") && "h" in b && "s" in b && "b" in b ? ( c = a.hsb2rgb(b), b.r = c.r, b.g = c.g, b.b = c.b, b.hex = c.hex) : a.is(b, "object") && "h" in b && "s" in b && "l" in b ? ( c = a.hsl2rgb(b), b.r = c.r, b.g = c.g, b.b = c.b, b.hex = c.hex) : (a.is(b, "string") && ( b = a.getRGB(b)), a.is(b, "object") && "r" in b && "g" in b && "b" in b ? ( c = a.rgb2hsl(b), b.h = c.h, b.s = c.s, b.l = c.l, c = a.rgb2hsb(b), b.v = c.b) : ( b = {
        hex : "none"
      }, b.r = b.g = b.b = b.h = b.s = b.v = b.l = -1)), b.toString = br;
      return b;
    }, a.hsb2rgb = function(a, b, c, d) {
      this.is(a, "object") && "h" in a && "s" in a && "b" in a && ( c = a.b, b = a.s, a = a.h, d = a.o), a *= 360;
      var e, f, g, h, i;
      a = a % 360 / 60, i = c * b, h = i * (1 - z(a % 2 - 1)), e = f = g = c - i, a = ~~a, e += [i,h,0,0,h,i][a], f += [h,i,i,h,0,0][a], g += [0,0,h,i,i,h][a];
      return bt(e, f, g, d);
    }, a.hsl2rgb = function(a, b, c, d) {
      this.is(a, "object") && "h" in a && "s" in a && "l" in a && ( c = a.l, b = a.s, a = a.h);
      if (a > 1 || b > 1 || c > 1) {
        a /= 360, b /= 100, c /= 100;
      }
      a *= 360;
      var e, f, g, h, i;
      a = a % 360 / 60, i = 2 * b * (c < 0.5 ? c : 1 - c), h = i * (1 - z(a % 2 - 1)), e = f = g = c - i / 2, a = ~~a, e += [i,h,0,0,h,i][a], f += [h,i,i,h,0,0][a], g += [0,0,h,i,i,h][a];
      return bt(e, f, g, d);
    }, a.rgb2hsb = function(a, b, c) {
      c = bs(a, b, c), a = c[0], b = c[1], c = c[2];
      var d, e, f, g;
      f = x(a, b, c), g = f - y(a, b, c), d = g == 0 ? null : f == a ? (b - c) / g : f == b ? (c - a) / g + 2 : (a - b) / g + 4, d = (d + 360) % 6 * 60 / 360, e = g == 0 ? 0 : g / f;
      return {
        h : d,
        s : e,
        b : f,
        toString : bp
      };
    }, a.rgb2hsl = function(a, b, c) {
      c = bs(a, b, c), a = c[0], b = c[1], c = c[2];
      var d, e, f, g, h, i;
      g = x(a, b, c), h = y(a, b, c), i = g - h, d = i == 0 ? null : g == a ? (b - c) / i : g == b ? (c - a) / i + 2 : (a - b) / i + 4, d = (d + 360) % 6 * 60 / 360, f = (g + h) / 2, e = i == 0 ? 0 : f < 0.5 ? i / (2 * f) : i / (2 - 2 * f);
      return {
        h : d,
        s : e,
        l : f,
        toString : bq
      };
    }, a._path2string = function() {
      return this.join(",").replace(Y, "$1");
    };
    var bw = a._preload = function(a, b) {
      var c = h.doc.createElement("img");
      c.style.cssText = "position:absolute;left:-9999em;top:-9999em", c.onload = function() {
        b.call(this), this.onload = null, h.doc.body.removeChild(this);
      }, c.onerror = function() {
        h.doc.body.removeChild(this);
      }, h.doc.body.appendChild(c), c.src = a;
    };
    a.getRGB = bv(function(b) {
      if (!b || !!(( b = r(b)).indexOf("-") + 1)) {
        return {
          r : -1,
          g : -1,
          b : -1,
          hex : "none",
          error : 1,
          toString : bx
        };
      }
      if (b == "none") {
        return {
          r : -1,
          g : -1,
          b : -1,
          hex : "none",
          toString : bx
        };
      }
      !X[g](b.toLowerCase().substring(0, 2)) && b.charAt() != "#" && ( b = bo(b));
      var c, d, e, f, h, i, j, k = b.match(L);
      if (k) {
        k[2] && ( f = R(k[2].substring(5), 16), e = R(k[2].substring(3, 5), 16), d = R(k[2].substring(1, 3), 16)), k[3] && ( f = R(( i = k[3].charAt(3)) + i, 16), e = R(( i = k[3].charAt(2)) + i, 16), d = R(( i = k[3].charAt(1)) + i, 16)), k[4] && ( j = k[4][s](W), d = Q(j[0]), j[0].slice(-1) == "%" && (d *= 2.55), e = Q(j[1]), j[1].slice(-1) == "%" && (e *= 2.55), f = Q(j[2]), j[2].slice(-1) == "%" && (f *= 2.55), k[1].toLowerCase().slice(0, 4) == "rgba" && ( h = Q(j[3])), j[3] && j[3].slice(-1) == "%" && (h /= 100));
        if (k[5]) {
          j = k[5][s](W), d = Q(j[0]), j[0].slice(-1) == "%" && (d *= 2.55), e = Q(j[1]), j[1].slice(-1) == "%" && (e *= 2.55), f = Q(j[2]), j[2].slice(-1) == "%" && (f *= 2.55), (j[0].slice(-3) == "deg" || j[0].slice(-1) == "°") && (d /= 360), k[1].toLowerCase().slice(0, 4) == "hsba" && ( h = Q(j[3])), j[3] && j[3].slice(-1) == "%" && (h /= 100);
          return a.hsb2rgb(d, e, f, h);
        }
        if (k[6]) {
          j = k[6][s](W), d = Q(j[0]), j[0].slice(-1) == "%" && (d *= 2.55), e = Q(j[1]), j[1].slice(-1) == "%" && (e *= 2.55), f = Q(j[2]), j[2].slice(-1) == "%" && (f *= 2.55), (j[0].slice(-3) == "deg" || j[0].slice(-1) == "°") && (d /= 360), k[1].toLowerCase().slice(0, 4) == "hsla" && ( h = Q(j[3])), j[3] && j[3].slice(-1) == "%" && (h /= 100);
          return a.hsl2rgb(d, e, f, h);
        }
        k = {
          r : d,
          g : e,
          b : f,
          toString : bx
        }, k.hex = "#" + (16777216 | f | e << 8 | d << 16).toString(16).slice(1), a.is(h, "finite") && (k.opacity = h);
        return k;
      }
      return {
        r : -1,
        g : -1,
        b : -1,
        hex : "none",
        error : 1,
        toString : bx
      };
    }, a), a.hsb = bv(function(b, c, d) {
      return a.hsb2rgb(b, c, d).hex;
    }), a.hsl = bv(function(b, c, d) {
      return a.hsl2rgb(b, c, d).hex;
    }), a.rgb = bv(function(a, b, c) {
      return "#" + (16777216 | c | b << 8 | a << 16).toString(16).slice(1);
    }), a.getColor = function(a) {
      var b = this.getColor.start = this.getColor.start || {
        h : 0,
        s : 1,
        b : a || 0.75
      }, c = this.hsb2rgb(b.h, b.s, b.b);
      b.h += 0.075, b.h > 1 && (b.h = 0, b.s -= 0.2, b.s <= 0 && (this.getColor.start = {
        h : 0,
        s : 1,
        b : b.b
      }));
      return c.hex;
    }, a.getColor.reset = function() {
      delete this.start;
    }, a.parsePathString = function(b) {
      if (!b) {
        return null;
      }
      var c = bz(b);
      if (c.arr) {
        return bJ(c.arr);
      }
      var d = {
        a : 7,
        c : 6,
        h : 1,
        l : 2,
        m : 2,
        r : 4,
        q : 4,
        s : 4,
        t : 2,
        v : 1,
        z : 0
      }, e = [];
      a.is(b, E) && a.is(b[0], E) && ( e = bJ(b)), e.length || r(b).replace(Z, function(a, b, c) {
        var f = [], g = b.toLowerCase();
        c.replace(_, function(a, b) {
          b && f.push(+b);
        }), g == "m" && f.length > 2 && (e.push([b][n](f.splice(0, 2))), g = "l", b = b == "m" ? "l" : "L");
        if (g == "r") {
          e.push([b][n](f));
        } else {
          while (f.length >= d[g]) {
            e.push([b][n](f.splice(0, d[g])));
            if (!d[g]) {
              break;
            }
          }
        }
      }), e.toString = a._path2string, c.arr = bJ(e);
      return e;
    }, a.parseTransformString = bv(function(b) {
      if (!b) {
        return null;
      }
      var c = {
        r : 3,
        s : 4,
        t : 2,
        m : 6
      }, d = [];
      a.is(b, E) && a.is(b[0], E) && ( d = bJ(b)), d.length || r(b).replace($, function(a, b, c) {
        var e = [], f = v.call(b);
        c.replace(_, function(a, b) {
          b && e.push(+b);
        }), d.push([b][n](e));
      }), d.toString = a._path2string;
      return d;
    });
    var bz = function(a) {
      var b = bz.ps = bz.ps || {};
      b[a] ? b[a].sleep = 100 : b[a] = {
        sleep : 100
      }, setTimeout(function() {
        for (var c in b) {
          b[g](c) && c != a && (b[c].sleep--, !b[c].sleep &&
          delete b[c]);
        }
      });
      return b[a];
    };
    a.findDotsAtSegment = function(a, b, c, d, e, f, g, h, i) {
      var j = 1 - i, k = A(j, 3), l = A(j, 2), m = i * i, n = m * i, o = k * a + l * 3 * i * c + j * 3 * i * i * e + n * g, p = k * b + l * 3 * i * d + j * 3 * i * i * f + n * h, q = a + 2 * i * (c - a) + m * (e - 2 * c + a), r = b + 2 * i * (d - b) + m * (f - 2 * d + b), s = c + 2 * i * (e - c) + m * (g - 2 * e + c), t = d + 2 * i * (f - d) + m * (h - 2 * f + d), u = j * a + i * c, v = j * b + i * d, x = j * e + i * g, y = j * f + i * h, z = 90 - w.atan2(q - s, r - t) * 180 / B;
      (q > s || r < t) && (z += 180);
      return {
        x : o,
        y : p,
        m : {
          x : q,
          y : r
        },
        n : {
          x : s,
          y : t
        },
        start : {
          x : u,
          y : v
        },
        end : {
          x : x,
          y : y
        },
        alpha : z
      };
    }, a.bezierBBox = function(b, c, d, e, f, g, h, i) {
      a.is(b, "array") || ( b = [b, c, d, e, f, g, h, i]);
      var j = bQ.apply(null, b);
      return {
        x : j.min.x,
        y : j.min.y,
        x2 : j.max.x,
        y2 : j.max.y,
        width : j.max.x - j.min.x,
        height : j.max.y - j.min.y
      };
    }, a.isPointInsideBBox = function(a, b, c) {
      return b >= a.x && b <= a.x2 && c >= a.y && c <= a.y2;
    }, a.isBBoxIntersect = function(b, c) {
      var d = a.isPointInsideBBox;
      return d(c, b.x, b.y) || d(c, b.x2, b.y) || d(c, b.x, b.y2) || d(c, b.x2, b.y2) || d(b, c.x, c.y) || d(b, c.x2, c.y) || d(b, c.x, c.y2) || d(b, c.x2, c.y2) || (b.x < c.x2 && b.x > c.x || c.x < b.x2 && c.x > b.x) && (b.y < c.y2 && b.y > c.y || c.y < b.y2 && c.y > b.y);
    }, a.pathIntersection = function(a, b) {
      return bH(a, b);
    }, a.pathIntersectionNumber = function(a, b) {
      return bH(a, b, 1);
    }, a.isPointInsidePath = function(b, c, d) {
      var e = a.pathBBox(b);
      return a.isPointInsideBBox(e, c, d) && bH(b, [["M", c, d], ["H", e.x2 + 10]], 1) % 2 == 1;
    }, a._removedFactory = function(a) {
      return function() {
        eve("raphael.log", null, "Raphaël: you are calling to method “" + a + "�? of removed object", a);
      };
    };
    var bI = a.pathBBox = function(a) {
      var b = bz(a);
      if (b.bbox) {
        return b.bbox;
      }
      if (!a) {
        return {
          x : 0,
          y : 0,
          width : 0,
          height : 0,
          x2 : 0,
          y2 : 0
        };
      }
      a = bR(a);
      var c = 0, d = 0, e = [], f = [], g;
      for (var h = 0, i = a.length; h < i; h++) {
        g = a[h];
        if (g[0] == "M") {
          c = g[1], d = g[2], e.push(c), f.push(d);
        } else {
          var j = bQ(c, d, g[1], g[2], g[3], g[4], g[5], g[6]);
          e = e[n](j.min.x, j.max.x), f = f[n](j.min.y, j.max.y), c = g[5], d = g[6];
        }
      }
      var k = y[m](0, e), l = y[m](0, f), o = x[m](0, e), p = x[m](0, f), q = {
        x : k,
        y : l,
        x2 : o,
        y2 : p,
        width : o - k,
        height : p - l
      };
      b.bbox = bm(q);
      return q;
    }, bJ = function(b) {
      var c = bm(b);
      c.toString = a._path2string;
      return c;
    }, bK = a._pathToRelative = function(b) {
      var c = bz(b);
      if (c.rel) {
        return bJ(c.rel);
      }
      if (!a.is(b, E) || !a.is(b && b[0], E)) {
        b = a.parsePathString(b);
      }
      var d = [], e = 0, f = 0, g = 0, h = 0, i = 0;
      b[0][0] == "M" && ( e = b[0][1], f = b[0][2], g = e, h = f, i++, d.push(["M", e, f]));
      for (var j = i, k = b.length; j < k; j++) {
        var l = d[j] = [], m = b[j];
        if (m[0] != v.call(m[0])) {
          l[0] = v.call(m[0]);
          switch(l[0]) {
            case"a":
              l[1] = m[1], l[2] = m[2], l[3] = m[3], l[4] = m[4], l[5] = m[5], l[6] = +(m[6] - e).toFixed(3), l[7] = +(m[7] - f).toFixed(3);
              break;
            case"v":
              l[1] = +(m[1] - f).toFixed(3);
              break;
            case"m":
              g = m[1], h = m[2];
            default:
              for (var n = 1, o = m.length; n < o; n++) {
                l[n] = +(m[n] - (n % 2 ? e : f)).toFixed(3);
              }
          }
        } else {
          l = d[j] = [], m[0] == "m" && ( g = m[1] + e, h = m[2] + f);
          for (var p = 0, q = m.length; p < q; p++) {
            d[j][p] = m[p];
          }
        }
        var r = d[j].length;
        switch(d[j][0]) {
          case"z":
            e = g, f = h;
            break;
          case"h":
            e += +d[j][r - 1];
            break;
          case"v":
            f += +d[j][r - 1];
            break;
          default:
            e += +d[j][r - 2], f += +d[j][r - 1];
        }
      }
      d.toString = a._path2string, c.rel = bJ(d);
      return d;
    }, bL = a._pathToAbsolute = function(b) {
      var c = bz(b);
      if (c.abs) {
        return bJ(c.abs);
      }
      if (!a.is(b, E) || !a.is(b && b[0], E)) {
        b = a.parsePathString(b);
      }
      if (!b || !b.length) {
        return [["M", 0, 0]];
      }
      var d = [], e = 0, f = 0, g = 0, h = 0, i = 0;
      b[0][0] == "M" && ( e = +b[0][1], f = +b[0][2], g = e, h = f, i++, d[0] = ["M", e, f]);
      var j = b.length == 3 && b[0][0] == "M" && b[1][0].toUpperCase() == "R" && b[2][0].toUpperCase() == "Z";
      for (var k, l, m = i, o = b.length; m < o; m++) {
        d.push( k = []), l = b[m];
        if (l[0] != S.call(l[0])) {
          k[0] = S.call(l[0]);
          switch(k[0]) {
            case"A":
              k[1] = l[1], k[2] = l[2], k[3] = l[3], k[4] = l[4], k[5] = l[5], k[6] = +(l[6] + e), k[7] = +(l[7] + f);
              break;
            case"V":
              k[1] = +l[1] + f;
              break;
            case"H":
              k[1] = +l[1] + e;
              break;
            case"R":
              var p = [e,f][n](l.slice(1));
              for (var q = 2, r = p.length; q < r; q++) {
                p[q] = +p[q] + e, p[++q] = +p[q] + f;
              }
              d.pop(), d = d[n](by(p, j));
              break;
            case"M":
              g = +l[1] + e, h = +l[2] + f;
            default:
              for ( q = 1, r = l.length; q < r; q++) {
                k[q] = +l[q] + (q % 2 ? e : f);
              }
          }
        } else {
          if (l[0] == "R") {
            p = [e,f][n](l.slice(1)), d.pop(), d = d[n](by(p, j)), k = ["R"][n](l.slice(-2));
          } else {
            for (var s = 0, t = l.length; s < t; s++) {
              k[s] = l[s];
            }
          }
        }
        switch(k[0]) {
          case"Z":
            e = g, f = h;
            break;
          case"H":
            e = k[1];
            break;
          case"V":
            f = k[1];
            break;
          case"M":
            g = k[k.length - 2], h = k[k.length - 1];
          default:
            e = k[k.length - 2], f = k[k.length - 1];
        }
      }
      d.toString = a._path2string, c.abs = bJ(d);
      return d;
    }, bM = function(a, b, c, d) {
      return [a, b, c, d, c, d];
    }, bN = function(a, b, c, d, e, f) {
      var g = 1 / 3, h = 2 / 3;
      return [g * a + h * c, g * b + h * d, g * e + h * c, g * f + h * d, e, f];
    }, bO = function(a, b, c, d, e, f, g, h, i, j) {
      var k = B * 120 / 180, l = B / 180 * (+e || 0), m = [], o, p = bv(function(a, b, c) {
        var d = a * w.cos(c) - b * w.sin(c), e = a * w.sin(c) + b * w.cos(c);
        return {
          x : d,
          y : e
        };
      });
      if (!j) {
        o = p(a, b, -l), a = o.x, b = o.y, o = p(h, i, -l), h = o.x, i = o.y;
        var q = w.cos(B / 180 * e), r = w.sin(B / 180 * e), t = (a - h) / 2, u = (b - i) / 2, v = t * t / (c * c) + u * u / (d * d);
        v > 1 && ( v = w.sqrt(v), c = v * c, d = v * d);
        var x = c * c, y = d * d, A = (f == g ? -1 : 1) * w.sqrt(z((x * y - x * u * u - y * t * t) / (x * u * u + y * t * t))), C = A * c * u / d + (a + h) / 2, D = A * -d * t / c + (b + i) / 2, E = w.asin(((b - D) / d).toFixed(9)), F = w.asin(((i - D) / d).toFixed(9));
        E = a < C ? B - E : E, F = h < C ? B - F : F, E < 0 && ( E = B * 2 + E), F < 0 && ( F = B * 2 + F), g && E > F && ( E = E - B * 2), !g && F > E && ( F = F - B * 2);
      } else {
        E = j[0], F = j[1], C = j[2], D = j[3];
      }
      var G = F - E;
      if (z(G) > k) {
        var H = F, I = h, J = i;
        F = E + k * (g && F > E ? 1 : -1), h = C + c * w.cos(F), i = D + d * w.sin(F), m = bO(h, i, c, d, e, 0, g, I, J, [F, H, C, D]);
      }
      G = F - E;
      var K = w.cos(E), L = w.sin(E), M = w.cos(F), N = w.sin(F), O = w.tan(G / 4), P = 4 / 3 * c * O, Q = 4 / 3 * d * O, R = [a, b], S = [a + P * L, b - Q * K], T = [h + P * N, i - Q * M], U = [h, i];
      S[0] = 2 * R[0] - S[0], S[1] = 2 * R[1] - S[1];
      if (j) {
        return [S,T,U][n](m);
      }
      m = [S,T,U][n](m).join()[s](",");
      var V = [];
      for (var W = 0, X = m.length; W < X; W++) {
        V[W] = W % 2 ? p(m[W - 1], m[W], l).y : p(m[W], m[W + 1], l).x;
      }
      return V;
    }, bP = function(a, b, c, d, e, f, g, h, i) {
      var j = 1 - i;
      return {
        x : A(j, 3) * a + A(j, 2) * 3 * i * c + j * 3 * i * i * e + A(i, 3) * g,
        y : A(j, 3) * b + A(j, 2) * 3 * i * d + j * 3 * i * i * f + A(i, 3) * h
      };
    }, bQ = bv(function(a, b, c, d, e, f, g, h) {
      var i = e - 2 * c + a - (g - 2 * e + c), j = 2 * (c - a) - 2 * (e - c), k = a - c, l = (-j + w.sqrt(j * j - 4 * i * k)) / 2 / i, n = (-j - w.sqrt(j * j - 4 * i * k)) / 2 / i, o = [b, h], p = [a, g], q;
      z(l) > "1e12" && ( l = 0.5), z(n) > "1e12" && ( n = 0.5), l > 0 && l < 1 && ( q = bP(a, b, c, d, e, f, g, h, l), p.push(q.x), o.push(q.y)), n > 0 && n < 1 && ( q = bP(a, b, c, d, e, f, g, h, n), p.push(q.x), o.push(q.y)), i = f - 2 * d + b - (h - 2 * f + d), j = 2 * (d - b) - 2 * (f - d), k = b - d, l = (-j + w.sqrt(j * j - 4 * i * k)) / 2 / i, n = (-j - w.sqrt(j * j - 4 * i * k)) / 2 / i, z(l) > "1e12" && ( l = 0.5), z(n) > "1e12" && ( n = 0.5), l > 0 && l < 1 && ( q = bP(a, b, c, d, e, f, g, h, l), p.push(q.x), o.push(q.y)), n > 0 && n < 1 && ( q = bP(a, b, c, d, e, f, g, h, n), p.push(q.x), o.push(q.y));
      return {
        min : {
          x : y[m](0, p),
          y : y[m](0, o)
        },
        max : {
          x : x[m](0, p),
          y : x[m](0, o)
        }
      };
    }), bR = a._path2curve = bv(function(a, b) {
      var c = !b && bz(a);
      if (!b && c.curve) {
        return bJ(c.curve);
      }
      var d = bL(a), e = b && bL(b), f = {
        x : 0,
        y : 0,
        bx : 0,
        by : 0,
        X : 0,
        Y : 0,
        qx : null,
        qy : null
      }, g = {
        x : 0,
        y : 0,
        bx : 0,
        by : 0,
        X : 0,
        Y : 0,
        qx : null,
        qy : null
      }, h = function(a, b) {
        var c, d;
        if (!a) {
          return ["C", b.x, b.y, b.x, b.y, b.x, b.y];
        }
        !(a[0] in {
          T : 1,
          Q : 1
        }) && (b.qx = b.qy = null);
        switch(a[0]) {
          case"M":
            b.X = a[1], b.Y = a[2];
            break;
          case"A":
            a = ["C"][n](bO[m](0, [b.x,b.y][n](a.slice(1))));
            break;
          case"S":
            c = b.x + (b.x - (b.bx || b.x)), d = b.y + (b.y - (b.by || b.y)), a = ["C",c,d][n](a.slice(1));
            break;
          case"T":
            b.qx = b.x + (b.x - (b.qx || b.x)), b.qy = b.y + (b.y - (b.qy || b.y)), a = ["C"][n](bN(b.x, b.y, b.qx, b.qy, a[1], a[2]));
            break;
          case"Q":
            b.qx = a[1], b.qy = a[2], a = ["C"][n](bN(b.x, b.y, a[1], a[2], a[3], a[4]));
            break;
          case"L":
            a = ["C"][n](bM(b.x, b.y, a[1], a[2]));
            break;
          case"H":
            a = ["C"][n](bM(b.x, b.y, a[1], b.y));
            break;
          case"V":
            a = ["C"][n](bM(b.x, b.y, b.x, a[1]));
            break;
          case"Z":
            a = ["C"][n](bM(b.x, b.y, b.X, b.Y));
        }
        return a;
      }, i = function(a, b) {
        if (a[b].length > 7) {
          a[b].shift();
          var c = a[b];
          while (c.length) {
            a.splice(b++, 0, ["C"][n](c.splice(0, 6)));
          }
          a.splice(b, 1), l = x(d.length, e && e.length || 0);
        }
      }, j = function(a, b, c, f, g) {
        a && b && a[g][0] == "M" && b[g][0] != "M" && (b.splice(g, 0, ["M", f.x, f.y]), c.bx = 0, c.by = 0, c.x = a[g][1], c.y = a[g][2], l = x(d.length, e && e.length || 0));
      };
      for (var k = 0, l = x(d.length, e && e.length || 0); k < l; k++) {
        d[k] = h(d[k], f), i(d, k), e && (e[k] = h(e[k], g)), e && i(e, k), j(d, e, f, g, k), j(e, d, g, f, k);
        var o = d[k], p = e && e[k], q = o.length, r = e && p.length;
        f.x = o[q - 2], f.y = o[q - 1], f.bx = Q(o[q - 4]) || f.x, f.by = Q(o[q - 3]) || f.y, g.bx = e && (Q(p[r - 4]) || g.x), g.by = e && (Q(p[r - 3]) || g.y), g.x = e && p[r - 2], g.y = e && p[r - 1];
      }
      e || (c.curve = bJ(d));
      return e ? [d, e] : d;
    }, null, bJ), bS = a._parseDots = bv(function(b) {
      var c = [];
      for (var d = 0, e = b.length; d < e; d++) {
        var f = {}, g = b[d].match(/^([^:]*):?([\d\.]*)/);
        f.color = a.getRGB(g[1]);
        if (f.color.error) {
          return null;
        }
        f.color = f.color.hex, g[2] && (f.offset = g[2] + "%"), c.push(f);
      }
      for ( d = 1, e = c.length - 1; d < e; d++) {
        if (!c[d].offset) {
          var h = Q(c[d - 1].offset || 0), i = 0;
          for (var j = d + 1; j < e; j++) {
            if (c[j].offset) {
              i = c[j].offset;
              break;
            }
          }
          i || ( i = 100, j = e), i = Q(i);
          var k = (i - h) / (j - d + 1);
          for (; d < j; d++) {
            h += k, c[d].offset = h + "%";
          }
        }
      }
      return c;
    }), bT = a._tear = function(a, b) {
      a == b.top && (b.top = a.prev), a == b.bottom && (b.bottom = a.next), a.next && (a.next.prev = a.prev), a.prev && (a.prev.next = a.next);
    }, bU = a._tofront = function(a, b) {
      b.top !== a && (bT(a, b), a.next = null, a.prev = b.top, b.top.next = a, b.top = a);
    }, bV = a._toback = function(a, b) {
      b.bottom !== a && (bT(a, b), a.next = b.bottom, a.prev = null, b.bottom.prev = a, b.bottom = a);
    }, bW = a._insertafter = function(a, b, c) {
      bT(a, c), b == c.top && (c.top = a), b.next && (b.next.prev = a), a.next = b.next, a.prev = b, b.next = a;
    }, bX = a._insertbefore = function(a, b, c) {
      bT(a, c), b == c.bottom && (c.bottom = a), b.prev && (b.prev.next = a), a.prev = b.prev, b.prev = a, a.next = b;
    }, bY = a.toMatrix = function(a, b) {
      var c = bI(a), d = {
        _ : {
          transform : p
        },
        getBBox : function() {
          return c;
        }
      };
      b$(d, b);
      return d.matrix;
    }, bZ = a.transformPath = function(a, b) {
      return bj(a, bY(a, b));
    }, b$ = a._extractTransform = function(b, c) {
      if (c == null) {
        return b._.transform;
      }
      c = r(c).replace(/\.{3}|\u2026/g, b._.transform || p);
      var d = a.parseTransformString(c), e = 0, f = 0, g = 0, h = 1, i = 1, j = b._, k = new cb;
      j.transform = d || [];
      if (d) {
        for (var l = 0, m = d.length; l < m; l++) {
          var n = d[l], o = n.length, q = r(n[0]).toLowerCase(), s = n[0] != q, t = s ? k.invert() : 0, u, v, w, x, y;
          q == "t" && o == 3 ? s ? ( u = t.x(0, 0), v = t.y(0, 0), w = t.x(n[1], n[2]), x = t.y(n[1], n[2]), k.translate(w - u, x - v)) : k.translate(n[1], n[2]) : q == "r" ? o == 2 ? ( y = y || b.getBBox(1), k.rotate(n[1], y.x + y.width / 2, y.y + y.height / 2), e += n[1]) : o == 4 && ( s ? ( w = t.x(n[2], n[3]), x = t.y(n[2], n[3]), k.rotate(n[1], w, x)) : k.rotate(n[1], n[2], n[3]), e += n[1]) : q == "s" ? o == 2 || o == 3 ? ( y = y || b.getBBox(1), k.scale(n[1], n[o - 1], y.x + y.width / 2, y.y + y.height / 2), h *= n[1], i *= n[o - 1]) : o == 5 && ( s ? ( w = t.x(n[3], n[4]), x = t.y(n[3], n[4]), k.scale(n[1], n[2], w, x)) : k.scale(n[1], n[2], n[3], n[4]), h *= n[1], i *= n[2]) : q == "m" && o == 7 && k.add(n[1], n[2], n[3], n[4], n[5], n[6]), j.dirtyT = 1, b.matrix = k;
        }
      }
      b.matrix = k, j.sx = h, j.sy = i, j.deg = e, j.dx = f = k.e, j.dy = g = k.f, h == 1 && i == 1 && !e && j.bbox ? (j.bbox.x += +f, j.bbox.y += +g) : j.dirtyT = 1;
    }, b_ = function(a) {
      var b = a[0];
      switch(b.toLowerCase()) {
        case"t":
          return [b, 0, 0];
        case"m":
          return [b, 1, 0, 0, 1, 0, 0];
        case"r":
          return a.length == 4 ? [b, 0, a[2], a[3]] : [b, 0];
        case"s":
          return a.length == 5 ? [b, 1, 1, a[3], a[4]] : a.length == 3 ? [b, 1, 1] : [b, 1];
      }
    }, ca = a._equaliseTransform = function(b, c) {
      c = r(c).replace(/\.{3}|\u2026/g, b), b = a.parseTransformString(b) || [], c = a.parseTransformString(c) || [];
      var d = x(b.length, c.length), e = [], f = [], g = 0, h, i, j, k;
      for (; g < d; g++) {
        j = b[g] || b_(c[g]), k = c[g] || b_(j);
        if (j[0] != k[0] || j[0].toLowerCase() == "r" && (j[2] != k[2] || j[3] != k[3]) || j[0].toLowerCase() == "s" && (j[3] != k[3] || j[4] != k[4])) {
          return;
        }
        e[g] = [], f[g] = [];
        for ( h = 0, i = x(j.length, k.length); h < i; h++) {
          h in j && (e[g][h] = j[h]), h in k && (f[g][h] = k[h]);
        }
      }
      return {
        from : e,
        to : f
      };
    };
    a._getContainer = function(b, c, d, e) {
      var f;
      f = e == null && !a.is(b, "object") ? h.doc.getElementById(b) : b;
      if (f != null) {
        if (f.tagName) {
          return c == null ? {
            container : f,
            width : f.style.pixelWidth || f.offsetWidth,
            height : f.style.pixelHeight || f.offsetHeight
          } : {
            container : f,
            width : c,
            height : d
          };
        }
        return {
          container : 1,
          x : b,
          y : c,
          width : d,
          height : e
        };
      }
    }, a.pathToRelative = bK, a._engine = {}, a.path2curve = bR, a.matrix = function(a, b, c, d, e, f) {
      return new cb(a, b, c, d, e, f);
    }, function(b) {
      function d(a) {
        var b = w.sqrt(c(a));
        a[0] && (a[0] /= b), a[1] && (a[1] /= b);
      }

      function c(a) {
        return a[0] * a[0] + a[1] * a[1];
      }
      b.add = function(a, b, c, d, e, f) {
        var g = [[], [], []], h = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]], i = [[a, c, e], [b, d, f], [0, 0, 1]], j, k, l, m;
        a && a instanceof cb && ( i = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]]);
        for ( j = 0; j < 3; j++) {
          for ( k = 0; k < 3; k++) {
            m = 0;
            for ( l = 0; l < 3; l++) {
              m += h[j][l] * i[l][k];
            }
            g[j][k] = m;
          }
        }
        this.a = g[0][0], this.b = g[1][0], this.c = g[0][1], this.d = g[1][1], this.e = g[0][2], this.f = g[1][2];
      }, b.invert = function() {
        var a = this, b = a.a * a.d - a.b * a.c;
        return new cb(a.d / b, -a.b / b, -a.c / b, a.a / b, (a.c * a.f - a.d * a.e) / b, (a.b * a.e - a.a * a.f) / b);
      }, b.clone = function() {
        return new cb(this.a, this.b, this.c, this.d, this.e, this.f);
      }, b.translate = function(a, b) {
        this.add(1, 0, 0, 1, a, b);
      }, b.scale = function(a, b, c, d) {
        b == null && ( b = a), (c || d) && this.add(1, 0, 0, 1, c, d), this.add(a, 0, 0, b, 0, 0), (c || d) && this.add(1, 0, 0, 1, -c, -d);
      }, b.rotate = function(b, c, d) {
        b = a.rad(b), c = c || 0, d = d || 0;
        var e = +w.cos(b).toFixed(9), f = +w.sin(b).toFixed(9);
        this.add(e, f, -f, e, c, d), this.add(1, 0, 0, 1, -c, -d);
      }, b.x = function(a, b) {
        return a * this.a + b * this.c + this.e;
      }, b.y = function(a, b) {
        return a * this.b + b * this.d + this.f;
      }, b.get = function(a) {
        return +this[r.fromCharCode(97 + a)].toFixed(4);
      }, b.toString = function() {
        return a.svg ? "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
      }, b.toFilter = function() {
        return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) + ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) + ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
      }, b.offset = function() {
        return [this.e.toFixed(4), this.f.toFixed(4)];
      }, b.split = function() {
        var b = {};
        b.dx = this.e, b.dy = this.f;
        var e = [[this.a, this.c], [this.b, this.d]];
        b.scalex = w.sqrt(c(e[0])), d(e[0]), b.shear = e[0][0] * e[1][0] + e[0][1] * e[1][1], e[1] = [e[1][0] - e[0][0] * b.shear, e[1][1] - e[0][1] * b.shear], b.scaley = w.sqrt(c(e[1])), d(e[1]), b.shear /= b.scaley;
        var f = -e[0][1], g = e[1][1];
        g < 0 ? (b.rotate = a.deg(w.acos(g)), f < 0 && (b.rotate = 360 - b.rotate)) : b.rotate = a.deg(w.asin(f)), b.isSimple = !+b.shear.toFixed(9) && (b.scalex.toFixed(9) == b.scaley.toFixed(9) || !b.rotate), b.isSuperSimple = !+b.shear.toFixed(9) && b.scalex.toFixed(9) == b.scaley.toFixed(9) && !b.rotate, b.noRotation = !+b.shear.toFixed(9) && !b.rotate;
        return b;
      }, b.toTransformString = function(a) {
        var b = a || this[s]();
        if (b.isSimple) {
          b.scalex = +b.scalex.toFixed(4), b.scaley = +b.scaley.toFixed(4), b.rotate = +b.rotate.toFixed(4);
          return (b.dx || b.dy ? "t" + [b.dx, b.dy] : p) + (b.scalex != 1 || b.scaley != 1 ? "s" + [b.scalex, b.scaley, 0, 0] : p) + (b.rotate ? "r" + [b.rotate, 0, 0] : p);
        }
        return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
      };
    }(cb.prototype);
    var cc = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
    navigator.vendor == "Apple Computer, Inc." && (cc && cc[1] < 4 || navigator.platform.slice(0, 2) == "iP") || navigator.vendor == "Google Inc." && cc && cc[1] < 8 ? k.safari = function() {
      var a = this.rect(-99, -99, this.width + 99, this.height + 99).attr({
        stroke : "none"
      });
      setTimeout(function() {
        a.remove();
      });
    } : k.safari = be;
    var cd = function() {
      this.returnValue = !1;
    }, ce = function() {
      return this.originalEvent.preventDefault();
    }, cf = function() {
      this.cancelBubble = !0;
    }, cg = function() {
      return this.originalEvent.stopPropagation();
    }, ch = function() {
      if (h.doc.addEventListener) {
        return function(a, b, c, d) {
          var e = o && u[b] ? u[b] : b, f = function(e) {
            var f = h.doc.documentElement.scrollTop || h.doc.body.scrollTop, i = h.doc.documentElement.scrollLeft || h.doc.body.scrollLeft, j = e.clientX + i, k = e.clientY + f;
            if (o && u[g](b)) {
              for (var l = 0, m = e.targetTouches && e.targetTouches.length; l < m; l++) {
                if (e.targetTouches[l].target == a) {
                  var n = e;
                  e = e.targetTouches[l], e.originalEvent = n, e.preventDefault = ce, e.stopPropagation = cg;
                  break;
                }
              }
            }
            return c.call(d, e, j, k);
          };
          a.addEventListener(e, f, !1);
          return function() {
            a.removeEventListener(e, f, !1);
            return !0;
          };
        };
      }
      if (h.doc.attachEvent) {
        return function(a, b, c, d) {
          var e = function(a) {
            a = a || h.win.event;
            var b = h.doc.documentElement.scrollTop || h.doc.body.scrollTop, e = h.doc.documentElement.scrollLeft || h.doc.body.scrollLeft, f = a.clientX + e, g = a.clientY + b;
            a.preventDefault = a.preventDefault || cd, a.stopPropagation = a.stopPropagation || cf;
            return c.call(d, a, f, g);
          };
          a.attachEvent("on" + b, e);
          var f = function() {
            a.detachEvent("on" + b, e);
            return !0;
          };
          return f;
        };
      }
    }(), ci = [], cj = function(a) {
      var b = a.clientX, c = a.clientY, d = h.doc.documentElement.scrollTop || h.doc.body.scrollTop, e = h.doc.documentElement.scrollLeft || h.doc.body.scrollLeft, f, g = ci.length;
      while (g--) {
        f = ci[g];
        if (o) {
          var i = a.touches.length, j;
          while (i--) {
            j = a.touches[i];
            if (j.identifier == f.el._drag.id) {
              b = j.clientX, c = j.clientY, (a.originalEvent ? a.originalEvent : a).preventDefault();
              break;
            }
          }
        } else {
          a.preventDefault();
        }
        var k = f.el.node, l, m = k.nextSibling, n = k.parentNode, p = k.style.display;
        h.win.opera && n.removeChild(k), k.style.display = "none", l = f.el.paper.getElementByPoint(b, c), k.style.display = p, h.win.opera && ( m ? n.insertBefore(k, m) : n.appendChild(k)), l && eve("raphael.drag.over." + f.el.id, f.el, l), b += e, c += d, eve("raphael.drag.move." + f.el.id, f.move_scope || f.el, b - f.el._drag.x, c - f.el._drag.y, b, c, a);
      }
    }, ck = function(b) {
      a.unmousemove(cj).unmouseup(ck);
      var c = ci.length, d;
      while (c--) {
        d = ci[c], d.el._drag = {}, eve("raphael.drag.end." + d.el.id, d.end_scope || d.start_scope || d.move_scope || d.el, b);
      }
      ci = [];
    }, cl = a.el = {};
    for (var cm = t.length; cm--; ) {
      (function(b) {
        a[b] = cl[b] = function(c, d) {
          a.is(c, "function") && (this.events = this.events || [], this.events.push({
            name : b,
            f : c,
            unbind : ch(this.shape || this.node || h.doc, b, c, d || this)
          }));
          return this;
        }, a["un" + b] = cl["un" + b] = function(a) {
          var c = this.events || [], d = c.length;
          while (d--) {
            if (c[d].name == b && c[d].f == a) {
              c[d].unbind(), c.splice(d, 1), !c.length &&
              delete this.events;
              return this;
            }
          }
          return this;
        };
      })(t[cm]);
    }
    cl.data = function(b, c) {
      var d = bb[this.id] = bb[this.id] || {};
      if (arguments.length == 1) {
        if (a.is(b, "object")) {
          for (var e in b) {
            b[g](e) && this.data(e, b[e]);
          }
          return this;
        }
        eve("raphael.data.get." + this.id, this, d[b], b);
        return d[b];
      }
      d[b] = c, eve("raphael.data.set." + this.id, this, c, b);
      return this;
    }, cl.removeData = function(a) {
      a == null ? bb[this.id] = {} : bb[this.id] &&
      delete bb[this.id][a];
      return this;
    }, cl.hover = function(a, b, c, d) {
      return this.mouseover(a, c).mouseout(b, d || c);
    }, cl.unhover = function(a, b) {
      return this.unmouseover(a).unmouseout(b);
    };
    var cn = [];
    cl.drag = function(b, c, d, e, f, g) {
      function i(i) {
        (i.originalEvent || i).preventDefault();
        var j = h.doc.documentElement.scrollTop || h.doc.body.scrollTop, k = h.doc.documentElement.scrollLeft || h.doc.body.scrollLeft;
        this._drag.x = i.clientX + k, this._drag.y = i.clientY + j, this._drag.id = i.identifier, !ci.length && a.mousemove(cj).mouseup(ck), ci.push({
          el : this,
          move_scope : e,
          start_scope : f,
          end_scope : g
        }), c && eve.on("raphael.drag.start." + this.id, c), b && eve.on("raphael.drag.move." + this.id, b), d && eve.on("raphael.drag.end." + this.id, d), eve("raphael.drag.start." + this.id, f || e || this, i.clientX + k, i.clientY + j, i);
      }
      this._drag = {}, cn.push({
        el : this,
        start : i
      }), this.mousedown(i);
      return this;
    }, cl.onDragOver = function(a) {
      a ? eve.on("raphael.drag.over." + this.id, a) : eve.unbind("raphael.drag.over." + this.id);
    }, cl.undrag = function() {
      var b = cn.length;
      while (b--) {
        cn[b].el == this && (this.unmousedown(cn[b].start), cn.splice(b, 1), eve.unbind("raphael.drag.*." + this.id));
      }
      !cn.length && a.unmousemove(cj).unmouseup(ck);
    }, k.circle = function(b, c, d) {
      var e = a._engine.circle(this, b || 0, c || 0, d || 0);
      this.__set__ && this.__set__.push(e);
      return e;
    }, k.rect = function(b, c, d, e, f) {
      var g = a._engine.rect(this, b || 0, c || 0, d || 0, e || 0, f || 0);
      this.__set__ && this.__set__.push(g);
      return g;
    }, k.ellipse = function(b, c, d, e) {
      var f = a._engine.ellipse(this, b || 0, c || 0, d || 0, e || 0);
      this.__set__ && this.__set__.push(f);
      return f;
    }, k.path = function(b) {
      b && !a.is(b, D) && !a.is(b[0], E) && (b += p);
      var c = a._engine.path(a.format[m](a, arguments), this);
      this.__set__ && this.__set__.push(c);
      return c;
    }, k.image = function(b, c, d, e, f) {
      var g = a._engine.image(this, b || "about:blank", c || 0, d || 0, e || 0, f || 0);
      this.__set__ && this.__set__.push(g);
      return g;
    }, k.text = function(b, c, d) {
      var e = a._engine.text(this, b || 0, c || 0, r(d));
      this.__set__ && this.__set__.push(e);
      return e;
    }, k.set = function(b) {
      !a.is(b, "array") && ( b = Array.prototype.splice.call(arguments, 0, arguments.length));
      var c = new cG(b);
      this.__set__ && this.__set__.push(c);
      return c;
    }, k.setStart = function(a) {
      this.__set__ = a || this.set();
    }, k.setFinish = function(a) {
      var b = this.__set__;
      delete this.__set__;
      return b;
    }, k.setSize = function(b, c) {
      return a._engine.setSize.call(this, b, c);
    }, k.setViewBox = function(b, c, d, e, f) {
      return a._engine.setViewBox.call(this, b, c, d, e, f);
    }, k.top = k.bottom = null, k.raphael = a;
    var co = function(a) {
      var b = a.getBoundingClientRect(), c = a.ownerDocument, d = c.body, e = c.documentElement, f = e.clientTop || d.clientTop || 0, g = e.clientLeft || d.clientLeft || 0, i = b.top + (h.win.pageYOffset || e.scrollTop || d.scrollTop) - f, j = b.left + (h.win.pageXOffset || e.scrollLeft || d.scrollLeft) - g;
      return {
        y : i,
        x : j
      };
    };
    k.getElementByPoint = function(a, b) {
      var c = this, d = c.canvas, e = h.doc.elementFromPoint(a, b);
      if (h.win.opera && e.tagName == "svg") {
        var f = co(d), g = d.createSVGRect();
        g.x = a - f.x, g.y = b - f.y, g.width = g.height = 1;
        var i = d.getIntersectionList(g, null);
        i.length && ( e = i[i.length - 1]);
      }
      if (!e) {
        return null;
      }
      while (e.parentNode && e != d.parentNode && !e.raphael) {
        e = e.parentNode;
      }
      e == c.canvas.parentNode && ( e = d), e = e && e.raphael ? c.getById(e.raphaelid) : null;
      return e;
    }, k.getById = function(a) {
      var b = this.bottom;
      while (b) {
        if (b.id == a) {
          return b;
        }
        b = b.next;
      }
      return null;
    }, k.forEach = function(a, b) {
      var c = this.bottom;
      while (c) {
        if (a.call(b, c) === !1) {
          return this;
        }
        c = c.next;
      }
      return this;
    }, k.getElementsByPoint = function(a, b) {
      var c = this.set();
      this.forEach(function(d) {
        d.isPointInside(a, b) && c.push(d);
      });
      return c;
    }, cl.isPointInside = function(b, c) {
      var d = this.realPath = this.realPath || bi[this.type](this);
      return a.isPointInsidePath(d, b, c);
    }, cl.getBBox = function(a) {
      if (this.removed) {
        return {};
      }
      var b = this._;
      if (a) {
        if (b.dirty || !b.bboxwt) {
          this.realPath = bi[this.type](this), b.bboxwt = bI(this.realPath), b.bboxwt.toString = cq, b.dirty = 0;
        }
        return b.bboxwt;
      }
      if (b.dirty || b.dirtyT || !b.bbox) {
        if (b.dirty || !this.realPath) {
          b.bboxwt = 0, this.realPath = bi[this.type](this);
        }
        b.bbox = bI(bj(this.realPath, this.matrix)), b.bbox.toString = cq, b.dirty = b.dirtyT = 0;
      }
      return b.bbox;
    }, cl.clone = function() {
      if (this.removed) {
        return null;
      }
      var a = this.paper[this.type]().attr(this.attr());
      this.__set__ && this.__set__.push(a);
      return a;
    }, cl.glow = function(a) {
      if (this.type == "text") {
        return null;
      }
      a = a || {};
      var b = {
        width : (a.width || 10) + (+this.attr("stroke-width") || 1),
        fill : a.fill || !1,
        opacity : a.opacity || 0.5,
        offsetx : a.offsetx || 0,
        offsety : a.offsety || 0,
        color : a.color || "#000"
      }, c = b.width / 2, d = this.paper, e = d.set(), f = this.realPath || bi[this.type](this);
      f = this.matrix ? bj(f, this.matrix) : f;
      for (var g = 1; g < c + 1; g++) {
        e.push(d.path(f).attr({
          stroke : b.color,
          fill : b.fill ? b.color : "none",
          "stroke-linejoin" : "round",
          "stroke-linecap" : "round",
          "stroke-width" : +(b.width / c * g).toFixed(3),
          opacity : +(b.opacity / c).toFixed(3)
        }));
      }
      return e.insertBefore(this).translate(b.offsetx, b.offsety);
    };
    var cr = {}, cs = function(b, c, d, e, f, g, h, i, j) {
      return j == null ? bB(b, c, d, e, f, g, h, i) : a.findDotsAtSegment(b, c, d, e, f, g, h, i, bC(b, c, d, e, f, g, h, i, j));
    }, ct = function(b, c) {
      return function(d, e, f) {
        d = bR(d);
        var g, h, i, j, k = "", l = {}, m, n = 0;
        for (var o = 0, p = d.length; o < p; o++) {
          i = d[o];
          if (i[0] == "M") {
            g = +i[1], h = +i[2];
          } else {
            j = cs(g, h, i[1], i[2], i[3], i[4], i[5], i[6]);
            if (n + j > e) {
              if (c && !l.start) {
                m = cs(g, h, i[1], i[2], i[3], i[4], i[5], i[6], e - n), k += ["C" + m.start.x, m.start.y, m.m.x, m.m.y, m.x, m.y];
                if (f) {
                  return k;
                }
                l.start = k, k = ["M" + m.x, m.y + "C" + m.n.x, m.n.y, m.end.x, m.end.y, i[5], i[6]].join(), n += j, g = +i[5], h = +i[6];
                continue;
              }
              if (!b && !c) {
                m = cs(g, h, i[1], i[2], i[3], i[4], i[5], i[6], e - n);
                return {
                  x : m.x,
                  y : m.y,
                  alpha : m.alpha
                };
              }
            }
            n += j, g = +i[5], h = +i[6];
          }
          k += i.shift() + i;
        }
        l.end = k, m = b ? n : c ? l : a.findDotsAtSegment(g, h, i[0], i[1], i[2], i[3], i[4], i[5], 1), m.alpha && ( m = {
          x : m.x,
          y : m.y,
          alpha : m.alpha
        });
        return m;
      };
    }, cu = ct(1), cv = ct(), cw = ct(0, 1);
    a.getTotalLength = cu, a.getPointAtLength = cv, a.getSubpath = function(a, b, c) {
      if (this.getTotalLength(a) - c < 0.000001) {
        return cw(a, b).end;
      }
      var d = cw(a, c, 1);
      return b ? cw(d, b).end : d;
    }, cl.getTotalLength = function() {
      if (this.type == "path") {
        if (this.node.getTotalLength) {
          return this.node.getTotalLength();
        }
        return cu(this.attrs.path);
      }
    }, cl.getPointAtLength = function(a) {
      if (this.type == "path") {
        return cv(this.attrs.path, a);
      }
    }, cl.getSubpath = function(b, c) {
      if (this.type == "path") {
        return a.getSubpath(this.attrs.path, b, c);
      }
    };
    var cx = a.easing_formulas = {
      linear : function(a) {
        return a;
      },
      "<" : function(a) {
        return A(a, 1.7);
      },
      ">" : function(a) {
        return A(a, 0.48);
      },
      "<>" : function(a) {
        var b = 0.48 - a / 1.04, c = w.sqrt(0.1734 + b * b), d = c - b, e = A(z(d), 1 / 3) * (d < 0 ? -1 : 1), f = -c - b, g = A(z(f), 1 / 3) * (f < 0 ? -1 : 1), h = e + g + 0.5;
        return (1 - h) * 3 * h * h + h * h * h;
      },
      backIn : function(a) {
        var b = 1.70158;
        return a * a * ((b + 1) * a - b);
      },
      backOut : function(a) {
        a = a - 1;
        var b = 1.70158;
        return a * a * ((b + 1) * a + b) + 1;
      },
      elastic : function(a) {
        if (a == !!a) {
          return a;
        }
        return A(2, -10 * a) * w.sin((a - 0.075) * 2 * B / 0.3) + 1;
      },
      bounce : function(a) {
        var b = 7.5625, c = 2.75, d;
        a < 1 / c ? d = b * a * a : a < 2 / c ? (a -= 1.5 / c, d = b * a * a + 0.75) : a < 2.5 / c ? (a -= 2.25 / c, d = b * a * a + 0.9375) : (a -= 2.625 / c, d = b * a * a + 0.984375);
        return d;
      }
    };
    cx.easeIn = cx["ease-in"] = cx["<"], cx.easeOut = cx["ease-out"] = cx[">"], cx.easeInOut = cx["ease-in-out"] = cx["<>"], cx["back-in"] = cx.backIn, cx["back-out"] = cx.backOut;
    var cy = [], cz = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
    function(a) {
      setTimeout(a, 16);
    }, cA = function() {
      var b = +(new Date), c = 0;
      for (; c < cy.length; c++) {
        var d = cy[c];
        if (d.el.removed || d.paused) {
          continue;
        }
        var e = b - d.start, f = d.ms, h = d.easing, i = d.from, j = d.diff, k = d.to, l = d.t, m = d.el, o = {}, p, r = {}, s;
        d.initstatus ? ( e = (d.initstatus * d.anim.top - d.prev) / (d.percent - d.prev) * f, d.status = d.initstatus,
        delete d.initstatus, d.stop && cy.splice(c--, 1)) : d.status = (d.prev + (d.percent - d.prev) * (e / f)) / d.anim.top;
        if (e < 0) {
          continue;
        }
        if (e < f) {
          var t = h(e / f);
          for (var u in i) {
            if (i[g](u)) {
              switch(U[u]) {
                case C:
                  p = +i[u] + t * f * j[u];
                  break;
                case"colour":
                  p = "rgb(" + [cB(O(i[u].r + t * f * j[u].r)), cB(O(i[u].g + t * f * j[u].g)), cB(O(i[u].b + t * f * j[u].b))].join(",") + ")";
                  break;
                case"path":
                  p = [];
                  for (var v = 0, w = i[u].length; v < w; v++) {
                    p[v] = [i[u][v][0]];
                    for (var x = 1, y = i[u][v].length; x < y; x++) {
                      p[v][x] = +i[u][v][x] + t * f * j[u][v][x];
                    }
                    p[v] = p[v].join(q);
                  }
                  p = p.join(q);
                  break;
                case"transform":
                  if (j[u].real) {
                    p = [];
                    for ( v = 0, w = i[u].length; v < w; v++) {
                      p[v] = [i[u][v][0]];
                      for ( x = 1, y = i[u][v].length; x < y; x++) {
                        p[v][x] = i[u][v][x] + t * f * j[u][v][x];
                      }
                    }
                  } else {
                    var z = function(a) {
                      return +i[u][a] + t * f * j[u][a];
                    };
                    p = [["m", z(0), z(1), z(2), z(3), z(4), z(5)]];
                  }
                  break;
                case"csv":
                  if (u == "clip-rect") {
                    p = [], v = 4;
                    while (v--) {
                      p[v] = +i[u][v] + t * f * j[u][v];
                    }
                  }
                  break;
                default:
                  var A = [][n](i[u]);
                  p = [], v = m.paper.customAttributes[u].length;
                  while (v--) {
                    p[v] = +A[v] + t * f * j[u][v];
                  }
              }
              o[u] = p;
            }
          }
          m.attr(o), function(a, b, c) {
            setTimeout(function() {
              eve("raphael.anim.frame." + a, b, c);
            });
          }(m.id, m, d.anim);
        } else {
          (function(b, c, d) {
            setTimeout(function() {
              eve("raphael.anim.frame." + c.id, c, d), eve("raphael.anim.finish." + c.id, c, d), a.is(b, "function") && b.call(c);
            });
          })(d.callback, m, d.anim), m.attr(k), cy.splice(c--, 1);
          if (d.repeat > 1 && !d.next) {
            for (s in k) {
              k[g](s) && (r[s] = d.totalOrigin[s]);
            }
            d.el.attr(r), cE(d.anim, d.el, d.anim.percents[0], null, d.totalOrigin, d.repeat - 1);
          }
          d.next && !d.stop && cE(d.anim, d.el, d.next, null, d.totalOrigin, d.repeat);
        }
      }
      a.svg && m && m.paper && m.paper.safari(), cy.length && cz(cA);
    }, cB = function(a) {
      return a > 255 ? 255 : a < 0 ? 0 : a;
    };
    cl.animateWith = function(b, c, d, e, f, g) {
      var h = this;
      if (h.removed) {
        g && g.call(h);
        return h;
      }
      var i = d instanceof cD ? d : a.animation(d, e, f, g), j, k;
      cE(i, h, i.percents[0], null, h.attr());
      for (var l = 0, m = cy.length; l < m; l++) {
        if (cy[l].anim == c && cy[l].el == b) {
          cy[m - 1].start = cy[l].start;
          break;
        }
      }
      return h;
    }, cl.onAnimation = function(a) {
      a ? eve.on("raphael.anim.frame." + this.id, a) : eve.unbind("raphael.anim.frame." + this.id);
      return this;
    }, cD.prototype.delay = function(a) {
      var b = new cD(this.anim, this.ms);
      b.times = this.times, b.del = +a || 0;
      return b;
    }, cD.prototype.repeat = function(a) {
      var b = new cD(this.anim, this.ms);
      b.del = this.del, b.times = w.floor(x(a, 0)) || 1;
      return b;
    }, a.animation = function(b, c, d, e) {
      if ( b instanceof cD) {
        return b;
      }
      if (a.is(d, "function") || !d) {
        e = e || d || null, d = null;
      }
      b = Object(b), c = +c || 0;
      var f = {}, h, i;
      for (i in b) {
        b[g](i) && Q(i) != i && Q(i) + "%" != i && ( h = !0, f[i] = b[i]);
      }
      if (!h) {
        return new cD(b, c);
      }
      d && (f.easing = d), e && (f.callback = e);
      return new cD({
        100 : f
      }, c);
    }, cl.animate = function(b, c, d, e) {
      var f = this;
      if (f.removed) {
        e && e.call(f);
        return f;
      }
      var g = b instanceof cD ? b : a.animation(b, c, d, e);
      cE(g, f, g.percents[0], null, f.attr());
      return f;
    }, cl.setTime = function(a, b) {
      a && b != null && this.status(a, y(b, a.ms) / a.ms);
      return this;
    }, cl.status = function(a, b) {
      var c = [], d = 0, e, f;
      if (b != null) {
        cE(a, this, -1, y(b, 1));
        return this;
      }
      e = cy.length;
      for (; d < e; d++) {
        f = cy[d];
        if (f.el.id == this.id && (!a || f.anim == a)) {
          if (a) {
            return f.status;
          }
          c.push({
            anim : f.anim,
            status : f.status
          });
        }
      }
      if (a) {
        return 0;
      }
      return c;
    }, cl.pause = function(a) {
      for (var b = 0; b < cy.length; b++) {
        cy[b].el.id == this.id && (!a || cy[b].anim == a) && eve("raphael.anim.pause." + this.id, this, cy[b].anim) !== !1 && (cy[b].paused = !0);
      }
      return this;
    }, cl.resume = function(a) {
      for (var b = 0; b < cy.length; b++) {
        if (cy[b].el.id == this.id && (!a || cy[b].anim == a)) {
          var c = cy[b];
          eve("raphael.anim.resume." + this.id, this, c.anim) !== !1 && (
          delete c.paused, this.status(c.anim, c.status));
        }
      }
      return this;
    }, cl.stop = function(a) {
      for (var b = 0; b < cy.length; b++) {
        cy[b].el.id == this.id && (!a || cy[b].anim == a) && eve("raphael.anim.stop." + this.id, this, cy[b].anim) !== !1 && cy.splice(b--, 1);
      }
      return this;
    }, eve.on("raphael.remove", cF), eve.on("raphael.clear", cF), cl.toString = function() {
      return "Raphaël’s object";
    };
    var cG = function(a) {
      this.items = [], this.length = 0, this.type = "set";
      if (a) {
        for (var b = 0, c = a.length; b < c; b++) {
          a[b] && (a[b].constructor == cl.constructor || a[b].constructor == cG) && (this[this.items.length] = this.items[this.items.length] = a[b], this.length++);
        }
      }
    }, cH = cG.prototype;
    cH.push = function() {
      var a, b;
      for (var c = 0, d = arguments.length; c < d; c++) {
        a = arguments[c], a && (a.constructor == cl.constructor || a.constructor == cG) && ( b = this.items.length, this[b] = this.items[b] = a, this.length++);
      }
      return this;
    }, cH.pop = function() {
      this.length &&
      delete this[this.length--];
      return this.items.pop();
    }, cH.forEach = function(a, b) {
      for (var c = 0, d = this.items.length; c < d; c++) {
        if (a.call(b, this.items[c], c) === !1) {
          return this;
        }
      }
      return this;
    };
    for (var cI in cl) {
      cl[g](cI) && (cH[cI] = function(a) {
        return function() {
          var b = arguments;
          return this.forEach(function(c) {
            c[a][m](c, b);
          });
        };
      }(cI));
    }
    cH.attr = function(b, c) {
      if (b && a.is(b, E) && a.is(b[0], "object")) {
        for (var d = 0, e = b.length; d < e; d++) {
          this.items[d].attr(b[d]);
        }
      } else {
        for (var f = 0, g = this.items.length; f < g; f++) {
          this.items[f].attr(b, c);
        }
      }
      return this;
    }, cH.clear = function() {
      while (this.length) {
        this.pop();
      }
    }, cH.splice = function(a, b, c) {
      a = a < 0 ? x(this.length + a, 0) : a, b = x(0, y(this.length - a, b));
      var d = [], e = [], f = [], g;
      for ( g = 2; g < arguments.length; g++) {
        f.push(arguments[g]);
      }
      for ( g = 0; g < b; g++) {
        e.push(this[a + g]);
      }
      for (; g < this.length - a; g++) {
        d.push(this[a + g]);
      }
      var h = f.length;
      for ( g = 0; g < h + d.length; g++) {
        this.items[a + g] = this[a + g] = g < h ? f[g] : d[g - h];
      }
      g = this.items.length = this.length -= b - h;
      while (this[g]) {
        delete this[g++];
      }
      return new cG(e);
    }, cH.exclude = function(a) {
      for (var b = 0, c = this.length; b < c; b++) {
        if (this[b] == a) {
          this.splice(b, 1);
          return !0;
        }
      }
    }, cH.animate = function(b, c, d, e) {
      (a.is(d, "function") || !d) && ( e = d || null);
      var f = this.items.length, g = f, h, i = this, j;
      if (!f) {
        return this;
      }
      e && ( j = function() {
        !--f && e.call(i);
      }), d = a.is(d, D) ? d : j;
      var k = a.animation(b, c, d, j);
      h = this.items[--g].animate(k);
      while (g--) {
        this.items[g] && !this.items[g].removed && this.items[g].animateWith(h, k, k);
      }
      return this;
    }, cH.insertAfter = function(a) {
      var b = this.items.length;
      while (b--) {
        this.items[b].insertAfter(a);
      }
      return this;
    }, cH.getBBox = function() {
      var a = [], b = [], c = [], d = [];
      for (var e = this.items.length; e--; ) {
        if (!this.items[e].removed) {
          var f = this.items[e].getBBox();
          a.push(f.x), b.push(f.y), c.push(f.x + f.width), d.push(f.y + f.height);
        }
      }
      a = y[m](0, a), b = y[m](0, b), c = x[m](0, c), d = x[m](0, d);
      return {
        x : a,
        y : b,
        x2 : c,
        y2 : d,
        width : c - a,
        height : d - b
      };
    }, cH.clone = function(a) {
      a = new cG;
      for (var b = 0, c = this.items.length; b < c; b++) {
        a.push(this.items[b].clone());
      }
      return a;
    }, cH.toString = function() {
      return "Raphaël‘s set";
    }, a.registerFont = function(a) {
      if (!a.face) {
        return a;
      }
      this.fonts = this.fonts || {};
      var b = {
        w : a.w,
        face : {},
        glyphs : {}
      }, c = a.face["font-family"];
      for (var d in a.face) {
        a.face[g](d) && (b.face[d] = a.face[d]);
      }
      this.fonts[c] ? this.fonts[c].push(b) : this.fonts[c] = [b];
      if (!a.svg) {
        b.face["units-per-em"] = R(a.face["units-per-em"], 10);
        for (var e in a.glyphs) {
          if (a.glyphs[g](e)) {
            var f = a.glyphs[e];
            b.glyphs[e] = {
              w : f.w,
              k : {},
              d : f.d && "M" + f.d.replace(/[mlcxtrv]/g, function(a) {
                return {l:"L",c:"C",x:"z",t:"m",r:"l",v:"c"}[a] || "M";
              }) + "z"
            };
            if (f.k) {
              for (var h in f.k) {
                f[g](h) && (b.glyphs[e].k[h] = f.k[h]);
              }
            }
          }
        }
      }
      return a;
    }, k.getFont = function(b, c, d, e) {
      e = e || "normal", d = d || "normal", c = +c || {normal:400,bold:700,lighter:300,bolder:800}[c] || 400;
      if (!!a.fonts) {
        var f = a.fonts[b];
        if (!f) {
          var h = new RegExp("(^|\\s)" + b.replace(/[^\w\d\s+!~.:_-]/g, p) + "(\\s|$)", "i");
          for (var i in a.fonts) {
            if (a.fonts[g](i) && h.test(i)) {
              f = a.fonts[i];
              break;
            }
          }
        }
        var j;
        if (f) {
          for (var k = 0, l = f.length; k < l; k++) {
            j = f[k];
            if (j.face["font-weight"] == c && (j.face["font-style"] == d || !j.face["font-style"]) && j.face["font-stretch"] == e) {
              break;
            }
          }
        }
        return j;
      }
    }, k.print = function(b, d, e, f, g, h, i) {
      h = h || "middle", i = x(y(i || 0, 1), -1);
      var j = r(e)[s](p), k = 0, l = 0, m = p, n;
      a.is(f, e) && ( f = this.getFont(f));
      if (f) {
        n = (g || 16) / f.face["units-per-em"];
        var o = f.face.bbox[s](c), q = +o[0], t = o[3] - o[1], u = 0, v = +o[1] + (h == "baseline" ? t + +f.face.descent : t / 2);
        for (var w = 0, z = j.length; w < z; w++) {
          if (j[w] == "\n") {
            k = 0, B = 0, l = 0, u += t;
          } else {
            var A = l && f.glyphs[j[w - 1]] || {}, B = f.glyphs[j[w]];
            k += l ? (A.w || f.w) + (A.k && A.k[j[w]] || 0) + f.w * i : 0, l = 1;
          }
          B && B.d && (m += a.transformPath(B.d, ["t", k * n, u * n, "s", n, n, q, v, "t", (b - q) / n, (d - v) / n]));
        }
      }
      return this.path(m).attr({
        fill : "#000",
        stroke : "none"
      });
    }, k.add = function(b) {
      if (a.is(b, "array")) {
        var c = this.set(), e = 0, f = b.length, h;
        for (; e < f; e++) {
          h = b[e] || {}, d[g](h.type) && c.push(this[h.type]().attr(h));
        }
      }
      return c;
    }, a.format = function(b, c) {
      var d = a.is(c, E) ? [0][n](c) : arguments;
      b && a.is(b, D) && d.length - 1 && ( b = b.replace(e, function(a, b) {
        return d[++b] == null ? p : d[b];
      }));
      return b || p;
    }, a.fullfill = function() {
      var a = /\{([^\}]+)\}/g, b = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, c = function(a, c, d) {
        var e = d;
        c.replace(b, function(a, b, c, d, f) {
          b = b || d, e && ( b in e && ( e = e[b]), typeof e == "function" && f && ( e = e()));
        }), e = (e == null || e == d ? a : e) + "";
        return e;
      };
      return function(b, d) {
        return String(b).replace(a, function(a, b) {
          return c(a, b, d);
        });
      };
    }(), a.ninja = function() {
      i.was ? h.win.Raphael = i.is :
      delete Raphael;
      return a;
    }, a.st = cH, function(b, c, d) {
      function e() {
        /in/.test(b.readyState) ? setTimeout(e, 9) : a.eve("raphael.DOMload");
      }
      b.readyState == null && b.addEventListener && (b.addEventListener(c, d = function() {
        b.removeEventListener(c, d, !1), b.readyState = "complete";
      }, !1), b.readyState = "loading"), e();
    }(document, "DOMContentLoaded"), i.was ? h.win.Raphael = a : Raphael = a, eve.on("raphael.DOMload", function() {
      b = !0;
    });
  }(), window.Raphael.svg && function(a) {
    var b = "hasOwnProperty", c = String, d = parseFloat, e = parseInt, f = Math, g = f.max, h = f.abs, i = f.pow, j = /[, ]+/, k = a.eve, l = "", m = " ", n = "http://www.w3.org/1999/xlink", o = {
      block : "M5,0 0,2.5 5,5z",
      classic : "M5,0 0,2.5 5,5 3.5,3 3.5,2z",
      diamond : "M2.5,0 5,2.5 2.5,5 0,2.5z",
      open : "M6,1 1,3.5 6,6",
      oval : "M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"
    }, p = {};
    a.toString = function() {
      return "Your browser supports SVG.\nYou are running Raphaël " + this.version;
    };
    var q = function(d, e) {
      if (e) {
        typeof d == "string" && ( d = q(d));
        for (var f in e) {
          e[b](f) && (f.substring(0, 6) == "xlink:" ? d.setAttributeNS(n, f.substring(6), c(e[f])) : d.setAttribute(f, c(e[f])));
        }
      } else {
        d = a._g.doc.createElementNS("http://www.w3.org/2000/svg", d), d.style && (d.style.webkitTapHighlightColor = "rgba(0,0,0,0)");
      }
      return d;
    }, r = function(b, e) {
      var j = "linear", k = b.id + e, m = 0.5, n = 0.5, o = b.node, p = b.paper, r = o.style, s = a._g.doc.getElementById(k);
      if (!s) {
        e = c(e).replace(a._radial_gradient, function(a, b, c) {
          j = "radial";
          if (b && c) {
            m = d(b), n = d(c);
            var e = (n > 0.5) * 2 - 1;
            i(m - 0.5, 2) + i(n - 0.5, 2) > 0.25 && ( n = f.sqrt(0.25 - i(m - 0.5, 2)) * e + 0.5) && n != 0.5 && ( n = n.toFixed(5) - 0.00001 * e);
          }
          return l;
        }), e = e.split(/\s*\-\s*/);
        if (j == "linear") {
          var t = e.shift();
          t = -d(t);
          if (isNaN(t)) {
            return null;
          }
          var u = [0, 0, f.cos(a.rad(t)), f.sin(a.rad(t))], v = 1 / (g(h(u[2]), h(u[3])) || 1);
          u[2] *= v, u[3] *= v, u[2] < 0 && (u[0] = -u[2], u[2] = 0), u[3] < 0 && (u[1] = -u[3], u[3] = 0);
        }
        var w = a._parseDots(e);
        if (!w) {
          return null;
        }
        k = k.replace(/[\(\)\s,\xb0#]/g, "_"), b.gradient && k != b.gradient.id && (p.defs.removeChild(b.gradient),
        delete b.gradient);
        if (!b.gradient) {
          s = q(j + "Gradient", {
            id : k
          }), b.gradient = s, q(s, j == "radial" ? {
            fx : m,
            fy : n
          } : {
            x1 : u[0],
            y1 : u[1],
            x2 : u[2],
            y2 : u[3],
            gradientTransform : b.matrix.invert()
          }), p.defs.appendChild(s);
          for (var x = 0, y = w.length; x < y; x++) {
            s.appendChild(q("stop", {
              offset : w[x].offset ? w[x].offset : x ? "100%" : "0%",
              "stop-color" : w[x].color || "#fff"
            }));
          }
        }
      }
      q(o, {
        fill : "url(#" + k + ")",
        opacity : 1,
        "fill-opacity" : 1
      }), r.fill = l, r.opacity = 1, r.fillOpacity = 1;
      return 1;
    }, s = function(a) {
      var b = a.getBBox(1);
      q(a.pattern, {
        patternTransform : a.matrix.invert() + " translate(" + b.x + "," + b.y + ")"
      });
    }, t = function(d, e, f) {
      if (d.type == "path") {
        var g = c(e).toLowerCase().split("-"), h = d.paper, i = f ? "end" : "start", j = d.node, k = d.attrs, m = k["stroke-width"], n = g.length, r = "classic", s, t, u, v, w, x = 3, y = 3, z = 5;
        while (n--) {
          switch(g[n]) {
            case"block":
            case"classic":
            case"oval":
            case"diamond":
            case"open":
            case"none":
              r = g[n];
              break;
            case"wide":
              y = 5;
              break;
            case"narrow":
              y = 2;
              break;
            case"long":
              x = 5;
              break;
            case"short":
              x = 2;
          }
        }
        r == "open" ? (x += 2, y += 2, z += 2, u = 1, v = f ? 4 : 1, w = {
          fill : "none",
          stroke : k.stroke
        }) : ( v = u = x / 2, w = {
          fill : k.stroke,
          stroke : "none"
        }), d._.arrows ? f ? (d._.arrows.endPath && p[d._.arrows.endPath]--, d._.arrows.endMarker && p[d._.arrows.endMarker]--) : (d._.arrows.startPath && p[d._.arrows.startPath]--, d._.arrows.startMarker && p[d._.arrows.startMarker]--) : d._.arrows = {};
        if (r != "none") {
          var A = "raphael-marker-" + r, B = "raphael-marker-" + i + r + x + y;
          a._g.doc.getElementById(A) ? p[A]++ : (h.defs.appendChild(q(q("path"), {
            "stroke-linecap" : "round",
            d : o[r],
            id : A
          })), p[A] = 1);
          var C = a._g.doc.getElementById(B), D;
          C ? (p[B]++, D = C.getElementsByTagName("use")[0]) : ( C = q(q("marker"), {
            id : B,
            markerHeight : y,
            markerWidth : x,
            orient : "auto",
            refX : v,
            refY : y / 2
          }), D = q(q("use"), {
            "xlink:href" : "#" + A,
            transform : ( f ? "rotate(180 " + x / 2 + " " + y / 2 + ") " : l) + "scale(" + x / z + "," + y / z + ")",
            "stroke-width" : (1 / ((x / z + y / z) / 2)).toFixed(4)
          }), C.appendChild(D), h.defs.appendChild(C), p[B] = 1), q(D, w);
          var F = u * (r != "diamond" && r != "oval");
          f ? ( s = d._.arrows.startdx * m || 0, t = a.getTotalLength(k.path) - F * m) : ( s = F * m, t = a.getTotalLength(k.path) - (d._.arrows.enddx * m || 0)), w = {}, w["marker-" + i] = "url(#" + B + ")";
          if (t || s) {
            w.d = Raphael.getSubpath(k.path, s, t);
          }
          q(j, w), d._.arrows[i + "Path"] = A, d._.arrows[i + "Marker"] = B, d._.arrows[i + "dx"] = F, d._.arrows[i + "Type"] = r, d._.arrows[i + "String"] = e;
        } else {
          f ? ( s = d._.arrows.startdx * m || 0, t = a.getTotalLength(k.path) - s) : ( s = 0, t = a.getTotalLength(k.path) - (d._.arrows.enddx * m || 0)), d._.arrows[i + "Path"] && q(j, {
            d : Raphael.getSubpath(k.path, s, t)
          }),
          delete d._.arrows[i + "Path"],
          delete d._.arrows[i + "Marker"],
          delete d._.arrows[i + "dx"],
          delete d._.arrows[i + "Type"],
          delete d._.arrows[i + "String"];
        }
        for (w in p) {
          if (p[b](w) && !p[w]) {
            var G = a._g.doc.getElementById(w);
            G && G.parentNode.removeChild(G);
          }
        }
      }
    }, u = {
      "" : [0],
      none : [0],
      "-" : [3, 1],
      "." : [1, 1],
      "-." : [3, 1, 1, 1],
      "-.." : [3, 1, 1, 1, 1, 1],
      ". " : [1, 3],
      "- " : [4, 3],
      "--" : [8, 3],
      "- ." : [4, 3, 1, 3],
      "--." : [8, 3, 1, 3],
      "--.." : [8, 3, 1, 3, 1, 3]
    }, v = function(a, b, d) {
      b = u[c(b).toLowerCase()];
      if (b) {
        var e = a.attrs["stroke-width"] || "1", f = {round:e,square:e,butt:0}[a.attrs["stroke-linecap"] || d["stroke-linecap"]] || 0, g = [], h = b.length;
        while (h--) {
          g[h] = b[h] * e + (h % 2 ? 1 : -1) * f;
        }
        q(a.node, {
          "stroke-dasharray" : g.join(",")
        });
      }
    }, w = function(d, f) {
      var i = d.node, k = d.attrs, m = i.style.visibility;
      i.style.visibility = "hidden";
      for (var o in f) {
        if (f[b](o)) {
          if (!a._availableAttrs[b](o)) {
            continue;
          }
          var p = f[o];
          k[o] = p;
          switch(o) {
            case"blur":
              d.blur(p);
              break;
            case"href":
            case"title":
            case"target":
              var u = i.parentNode;
              if (u.tagName.toLowerCase() != "a") {
                var w = q("a");
                u.insertBefore(w, i), w.appendChild(i), u = w;
              }
              o == "target" ? u.setAttributeNS(n, "show", p == "blank" ? "new" : p) : u.setAttributeNS(n, o, p);
              break;
            case"cursor":
              i.style.cursor = p;
              break;
            case"transform":
              d.transform(p);
              break;
            case"arrow-start":
              t(d, p);
              break;
            case"arrow-end":
              t(d, p, 1);
              break;
            case"clip-rect":
              var x = c(p).split(j);
              if (x.length == 4) {
                d.clip && d.clip.parentNode.parentNode.removeChild(d.clip.parentNode);
                var z = q("clipPath"), A = q("rect");
                z.id = a.createUUID(), q(A, {
                  x : x[0],
                  y : x[1],
                  width : x[2],
                  height : x[3]
                }), z.appendChild(A), d.paper.defs.appendChild(z), q(i, {
                  "clip-path" : "url(#" + z.id + ")"
                }), d.clip = A;
              }
              if (!p) {
                var B = i.getAttribute("clip-path");
                if (B) {
                  var C = a._g.doc.getElementById(B.replace(/(^url\(#|\)$)/g, l));
                  C && C.parentNode.removeChild(C), q(i, {
                    "clip-path" : l
                  }),
                  delete d.clip;
                }
              }
              break;
            case"path":
              d.type == "path" && (q(i, {
                d : p ? k.path = a._pathToAbsolute(p) : "M0,0"
              }), d._.dirty = 1, d._.arrows && ("startString" in d._.arrows && t(d, d._.arrows.startString), "endString" in d._.arrows && t(d, d._.arrows.endString, 1)));
              break;
            case"width":
              i.setAttribute(o, p), d._.dirty = 1;
              if (k.fx) {
                o = "x", p = k.x;
              } else {
                break;
              }
            case"x":
              k.fx && ( p = -k.x - (k.width || 0));
            case"rx":
              if (o == "rx" && d.type == "rect") {
                break;
              }
            case"cx":
              i.setAttribute(o, p), d.pattern && s(d), d._.dirty = 1;
              break;
            case"height":
              i.setAttribute(o, p), d._.dirty = 1;
              if (k.fy) {
                o = "y", p = k.y;
              } else {
                break;
              }
            case"y":
              k.fy && ( p = -k.y - (k.height || 0));
            case"ry":
              if (o == "ry" && d.type == "rect") {
                break;
              }
            case"cy":
              i.setAttribute(o, p), d.pattern && s(d), d._.dirty = 1;
              break;
            case"r":
              d.type == "rect" ? q(i, {
                rx : p,
                ry : p
              }) : i.setAttribute(o, p), d._.dirty = 1;
              break;
            case"src":
              d.type == "image" && i.setAttributeNS(n, "href", p);
              break;
            case"stroke-width":
              if (d._.sx != 1 || d._.sy != 1) {
                p /= g(h(d._.sx), h(d._.sy)) || 1;
              }
              d.paper._vbSize && (p *= d.paper._vbSize), i.setAttribute(o, p), k["stroke-dasharray"] && v(d, k["stroke-dasharray"], f), d._.arrows && ("startString" in d._.arrows && t(d, d._.arrows.startString), "endString" in d._.arrows && t(d, d._.arrows.endString, 1));
              break;
            case"stroke-dasharray":
              v(d, p, f);
              break;
            case"fill":
              var D = c(p).match(a._ISURL);
              if (D) {
                z = q("pattern");
                var F = q("image");
                z.id = a.createUUID(), q(z, {
                  x : 0,
                  y : 0,
                  patternUnits : "userSpaceOnUse",
                  height : 1,
                  width : 1
                }), q(F, {
                  x : 0,
                  y : 0,
                  "xlink:href" : D[1]
                }), z.appendChild(F), function(b) {
                  a._preload(D[1], function() {
                    var a = this.offsetWidth, c = this.offsetHeight;
                    q(b, {
                      width : a,
                      height : c
                    }), q(F, {
                      width : a,
                      height : c
                    }), d.paper.safari();
                  });
                }(z), d.paper.defs.appendChild(z), q(i, {
                  fill : "url(#" + z.id + ")"
                }), d.pattern = z, d.pattern && s(d);
                break;
              }
              var G = a.getRGB(p);
              if (!G.error) {
                delete f.gradient,
                delete k.gradient, !a.is(k.opacity, "undefined") && a.is(f.opacity, "undefined") && q(i, {
                  opacity : k.opacity
                }), !a.is(k["fill-opacity"], "undefined") && a.is(f["fill-opacity"], "undefined") && q(i, {
                  "fill-opacity" : k["fill-opacity"]
                });
              } else {
                if ((d.type == "circle" || d.type == "ellipse" || c(p).charAt() != "r") && r(d, p)) {
                  if ("opacity" in k || "fill-opacity" in k) {
                    var H = a._g.doc.getElementById(i.getAttribute("fill").replace(/^url\(#|\)$/g, l));
                    if (H) {
                      var I = H.getElementsByTagName("stop");
                      q(I[I.length - 1], {
                        "stop-opacity" : ("opacity" in k ? k.opacity : 1) * ("fill-opacity" in k ? k["fill-opacity"] : 1)
                      });
                    }
                  }
                  k.gradient = p, k.fill = "none";
                  break;
                }
              }
              G[b]("opacity") && q(i, {
                "fill-opacity" : G.opacity > 1 ? G.opacity / 100 : G.opacity
              });
            case"stroke":
              G = a.getRGB(p), i.setAttribute(o, G.hex), o == "stroke" && G[b]("opacity") && q(i, {
                "stroke-opacity" : G.opacity > 1 ? G.opacity / 100 : G.opacity
              }), o == "stroke" && d._.arrows && ("startString" in d._.arrows && t(d, d._.arrows.startString), "endString" in d._.arrows && t(d, d._.arrows.endString, 1));
              break;
            case"gradient":
              (d.type == "circle" || d.type == "ellipse" || c(p).charAt() != "r") && r(d, p);
              break;
            case"opacity":
              k.gradient && !k[b]("stroke-opacity") && q(i, {
                "stroke-opacity" : p > 1 ? p / 100 : p
              });
            case"fill-opacity":
              if (k.gradient) {
                H = a._g.doc.getElementById(i.getAttribute("fill").replace(/^url\(#|\)$/g, l)), H && ( I = H.getElementsByTagName("stop"), q(I[I.length - 1], {
                  "stop-opacity" : p
                }));
                break;
              }
            default:
              o == "font-size" && ( p = e(p, 10) + "px");
              var J = o.replace(/(\-.)/g, function(a) {
                return a.substring(1).toUpperCase();
              });
              i.style[J] = p, d._.dirty = 1, i.setAttribute(o, p);
          }
        }
      }
      y(d, f), i.style.visibility = m;
    }, x = 1.2, y = function(d, f) {
      if (d.type == "text" && !!(f[b]("text") || f[b]("font") || f[b]("font-size") || f[b]("x") || f[b]("y"))) {
        var g = d.attrs, h = d.node, i = h.firstChild ? e(a._g.doc.defaultView.getComputedStyle(h.firstChild, l).getPropertyValue("font-size"), 10) : 10;
        if (f[b]("text")) {
          g.text = f.text;
          while (h.firstChild) {
            h.removeChild(h.firstChild);
          }
          var j = c(f.text).split("\n"), k = [], m;
          for (var n = 0, o = j.length; n < o; n++) {
            m = q("tspan"), n && q(m, {
              dy : i * x,
              x : g.x
            }), m.appendChild(a._g.doc.createTextNode(j[n])), h.appendChild(m), k[n] = m;
          }
        } else {
          k = h.getElementsByTagName("tspan");
          for ( n = 0, o = k.length; n < o; n++) {
            n ? q(k[n], {
              dy : i * x,
              x : g.x
            }) : q(k[0], {
              dy : 0
            });
          }
        }
        q(h, {
          x : g.x,
          y : g.y
        }), d._.dirty = 1;
        var p = d._getBBox(), r = g.y - (p.y + p.height / 2);
        r && a.is(r, "finite") && q(k[0], {
          dy : r
        });
      }
    }, z = function(b, c) {
      var d = 0, e = 0;
      this[0] = this.node = b, b.raphael = !0, this.id = a._oid++, b.raphaelid = this.id, this.matrix = a.matrix(), this.realPath = null, this.paper = c, this.attrs = this.attrs || {}, this._ = {
        transform : [],
        sx : 1,
        sy : 1,
        deg : 0,
        dx : 0,
        dy : 0,
        dirty : 1
      }, !c.bottom && (c.bottom = this), this.prev = c.top, c.top && (c.top.next = this), c.top = this, this.next = null;
    }, A = a.el;
    z.prototype = A, A.constructor = z, a._engine.path = function(a, b) {
      var c = q("path");
      b.canvas && b.canvas.appendChild(c);
      var d = new z(c, b);
      d.type = "path", w(d, {
        fill : "none",
        stroke : "#000",
        path : a
      });
      return d;
    }, A.rotate = function(a, b, e) {
      if (this.removed) {
        return this;
      }
      a = c(a).split(j), a.length - 1 && ( b = d(a[1]), e = d(a[2])), a = d(a[0]), e == null && ( b = e);
      if (b == null || e == null) {
        var f = this.getBBox(1);
        b = f.x + f.width / 2, e = f.y + f.height / 2;
      }
      this.transform(this._.transform.concat([["r", a, b, e]]));
      return this;
    }, A.scale = function(a, b, e, f) {
      if (this.removed) {
        return this;
      }
      a = c(a).split(j), a.length - 1 && ( b = d(a[1]), e = d(a[2]), f = d(a[3])), a = d(a[0]), b == null && ( b = a), f == null && ( e = f);
      if (e == null || f == null) {
        var g = this.getBBox(1);
      }
      e = e == null ? g.x + g.width / 2 : e, f = f == null ? g.y + g.height / 2 : f, this.transform(this._.transform.concat([["s", a, b, e, f]]));
      return this;
    }, A.translate = function(a, b) {
      if (this.removed) {
        return this;
      }
      a = c(a).split(j), a.length - 1 && ( b = d(a[1])), a = d(a[0]) || 0, b = +b || 0, this.transform(this._.transform.concat([["t", a, b]]));
      return this;
    }, A.transform = function(c) {
      var d = this._;
      if (c == null) {
        return d.transform;
      }
      a._extractTransform(this, c), this.clip && q(this.clip, {
        transform : this.matrix.invert()
      }), this.pattern && s(this), this.node && q(this.node, {
        transform : this.matrix
      });
      if (d.sx != 1 || d.sy != 1) {
        var e = this.attrs[b]("stroke-width") ? this.attrs["stroke-width"] : 1;
        this.attr({
          "stroke-width" : e
        });
      }
      return this;
    }, A.hide = function() {
      !this.removed && this.paper.safari(this.node.style.display = "none");
      return this;
    }, A.show = function() {
      !this.removed && this.paper.safari(this.node.style.display = "");
      return this;
    }, A.remove = function() {
      if (!this.removed && !!this.node.parentNode) {
        var b = this.paper;
        b.__set__ && b.__set__.exclude(this), k.unbind("raphael.*.*." + this.id), this.gradient && b.defs.removeChild(this.gradient), a._tear(this, b), this.node.parentNode.tagName.toLowerCase() == "a" ? this.node.parentNode.parentNode.removeChild(this.node.parentNode) : this.node.parentNode.removeChild(this.node);
        for (var c in this) {
          this[c] = typeof this[c] == "function" ? a._removedFactory(c) : null;
        }
        this.removed = !0;
      }
    }, A._getBBox = function() {
      if (this.node.style.display == "none") {
        this.show();
        var a = !0;
      }
      var b = {};
      try {
        b = this.node.getBBox();
      } catch(c) {
      } finally {
        b = b || {};
      }
      a && this.hide();
      return b;
    }, A.attr = function(c, d) {
      if (this.removed) {
        return this;
      }
      if (c == null) {
        var e = {};
        for (var f in this.attrs) {
          this.attrs[b](f) && (e[f] = this.attrs[f]);
        }
        e.gradient && e.fill == "none" && (e.fill = e.gradient) &&
        delete e.gradient, e.transform = this._.transform;
        return e;
      }
      if (d == null && a.is(c, "string")) {
        if (c == "fill" && this.attrs.fill == "none" && this.attrs.gradient) {
          return this.attrs.gradient;
        }
        if (c == "transform") {
          return this._.transform;
        }
        var g = c.split(j), h = {};
        for (var i = 0, l = g.length; i < l; i++) {
          c = g[i], c in this.attrs ? h[c] = this.attrs[c] : a.is(this.paper.customAttributes[c], "function") ? h[c] = this.paper.customAttributes[c].def : h[c] = a._availableAttrs[c];
        }
        return l - 1 ? h : h[g[0]];
      }
      if (d == null && a.is(c, "array")) {
        h = {};
        for ( i = 0, l = c.length; i < l; i++) {
          h[c[i]] = this.attr(c[i]);
        }
        return h;
      }
      if (d != null) {
        var m = {};
        m[c] = d;
      } else {
        c != null && a.is(c, "object") && ( m = c);
      }
      for (var n in m) {
        k("raphael.attr." + n + "." + this.id, this, m[n]);
      }
      for (n in this.paper.customAttributes) {
        if (this.paper.customAttributes[b](n) && m[b](n) && a.is(this.paper.customAttributes[n], "function")) {
          var o = this.paper.customAttributes[n].apply(this, [].concat(m[n]));
          this.attrs[n] = m[n];
          for (var p in o) {
            o[b](p) && (m[p] = o[p]);
          }
        }
      }
      w(this, m);
      return this;
    }, A.toFront = function() {
      if (this.removed) {
        return this;
      }
      this.node.parentNode.tagName.toLowerCase() == "a" ? this.node.parentNode.parentNode.appendChild(this.node.parentNode) : this.node.parentNode.appendChild(this.node);
      var b = this.paper;
      b.top != this && a._tofront(this, b);
      return this;
    }, A.toBack = function() {
      if (this.removed) {
        return this;
      }
      var b = this.node.parentNode;
      b.tagName.toLowerCase() == "a" ? b.parentNode.insertBefore(this.node.parentNode, this.node.parentNode.parentNode.firstChild) : b.firstChild != this.node && b.insertBefore(this.node, this.node.parentNode.firstChild), a._toback(this, this.paper);
      var c = this.paper;
      return this;
    }, A.insertAfter = function(b) {
      if (this.removed) {
        return this;
      }
      var c = b.node || b[b.length - 1].node;
      c.nextSibling ? c.parentNode.insertBefore(this.node, c.nextSibling) : c.parentNode.appendChild(this.node), a._insertafter(this, b, this.paper);
      return this;
    }, A.insertBefore = function(b) {
      if (this.removed) {
        return this;
      }
      var c = b.node || b[0].node;
      c.parentNode.insertBefore(this.node, c), a._insertbefore(this, b, this.paper);
      return this;
    }, A.blur = function(b) {
      var c = this;
      if (+b !== 0) {
        var d = q("filter"), e = q("feGaussianBlur");
        c.attrs.blur = b, d.id = a.createUUID(), q(e, {
          stdDeviation : +b || 1.5
        }), d.appendChild(e), c.paper.defs.appendChild(d), c._blur = d, q(c.node, {
          filter : "url(#" + d.id + ")"
        });
      } else {
        c._blur && (c._blur.parentNode.removeChild(c._blur),
        delete c._blur,
        delete c.attrs.blur), c.node.removeAttribute("filter");
      }
    }, a._engine.circle = function(a, b, c, d) {
      var e = q("circle");
      a.canvas && a.canvas.appendChild(e);
      var f = new z(e, a);
      f.attrs = {
        cx : b,
        cy : c,
        r : d,
        fill : "none",
        stroke : "#000"
      }, f.type = "circle", q(e, f.attrs);
      return f;
    }, a._engine.rect = function(a, b, c, d, e, f) {
      var g = q("rect");
      a.canvas && a.canvas.appendChild(g);
      var h = new z(g, a);
      h.attrs = {
        x : b,
        y : c,
        width : d,
        height : e,
        r : f || 0,
        rx : f || 0,
        ry : f || 0,
        fill : "none",
        stroke : "#000"
      }, h.type = "rect", q(g, h.attrs);
      return h;
    }, a._engine.ellipse = function(a, b, c, d, e) {
      var f = q("ellipse");
      a.canvas && a.canvas.appendChild(f);
      var g = new z(f, a);
      g.attrs = {
        cx : b,
        cy : c,
        rx : d,
        ry : e,
        fill : "none",
        stroke : "#000"
      }, g.type = "ellipse", q(f, g.attrs);
      return g;
    }, a._engine.image = function(a, b, c, d, e, f) {
      var g = q("image");
      q(g, {
        x : c,
        y : d,
        width : e,
        height : f,
        preserveAspectRatio : "none"
      }), g.setAttributeNS(n, "href", b), a.canvas && a.canvas.appendChild(g);
      var h = new z(g, a);
      h.attrs = {
        x : c,
        y : d,
        width : e,
        height : f,
        src : b
      }, h.type = "image";
      return h;
    }, a._engine.text = function(b, c, d, e) {
      var f = q("text");
      b.canvas && b.canvas.appendChild(f);
      var g = new z(f, b);
      g.attrs = {
        x : c,
        y : d,
        "text-anchor" : "middle",
        text : e,
        font : a._availableAttrs.font,
        stroke : "none",
        fill : "#000"
      }, g.type = "text", w(g, g.attrs);
      return g;
    }, a._engine.setSize = function(a, b) {
      this.width = a || this.width, this.height = b || this.height, this.canvas.setAttribute("width", this.width), this.canvas.setAttribute("height", this.height), this._viewBox && this.setViewBox.apply(this, this._viewBox);
      return this;
    }, a._engine.create = function() {
      var b = a._getContainer.apply(0, arguments), c = b && b.container, d = b.x, e = b.y, f = b.width, g = b.height;
      if (!c) {
        throw new Error("SVG container not found.");
      }
      var h = q("svg"), i = "overflow:hidden;", j;
      d = d || 0, e = e || 0, f = f || 512, g = g || 342, q(h, {
        height : g,
        version : 1.1,
        width : f,
        xmlns : "http://www.w3.org/2000/svg"
      }), c == 1 ? (h.style.cssText = i + "position:absolute;left:" + d + "px;top:" + e + "px", a._g.doc.body.appendChild(h), j = 1) : (h.style.cssText = i + "position:relative", c.firstChild ? c.insertBefore(h, c.firstChild) : c.appendChild(h)), c = new a._Paper, c.width = f, c.height = g, c.canvas = h, c.clear(), c._left = c._top = 0, j && (c.renderfix = function() {
      }), c.renderfix();
      return c;
    }, a._engine.setViewBox = function(a, b, c, d, e) {
      k("raphael.setViewBox", this, this._viewBox, [a, b, c, d, e]);
      var f = g(c / this.width, d / this.height), h = this.top, i = e ? "meet" : "xMinYMin", j, l;
      a == null ? (this._vbSize && ( f = 1),
      delete this._vbSize, j = "0 0 " + this.width + m + this.height) : (this._vbSize = f, j = a + m + b + m + c + m + d), q(this.canvas, {
        viewBox : j,
        preserveAspectRatio : i
      });
      while (f && h) {
        l = "stroke-width" in h.attrs ? h.attrs["stroke-width"] : 1, h.attr({
          "stroke-width" : l
        }), h._.dirty = 1, h._.dirtyT = 1, h = h.prev;
      }
      this._viewBox = [a, b, c, d, !!e];
      return this;
    }, a.prototype.renderfix = function() {
      var a = this.canvas, b = a.style, c;
      try {
        c = a.getScreenCTM() || a.createSVGMatrix();
      } catch(d) {
        c = a.createSVGMatrix();
      }
      var e = -c.e % 1, f = -c.f % 1;
      if (e || f) {
        e && (this._left = (this._left + e) % 1, b.left = this._left + "px"), f && (this._top = (this._top + f) % 1, b.top = this._top + "px");
      }
    }, a.prototype.clear = function() {
      a.eve("raphael.clear", this);
      var b = this.canvas;
      while (b.firstChild) {
        b.removeChild(b.firstChild);
      }
      this.bottom = this.top = null, (this.desc = q("desc")).appendChild(a._g.doc.createTextNode("Created with Raphaël " + a.version)), b.appendChild(this.desc), b.appendChild(this.defs = q("defs"));
    }, a.prototype.remove = function() {
      k("raphael.remove", this), this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas);
      for (var b in this) {
        this[b] = typeof this[b] == "function" ? a._removedFactory(b) : null;
      }
    };
    var B = a.st;
    for (var C in A) {
      A[b](C) && !B[b](C) && (B[C] = function(a) {
        return function() {
          var b = arguments;
          return this.forEach(function(c) {
            c[a].apply(c, b);
          });
        };
      }(C));
    }
  }(window.Raphael), window.Raphael.vml && function(a) {
    var b = "hasOwnProperty", c = String, d = parseFloat, e = Math, f = e.round, g = e.max, h = e.min, i = e.abs, j = "fill", k = /[, ]+/, l = a.eve, m = " progid:DXImageTransform.Microsoft", n = " ", o = "", p = {
      M : "m",
      L : "l",
      C : "c",
      Z : "x",
      m : "t",
      l : "r",
      c : "v",
      z : "x"
    }, q = /([clmz]),?([^clmz]*)/gi, r = / progid:\S+Blur\([^\)]+\)/g, s = /-?[^,\s-]+/g, t = "position:absolute;left:0;top:0;width:1px;height:1px", u = 21600, v = {
      path : 1,
      rect : 1,
      image : 1
    }, w = {
      circle : 1,
      ellipse : 1
    }, x = function(b) {
      var d = /[ahqstv]/ig, e = a._pathToAbsolute;
      c(b).match(d) && ( e = a._path2curve), d = /[clmz]/g;
      if (e == a._pathToAbsolute && !c(b).match(d)) {
        var g = c(b).replace(q, function(a, b, c) {
          var d = [], e = b.toLowerCase() == "m", g = p[b];
          c.replace(s, function(a) {
            e && d.length == 2 && (g += d + p[b == "m" ? "l" : "L"], d = []), d.push(f(a * u));
          });
          return g + d;
        });
        return g;
      }
      var h = e(b), i, j;
      g = [];
      for (var k = 0, l = h.length; k < l; k++) {
        i = h[k], j = h[k][0].toLowerCase(), j == "z" && ( j = "x");
        for (var m = 1, r = i.length; m < r; m++) {
          j += f(i[m] * u) + (m != r - 1 ? "," : o);
        }
        g.push(j);
      }
      return g.join(n);
    }, y = function(b, c, d) {
      var e = a.matrix();
      e.rotate(-b, 0.5, 0.5);
      return {
        dx : e.x(c, d),
        dy : e.y(c, d)
      };
    }, z = function(a, b, c, d, e, f) {
      var g = a._, h = a.matrix, k = g.fillpos, l = a.node, m = l.style, o = 1, p = "", q, r = u / b, s = u / c;
      m.visibility = "hidden";
      if (!!b && !!c) {
        l.coordsize = i(r) + n + i(s), m.rotation = f * (b * c < 0 ? -1 : 1);
        if (f) {
          var t = y(f, d, e);
          d = t.dx, e = t.dy;
        }
        b < 0 && (p += "x"), c < 0 && (p += " y") && ( o = -1), m.flip = p, l.coordorigin = d * -r + n + e * -s;
        if (k || g.fillsize) {
          var v = l.getElementsByTagName(j);
          v = v && v[0], l.removeChild(v), k && ( t = y(f, h.x(k[0], k[1]), h.y(k[0], k[1])), v.position = t.dx * o + n + t.dy * o), g.fillsize && (v.size = g.fillsize[0] * i(b) + n + g.fillsize[1] * i(c)), l.appendChild(v);
        }
        m.visibility = "visible";
      }
    };
    a.toString = function() {
      return "Your browser doesn’t support SVG. Falling down to VML.\nYou are running Raphaël " + this.version;
    };
    var A = function(a, b, d) {
      var e = c(b).toLowerCase().split("-"), f = d ? "end" : "start", g = e.length, h = "classic", i = "medium", j = "medium";
      while (g--) {
        switch(e[g]) {
          case"block":
          case"classic":
          case"oval":
          case"diamond":
          case"open":
          case"none":
            h = e[g];
            break;
          case"wide":
          case"narrow":
            j = e[g];
            break;
          case"long":
          case"short":
            i = e[g];
        }
      }
      var k = a.node.getElementsByTagName("stroke")[0];
      k[f + "arrow"] = h, k[f + "arrowlength"] = i, k[f + "arrowwidth"] = j;
    }, B = function(e, i) {
      e.attrs = e.attrs || {};
      var l = e.node, m = e.attrs, p = l.style, q, r = v[e.type] && (i.x != m.x || i.y != m.y || i.width != m.width || i.height != m.height || i.cx != m.cx || i.cy != m.cy || i.rx != m.rx || i.ry != m.ry || i.r != m.r), s = w[e.type] && (m.cx != i.cx || m.cy != i.cy || m.r != i.r || m.rx != i.rx || m.ry != i.ry), t = e;
      for (var y in i) {
        i[b](y) && (m[y] = i[y]);
      }
      r && (m.path = a._getPath[e.type](e), e._.dirty = 1), i.href && (l.href = i.href), i.title && (l.title = i.title), i.target && (l.target = i.target), i.cursor && (p.cursor = i.cursor), "blur" in i && e.blur(i.blur);
      if (i.path && e.type == "path" || r) {
        l.path = x(~c(m.path).toLowerCase().indexOf("r") ? a._pathToAbsolute(m.path) : m.path), e.type == "image" && (e._.fillpos = [m.x, m.y], e._.fillsize = [m.width, m.height], z(e, 1, 1, 0, 0, 0));
      }
      "transform" in i && e.transform(i.transform);
      if (s) {
        var B = +m.cx, D = +m.cy, E = +m.rx || +m.r || 0, G = +m.ry || +m.r || 0;
        l.path = a.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x", f((B - E) * u), f((D - G) * u), f((B + E) * u), f((D + G) * u), f(B * u));
      }
      if ("clip-rect" in i) {
        var H = c(i["clip-rect"]).split(k);
        if (H.length == 4) {
          H[2] = +H[2] + +H[0], H[3] = +H[3] + +H[1];
          var I = l.clipRect || a._g.doc.createElement("div"), J = I.style;
          J.clip = a.format("rect({1}px {2}px {3}px {0}px)", H), l.clipRect || (J.position = "absolute", J.top = 0, J.left = 0, J.width = e.paper.width + "px", J.height = e.paper.height + "px", l.parentNode.insertBefore(I, l), I.appendChild(l), l.clipRect = I);
        }
        i["clip-rect"] || l.clipRect && (l.clipRect.style.clip = "auto");
      }
      if (e.textpath) {
        var K = e.textpath.style;
        i.font && (K.font = i.font), i["font-family"] && (K.fontFamily = '"' + i["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, o) + '"'), i["font-size"] && (K.fontSize = i["font-size"]), i["font-weight"] && (K.fontWeight = i["font-weight"]), i["font-style"] && (K.fontStyle = i["font-style"]);
      }
      "arrow-start" in i && A(t, i["arrow-start"]), "arrow-end" in i && A(t, i["arrow-end"], 1);
      if (i.opacity != null || i["stroke-width"] != null || i.fill != null || i.src != null || i.stroke != null || i["stroke-width"] != null || i["stroke-opacity"] != null || i["fill-opacity"] != null || i["stroke-dasharray"] != null || i["stroke-miterlimit"] != null || i["stroke-linejoin"] != null || i["stroke-linecap"] != null) {
        var L = l.getElementsByTagName(j), M = !1;
        L = L && L[0], !L && ( M = L = F(j)), e.type == "image" && i.src && (L.src = i.src), i.fill && (L.on = !0);
        if (L.on == null || i.fill == "none" || i.fill === null) {
          L.on = !1;
        }
        if (L.on && i.fill) {
          var N = c(i.fill).match(a._ISURL);
          if (N) {
            L.parentNode == l && l.removeChild(L), L.rotate = !0, L.src = N[1], L.type = "tile";
            var O = e.getBBox(1);
            L.position = O.x + n + O.y, e._.fillpos = [O.x, O.y], a._preload(N[1], function() {
              e._.fillsize = [this.offsetWidth, this.offsetHeight];
            });
          } else {
            L.color = a.getRGB(i.fill).hex, L.src = o, L.type = "solid", a.getRGB(i.fill).error && (t.type in {
              circle : 1,
              ellipse : 1
            } || c(i.fill).charAt() != "r") && C(t, i.fill, L) && (m.fill = "none", m.gradient = i.fill, L.rotate = !1);
          }
        }
        if ("fill-opacity" in i || "opacity" in i) {
          var P = ((+m["fill-opacity"] + 1 || 2) - 1) * ((+m.opacity + 1 || 2) - 1) * ((+a.getRGB(i.fill).o + 1 || 2) - 1);
          P = h(g(P, 0), 1), L.opacity = P, L.src && (L.color = "none");
        }
        l.appendChild(L);
        var Q = l.getElementsByTagName("stroke") && l.getElementsByTagName("stroke")[0], T = !1;
        !Q && ( T = Q = F("stroke"));
        if (i.stroke && i.stroke != "none" || i["stroke-width"] || i["stroke-opacity"] != null || i["stroke-dasharray"] || i["stroke-miterlimit"] || i["stroke-linejoin"] || i["stroke-linecap"]) {
          Q.on = !0;
        }
        (i.stroke == "none" || i.stroke === null || Q.on == null || i.stroke == 0 || i["stroke-width"] == 0) && (Q.on = !1);
        var U = a.getRGB(i.stroke);
        Q.on && i.stroke && (Q.color = U.hex), P = ((+m["stroke-opacity"] + 1 || 2) - 1) * ((+m.opacity + 1 || 2) - 1) * ((+U.o + 1 || 2) - 1);
        var V = (d(i["stroke-width"]) || 1) * 0.75;
        P = h(g(P, 0), 1), i["stroke-width"] == null && ( V = m["stroke-width"]), i["stroke-width"] && (Q.weight = V), V && V < 1 && (P *= V) && (Q.weight = 1), Q.opacity = P, i["stroke-linejoin"] && (Q.joinstyle = i["stroke-linejoin"] || "miter"), Q.miterlimit = i["stroke-miterlimit"] || 8, i["stroke-linecap"] && (Q.endcap = i["stroke-linecap"] == "butt" ? "flat" : i["stroke-linecap"] == "square" ? "square" : "round");
        if (i["stroke-dasharray"]) {
          var W = {
            "-" : "shortdash",
            "." : "shortdot",
            "-." : "shortdashdot",
            "-.." : "shortdashdotdot",
            ". " : "dot",
            "- " : "dash",
            "--" : "longdash",
            "- ." : "dashdot",
            "--." : "longdashdot",
            "--.." : "longdashdotdot"
          };
          Q.dashstyle = W[b](i["stroke-dasharray"]) ? W[i["stroke-dasharray"]] : o;
        }
        T && l.appendChild(Q);
      }
      if (t.type == "text") {
        t.paper.canvas.style.display = o;
        var X = t.paper.span, Y = 100, Z = m.font && m.font.match(/\d+(?:\.\d*)?(?=px)/);
        p = X.style, m.font && (p.font = m.font), m["font-family"] && (p.fontFamily = m["font-family"]), m["font-weight"] && (p.fontWeight = m["font-weight"]), m["font-style"] && (p.fontStyle = m["font-style"]), Z = d(m["font-size"] || Z && Z[0]) || 10, p.fontSize = Z * Y + "px", t.textpath.string && (X.innerHTML = c(t.textpath.string).replace(/</g, "&#60;").replace(/&/g, "&#38;").replace(/\n/g, "<br>"));
        var $ = X.getBoundingClientRect();
        t.W = m.w = ($.right - $.left) / Y, t.H = m.h = ($.bottom - $.top) / Y, t.X = m.x, t.Y = m.y + t.H / 2, ("x" in i || "y" in i) && (t.path.v = a.format("m{0},{1}l{2},{1}", f(m.x * u), f(m.y * u), f(m.x * u) + 1));
        var _ = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"];
        for (var ba = 0, bb = _.length; ba < bb; ba++) {
          if (_[ba] in i) {
            t._.dirty = 1;
            break;
          }
        }
        switch(m["text-anchor"]) {
          case"start":
            t.textpath.style["v-text-align"] = "left", t.bbx = t.W / 2;
            break;
          case"end":
            t.textpath.style["v-text-align"] = "right", t.bbx = -t.W / 2;
            break;
          default:
            t.textpath.style["v-text-align"] = "center", t.bbx = 0;
        }
        t.textpath.style["v-text-kern"] = !0;
      }
    }, C = function(b, f, g) {
      b.attrs = b.attrs || {};
      var h = b.attrs, i = Math.pow, j, k, l = "linear", m = ".5 .5";
      b.attrs.gradient = f, f = c(f).replace(a._radial_gradient, function(a, b, c) {
        l = "radial", b && c && ( b = d(b), c = d(c), i(b - 0.5, 2) + i(c - 0.5, 2) > 0.25 && ( c = e.sqrt(0.25 - i(b - 0.5, 2)) * ((c > 0.5) * 2 - 1) + 0.5), m = b + n + c);
        return o;
      }), f = f.split(/\s*\-\s*/);
      if (l == "linear") {
        var p = f.shift();
        p = -d(p);
        if (isNaN(p)) {
          return null;
        }
      }
      var q = a._parseDots(f);
      if (!q) {
        return null;
      }
      b = b.shape || b.node;
      if (q.length) {
        b.removeChild(g), g.on = !0, g.method = "none", g.color = q[0].color, g.color2 = q[q.length - 1].color;
        var r = [];
        for (var s = 0, t = q.length; s < t; s++) {
          q[s].offset && r.push(q[s].offset + n + q[s].color);
        }
        g.colors = r.length ? r.join() : "0% " + g.color, l == "radial" ? (g.type = "gradientTitle", g.focus = "100%", g.focussize = "0 0", g.focusposition = m, g.angle = 0) : (g.type = "gradient", g.angle = (270 - p) % 360), b.appendChild(g);
      }
      return 1;
    }, D = function(b, c) {
      this[0] = this.node = b, b.raphael = !0, this.id = a._oid++, b.raphaelid = this.id, this.X = 0, this.Y = 0, this.attrs = {}, this.paper = c, this.matrix = a.matrix(), this._ = {
        transform : [],
        sx : 1,
        sy : 1,
        dx : 0,
        dy : 0,
        deg : 0,
        dirty : 1,
        dirtyT : 1
      }, !c.bottom && (c.bottom = this), this.prev = c.top, c.top && (c.top.next = this), c.top = this, this.next = null;
    }, E = a.el;
    D.prototype = E, E.constructor = D, E.transform = function(b) {
      if (b == null) {
        return this._.transform;
      }
      var d = this.paper._viewBoxShift, e = d ? "s" + [d.scale, d.scale] + "-1-1t" + [d.dx, d.dy] : o, f;
      d && ( f = b = c(b).replace(/\.{3}|\u2026/g, this._.transform || o)), a._extractTransform(this, e + b);
      var g = this.matrix.clone(), h = this.skew, i = this.node, j, k = ~c(this.attrs.fill).indexOf("-"), l = !c(this.attrs.fill).indexOf("url(");
      g.translate(-0.5, -0.5);
      if (l || k || this.type == "image") {
        h.matrix = "1 0 0 1", h.offset = "0 0", j = g.split();
        if (k && j.noRotation || !j.isSimple) {
          i.style.filter = g.toFilter();
          var m = this.getBBox(), p = this.getBBox(1), q = m.x - p.x, r = m.y - p.y;
          i.coordorigin = q * -u + n + r * -u, z(this, 1, 1, q, r, 0);
        } else {
          i.style.filter = o, z(this, j.scalex, j.scaley, j.dx, j.dy, j.rotate);
        }
      } else {
        i.style.filter = o, h.matrix = c(g), h.offset = g.offset();
      }
      f && (this._.transform = f);
      return this;
    }, E.rotate = function(a, b, e) {
      if (this.removed) {
        return this;
      }
      if (a != null) {
        a = c(a).split(k), a.length - 1 && ( b = d(a[1]), e = d(a[2])), a = d(a[0]), e == null && ( b = e);
        if (b == null || e == null) {
          var f = this.getBBox(1);
          b = f.x + f.width / 2, e = f.y + f.height / 2;
        }
        this._.dirtyT = 1, this.transform(this._.transform.concat([["r", a, b, e]]));
        return this;
      }
    }, E.translate = function(a, b) {
      if (this.removed) {
        return this;
      }
      a = c(a).split(k), a.length - 1 && ( b = d(a[1])), a = d(a[0]) || 0, b = +b || 0, this._.bbox && (this._.bbox.x += a, this._.bbox.y += b), this.transform(this._.transform.concat([["t", a, b]]));
      return this;
    }, E.scale = function(a, b, e, f) {
      if (this.removed) {
        return this;
      }
      a = c(a).split(k), a.length - 1 && ( b = d(a[1]), e = d(a[2]), f = d(a[3]), isNaN(e) && ( e = null), isNaN(f) && ( f = null)), a = d(a[0]), b == null && ( b = a), f == null && ( e = f);
      if (e == null || f == null) {
        var g = this.getBBox(1);
      }
      e = e == null ? g.x + g.width / 2 : e, f = f == null ? g.y + g.height / 2 : f, this.transform(this._.transform.concat([["s", a, b, e, f]])), this._.dirtyT = 1;
      return this;
    }, E.hide = function() {
      !this.removed && (this.node.style.display = "none");
      return this;
    }, E.show = function() {
      !this.removed && (this.node.style.display = o);
      return this;
    }, E._getBBox = function() {
      if (this.removed) {
        return {};
      }
      return {
        x : this.X + (this.bbx || 0) - this.W / 2,
        y : this.Y - this.H,
        width : this.W,
        height : this.H
      };
    }, E.remove = function() {
      if (!this.removed && !!this.node.parentNode) {
        this.paper.__set__ && this.paper.__set__.exclude(this), a.eve.unbind("raphael.*.*." + this.id), a._tear(this, this.paper), this.node.parentNode.removeChild(this.node), this.shape && this.shape.parentNode.removeChild(this.shape);
        for (var b in this) {
          this[b] = typeof this[b] == "function" ? a._removedFactory(b) : null;
        }
        this.removed = !0;
      }
    }, E.attr = function(c, d) {
      if (this.removed) {
        return this;
      }
      if (c == null) {
        var e = {};
        for (var f in this.attrs) {
          this.attrs[b](f) && (e[f] = this.attrs[f]);
        }
        e.gradient && e.fill == "none" && (e.fill = e.gradient) &&
        delete e.gradient, e.transform = this._.transform;
        return e;
      }
      if (d == null && a.is(c, "string")) {
        if (c == j && this.attrs.fill == "none" && this.attrs.gradient) {
          return this.attrs.gradient;
        }
        var g = c.split(k), h = {};
        for (var i = 0, m = g.length; i < m; i++) {
          c = g[i], c in this.attrs ? h[c] = this.attrs[c] : a.is(this.paper.customAttributes[c], "function") ? h[c] = this.paper.customAttributes[c].def : h[c] = a._availableAttrs[c];
        }
        return m - 1 ? h : h[g[0]];
      }
      if (this.attrs && d == null && a.is(c, "array")) {
        h = {};
        for ( i = 0, m = c.length; i < m; i++) {
          h[c[i]] = this.attr(c[i]);
        }
        return h;
      }
      var n;
      d != null && ( n = {}, n[c] = d), d == null && a.is(c, "object") && ( n = c);
      for (var o in n) {
        l("raphael.attr." + o + "." + this.id, this, n[o]);
      }
      if (n) {
        for (o in this.paper.customAttributes) {
          if (this.paper.customAttributes[b](o) && n[b](o) && a.is(this.paper.customAttributes[o], "function")) {
            var p = this.paper.customAttributes[o].apply(this, [].concat(n[o]));
            this.attrs[o] = n[o];
            for (var q in p) {
              p[b](q) && (n[q] = p[q]);
            }
          }
        }
        n.text && this.type == "text" && (this.textpath.string = n.text), B(this, n);
      }
      return this;
    }, E.toFront = function() {
      !this.removed && this.node.parentNode.appendChild(this.node), this.paper && this.paper.top != this && a._tofront(this, this.paper);
      return this;
    }, E.toBack = function() {
      if (this.removed) {
        return this;
      }
      this.node.parentNode.firstChild != this.node && (this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild), a._toback(this, this.paper));
      return this;
    }, E.insertAfter = function(b) {
      if (this.removed) {
        return this;
      }
      b.constructor == a.st.constructor && ( b = b[b.length - 1]), b.node.nextSibling ? b.node.parentNode.insertBefore(this.node, b.node.nextSibling) : b.node.parentNode.appendChild(this.node), a._insertafter(this, b, this.paper);
      return this;
    }, E.insertBefore = function(b) {
      if (this.removed) {
        return this;
      }
      b.constructor == a.st.constructor && ( b = b[0]), b.node.parentNode.insertBefore(this.node, b.node), a._insertbefore(this, b, this.paper);
      return this;
    }, E.blur = function(b) {
      var c = this.node.runtimeStyle, d = c.filter;
      d = d.replace(r, o), +b !== 0 ? (this.attrs.blur = b, c.filter = d + n + m + ".Blur(pixelradius=" + (+b || 1.5) + ")", c.margin = a.format("-{0}px 0 0 -{0}px", f(+b || 1.5))) : (c.filter = d, c.margin = 0,
      delete this.attrs.blur);
    }, a._engine.path = function(a, b) {
      var c = F("shape");
      c.style.cssText = t, c.coordsize = u + n + u, c.coordorigin = b.coordorigin;
      var d = new D(c, b), e = {
        fill : "none",
        stroke : "#000"
      };
      a && (e.path = a), d.type = "path", d.path = [], d.Path = o, B(d, e), b.canvas.appendChild(c);
      var f = F("skew");
      f.on = !0, c.appendChild(f), d.skew = f, d.transform(o);
      return d;
    }, a._engine.rect = function(b, c, d, e, f, g) {
      var h = a._rectPath(c, d, e, f, g), i = b.path(h), j = i.attrs;
      i.X = j.x = c, i.Y = j.y = d, i.W = j.width = e, i.H = j.height = f, j.r = g, j.path = h, i.type = "rect";
      return i;
    }, a._engine.ellipse = function(a, b, c, d, e) {
      var f = a.path(), g = f.attrs;
      f.X = b - d, f.Y = c - e, f.W = d * 2, f.H = e * 2, f.type = "ellipse", B(f, {
        cx : b,
        cy : c,
        rx : d,
        ry : e
      });
      return f;
    }, a._engine.circle = function(a, b, c, d) {
      var e = a.path(), f = e.attrs;
      e.X = b - d, e.Y = c - d, e.W = e.H = d * 2, e.type = "circle", B(e, {
        cx : b,
        cy : c,
        r : d
      });
      return e;
    }, a._engine.image = function(b, c, d, e, f, g) {
      var h = a._rectPath(d, e, f, g), i = b.path(h).attr({
        stroke : "none"
      }), k = i.attrs, l = i.node, m = l.getElementsByTagName(j)[0];
      k.src = c, i.X = k.x = d, i.Y = k.y = e, i.W = k.width = f, i.H = k.height = g, k.path = h, i.type = "image", m.parentNode == l && l.removeChild(m), m.rotate = !0, m.src = c, m.type = "tile", i._.fillpos = [d, e], i._.fillsize = [f, g], l.appendChild(m), z(i, 1, 1, 0, 0, 0);
      return i;
    }, a._engine.text = function(b, d, e, g) {
      var h = F("shape"), i = F("path"), j = F("textpath");
      d = d || 0, e = e || 0, g = g || "", i.v = a.format("m{0},{1}l{2},{1}", f(d * u), f(e * u), f(d * u) + 1), i.textpathok = !0, j.string = c(g), j.on = !0, h.style.cssText = t, h.coordsize = u + n + u, h.coordorigin = "0 0";
      var k = new D(h, b), l = {
        fill : "#000",
        stroke : "none",
        font : a._availableAttrs.font,
        text : g
      };
      k.shape = h, k.path = i, k.textpath = j, k.type = "text", k.attrs.text = c(g), k.attrs.x = d, k.attrs.y = e, k.attrs.w = 1, k.attrs.h = 1, B(k, l), h.appendChild(j), h.appendChild(i), b.canvas.appendChild(h);
      var m = F("skew");
      m.on = !0, h.appendChild(m), k.skew = m, k.transform(o);
      return k;
    }, a._engine.setSize = function(b, c) {
      var d = this.canvas.style;
      this.width = b, this.height = c, b == +b && (b += "px"), c == +c && (c += "px"), d.width = b, d.height = c, d.clip = "rect(0 " + b + " " + c + " 0)", this._viewBox && a._engine.setViewBox.apply(this, this._viewBox);
      return this;
    }, a._engine.setViewBox = function(b, c, d, e, f) {
      a.eve("raphael.setViewBox", this, this._viewBox, [b, c, d, e, f]);
      var h = this.width, i = this.height, j = 1 / g(d / h, e / i), k, l;
      f && ( k = i / e, l = h / d, d * k < h && (b -= (h - d * k) / 2 / k), e * l < i && (c -= (i - e * l) / 2 / l)), this._viewBox = [b, c, d, e, !!f], this._viewBoxShift = {
        dx : -b,
        dy : -c,
        scale : j
      }, this.forEach(function(a) {
        a.transform("...");
      });
      return this;
    };
    var F;
    a._engine.initWin = function(a) {
      var b = a.document;
      b.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
      try {
        !b.namespaces.rvml && b.namespaces.add("rvml", "urn:schemas-microsoft-com:vml"), F = function(a) {
          return b.createElement("<rvml:" + a + ' class="rvml">');
        };
      } catch(c) {
        F = function(a) {
          return b.createElement("<" + a + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
        };
      }
    }, a._engine.initWin(a._g.win), a._engine.create = function() {
      var b = a._getContainer.apply(0, arguments), c = b.container, d = b.height, e, f = b.width, g = b.x, h = b.y;
      if (!c) {
        throw new Error("VML container not found.");
      }
      var i = new a._Paper, j = i.canvas = a._g.doc.createElement("div"), k = j.style;
      g = g || 0, h = h || 0, f = f || 512, d = d || 342, i.width = f, i.height = d, f == +f && (f += "px"), d == +d && (d += "px"), i.coordsize = u * 1000 + n + u * 1000, i.coordorigin = "0 0", i.span = a._g.doc.createElement("span"), i.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;", j.appendChild(i.span), k.cssText = a.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden", f, d), c == 1 ? (a._g.doc.body.appendChild(j), k.left = g + "px", k.top = h + "px", k.position = "absolute") : c.firstChild ? c.insertBefore(j, c.firstChild) : c.appendChild(j), i.renderfix = function() {
      };
      return i;
    }, a.prototype.clear = function() {
      a.eve("raphael.clear", this), this.canvas.innerHTML = o, this.span = a._g.doc.createElement("span"), this.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;", this.canvas.appendChild(this.span), this.bottom = this.top = null;
    }, a.prototype.remove = function() {
      a.eve("raphael.remove", this), this.canvas.parentNode.removeChild(this.canvas);
      for (var b in this) {
        this[b] = typeof this[b] == "function" ? a._removedFactory(b) : null;
      }
      return !0;
    };
    var G = a.st;
    for (var H in E) {
      E[b](H) && !G[b](H) && (G[H] = function(a) {
        return function() {
          var b = arguments;
          return this.forEach(function(c) {
            c[a].apply(c, b);
          });
        };
      }(H));
    }
  }(window.Raphael);
  $.Model("SCPTModel", {}, {
    points : 0,
    currentScore : 0,
    innerState : null,
    attempts : 0,
    id : "",
    questionType : "",
    selectedObject : -1,
    isChrome : /chrome/.test(navigator.userAgent.toLowerCase()),
    isIe : /microsoft/.test(navigator.userAgent.toLowerCase()),
    isIpad : navigator.userAgent.match(/iPad/i),
    isAndroid : navigator.userAgent.match(/Android/i),
    backgroundColor : "eeeeee",
    width : 500,
    height : 500,
    randArrs : {},
    currentIndex : -1,
    init : function(jsonObj, params, type) {
      this.containerId = params.containerId;
      this.maxScore = params.maxScore || jsonObj.value || 0;
      this.id = params.id || new Date().getTime();
      this.questionType = type;
      this.backgroundColor = params.backgroundColor || jsonObj.color || jsonObj.backgroundcolor || jsonObj.bgcolor || this.backgroundColor;
      this.width = params.width || this.width;
      this.height = params.height || this.height;
      this.correctSound = jsonObj.correctsound instanceof Array ? jsonObj.correctsound[0] : jsonObj.correctsound;
      this.incorrectSound = jsonObj.wrongsound instanceof Array ? jsonObj.wrongsound[0] : jsonObj.wrongsound;
      this.randArrs = {};
      this.showRestart = true;
      this.isBigText = jsonObj.largetext || false;

      if(Array.isArray(jsonObj.restarttext)) {
        jsonObj.restarttext = jsonObj.restarttext[0];
      }

      if(Array.isArray(jsonObj.resettext)) {
        jsonObj.resettext = jsonObj.resettext[0];
      }
      this.scoreText = jsonObj.scoretext || jsonObj.scoreText || "Score";
      this.restartText = jsonObj.restarttext || jsonObj.resettext || "Restart";
      this.finishText = jsonObj.finishtext || jsonObj.finishText || "Finish";
      if (params.showRestart + "" == "false") {
        this.showRestart = false;
      }
    },
    setState : function(jsonObj) {
      this.randArrs = jsonObj.randArrs;
      this.maxScore = jsonObj.maxScore;
      this.currentScore = jsonObj.curScore;
      this.attempts = jsonObj.attempts;
      this.id = jsonObj.id;
    },
    getState : function() {
      return {
        maxScore : this.maxScore,
        curScore : this.currentScore,
        attempts : this.attempts,
        id : this.id,
        randArrs : this.randArrs
      };
    },
    reinit : function() {
      this.currentScore = 0;
    },
    getIdByIndex : function(index) {
      return this.questionType + "_" + this.containerId + "_" + index;
    },
    shuffle : function(arr) {
      for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i, 10), x = arr[--i], arr[i] = arr[j], arr[j] = x) {
      }
      return arr;
    },
    returnRandomOrder : function(number) {
      if (!this.randArrs[number]) {
        var arr = [];
        for (var i = number; i; arr.push(--i)) {
        }
        this.randArrs[number] = this.shuffle(arr);
      }
      return this.randArrs[number];
    },
    decode : function(str) {
      if (str + "" == "[object Object]") {
        str = "";
      }
      var s = decodeURIComponent((str+"").replace(/\+/gi, ' ' ))
      s = s.replace(/\+/gi, ' ' );
      s = s.replace('&gt;', '>' );
      s = s.replace('&lt;', '<' );
      return s;
    }
  });
  $.Controller("SCPTController", {}, {
    playIsCorrect : function(isRight) {
      var sound = this.options.model.incorrectSound;
      if (isRight) {
        sound = this.options.model.correctSound;
      }
      $("#jp_" + this.options.model.containerId).jPlayer("setMedia", {
        mp3 : sound,
        oga : sound.substring(0, sound.lastIndexOf(".")) + ".ogg"
      }).jPlayer("play");
    },
    completed : function() {
      $("#" + this.options.model.containerId).trigger("sc." + this.options.model.questionType + ".complete", this.options.model.getState());
    },
    reset : function(onlyTrigger) {
      if (!onlyTrigger) {
        this.options.model.reinit();
        this.init();
        this.updateStatus();
        $("#inputf_" + this.options.model.containerId).focus();
      }
      var state = this.options.model.getState();
      delete state.curScore;
      $("#" + this.options.model.containerId).trigger("sc." + this.options.model.questionType + ".reset", state);
    },
    getState : function() {
      return this.options.model.getState();
    },
    setState : function(jsonObj) {
      this.options.model.setState(jsonObj);
      this.init();
    },
    showAnswer : function() {
    },
    fireDrag : function(id) {
      try {
        this.options.model.fromKeyBoard = true;
        $("#" + id).simulate("drag", {
          dx : 0,
          dy : 0
        });
        this.options.model.fromKeyBoard = false;
      } catch(e) {
      }
    },
    switchToNext : function() {
      var ind = this.options.model.currentIndex;
      var rarr = this.options.model.returnRandomOrder(this.options.model.pointsArr.length);
      $("#" + this.options.model.getIdByIndex(rarr[ind])).removeClass("sc-selected");
      this.options.model.currentIndex = (ind + 1) % this.options.model.pointsArr.length;
      this.options.model.selectedObject = rarr[this.options.model.currentIndex];
      var obj = $("#" + this.options.model.getIdByIndex(this.options.model.selectedObject));
      if (this.options.model.startCoords) {
        if (!this.options.model.startCoords[this.options.model.selectedObject]) {
          this.options.model.startCoords[this.options.model.selectedObject] = {
            x : obj.position().left,
            y : obj.position().top
          };
        }
      }
      obj.addClass("sc-selected");
    },
    handleKeys : function(e) {
      var self = e.data.self;
      var _objid = self.options.model.getIdByIndex(self.options.model.selectedObject);
      var draggable = $("#" + _objid);
      var container = $("#" + self.options.model.containerId);
      var distance = 10;
      var position = draggable.position();
      if (self.options.model.pointsArr[self.options.model.selectedObject] > 0 && e.keyCode != 9 && e.keyCode != 32) {
        return false;
      }
      try {
        if (e.altKey) {
          switch(e.keyCode) {
            case 85:
              e.data.self.reset(false);
              return false;
              break;
            case 81:
              e.data.self.showAnswer();
              e.data.self.completed();
              break;
            default:
              return true;
          }
        } else {
          switch(e.keyCode) {
            case 32:
              if (e.ctrlKey) {
              } else {
                self.switchToNext();
              }
              break;
            case 13:
              self.fireDrag(_objid);
              break;
            case 37:
              position.left -= distance;
              break;
            case 38:
              position.top -= distance;
              break;
            case 39:
              position.left += distance;
              break;
            case 40:
              position.top += distance;
              break;
            default:
              return true;
          }
        }
      } catch(e) {
      }
      if (position) {
        if (self.options.model.isChrome) {
          position.left = position.left + 0.5;
          position.top = position.top + 0.5;
        }
      }
      if (position && draggable.data("dropped") != "true") {
        if (position.left >= 0 && position.top >= 0 && position.left + draggable.width() <= container.width() && position.top + draggable.height() <= container.height()) {
          draggable.css(position);
        }
      }
      e.preventDefault();
    },
    init : function() {
      var self = this;
      var contId = self.options.model.containerId;
      if (this.options.model.correctSound) {
        if (this.options.model.correctSound) {
          new Audio(this.options.model.correctSound).load();
        }
        if (this.options.model.incorrectSound) {
          new Audio(this.options.model.incorrectSound).load();
        }
        $("#jp_" + contId).jPlayer({
          ready : function() {
            $(this).jPlayer("setMedia", {
              preload : "none",
              mp3 : self.options.model.correctSound,
              oga : self.options.model.correctSound.substring(0, self.options.model.correctSound.lastIndexOf(".")) + ".ogg"
            });
          },
          swfPath : "lib/jPlayer",
          wmode : "window",
          supplied : "mp3, oga",
          solution : "html, flash"
        });
      }

      //language
      $("#restart_" + self.options.model.containerId ).html(self.options.model.restartText);
      $("#finish_" + self.options.model.containerId ).html(self.options.model.finishText);

      this.bindEvents(self);
      self.updateStatus();
      if (!self.options.model.isIpad) {
        this.bindKeyEvents();
      }
      if (this.options.model.showRestart == false) {
        $("#restart_" + self.options.model.containerId).hide();
      }
      if (this.options.model.maxScore == 0) {
        $("#statusText_" + self.options.model.containerId).css({
          visibility : "hidden"
        });
      }
      if (navigator.userAgent.match(/iPad/i) != null) {
        $("#hintText_" + self.options.model.containerId).html("");
      }
      $("#" + self.options.model.containerId).addTouch();
    },
    bindKeyEvents : function() {
      var self = this;
      var contId = self.options.model.containerId;
      if (!this.options.model.isAndroid) {
        $("#" + contId).click( function(self) {
          return function() {
            $("#inputf_" + contId).focus();
          };
        }(self));
      }
      $("#inputf_" + contId).focusin( function(self) {
        return function() {
          $("#" + contId).children().first().addClass("sc-selectedQuestion");
        };
      }(self)).focusout( function(self) {
        return function() {
          $("#" + contId).children().first().removeClass("sc-selectedQuestion");
        };
      }(self)).bind("keyup", {
        self : self
      }, self.handleKeys).bind("keypress", {
        self : self
      }, function(evt) {
        self.options.model.keyPressed = evt.keyCode;
      }).bind("keydown", function(evt) {
        if (evt.keyCode == 32 || (evt.keyCode >= 37 && evt.keyCode <= 40)) {
          evt.preventDefault();
        }
      });
    },
    disableActivity : function() {
      $("#inputf_" + this.options.model.containerId).blur();
      $("#" + this.options.model.containerId).find("*").unbind();
    },
    bindEvents : function(self) {
    },
    updateStatus : function(self) {
    }
  });
  (function(j$) {
    j$.fn.plugin = function(action, params) {
      if (action == "initialize") {
        var obj = initialize(params);
        this.data("SoftChalk", obj);
      } else {
        if (action == "getState") {
          return this.data("SoftChalk").getState();
        } else {
          if (action == "setState") {
            this.data("SoftChalk").setState(params);
          } else {
            if (action == "disable") {
              this.data("SoftChalk").disableActivity();
            } else {
              if (action == "showAnswer") {
                this.data("SoftChalk").showAnswer();
              } else {
                if (action == "reset") {
                  this.data("SoftChalk").resetQuestion();
                }
              }
            }
          }
        }
      }
      return this;
    };
    function showTask(xml, params) {
      var obj = null, type = params.type, containerId = params.containerId;
      if (params.backgroundColor) {
        if (params.backgroundColor[0] == "#") {
          params.backgroundColor = params.backgroundColor.substr(1);
        }
      }
      if (type == "labeling") {
        obj = new Labelings($("#" + containerId), {
          model : new Labeling(xml2json.parser(xml).draglabel, params),
          template : "LABELING_EJS_SCRIPT"
        });
      } else {
        if (type == "dragndrop") {
          obj = new DragNDrops($("#" + containerId), {
            model : new DragNDrop(xml2json.parser(xml).match, params),
            template : "DRAG_N_DROP_EJS_SCRIPT"
          });
        } else {
          if (type == "ordering") {
            obj = new Orderings($("#" + containerId), {
              model : new Ordering(xml2json.parser(xml).order, params),
              template : "ORDERING_EJS_SCRIPT"
            });
          } else {
            if (type == "sorting") {
              obj = new Sortings($("#" + containerId), {
                model : new Sorting(xml2json.parser(xml).cardset, params),
                template : "SORTING_EJS_SCRIPT"
              });
            } else {
              if (type == "hotspot") {
                obj = new Hotspots($("#" + containerId), {
                  model : new Hotspot(xml2json.parser(xml).identify, params),
                  template : "HOTSPOT_EJS_SCRIPT"
                });
              } else {
                if (type == "jigsawpuzzle") {
                  obj = new Puzzles($("#" + containerId), {
                    model : new Puzzle(xml2json.parser(xml).jigsawpuzzleactivity, params),
                    template : "PUZZLE_EJS_SCRIPT"
                  });
                } else {
                  if (type == "photoalbum") {
                    obj = new PhotoAlbum($("#" + containerId), {
                      model : new iAlbum(xml2json.parser(xml).photoalbum, params),
                      template : '<svg class="sc-pa-notepad" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><style>.animated {fill:none;stroke-width:0.7;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:3;stroke:#C6C6C6;stroke-opacity:1;}</style><defs><radialGradient id=":radial-dradient-01" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.00845337, 0, 0, 0.00845337, 3.6, 68.45)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#787880;stop-opacity:1"/><stop offset="1" style="stop-color:#787880;stop-opacity:1"/></radialGradient><circle id=":notepad-hole" style="fill:url(#:radial-dradient-01);stroke-width:0.7;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:3;stroke:#C6C6C6;stroke-opacity:1" cx="0" cy="0" r="5"/><path id=":notepad-clip" transform="matrix(1.5 0 0 1.2 150 30)" style="fill:#636369;fill-opacity:1" d="M17.9 6.9L11.5 7.55Q6.7 7.55 3.35 6.45Q-0.05 5.3 0 3.75Q-0.05 2.2 3.35 1.1Q6.7 0 11.5 0Q16.3 0 19.65 1.1Q23 2.2 23.05 3.75Q23 4.65 21.95 5.4L21.95 4.9L19.05 4.9Q19.85 4.35 19.85 3.7Q19.85 2.6 17.45 1.8Q15.1 1.05 11.7 1.05Q8.3 1.05 5.9 1.8Q3.5 2.6 3.5 3.7Q3.5 4.8 5.9 5.6L11.7 6.4Q15.1 6.35 17.45 5.6L17.9 5.45L17.9 6.9"/><!-- gradients for frames --><radialGradient id=":notepad-01-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.713348, 0, 0, 0.713440, 419.50, 410.95)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#FFFFFF;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-02-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.726456, 0, 0, 0.726456, 424.30, 421.25)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#FFFFFF;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-03-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.595871, 0, 0, 0.595856, 308.55, 030.55)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#FFFFFF;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-04-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.696198, 0, 0, 0.696106, 013.70, 043.25)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#E7E7E7;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-05-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.676743, 0, 0, 0.676682, 013.70, 043.20)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#B3B3B3;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-06-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.611176, 0, 0, 0.611237, 013.65, 043.20)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#9E9E9E;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-07-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.730927, 0, 0, 0.730865, 115.80, -73.70)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#C0C0C0;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-07-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.729645, 0, 0, 0.729584, 116.60, 519.05)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#F1F1F1;stop-opacity:1"/><stop offset="1" style="stop-color:#E1E1E1;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-07-2" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.481094, 0, 0, 0.481064, 013.65, 043.25)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#EFEFEF;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-08-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.728363, 0, 0, 0.728607, 001.55, 521.00)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#FFFFFF;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-09-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.634674, 0, 0, 0.634674, 054.10, 436.30)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#FFFFFF;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-10-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.607635, 0, 0, 0.607635, -20.20, 435.00)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#FCFCFC;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-11-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.585632, 0, 0, 0.585449, -109.8, 425.40)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#F3F3F3;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-12-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.527481, 0, 0, 0.527542, -127.95, 374.95)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#F3F3F3;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-13-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.33754, 0, 0, 0.33754, -44.2, 197.55)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#E7E7E7;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-14-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.334198, 0, 0, 0.334244, -54, 205)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#E7E7E7;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-15-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.307373, 0, 0, 0.307373, -46.35, 209.45)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#E3E3E3;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-16-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.287613, 0, 0, 0.287521, -69.45, 209.05)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#E3E3E3;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-16-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.448532, 0, 0, 0.448395, -1.05, 383.6)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#FFFFFF;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-17-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.533173, 0, 0, 0.533218, -11.9, 413.4)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#ECECEC;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-17-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.441757, 0, 0, 0.441803, 32.85, 378.05)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#FFFFFF;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-18-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.516998, 0, 0, 0.516998, -14.3, 412.65)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#EDEDED;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-18-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.452026, 0, 0, 0.452026, 79.5, 380.2)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#FFFFFF;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-19-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.505356, 0, 0, 0.505356, -15.3, 411.9)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#F3F3F3;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-19-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.258102, 0, 0, 0.258102, 20.1, 201.4)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#F9F9F9;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-20-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.500702, 0, 0, 0.50058, -14.9, 410.9)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#E7E7E7;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-20-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.498306, 0, 0, 0.498184, -13.65, 2.15)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#DFDFDF;stop-opacity:1"/><stop offset="1" style="stop-color:#878787;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-20-2" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.318588, 0, 0, 0.318512, 29.65, 244.9)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#BCBCBC;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-21-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.495926, 0, 0, 0.495926, -10.4, 407.8)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#C4C4C4;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-21-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.497421, 0, 0, 0.497421, -11.2, 2.65)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#B4B4B4;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-21-2" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.51535, 0, 0, 0.51535, 196.15, 384.9)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#FDFDFD;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-22-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.49321, 0, 0, 0.493118, -6.65, 5.75)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#CFCFCF;stop-opacity:1"/><stop offset="1" style="stop-color:#A4A4A4;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-22-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.497284, 0, 0, 0.497192, -7.8, 2.4)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#C5C5C5;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-22-2" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.541748, 0, 0, 0.541656, 240.3, 385.25)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#F5F5F5;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-22-3" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.451309, 0, 0, 0.451233, 239.3, 18.3)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FEFEFE;stop-opacity:1"/><stop offset="1" style="stop-color:#AAAAAA;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-23-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.492386, 0, 0, 0.492386, -2.85, 5.95)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#A0A0A0;stop-opacity:1"/><stop offset="1" style="stop-color:#878787;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-23-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.496384, 0, 0, 0.496384, -3.35, 2.65)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#C5C5C5;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-23-2" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.566757, 0, 0, 0.566757, 275.75, 383.45)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#E6E6E6;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-24-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.491928, 0, 0, 0.492126, 0.15, 6)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#7F7F7F;stop-opacity:1"/><stop offset="1" style="stop-color:#676767;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-24-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.495911, 0, 0, 0.496109, 0.15, 2.75)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#C5C5C5;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-24-2" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.581711, 0, 0, 0.58194, 295.75, 382.7)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#DCDCDC;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-25-0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.495865, 0, 0, 0.495865, 1.55, 2.8)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#C5C5C5;stop-opacity:1"/></radialGradient><radialGradient id=":notepad-25-1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.585388, 0, 0, 0.585388, 303.3, 379.05)" spreadMethod="pad" cx="0" cy="0" r="819.2" fx="0" fy="0"><stop offset="0" style="stop-color:#FFFFFF;stop-opacity:1"/><stop offset="1" style="stop-color:#D5D5D5;stop-opacity:1"/></radialGradient></defs><g class="sc-pa-animated 16" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-16-1)" d="M-7.45 17.45L-3.7 17.95Q-0.7 20.2 -0.7 22.2L-0.7 378.45Q1.05 387.45 -7.45 388.2L-7.7 373.95L-7.7 367.95L-7.7 351.7L-7.7 345.7L-7.7 328.95L-7.7 322.95L-7.7 307.95L-7.7 301.95L-7.7 284.95L-7.7 279.2L-7.7 263.2L-7.7 257.45L-7.7 242.2L-7.7 236.45L-7.45 220.2L-7.7 214.45L-7.45 197.45L-7.7 191.7L-7.45 176.45L-7.7 170.7L-7.7 154.7L-7.7 148.95L-7.45 131.7L-7.7 126.2L-7.7 110.95L-7.7 105.2L-7.7 89.2L-7.7 83.45L-7.45 67.2L-7.7 61.7L-7.7 44.7L-7.7 38.95L-7.45 22.7L-7.45 17.45"/></g><g class="sc-pa-animated 17" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-17-1)" d="M-9.2 20.2L27.55 21.45Q32.3 21.65 33.05 25.45L32.8 366.05Q34.55 380.8 30.3 381.85L-9.45 384.35L-9.7 372.3L-9.7 368.55L-9.7 350.05L-9.7 346.55L-9.7 327.3L-9.7 323.8L-9.7 306.55L-9.7 302.8L-9.7 283.8L-9.7 280.05L-9.7 261.8L-9.7 258.05L-9.7 240.8L-9.7 237.25L-9.7 219L-9.7 215.25L-9.7 196.25L-9.7 192.5L-9.7 175.25L-9.7 171.75L-9.7 153.5L-9.7 149.75L-9.7 130.75L-9.7 127L-9.7 109.75L-9.7 106L-9.7 87.95L-9.7 84.2L-9.7 66.2L-9.7 62.45L-9.7 43.7L-9.7 39.95L-9.7 21.95L-9.2 20.2M-2.7 291.3L-1.2 291.3L9.3 290.3L-2.45 280.05L-2.7 291.3"/></g><g class="sc-pa-animated 18" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-18-1)" d="M79.6 345.15L79.25 379.7L77.75 383.2Q76.5 384.7 71.25 384.2L-11 382.2L-11.25 370.95L-11.25 368.7L-11.25 348.95L-11.25 346.7L-11.25 326.2L-11.25 323.95L-11.25 305.2L-11.25 302.95L-11.25 282.7L-11.25 280.2L-11.25 260.7L-11.25 258.45L-11.25 239.95L-11.25 237.7L-11.25 217.95L-11.25 215.7L-11.25 195.45L-11.25 193.2L-11.25 174.45L-11.25 172.2L-11.25 152.7L-11.25 150.45L-11.25 129.95L-11.25 127.7L-11.25 109.2L-11.25 106.95L-11.25 87.45L-11.25 85.2L-11.25 65.7L-11.25 63.45L-11.25 43.2L-11.25 40.7L-11.25 21.7L68.25 20.2Q76.75 19.45 77.75 21.2L79.5 25.45L79.7 48.25L79.6 345.15"/></g><g class="sc-pa-animated 19" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-19-1)" d="M113.1 391.35L112.25 391.75L18.75 379.75L-0.5 379L-11.9 379.25L-12 369L-12 348L-12 346.75L-12 325L-12 324L-12 304.45L-12 303.05L-12 281.45L-12 280.45L-12 259.3L-12 258.95L-12 238.8L-12 237.8L-12 217.05L-12 216.05L-12 194.8L-12 193.55L-12 173.8L-12 172.55L-12 152.05L-12 150.8L-12 128.45L-12 108.7L-12 107.3L-12 86.65L-12 85.65L-12 64.25L-12 42.65L-12 41.4L-11.9 23.5L7.25 23.65L26.1 22.65L102.6 15.5L112.35 14.9L112.6 15L112.85 15.15L113.05 15.15Q116.25 15.85 115.6 28.4L115.6 378.35Q116.25 390.6 113.1 391.35"/></g><g class="sc-pa-animated 20" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-20-2)" d="M136.35 403.2L133.95 403L63.3 382.4L48.3 379.8L29.3 378.6L15.5 378.6L-11.7 380.6L-11.7 369.4L-11.7 368.6L-11.7 347.4L-11.7 346.6L-11.7 324.8L-11.7 324L-11.7 304L-11.7 303.2L-11.7 281.4L-11.7 280.6L-11.7 259.8L-11.7 258.8L-11.7 239L-11.7 238L-11.7 217.2L-11.7 216.4L-11.7 194.8L-11.7 193.8L-11.7 174L-11.7 173.2L-11.7 152.2L-11.7 151.4L-11.7 129.6L-11.7 128.8L-11.7 108.8L-11.7 108L-11.7 87.2L-11.7 86.4L-11.7 65.6L-11.7 64.8L-11.7 43.2L-11.7 42.4L-11.7 22.6L7.1 23.8L30.5 24L56.1 22.4L136.35 6.8L136.6 6.9Q138.35 7.7 138.55 11.8L138.55 398.8Q138.05 402.8 136.75 403.2L136.35 403.2"/></g><g class="sc-pa-animated 21" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-21-2)" d="M-9.5 22.2L11.25 24.7L31 25.95L65.5 26.2L178.75 17.95L193.5 17.45L194.25 17.95L194.5 17.95L196.25 22.2L196.25 383.95L195 387.2L193.75 388.2L187 388.2L70.5 375.95L56.5 375.45L30.75 375.95L18.5 376.95L-9.5 381.2L-9.5 22.2"/></g><g class="sc-pa-animated 22" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-22-2)" d="M238.75 388L237.35 388.8L234.55 389L88.3 377.2L65.9 376.8L38.5 378.4L25.5 380L4.9 384L-5.9 387.2L-5.9 302.2L-6.1 301.6L-5.9 152.6L-6.1 150.4L-6.1 88.6L-5.9 86.8L-6.1 17.8L6.9 20.6L31.7 23.6L61.9 25.2L81.7 25.2L231.9 16.8L237.75 17.2L238.35 17.6L238.55 17.6L239.95 19.4L240.35 22L240.35 384.2Q240.35 386.6 238.75 388"/><path style="fill:url(#:notepad-22-3)" d="M240.35 384.2L240.35 22L239.95 19.4L238.55 17.6L239.95 18.8L240.75 21L240.75 370.6Q241.95 386.6 238.75 388Q240.35 386.6 240.35 384.2"/></g><g class="sc-pa-animated 23" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-23-2)" d="M-2.1 369L-1.9 368.4L-2.1 304L-1.9 301.8L-2.1 195.4L-1.9 195L-1.9 129.8L-2.1 128.2L-2.1 110L-1.9 108.4L-1.9 43.8L-2.1 42.4L-1.9 13.4L6.1 16L15.7 18.2L34.1 21L54.3 22.8L75.1 23.8L97.9 23.8L270.9 17.8L273.1 18.2L274.7 19.6L275.9 23.2L276 31.65L275.5 384.6L273.9 386.6L271.1 387.4L99.3 379L73.1 379L42.7 381.6L22.5 385.2L5.7 390.2L-1.9 393.8L-2.1 369"/></g><g class="sc-pa-animated 24" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-24-2)" d="M295.75 382.75L294.25 384.1L293.15 384.5L102.45 380.5L80.95 380.75L70.2 381.35L48.3 383.75L39.8 385.1L22.3 389.1Q3.7 395.1 1.05 399.1L0.95 390.5L1.2 387.35L0.95 386.35L0.95 369.75L1.2 368L1.2 367.1L0.95 365.6L0.95 348L1.2 344.85L0.95 343.85L1.2 342.35L0.95 325.5L1.2 322.35L0.95 321.35L1.2 305.05L0.95 304.8L1.2 303.2L0.95 282.3L1.05 281.55L1.2 281.2L0.95 272.8L1.2 259.55L0.95 240.2L1.2 236.95L0.95 236.05L0.95 218.55L1.2 215.45L0.95 214.45L1.2 207.95L0.95 196.2L1.2 194.45L0.95 175.55L1.2 172.3L0.95 171.45L1.2 152.7L0.95 110.95L1.2 107.8L0.95 89.4L1.2 86.15L0.95 85.25L0.95 68L1.2 64.75L0.95 63.9L1.2 44.25L0.95 41.5L0.95 24.15L1.2 20.9L0.95 20L1.05 9.65L3.45 11L8.45 13L21.2 16.4L31.8 18.25L49.45 20.5L81.7 22.5L130.2 22.25L292.25 19.75L293.9 20.15L296 21.75L296.9 23.75L296.9 379.6L295.75 382.75"/></g><g class="sc-pa-animated 25" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-25-0)" d="M1.3 404L1.3 391.4L1.1 384.6L1.3 370.6L1.1 364.2L1.3 348.8L1.1 342.4L1.3 326.4L1.1 319.8L1.1 305.8L1.1 299.2L1.1 283.4L1.3 276.8L1.3 261.8L1.1 255.4L1.1 241.4L1.1 234.8L1.3 219.6L1.3 213.2L1.1 197.4L1.3 190.8L1.3 176.6L1.3 170.2L1.1 155.2L1.3 148.8L1.3 132.8L1.3 126.2L1.1 112.2L1.1 105.8L1.3 90.8L1.1 84.2L1.1 69.4L1.3 62.8L1.1 47L1.1 40.6L1.1 25.8L1.3 19L1.1 4.2L0.3 2.8L1.7 2.8L2.3 8.2L2.1 41.4L2.3 42.4L2.3 175.2L2.1 175.8L2.1 235.8L2.3 236.8L2.3 346.8L2.1 348L2.3 369.6L2.1 370L2.3 401.2L2.1 408L1.7 409L0.5 409Q1.3 408.6 1.3 404"/><path style="fill:url(#:notepad-25-1)" d="M2.1 370L2.3 369.6L2.1 348L2.3 346.8L2.3 236.8L2.1 235.8L2.1 175.8L2.3 175.2L2.3 42.4L2.1 41.4L2.3 8.2Q7.7 12 12.9 13.2L26.9 16.6L55.1 20.4L80.9 22L125.1 22.2L298.3 20.8L301.3 21.6L303.5 24.6L303.1 380.4L301.7 382L299.7 383L106.3 381L72.7 382Q16.3 386.8 2.3 401.2L2.1 370"/></g><g class="sc-pa-animated 00" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-01-0)" d="M1.4 45.4L3.9 46.05L4.4 45.9L6.55 44.55L7.05 42.7L6.9 41.05L6.05 39.9L3.9 39.05L1.4 39.7L0.25 41.05L0.25 22.4L2.25 24.2L4.9 24.2Q8.75 22.05 5.75 18.05L4.05 17.55L2.05 17.7L0.25 19.4L0.4 4.55Q2.05 0.55 5.55 0.55L211.5 0.05L409.2 -1.8L416.35 -1.45Q419.2 -0.6 419.85 3.9L419.85 408.4Q420.2 411.2 418.5 413.4L416.7 414.9L415.2 415.4L163.2 412.4L5.4 411.9Q-2.6 411.7 0.25 391.55Q2.75 395.05 6.4 392.4Q8.25 387.7 4.55 386.7L3.55 386.55L2.9 386.7L1.4 387.2L0.25 388.55L0.25 370.7Q2.05 373.2 4.4 372.7L6.75 371.05Q7.9 366.55 4.4 365.9L3.55 365.7L1.4 366.4L0.25 367.7L0.25 348.7Q2.05 351.2 4.4 350.7L6.75 349.05Q7.9 344.55 4.4 343.9L3.55 343.7L1.4 344.4L0.25 345.7L0.25 326.05Q2.25 329.7 6.75 326.4L6.9 323.2L5.25 321.4L4.25 321.2L3.4 321.2L1.25 321.9L0.25 323.05L0.25 305.2Q2.4 308.7 6.55 305.9L7.05 302.7L5.75 300.9L4.4 300.4L1.75 300.7L0.25 302.4L0.25 282.55Q2.4 286.05 6.55 283.2Q7.4 279.4 6.55 279.05L4.4 277.7L1.9 278.05L0.25 279.7L0.25 260.9L2.4 262.7L4.25 262.9L5.55 262.2L6.75 261.2L7.05 259.55L6.55 257.4L5.75 256.55L3.75 255.9L1.25 256.7L0.25 257.9L0.25 240.05Q3.05 243.55 6.4 240.9Q8.4 235.55 3.55 235.2L1.25 235.9L0.25 237.05L0.25 218.55Q5.4 222.55 7.05 217.05L6.9 215.4L6.05 214.2L3.9 213.4L1.4 214.05L0.25 215.4L0.25 195.7Q6.4 200.55 7.05 193.4Q4.05 188.55 0.25 192.9L0.25 174.9Q2.75 178.4 6.55 175.55L7.05 172.4L5.75 170.55L4.4 170.05L1.75 170.4L0.25 172.05L0.25 153.2L2.4 155.05L4.25 155.2L5.55 154.55L6.75 153.55L7.05 151.9L6.4 149.55L5.55 148.7L3.75 148.2L1.25 149.05L0.25 150.2L0.25 130.55Q2.25 134.4 6.75 130.7L7.05 128.05L6.55 127.05L4.75 125.7L2.4 125.7L0.25 127.55L0.25 109.7Q6.4 114.55 7.05 107.4Q4.05 102.55 0.25 106.9L0.25 88.2Q4.05 92.9 7.05 86.9Q5.05 80.4 0.25 85.2L0.25 66.55L1.4 67.9L4.25 68.55L5.55 67.9L6.75 66.9L7.05 65.2L6.9 63.55L5.55 62.05L3.75 61.55L1.25 62.4L0.25 63.55L0.25 44.05L1.4 45.4"/></g><g class="sc-pa-animated 02" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-02-0)" d="M6.5 392Q7.65 386.9 4.15 386.65L3.15 386.65L1.15 387.4L0 388.9L0.15 370.5Q2.5 374.15 6.25 371.5L7 369.9L6.9 368L5 366L4.25 365.75L3.4 365.75L2.65 365.9L1.4 366.4L0 368.15L0.15 348.5Q2.5 352.15 6.25 349.5Q8.15 344.75 4.25 343.75L2.65 343.9L1.4 344.4L0 346.15L0.15 325.9Q2.5 329.4 5.75 327.25Q8.5 323.25 5 321.4L2.65 321.15L1.5 321.65L0 323.5L0.15 305.15Q5.15 309.75 7 303.9L6.4 301.65L5 300.65L3.75 300.25L1.25 301L0 302.65L0.15 282.5L1.65 284.15L2.5 284.5L4.4 284.5L5.9 283.75L6.9 282Q7.15 278.15 4.4 277.75L4 277.65L1.75 278L0 280L0.15 260.75Q5.15 265.4 7 259.5L6.25 257.15L5 256.25L3.75 255.9L1.25 256.65L0 258.25L0.15 239.9Q5.15 245.15 7 237.9Q4.15 232.5 0 237.5L0.15 218.15L1.15 219.5L2.65 220.25L5.15 220L6.25 219.15L6.9 218L7 216.15Q4.65 210.75 0 215.75L0.15 195.65Q5.65 200.65 7 193.65Q3.75 188.4 0 193.15L0.15 174.75L1.75 176.5L2.75 176.9L5 176.65L6.9 174.65L7 172.75Q4.15 167.4 0 172.4L0.15 153Q1.65 156.15 5.5 154.5Q8.65 150.5 5 148.5L2.9 148.25L1.75 148.65L0 150.65L0.15 130.4L1.75 132.15L2.75 132.5L5 132.25L6.9 130.25L7 128.4Q3.75 123.15 0 127.9L0.15 109.65L1.75 111.4L2.75 111.75L5 111.5L6.9 109.5L7 107.65Q3.75 102.4 0 107.15L0.15 88L1.75 89.75L4.15 90.15Q9 87.75 5.75 83.9L4.15 83.25L1.9 83.5L0 85.5L0.15 66.4L1.75 68.15L4.15 68.5L4.4 68.4Q8.9 66.15 5.75 62.25L4.15 61.65L1.9 61.9L0 63.9L0.15 43.75L1.65 45.5L3.9 46L4.9 45.75L6.4 44.65L7 42.65L6.65 40.75L5.75 39.75L3.75 39L1.25 39.75L0 41.4L0.15 22.25L1.75 24L4.25 24.4Q8.9 22 5.75 18.15Q0.9 16.5 0 19.75L0 5.9Q1.15 1 4.75 0.65L90.5 0.25L148.5 -0.5L231.5 -2.25L349.75 -6.1L415.4 -9Q422.5 -10.6 424.5 -4L423.25 423.65L421 425.25L418 425.65L331.75 420.5L219.25 415.5L161.25 413.75L56 412L5.65 411.9L3.25 411.4Q1.9 410.9 0.5 408.75L0 406.65L0.15 391.4Q3.4 395.25 6.5 392"/></g><g class="sc-pa-animated 03" transform="matrix(1.5 0 0 1.2 150 30)"><path d="M422.4 -14.95L422.4 437.1L421.05 440.95Q423.9 439.1 422.75 420.6L422.75 -15.95L421.25 -18.95L420.05 -19.8L421.75 -17.6L422.4 -14.95z"/><path style="fill:url(#:notepad-03-0)" d="M419.05 442.45L415.25 442.6L333.25 431.45L284.75 425.95L222.9 420.25L186.25 417.6L119.9 414.1L45.55 412.1L5.5 411.95Q-3 411.95 0.2 391.6Q3.7 395.1 6.35 392.45Q7.5 389.45 6.7 388.25L4.5 386.75L4 386.6L3 386.6L1.2 387.45L0.2 388.6L0.2 370.75Q3.7 374.25 6.35 371.6Q7.5 368.6 6.7 367.45L4.5 365.95L4 365.75L3 365.75L2.7 365.95L1.2 366.6L0.2 367.75L0.2 348.75Q3.7 352.25 6.35 349.6Q7.5 346.6 6.7 345.45L4.5 343.95L4 343.75L1.2 344.6L0.2 345.95L0.2 326.1Q2.2 329.95 6.7 326.25L7.2 324.45L6.5 322.6L4.35 321.25L3.85 321.1L1.2 321.95L0.2 323.25L0.2 305.25Q2.2 308.95 6.7 305.6Q7.35 300.1 3.5 300.45L1.5 300.95L0.2 302.45L0.2 282.6Q2.35 286.1 6.5 283.25Q8.5 279.45 4.35 277.75L2 277.95L0.2 279.75L0.2 260.95Q6 265.45 7.2 259.25Q4 253.1 0.2 258.1L0.2 240.1L2.7 242.1Q5 242.6 6.7 240.25Q8 235.75 3.5 235.25L1.2 235.95L0.2 237.25L0.2 218.25Q5.7 223.25 7 216.25Q4 211.1 0.2 215.45L0.2 195.75Q5.35 200.75 7 193.75Q3.7 188.45 0.2 192.95L0.2 174.95Q2.35 178.45 6.5 175.6Q8.5 171.75 4.35 170.1L2.2 170.25L0.2 172.1L0.2 153.25Q6 157.75 7.2 151.6Q4 145.45 0.2 150.45L0.2 130.6L2.7 132.6Q5 133.1 6.7 130.75Q6.85 122.6 0.2 127.75L0.2 109.75L1.7 111.45L4.35 111.75L6.2 110.75L6.85 109.95L7 107.75Q3.7 102.45 0.2 106.95L0.2 88.1L1.2 89.45L2.5 90.1L5.2 89.95L6.85 88.25L7.2 86.6Q4 80.45 0.2 85.25L0.2 66.6L2.7 68.6Q5 69.1 6.7 66.75Q6.85 58.6 0.2 63.75L0.2 44.1L1.2 45.25L3 46.1L5.5 45.45Q8.7 42.25 5.5 39.6L3 39.1L2 39.45L0.2 41.1L0.2 22.4Q6.35 26.9 7.2 20.7Q5.35 14.9 0.2 19.55L0 6.2Q0.2 1.9 4.35 0.7L80.9 0.05L134.05 -1.3L218.75 -4.95L284.4 -9.1L334.75 -13.1L414.25 -20.8L417.9 -20.8L420.05 -19.8L421.75 -17.6L422.4 -14.95L422.4 437.1L421.05 440.95L419.05 442.45"/></g><g class="sc-pa-animated 04" transform="matrix(1.5 0 0 1.2 150 30)"><path d="M396.8 -36.55Q399.6 -35.05 399.6 -32.4L400.1 -17.4L400.1 8.1L400.1 15.1L399.8 429.45L399.95 460.25Q399.05 463.9 397.95 465"/><path style="fill:url(#:notepad-04-0)" d="M2.05 45.75L4.25 46.1Q9.25 42.95 6.05 39.95L3.9 39.1L2.4 39.25L0.25 41.25L0.25 22.45Q4.75 26.6 7.05 21.95L7.05 20.45Q3.75 15.1 0.25 19.6L0.05 6.25Q0.25 2.25 4.4 0.75L71.1 -0.05L119.45 -1.9L181.1 -5.9L219.3 -9.4L283.8 -17.25L318.45 -22.55L352.95 -28.75L394.3 -36.9L396.8 -36.55Q399.6 -35.05 399.6 -32.4L400.1 -17.4L399.8 429.45L399.95 460.25Q399.05 463.9 397.95 465Q397.4 465.55 396.8 465.45L394.45 465.6L335.1 449.25L296.8 440.25L245.3 430.45L201.95 423.95L153.3 418.45L106.1 414.75L58.6 412.6L5.4 411.95Q-2.6 411.6 0.25 391.45Q6.05 396.45 7.05 389.45L5.9 387.25L4.4 386.6L2.75 386.75L0.9 387.75L0.25 388.75L0.25 370.6Q6.05 375.6 7.05 368.6L5.9 366.45L2.75 365.95L0.9 366.95L0.25 367.95L0.25 348.6Q6.05 353.45 7.25 346.95Q4.9 340.95 0.25 345.95L0.25 326.1Q3.4 329.6 6.55 326.75Q7.9 321.45 4.4 321.25L3.9 321.1L1.25 321.95L0.25 323.25L0.25 305.25Q2.25 308.95 6.75 305.6Q7.75 300.45 3.9 300.45L3.55 300.25L1.55 300.95L0.25 302.45L0.25 282.6Q6.4 287.1 7.25 280.75Q5.4 275.1 0.25 279.75L0.25 260.75Q6.05 265.6 7.25 259.1Q4.05 253.1 0.25 258.1L0.25 240.1L1.9 241.75L3.05 242.1L5.4 241.75L7.05 239.75L7.25 238.25Q3.4 232.25 0.25 237.25L0.25 218.25Q5.75 223.25 7.05 216.25Q4.05 211.1 0.25 215.45L0.25 195.75Q5.75 200.75 7.05 193.75Q3.75 188.45 0.25 192.95L0.25 174.95L1.55 176.45L4.25 176.95L5.4 176.6L6.75 175.25L7.05 172.95Q3.75 167.6 0.25 172.1L0.25 153.25L2.4 155.1L5.4 154.95L7.05 152.95L7.25 151.45Q3.4 145.45 0.25 150.45L0.25 130.6L2.75 132.6L5.4 132.25L7.05 130.25L7.25 128.75Q5.4 123.1 0.25 127.75L0.25 109.75Q5.75 114.75 7.05 107.75Q3.75 102.45 0.25 106.95L0.25 88.1L2.4 90.1L4.05 90.25L5.55 89.6Q8.75 86.1 5.55 83.75L3.05 83.25L1.9 83.6L0.25 85.25L0.25 66.6L2.75 68.6L5.4 68.25L7.05 66.25L7.25 64.75Q3.4 58.75 0.25 63.75L0.25 43.95L2.05 45.75"/></g><g class="sc-pa-animated 05" transform="matrix(1.5 0 0 1.2 150 30)"><path d="M342.25 -39.95L341.9 469.15L342.25 477.35Q342.25 490.35 339.9 491.5Q344.25 490.15 343.05 480.15L343.05 -49.95Q343.05 -52.3 341.75 -54.1L340.5 -54.7Q341.15 -53.95 341.75 -51.1L342.25 -39.95z"/><path style="fill:url(#:notepad-05-0)" d="M338.05 491.15L306.25 470.5L289.75 461.65L273.25 454.15L254.4 446.85L234.25 440.15L202.55 431.65L168.55 424.65L149.4 421.5L125.75 418.35L101.9 415.85L64.25 413.15L44.9 412.35L5.05 411.65Q-2.6 411.15 0.25 391.35Q5.75 396.35 7.05 389.35L5.9 387.15L4.4 386.5L2.4 386.65L1.25 387.35L0.05 388.85L0.25 370.5Q5.75 375.5 7.05 368.5L5.9 366.35L4.4 365.65L2.75 365.85L0.9 366.85L0.05 368L0.25 348.5Q5.75 353.5 7.05 346.5L6.9 345.5L5.4 344L2.9 343.65L0.9 344.85L0.05 346L0.25 325.85Q3.75 329.65 6.55 326.65Q8.55 322.65 4.55 321.15L4.05 321L1.25 321.85L0.25 323.15L0.25 305.15Q1.4 307.35 4.4 307.15L6.75 305.5Q7.9 302.85 6.4 301.35L4.05 300.35L3.75 300.15L1.55 300.85L0.25 302.35L0.25 282.5Q6.4 287.15 7.25 280.5Q4.75 275.15 0.25 279.65L0.25 260.65L1.25 262L2.55 262.65L5.25 262.5L7.05 260.5L7.25 258.85Q4.25 253.15 0.25 258L0.25 239.85Q2.9 243.85 6.75 240.35Q7.4 234.5 3.75 235L1.55 235.65L0.25 237.15L0.25 218.15Q5.75 223.15 7.05 216.15L6.55 214.65L5.4 213.65L2.9 213.35L0.9 214.5L0.05 215.65L0.25 195.65Q5.75 200.65 7.05 193.65Q3.75 188.35 0.25 192.85L0.25 174.85L1.55 176.35L4.25 176.85L5.75 176.35L6.75 175.35L7.05 172.85Q5.75 167.5 0.25 172L0.25 153L2.4 155L5.4 154.85L6.9 153.35L7.25 151.15Q2.9 145.5 0.25 150.35L0.25 130.35Q5.4 135.5 7.25 128.5Q4.75 123.15 0.25 127.65L0.25 109.65L1.55 111.15L3.55 111.65L6.25 110.85L7.25 108.85L7.05 107.65Q3.75 102.35 0.25 106.85L0.25 88L1.25 89.35L2.55 90L5.25 89.85L7.05 87.85L7.25 86.15Q4.4 80.5 0.05 85.5L0.25 66.4Q5.4 71.5 7.25 64.55Q4.75 59.2 0.25 63.7L0.25 43.9L1.05 45.05L2.75 45.9Q9.05 45.2 6.4 40.2Q1.75 37.7 0.25 41.2L0.25 22.4Q5.75 27.4 7.05 20.4Q3.75 15.05 0.25 19.55L0.05 6.05Q0.4 2.2 4.05 0.9L48.05 0.2L76.4 -0.8L115.9 -3.1L169.4 -8.45L211.55 -14.8L243.75 -21.3L264.25 -26.45L283.25 -32.1L307.4 -40.95L339.25 -55.1L339.75 -54.95L339.9 -54.95L340.5 -54.7Q341.15 -53.95 341.75 -51.1L342.25 -39.95L341.9 469.15L342.25 477.35Q342.25 490.35 339.9 491.5L338.05 491.15"/></g><g class="sc-pa-animated 06" transform="matrix(1.5 0 0 1.2 150 30)"><path d="M243.5 -70.8L243.5 355.1L243.55 353.75L244 -27.45L244 -57.45L243.5 -70.8L242.35 -70.8L242.2 -52.6"/><path style="fill:url(#:notepad-06-0)" d="M242.5 485.6L242.2 487.95Q238.35 470.75 223 458.6L211.2 450.25L204.5 446.45L187.7 438.6L171.7 432.75L146.35 425.75L130.85 422.45L104.85 418.1L90.5 416.25L53.35 413.1L3.85 411.6Q0.85 410.45 0.35 407.75L0.2 391.45Q5.7 396.45 7.2 389.45Q5.35 383.75 0 389.1L0.2 370.6Q5.7 375.6 7.2 368.6Q5.35 362.95 0 368.25L0.2 348.6Q2.35 351.1 3.85 350.75L6.5 349.45Q8.2 344.45 4.35 343.75L2.35 343.95L1.2 344.6L0 346.25L0.2 325.95L1.2 327.25L2.5 327.95L5.2 327.75L6.85 326.1L7.2 323.95L5.35 321.45L3 321.1L1.35 321.95L0 323.6L0.2 305.1Q2.85 309.1 6.7 305.6Q7.85 302.95 6.35 301.45L4 300.45L3.7 300.25L1.5 300.95L0 302.75L0.2 282.45Q3.2 286.45 6.7 282.95Q7.35 277.1 3.5 277.75L1.5 278.25L0 280.1L0.2 260.75L2.5 262.75L5.2 262.6L6.85 260.95L7.2 258.75Q2.7 253.25 0 258.45L0.2 239.95Q2.85 243.95 6.7 240.45Q7.85 237.75 6.35 236.25L3.7 235.1L1.5 235.75L0 237.6L0.2 218.25Q5.7 223.25 7.2 216.25L6 214.25L5 213.6L2.85 213.45L0.85 214.6L0.5 215.75L0 215.95L0.2 195.75Q6.7 200.45 7.2 193.75Q4.35 188.25 0 193.25L0.2 174.95Q5 179.1 7 174.45Q5.85 166.75 0 172.45L0.2 153.1Q1 154.95 3 155.25L5.35 154.95L6.5 153.95L7.2 152.45L7.2 151.25Q3 145.45 0 150.75L0.2 130.45Q6.35 135.25 7.2 128.6Q4 123.1 0 128.1L0.2 109.75L1.5 111.25L3.7 111.75Q9.2 110.45 5.85 105.6Q4.35 104.45 1.85 105.25L0 107.25L0.2 88.1L2.35 90.1L5.35 89.95L6.85 88.45L7.2 86.25L6.35 84.45L5.35 83.6L3.2 83.25L0.85 84.45L0.5 85.6L0 85.75L0.2 66.4Q2.35 69.95 5.7 67.9Q8.85 64.2 5.2 61.9L2 61.9L0 64.05L0.2 43.9L1 45.05L2.7 45.9Q8.35 46.2 6.35 40.2Q5.2 38.55 2 39.4L0 41.55L0.2 22.4Q5.7 27.4 7.2 20.4Q4.35 14.9 0 19.9L0 6.2Q0.35 2.2 4 0.9L47.35 0.05L69.2 -0.95L111 -4.3L133.85 -7.1L152.85 -10.1L172.35 -14.1L191.35 -19.1Q237.5 -33.45 242.2 -52.6L242.5 485.6"/></g><g class="sc-pa-animated 07" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-07-0)" d="M115.7 124.05L115.35 115.1L115.7 94.45L115.35 -6.9L115.5 -72.05Q115.5 -77.4 118.85 -78.25L117.5 -76.9L116.35 -72.05L116.7 57.75L116.35 75.25L116.7 205.05L116.35 242.55L116.7 500.55L116.35 516.7L116.85 522.55L118.35 524.9Q116 524.9 115.5 519.2L115.5 422.9L115.7 124.05"/><path style="fill:url(#:notepad-07-1)" d="M116.85 522.55L116.35 516.7L116.7 500.55L116.35 242.55L116.7 205.05L116.35 75.25L116.7 57.75L116.35 -72.05L117.5 -76.9L118.85 -78.25L121.35 -78.4L158 -62.05L164.5 -58.4Q177.2 -50.75 180.35 -42.55L181 -39.25L181 262.4L180.35 473.55Q178.85 482.55 165.35 495.55L159 500.7L151.35 506.05L121.5 524.7L120.35 525.2L118.5 524.9L118.35 524.9L116.85 522.55"/><path style="fill:url(#:notepad-07-2)" d="M0 20.1L0 6.45Q-0.3 3.1 4 0.95L46 -0.05L68.5 -1.4L95.85 -4.05L115.35 -6.9L115.7 94.45L115.35 115.1L115.7 124.05L115.5 422.9L97.85 419.05L86.7 417.2L68 414.9L34.85 412.4L4.35 411.7Q2.7 411.9 0.35 407.7L0.2 391.4Q5.7 396.4 7.2 389.4Q5.35 383.7 0 389.05L0.2 370.55Q5.7 375.55 7.2 368.55Q5.35 362.9 0 368.2L0.2 348.55Q5.7 353.55 7.2 346.55L5.7 344.2L2.85 343.7L0.85 344.9L0.5 346.05L0 346.2L0.2 325.9L2.5 327.9L5.2 327.7L6.85 326.05L7.2 323.9L5.35 321.4L2.85 321.05L1 322.2L0 323.55L0.2 305.05L2.35 307.05L5.35 306.9L7 304.9L7.2 303.05Q2.7 297.55 0 302.7L0.2 282.4Q3.2 286.4 6.7 282.9Q7.35 277.05 3.5 277.7L1.5 278.2L0 280.05L0.2 260.7L2.5 262.7L5.2 262.55L6.85 260.9L7.2 258.7L5.35 256.2L3 255.9L1.35 256.7L0 258.4L0.2 239.9Q0.7 241.4 3 242.05L5.35 241.7L7 239.7L7.2 237.9Q3 232.4 0 237.55L0.2 218.2Q5.7 223.2 7.2 216.2L5.7 213.9L2.85 213.4L0.85 214.55L0.5 215.7L0 215.9L0.2 195.55Q5.7 200.7 7.2 193.7Q5.35 188.05 0 193.4L0.2 174.7Q5 179.2 7 174.4Q5.85 166.7 0 172.4L0.2 153.05Q0.7 154.55 3 155.2L5.35 154.9L7 152.9L7.2 151.05Q3 145.55 0 150.7L0.2 130.4Q6.35 135.2 7.2 128.55Q4 123.1 0 128.05L0.2 109.75L1.5 111.25L3.7 111.75Q9.5 109.45 5.85 105.6L3.85 104.95L2 105.25L0 107.45L0.2 88.1L2.35 90.1L5.35 89.95L7 87.95L7.2 86.1Q2.7 80.6 0 85.75L0.2 66.45Q5.35 70.95 7 66.1Q5.5 58.45 0 64.1L0.2 43.95L2.2 45.95L5.35 45.75L7 43.75L7.2 41.95Q3.35 36.45 0 41.6L0.2 22.25L1.5 23.95L3.5 24.45L4 24.45Q9.5 21.6 5.7 18.1L2.7 17.6L1.85 17.95L0 20.1"/></g><g class="sc-pa-static"><use x="155" y="055.0" xlink:href="#:notepad-hole"/><use x="-28" y="020" xlink:href="#:notepad-clip"/><use x="155" y="081.7" xlink:href="#:notepad-hole"/><use x="-28" y="046" xlink:href="#:notepad-clip"/><use x="155" y="108.4" xlink:href="#:notepad-hole"/><use x="-28" y="074" xlink:href="#:notepad-clip"/><use x="155" y="134.5" xlink:href="#:notepad-hole"/><use x="-28" y="100" xlink:href="#:notepad-clip"/><use x="155" y="160.5" xlink:href="#:notepad-hole"/><use x="-28" y="125" xlink:href="#:notepad-clip"/><use x="155" y="185.0" xlink:href="#:notepad-hole"/><use x="-28" y="150" xlink:href="#:notepad-clip"/><use x="155" y="212.0" xlink:href="#:notepad-hole"/><use x="-28" y="177" xlink:href="#:notepad-clip"/><use x="155" y="238.0" xlink:href="#:notepad-hole"/><use x="-28" y="203" xlink:href="#:notepad-clip"/><use x="155" y="263.0" xlink:href="#:notepad-hole"/><use x="-28" y="228" xlink:href="#:notepad-clip"/><use x="155" y="290.0" xlink:href="#:notepad-hole"/><use x="-28" y="255" xlink:href="#:notepad-clip"/><use x="155" y="316.0" xlink:href="#:notepad-hole"/><use x="-28" y="280" xlink:href="#:notepad-clip"/><use x="155" y="341.0" xlink:href="#:notepad-hole"/><use x="-28" y="306" xlink:href="#:notepad-clip"/><use x="155" y="367.0" xlink:href="#:notepad-hole"/><use x="-28" y="332" xlink:href="#:notepad-clip"/><use x="155" y="395.0" xlink:href="#:notepad-hole"/><use x="-28" y="360" xlink:href="#:notepad-clip"/><use x="155" y="420.0" xlink:href="#:notepad-hole"/><use x="-28" y="385" xlink:href="#:notepad-clip"/><use x="155" y="447.0" xlink:href="#:notepad-hole"/><use x="-28" y="412" xlink:href="#:notepad-clip"/><use x="155" y="473.5" xlink:href="#:notepad-hole"/><use x="-28" y="438" xlink:href="#:notepad-clip"/><use x="155" y="498.0" xlink:href="#:notepad-hole"/><use x="-28" y="463" xlink:href="#:notepad-clip"/></g><g class="sc-pa-animated 08" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-08-0)" d="M-4.5 514.7L-4.55 507.9L-4.85 -24.75L-4.85 -46.4L-4.85 -51.85L-4.65 -69.3L-4.15 -70.6L-4.5 -70.8L-3.8 -71.6L-4 -72.1L-3.5 -72.95L-3.3 -73.1L-3.15 -73.45L-2.5 -74.1L-0.3 -75.45L4.2 -75.6L71.8 -63.45L94.65 -57.95Q139.15 -45.95 144.3 -30.3L144.3 456.05Q144.45 471.05 105.8 490.7L94.15 495.7L69.15 504.2L3.85 520.9Q0.5 521.55 -1.65 520.05L-4.5 514.7"/></g><g class="sc-pa-animated 09" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-09-0)" d="M-90.5 498.45L-89.8 -60.75Q-89.8 -62.25 -86 -64.4L-81.3 -64.9L-12.15 -60.9L21.7 -57.4Q87.85 -49.55 115.85 -31.4Q121.35 -26.4 120.85 -24.25L119.85 451.45Q117 459.6 100.7 469.6L91.7 474.25L82.5 478.25L71.2 482.45L57.7 486.6L40.2 491.1L9.7 496.95L-24.65 501.1L-82.15 505.6L-90.5 498.45"/></g><g class="sc-pa-animated 10" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-10-0)" d="M22.1 -46.6L54.3 -40.6Q92.3 -32.2 95.9 -19.4L95.3 443.8Q95.9 456.2 45.3 473.6L28.7 478L-1.1 483.6L-36.5 487.6L-68.7 488.8L-94.5 488L-113.7 486.2L-127.7 484L-142.7 480.6Q-145.7 478.6 -146.5 474.6L-146.5 -41.4L-145.3 -44.8Q-144.1 -47 -142.1 -47.6L-117.9 -51L-105.9 -52L-71.9 -53.2L-43.7 -52.6L-7.7 -50.2L22.1 -46.6"/></g><g class="sc-pa-animated 11" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-11-0)" d="M-91 -44.1L-61.25 -43.85L-37.75 -42.6L-0.5 -38.6Q52 -31.85 63.5 -16.35L63.5 436.1Q63.75 447.35 27.75 460.6L16 464.1L-14.25 470.6L-44 474.35L-71.5 475.85Q-152.55 476.85 -163.8 453.6L-163.8 -27.35Q-161.55 -39.85 -109.25 -43.35L-91 -44.1"/></g><g class="sc-pa-animated 12" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-12-0)" d="M34.2 -12.25L34.2 430.3Q34.45 441.5 -3.3 453.55L-15.05 456.55L-39.05 461.05L-62.05 463.8L-88.8 465.05Q-158.55 464.8 -164.3 445.3L-164.3 -22.5Q-160.55 -35.05 -100.8 -36.25L-63.05 -35.5L-43.55 -34L-12.8 -30L15.95 -23.5Q33.7 -17.75 34.2 -12.25"/></g><g class="sc-pa-animated 13" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-13-0)" d="M-94 -30.3L-79.25 -29.8L-46.75 -27.05Q-1.25 -22.55 13 -9.55L13 426.7Q13 433.95 -18 444.95L-45.5 451.45L-60 453.7L-93.25 456.45Q-154.75 458.7 -169.5 440.7L-169.5 -18.55Q-168.25 -26.05 -136 -29.3L-119.75 -30.3L-94 -30.3"/></g><g class="sc-pa-animated 14" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-14-0)" d="M-96 -24.25L-74.5 -23.25L-50.5 -20.75Q-4.75 -14.55 0 -5.75L0 421.3Q-1.75 429.55 -32.5 438.8L-59 444.3L-72 446.05L-100.25 448.05Q-151.5 450.3 -168 434.3L-168 -13.5Q-162.25 -22.8 -128.5 -24L-96 -24.25"/></g><g class="sc-pa-animated 15" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-15-0)" d="M-6.1 16L-6.25 17L-6.1 22.9L-5.6 23.15L-5.6 37.9Q-6.85 42 -5.6 44.9L-5.6 60.65L-6.1 60.75L-6.1 67.4L-5.6 67.65L-5.6 82.4Q-6.5 82.75 -6.25 88.15L-5.6 89.4L-5.6 104.25Q-6.6 110.5 -5.6 111.25L-5.6 125.25L-6 125.25L-6.25 130.75L-6 132L-5.6 132.15L-5.6 148L-6.1 148.5L-6.1 153.75L-6 154.9L-5.6 155L-5.6 170Q-6.85 174.15 -5.6 177L-5.6 191Q-6.6 197.25 -5.6 198L-5.6 213.75Q-6.85 220 -5.6 220.75L-5.6 235.75Q-6.85 236.4 -5.6 242.65L-5.6 256.65Q-6.85 262.9 -5.6 263.65L-5.6 278.65Q-6.85 283.9 -5.6 285.65L-5.6 301.5Q-6.6 302 -6.1 308.25L-5.6 308.5L-5.6 322.4Q-6.85 326.5 -5.6 329.5L-5.6 345.25Q-6.85 351.65 -5.6 352.4L-5.75 367.5L-6.25 372.4L-6 374.65L-5.6 374.65L-5.6 388.5Q-6.85 394.9 -5.6 395.65L-5.6 414.25L-7.6 418.15Q-15 425.75 -37.35 431.75L-49.25 434.5L-63.25 437L-77 438.75L-88.85 439.75L-105 440.5L-121.6 440.4L-134.1 439.5L-145.25 438L-153 436.25L-160.75 433.5Q-166.6 430.65 -167.5 427.15L-167.5 -10.1Q-165.5 -13.85 -154.5 -16.25L-145.25 -17.75L-127.5 -19.1L-111.5 -19.5L-92.75 -19.1L-64.35 -17.1L-48.25 -15.1L-27.35 -11.25L-18.75 -8.85L-12 -6.35L-7.85 -4L-5.6 -1.1L-5.6 16L-6.1 16"/></g><g class="sc-pa-animated 16" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-16-0)" d="M-9.2 16.2Q-11.2 16.7 -10.45 20.95L-8.7 23.2L-7.45 22.7L-7.7 38.95L-8.2 37.95L-9.45 37.95Q-10.95 39.2 -10.45 42.45L-9.7 43.95L-9.7 44.2L-8.7 44.95L-7.7 44.7L-7.7 61.7L-8.7 60.7L-9.7 61.2L-10.45 62.95L-10.2 65.2L-10.2 65.45L-9.95 66.45L-8.7 67.7L-7.45 67.2L-7.7 83.45L-8.95 82.45L-9.95 83.2L-10 84.2L-10.2 88.2L-8.95 89.45L-7.7 89.2L-7.7 105.2L-8.2 104.45L-9.7 104.95L-10.2 106.2L-9.95 109.95L-9.95 110.2L-9.7 110.7L-8.95 111.2L-7.7 110.95L-7.7 126.2L-8.45 125.2L-9.2 125.45L-9.7 125.95L-10.2 127.2L-9.95 130.95L-9.95 131.2L-9.7 131.7L-8.95 132.2L-7.45 131.7L-7.7 148.95L-8.95 148.2L-10.45 149.7L-10.2 152.95L-10.2 153.2L-9.7 154.45L-9.7 154.7L-9.2 154.95L-7.7 154.7L-7.7 170.7L-8.95 170.2L-9.95 170.7L-10.45 172.45L-10.2 174.95L-10.2 175.2L-9.45 176.7L-8.2 177.2L-7.45 176.45L-7.7 191.7L-8.95 191.2L-9.7 191.45L-10.45 193.7L-9.7 197.45L-9.7 197.7L-8.95 198.2L-7.45 197.45L-7.7 214.45L-8.95 213.95L-9.7 214.45L-9.7 214.7L-10.45 216.7L-10.2 218.95L-10.2 219.2L-9.2 220.95L-7.45 220.2L-7.7 236.45L-8.95 235.95L-10.45 238.2L-10.2 240.95L-10.2 241.2L-9.45 242.7L-8.7 242.95L-7.7 242.2L-7.7 257.45L-8.95 256.95L-9.7 257.2L-10.2 259.2L-10.2 262.95L-9.45 263.7L-8.45 263.95L-7.7 263.2L-7.7 279.2L-8.95 278.95L-9.7 279.2L-10.2 281.2L-10.2 284.95L-9.45 285.7L-7.7 284.95L-7.7 301.95L-9.45 302.2L-10.45 304.2L-10.2 306.95L-10.2 307.2L-9.7 308.2L-8.45 308.7L-7.7 307.95L-7.7 322.95L-9.2 322.95L-10.2 324.95L-10.2 325.2L-10.45 328.2L-9.7 329.2L-8.45 329.7L-7.7 328.95L-7.7 345.7L-8.7 345.45L-9.95 346.45L-10.45 348.45L-10.2 350.95L-10.2 351.2L-9.7 352.2L-8.45 352.45L-7.7 351.7L-7.7 367.95L-8.7 367.7L-9.95 368.7L-10.2 370.45L-10.2 374.2L-9.2 374.7L-7.7 373.95L-7.45 388.2L-7.45 388.95L-8.7 388.7L-10.45 390.7Q-11.2 395.7 -9.2 395.95L-7.45 394.45L-7.45 408.7Q-7.45 412.45 -9.45 414.95L-23.2 421.2L-33.95 424.45L-58.7 429.45L-91.45 432.7L-126.45 432.45Q-156.5 431.2 -164.5 419.45L-164.25 -5.55Q-162 -11.05 -129.2 -13.55L-92.7 -13.8L-77.2 -13.05L-46.7 -10.05L-25.7 -6.3L-9.95 -1.55Q-8.2 -1.3 -7.45 3.7L-7.45 17.45L-9.2 16.2"/></g><g class="sc-pa-animated 17" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-17-0)" d="M-11.95 16.2L-13.45 16.7L-14.2 17.2L-14.7 18.7L-14.7 20.2L-14.2 21.45L-14.2 21.7L-12.95 22.95L-12.45 23.2L-10.45 23.2L-9.7 21.95L-9.7 39.95Q-14.7 35.45 -14.7 41.95L-13.45 44.2L-12.95 44.7L-12.45 44.95L-11.2 44.95L-9.7 43.7L-9.7 62.45L-11.7 60.7L-12.7 60.7L-14.45 62.45L-14.7 62.95L-14.7 64.95L-14.45 65.45L-12.95 67.45L-11.2 67.7L-10.2 67.45L-9.7 66.2L-9.7 84.2L-11.7 82.7L-13.7 83.2L-14.2 83.7L-14.7 85.7L-14.7 86.7L-13.95 88.45L-13.45 88.95L-12.45 89.45L-10.45 89.45L-9.7 87.95L-9.7 106L-11.45 104.5L-13.45 105L-13.95 105.5L-14.45 106.25L-14.7 106.75L-14.7 108.75L-14.45 109.25L-14.2 110L-13.7 110.5L-12.7 111.25L-12.2 111.5L-10.45 111.25L-9.7 109.75L-9.7 127Q-10.95 124.45 -13.2 125.5L-14.45 127.25L-14.7 127.75L-14.45 130.25L-13.7 131.5L-11.45 132.5L-9.7 130.75L-9.7 149.75L-11.45 148.25L-13.7 149L-14.2 149.5L-14.45 153.25L-14.2 153.75L-12.7 155.25L-10.95 155.25L-9.7 153.5L-9.7 171.75Q-15.2 168.25 -14.7 174.5L-14.2 175.75Q-12.45 178.5 -9.7 175.25L-9.7 192.5L-11.7 191.25L-13.7 192L-14.7 193.75Q-12.95 201.25 -9.7 196.25L-9.7 215.25L-10.95 214L-12.95 214.25L-13.7 214.75L-14.2 215.25L-14.45 216L-14.7 216.5L-14.7 218.5L-14.45 219Q-12.95 221.25 -11.45 221L-9.7 219L-9.7 237.25L-11.95 235.75L-13.7 236.75L-14.7 238.5Q-13.7 245.75 -9.7 240.8L-9.7 258.05L-11.2 256.8L-12.45 256.8L-13.7 257.8L-14.2 258.3L-14.7 259.8L-14.7 261.55L-14.45 262.05Q-13.7 264.55 -10.95 263.8L-9.7 261.8L-9.7 280.05L-10.7 278.8L-12.7 278.8L-13.7 279.8L-14.7 281.55Q-13.2 288.8 -9.7 283.8L-9.7 302.8L-10.45 301.8L-11.95 301.55L-12.95 302.05L-13.7 302.55L-14.7 304.3L-14.7 306.3L-14.2 307.55L-12.95 308.55L-11.2 308.55L-9.7 306.55L-9.7 323.8L-11.7 322.55L-13.2 323.05L-13.7 323.55L-14.7 325.55L-14.45 328.05L-14.2 328.55L-13.45 329.55L-11.2 329.55L-9.7 327.3L-9.7 346.55L-11.2 345.55L-12.45 345.55L-12.95 345.8L-14.2 347.05L-14.7 350.3L-14.45 351.05L-12.45 352.55Q-10.95 353.3 -9.7 350.05L-9.7 368.55L-10.7 367.55L-11.95 367.55L-12.95 368.05L-14.2 369.3L-14.7 371.05L-14.7 372.55L-14.45 373.3L-13.2 374.55L-11.2 374.55L-9.7 372.3L-9.45 384.35L-9.45 389.85L-10.7 388.6L-11.95 388.6L-12.95 389.1L-14.2 390.35L-14.7 392.1L-14.7 392.85Q-12.45 398.35 -9.45 393.35L-9.45 407.6Q-9.2 410.3 -11.95 413.85L-21.95 417.1L-45.45 421.6L-72.2 424.35L-83.95 424.85L-113.95 424.1Q-148.5 420.6 -148.5 410.85L-148.25 -0.05Q-145 -3.6 -135 -5.3L-111.7 -7.8L-78.7 -8.05L-61.95 -7.3L-35.2 -4.8L-12.2 -0.55Q-8.2 0.65 -9.45 18.45L-11.95 16.2"/></g><g class="sc-pa-animated 18" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-18-0)" d="M-11.25 40.7Q-17 35.7 -18 41.45Q-15 48.45 -11.25 43.2L-11.25 63.45Q-12.5 60.45 -14.75 60.95L-17.5 62.45Q-18.5 65.2 -17.5 66.45L-14.75 67.95L-12 67.45L-11.25 65.7L-11.25 85.2L-13.25 82.95L-16 82.95L-17.25 83.7L-18 85.95Q-16 92.45 -11.25 87.45L-11.25 106.95Q-17.5 101.45 -18 108.7Q-15 113.7 -11.25 109.2L-11.25 127.7Q-16.5 122.2 -18 129.45Q-16 134.95 -11.25 129.95L-11.25 150.45L-13.75 148.2L-16.5 148.7L-17.75 150.45L-18 152.45L-15.5 155.2L-13.25 155.2L-11.75 154.2L-11.25 152.7L-11.25 172.2Q-18 167.7 -18 174.2Q-17.5 177.7 -13 176.95L-11.25 174.45L-11.25 193.2L-13.25 191.2L-16.25 191.45L-17.75 193.45L-18 195.2L-16.5 197.7L-13.25 197.95L-11.75 196.95L-11.25 195.45L-11.25 215.7L-12.75 213.95L-14.75 213.7L-15.25 213.95Q-18.5 215.2 -18 217.2L-17 219.95Q-15.75 220.95 -12.75 220.45L-11.25 217.95L-11.25 237.7Q-16.5 232.45 -18 239.95Q-13.5 245.2 -11.25 239.95L-11.25 258.45L-12.75 256.7L-16.25 256.95L-17.75 258.95L-18 260.95Q-17.5 263.95 -13.25 263.45L-11.25 260.7L-11.25 280.2Q-12.75 277.2 -16.5 278.95L-18 282.7Q-13.5 287.95 -11.25 282.7L-11.25 302.95L-12.5 301.45L-15.5 301.45L-18 303.95Q-18.25 306.95 -16.75 307.7Q-13.25 308.45 -12.75 307.7L-11.25 305.2L-11.25 323.95L-12.5 322.45L-13.75 322.2L-14.75 322.2L-16.25 322.7Q-19 325.7 -18 326.7L-16.25 328.95L-14 329.2L-12.5 328.45L-11.25 326.2L-11.25 346.7L-13 344.95L-15.25 344.95L-15.75 345.2Q-18.25 346.45 -18 348.45L-16.75 351.45L-13.25 351.7L-11.25 348.95L-11.25 368.7Q-12.4 368.3 -12.75 367.2L-14.5 366.95L-15.25 367.2Q-18 368.2 -18 370.2L-17 373.45L-13.5 373.95Q-11.75 373.45 -11.25 370.95L-11 382.2L-11 390.2L-12.5 388.2L-14.75 387.95L-15.25 388.2Q-18 389.2 -18 391.2L-17 394.45Q-13.25 395.2 -12.75 394.45L-11 391.95L-11.5 409.7Q-11.5 413.7 -24 414.95L-48.25 417.2L-66.25 417.7L-82.5 417.2Q-117.25 414.7 -121 404.95L-121 5.95Q-119.75 0.2 -92.75 -2.3L-70 -3.3L-45.25 -2.8L-20.75 -1.05Q-8.25 -4.55 -11 19.45Q-13.5 14.7 -17.25 17.7Q-18.5 18.45 -17.75 21.2L-15.25 23.45L-14.75 23.7L-12.75 23.45L-11.25 21.7L-11.25 40.7"/></g><g class="sc-pa-animated 19" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-19-0)" d="M-11.9 23.5L-12 41.4Q-15 36.75 -18.5 39.9Q-20.5 44.65 -16 45.65L-15 45.65L-14.25 45.5L-13.15 44.9L-12 42.65L-12 64.25Q-14.5 59.4 -18.5 62.5Q-20.75 66.15 -16.5 68.15L-16 68.25L-14.9 68.25L-14.65 68.15L-14.4 68.15L-12.75 67.15L-12.15 65.75L-12 64.25L-12 85.65Q-14.65 80.75 -18.9 84.75Q-19.75 89.9 -15.75 89.9L-15.15 89.9L-14.25 89.75L-12.9 88.9L-12 86.65L-12 107.3Q-16.15 102.4 -18.75 106.3Q-20.15 111.55 -15 111.7L-14.75 111.55L-12.9 110.7L-12 108.7L-12 128.45L-13.25 126.3L-14 125.8L-16.5 125.55L-18.15 126.45L-18.9 127.3L-19.25 129.45L-18.4 131.3L-17.25 132.2L-14.65 132.45L-12.75 131.3L-12.15 129.95L-12 128.45L-12 150.8L-13 149.2L-13.9 148.55L-17 148.45L-19 150.3L-19.25 152.05L-18.15 154.3L-16.15 155.2L-14.9 155.2L-12.9 154.05L-12 152.05L-12 172.55L-13.5 170.55L-14.9 170.05L-16.5 170.05L-18 170.8L-18.75 171.7L-19.25 173.95L-18.25 175.95L-17.25 176.7L-14.65 176.95L-12.75 175.8L-12 173.8L-12 193.55Q-16.9 187.7 -19.25 194.8L-18.5 196.55L-17.5 197.45L-15.4 197.95L-13.9 197.55L-12.75 196.7L-12 194.8L-12 216.05L-13 214.45L-14 213.8L-16.5 213.7Q-21.4 216.55 -17.9 219.8Q-12.65 221.7 -12 217.05L-12 237.8L-13.4 235.95L-14.9 235.3Q-21.5 236.2 -18.15 241.45Q-12.75 243.7 -12 238.8L-12 258.95L-13.25 256.8L-14.9 256.2L-16.4 256.3L-18.25 257.2L-19.15 258.7L-19.25 259.7L-18.75 261.55L-17.4 262.8Q-12.1 263.65 -12 259.3L-12 280.45L-13.5 278.45L-15.15 277.95L-15.9 277.95L-16.25 278.05Q-21.65 281.05 -17.65 284.45Q-13 286.2 -12 281.45L-12 303.05L-13.25 301.3L-14.75 300.7L-16.25 300.7L-17.25 301.05Q-21.25 305.2 -17.4 307.3L-14.75 307.6L-13.4 306.95L-12 304.45L-12 324L-13.25 322.35L-14 321.85L-14.75 321.6L-16 321.6L-17.25 322Q-21.5 324.75 -17.25 328.25Q-12.65 329.35 -12 325L-12 346.75L-12.75 345.6L-13.9 344.6L-14.15 344.5L-16.4 344.35Q-21.5 347.6 -17.75 350.75Q-12.9 352.35 -12 348L-12 369L-12.75 367.6L-13.25 367.1L-14 366.6L-14.75 366.35L-16.25 366.35L-17.15 366.6L-17.25 366.75Q-21.5 370.6 -16.75 373.25Q-14 373.6 -12.75 372L-12 369L-11.9 379.25L-12 389.85L-12.75 388.5L-13.25 388L-14 387.5L-14.75 387.25L-16.65 387.35L-17.25 387.6Q-21.4 391.6 -17.15 394Q-12.6 394 -12 391.5L-12 407.85Q-13 411.6 -17.65 412.75L-43.15 413.1L-55 412.5L-65.25 411.35L-74.45 409.75L-81.95 407.6L-86.95 405.25Q-90.8 402.6 -90.7 399.75L-90.7 9.25Q-90.8 4.65 -74.45 2.15L-55.9 0.25L-43.15 -0.25L-17.15 0.15Q-13.75 0.25 -12 4.65L-12 19.75Q-14.25 15.15 -18.5 18.25Q-20.25 23.15 -16.5 23.9L-16.15 24L-15 24L-14.25 23.9L-12.9 22.9L-12.65 22.5L-12 21L-11.9 23.5"/></g><g class="sc-pa-animated 20" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-20-0)" d="M-14.3 24.6L-12.9 24L-12.1 22.6L-12.1 41.2L-13.3 40L-13.9 39.6L-16.5 39.4L-17.5 40L-18.7 42.2Q-19.1 44.6 -17.3 45.8L-14.9 46.2L-13.5 46L-12.1 44.2L-11.9 64L-12.9 63L-14.5 61.8L-16.3 61.8L-18.5 63.6L-18.7 66.4L-18.1 67.6L-15.7 68.6L-13.9 68.6L-12.1 66.8L-11.9 85.6L-12.9 84.6L-13.3 84L-14.1 83.6L-16.9 83.6L-18.5 85.2L-18.7 86.2L-18.5 88.4L-17.7 89.6L-15.5 90.2L-14.5 90.2L-13.1 89.8L-12.1 88.4L-12.1 106.8L-12.9 106.2L-13.1 105.8L-14.7 105L-16.3 105L-17.7 105.8L-18.7 107.6L-18.5 110L-17.7 111.2L-15.5 111.8L-14.5 111.8L-13.1 111.4L-12.1 110L-12.1 127.6L-13.9 126L-14.1 126L-14.7 125.8Q-17.3 125.4 -18.3 127.2L-18.7 130.2L-16.9 132.4L-14.7 132.6L-13.5 132.4L-12.1 130.6L-12.1 150.2L-13.9 148.6L-14.1 148.6L-14.5 148.4Q-17.5 148 -18.3 149.8L-18.7 152.8L-16.9 155L-14.5 155.2L-13.5 155L-12.1 153.4L-12.1 172L-13.1 170.6L-14.3 170.2L-14.5 170.2L-14.9 170Q-18.3 170.2 -18.5 171.8L-18.7 174.6L-16.7 176.8L-15.1 177L-14.7 176.8L-14.3 176.8L-13.1 176.4L-12.1 175L-12.1 192.8L-13.1 191.4L-14.3 191L-14.7 191L-15.1 190.8L-17.7 191.6L-18.3 192.4L-18.5 196L-17.5 197.2L-15.9 197.8L-13.5 197.2L-12.1 195.8L-12.1 215.4L-14.1 213.6L-14.3 213.6L-14.7 213.4Q-17.3 213 -18.3 214.8L-18.7 217.8L-16.9 220L-14.5 220.2L-14.1 220L-13.5 219.8L-13.3 219.6L-12.1 218.4L-12.1 237L-13.1 235.6L-14.3 235.2L-14.5 235.2L-15.5 235L-18.1 236.2L-18.7 238L-18.5 240L-17.1 241.6L-15.9 242L-13.5 241.4L-12.1 240L-12.1 257.8L-13.7 256L-15.1 255.8Q-18.3 256 -18.5 257.6L-18.5 260.8L-17.7 262L-16.1 262.8L-13.5 262.2L-12.1 260.8L-12.1 279.4L-13.3 278L-14.5 277.6L-15.3 277.6Q-17.7 277.2 -18.7 279.8L-18.5 282.6L-16.5 284.4L-13.7 284L-13.3 283.8L-12.9 283.2L-12.1 282.6L-12.1 302L-12.9 300.8L-14.7 300.2L-15.3 300.2Q-18.5 300.8 -18.5 302L-18.3 305.6L-16.5 307L-14.1 307L-13.3 306.4L-12.1 305.2L-12.1 322.8L-13.9 321L-15.7 321Q-18.3 321.4 -18.7 323.4L-18.1 326.6Q-15.7 328.2 -14.3 327.8L-12.9 326.6L-12.1 326L-12.1 345.4L-13 344.5L-13.55 343.95L-13.9 343.6L-14.4 343.6L-15.7 343.6Q-18.3 344 -18.7 346L-18.1 349.2Q-16.5 350.8 -14.1 350.4L-12.9 349.2L-12.1 348.6L-12.1 367.4L-14.3 365.4L-16.1 365.6Q-18.5 366 -18.7 368L-18.5 370.6L-16.3 372.4L-13.3 372L-12.9 371.2L-12.1 370.4L-12.1 388.2L-14.3 386.2L-16.1 386.4Q-20.5 388.2 -17.9 392.2L-16.3 393.2L-14.3 393.2L-12.9 392L-12.1 391.2L-11.9 405.4Q-11.7 408 -13.9 410.4L-17.1 411.6L-36.7 409.8L-47.3 407.8L-54.3 405.6L-58.7 403.2Q-62.1 400.2 -61.5 399.4L-61.5 9.6Q-55.3 1.2 -14.9 1.4Q-14.2 1.6 -13.7 2.05Q-12.5 3.05 -12.1 5.4L-12.1 19.4L-12.9 19L-14.3 17.8L-16.5 17.8L-18.5 19.6Q-19.3 24.6 -15.5 24.6L-14.3 24.6"/><path style="fill:url(#:notepad-20-1)" d="M-11.5 5.4L-11.7 20.8L-12.1 19.8L-12.1 19.4L-12.1 5.4Q-12.5 3.05 -13.7 2.05Q-12.1 3.15 -11.5 5.4M-13.9 410.4Q-11.7 408 -11.9 405.4L-12.1 391.2L-11.7 390.2L-11.5 407.2Q-12.3 409.6 -13.9 410.4M-11.7 369.4L-11.7 380.6L-11.7 389.4L-12.1 389.2L-12.1 388.2L-12.1 370.4L-11.7 369.4M-11.7 347.4L-11.7 368.6L-12.1 368.4L-12.1 367.4L-12.1 348.6L-11.7 347.4M-11.7 324.8L-11.7 346.6L-12.1 345.4L-12.1 326L-11.7 324.8M-11.7 304L-11.7 324L-12.1 323.8L-12.1 322.8L-12.1 305.2L-11.7 304M-11.7 281.4L-11.7 303.2L-12.1 303L-12.1 302L-12.1 282.6L-11.7 281.4M-11.7 259.8L-11.7 280.6L-12.1 280.4L-12.1 279.4L-12.1 260.8L-11.7 259.8M-11.7 239L-11.7 258.8L-12.1 257.8L-12.1 240L-11.7 239M-11.7 217.2L-11.7 238L-12.1 237L-12.1 218.4L-11.7 217.2M-11.7 194.8L-11.7 216.4L-12.1 216.2L-12.1 215.4L-12.1 195.8L-11.7 194.8M-11.7 174L-11.7 193.8L-12.1 192.8L-12.1 175L-11.7 174M-11.7 152.2L-11.7 173.2L-12.1 172.8L-12.1 172L-12.1 153.4L-11.7 152.2M-11.7 129.6L-11.7 151.4L-12.1 150.2L-12.1 130.6L-11.7 129.6M-11.7 108.8L-11.7 128.8L-12.1 127.6L-12.1 110L-11.7 108.8M-11.7 87.2L-11.7 108L-12.1 107.8L-12.1 106.8L-12.1 88.4L-11.7 87.2M-11.7 65.6L-11.7 86.4L-12.1 86.2L-11.9 85.6L-12.1 66.8L-11.7 65.6M-11.7 43.2L-11.7 64.8L-12.1 64.6L-11.9 64L-12.1 44.2L-11.7 43.2M-11.7 21.6L-11.7 22.6L-11.7 42.4L-12.1 41.2L-12.1 22.6L-11.7 21.6"/></g><g class="sc-pa-animated 21" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-21-0)" d="M-12.25 385.45L-13.5 385.7L-15 386.2L-15.75 387.45L-15.75 390.2L-13.75 392.45L-11.5 392.2L-10.25 391.2L-10 404.95Q-10.5 409.2 -12.25 410.2Q-45 406.95 -42.5 394.7L-42.5 13.2Q-43 3.45 -13.5 1.7L-13 1.95L-12.75 1.95Q-10.75 2.2 -10 6.95L-10.25 19.7L-11.5 18.7L-12 18.45L-14.5 18.7L-15.75 20.7L-15.5 23.95L-14 25.2L-12.75 25.2L-12.65 25.2L-11.25 24.95L-10.25 23.45L-10.25 41.45L-11.5 40.2L-12 39.95L-14.5 40.2L-15.75 42.2L-15.5 45.45L-14 46.7L-12.75 46.7L-11.25 46.45L-10.25 44.95L-10.25 63.95L-11.75 62.45L-12 62.45L-12.5 62.2L-15.5 63.45L-15.75 65.2L-15 68.45L-13 69.2L-11.5 68.95L-10.25 67.45L-10.25 85.45L-10.95 84.85L-11 84.7L-12 83.95L-14.25 83.95L-15.75 86.2L-15 89.95L-12.75 90.7L-12.25 90.45L-12 90.45L-10.25 88.95L-10.25 106.7L-12 105.45L-14.25 105.45L-15.75 107.7L-15 111.45L-12.75 112.2L-11.25 111.95L-10.25 110.45L-10.25 127.7L-11.75 126.2L-12 126.2L-12.5 125.95L-15 126.7L-15.75 128.2L-15 132.2L-13.25 132.7L-11.5 132.7L-10.25 131.45L-10.25 150.2L-12 148.7L-12.5 148.45L-14.25 148.7L-15.5 149.95L-15.75 153.2L-14.25 155.2L-12.75 155.45L-11 154.95L-10.25 153.7L-10.25 171.95L-12.25 170.2L-14 170.2L-15.25 171.2L-15.75 174.95L-14 176.95L-12.25 176.95L-11.4 176.35L-10.25 175.45L-10.25 192.7L-12.25 190.95L-14 190.95L-15.25 191.95L-15.75 195.7L-14 197.7L-12.25 197.7L-10.25 196.2L-10.25 214.95L-11.5 213.45L-12.25 213.45L-13.25 213.45L-15 213.95L-15.5 214.95L-15.75 217.95L-13.75 220.2L-12.5 220.2L-11 219.2L-10.25 218.7L-10.25 236.7L-11.25 235.2L-12.5 234.95L-14 234.95L-15.25 235.95L-15.75 239.7L-14.5 241.45L-12 241.7L-10.25 240.2L-10.25 257.45L-11 256.2L-12.5 255.7L-14.5 255.95L-15.5 256.95L-15.75 260.2L-14 262.45L-12.25 262.45L-10.25 260.95L-10.25 279.2L-11.5 277.45L-12.75 277.2Q-15.75 277.7 -15.75 279.2L-15.75 281.95L-14.25 283.95L-12.5 284.2L-12 283.95L-11.75 283.95L-10.25 282.7L-10 301.7L-12 299.7L-13.25 299.7L-15 300.45L-15.75 301.7L-15.75 304.45L-13.5 306.7L-11.75 306.45L-10.25 305.45L-10 322.45L-12 320.45L-13.25 320.45L-15.5 321.95L-15.75 324.95L-14.5 326.95L-12.5 327.45L-12 327.2L-11.75 327.2L-10.25 325.95L-10.25 344.7L-12 342.95L-13.25 342.95L-15.5 344.45L-15.75 347.45L-14.25 349.7L-11.75 349.7L-10.25 348.45L-10.25 366.95L-11.75 364.95L-13 364.95L-15.25 365.7L-15.75 366.7L-15.75 369.45L-14 371.7L-11.5 371.45L-10.25 370.45L-10 387.7L-12.25 385.45"/><path style="fill:url(#:notepad-21-1)" d="M-10 404.95L-10.25 391.2L-10 387.7L-10.25 370.45L-9.75 368.7L-10.25 366.95L-10.25 348.45L-9.75 346.7L-10.25 344.7L-10.25 325.95L-10 322.45L-10.25 305.45L-10 301.7L-10.25 282.7L-9.75 280.95L-10.25 279.2L-10.25 260.95L-9.75 259.2L-10.25 257.45L-10.25 240.2L-9.75 238.45L-10.25 236.7L-10.25 218.7L-10.25 214.95L-10.25 196.2L-9.75 194.45L-10.25 192.7L-10.25 175.45L-10.25 171.95L-10.25 153.7L-9.75 151.95L-10.25 150.2L-10.25 131.45L-10.25 127.7L-10.25 110.45L-9.75 108.7L-10.25 106.7L-10.25 88.95L-10.25 85.45L-10.25 67.45L-10.25 63.95L-10.25 44.95L-10.25 41.45L-10.25 23.45L-10.25 19.7L-10 6.95Q-10.75 2.2 -12.75 1.95Q-11.5 1.2 -9.5 5.2L-9.5 22.2L-9.5 381.2L-9.25 406.2Q-9.75 409.7 -12.25 410.2Q-10.5 409.2 -10 404.95"/></g><g class="sc-pa-animated 22" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-22-0)" d="M-8.7 392L-8.1 391.8L-6.9 391L-6.7 405.2Q-6.9 408.9 -8.45 409.7L-8.7 409.8Q-22.7 406 -23.1 399.6L-23.1 10.2Q-24.3 4.8 -8.9 2.2Q-6.9 3.2 -6.7 7L-6.9 19.8L-7.3 19L-8.7 18.6Q-13.3 23 -9.1 25.6L-7.7 25.4L-6.9 24L-6.9 41.2L-7.3 40.4L-8.3 40.2L-8.7 40Q-13.5 44.4 -8.9 47L-7.5 46.6L-6.9 45.4L-6.9 63.6L-7.3 62.8L-8.7 62.4Q-13.3 66.6 -9.3 69.2L-8.1 69.4L-6.9 67.8L-6.7 70L-6.9 85.2L-8.3 84L-9.7 84L-10.3 84.6L-11.1 87.6L-10.5 90L-8.9 90.8L-7.9 90.8L-6.9 89.4L-6.9 106.6Q-7.55 106.3 -7.5 105.6L-8.7 105.4L-10.1 105.8L-10.9 107.4L-10.9 110.6L-9.7 112.2L-8.45 112.2L-7.5 112L-6.9 110.8L-6.9 127.4L-7.7 126.2L-8.7 126L-10.3 126.6L-11.1 129.6L-10.5 132L-9.7 132.8L-8.45 132.8L-7.5 132.6L-6.9 131.6L-6.9 149.8L-7.7 148.6L-8.9 148.4Q-13.3 152 -8.9 155.4L-7.7 155.2L-6.9 154L-6.9 171.4L-7.7 170.2L-8.7 170L-10.3 170.6L-11.1 173.6L-10.5 176L-9.1 176.8L-7.7 176.8L-6.9 175.6L-6.9 192L-7.5 191L-8.7 190.8L-9.9 191L-10.7 192L-11.1 194.2L-9.9 197.4L-8.5 197.6L-8.4 197.6L-7.5 197.4L-6.9 196.4L-6.9 214.4L-7.9 213.2L-8.7 213.2L-10.3 213.6L-10.9 215L-10.9 218L-9.5 220L-8.5 220L-8.4 220L-7.5 219.8L-6.9 218.8L-6.9 236L-7.7 234.8L-9.1 234.6Q-13.3 237.8 -8.7 241.6L-7.3 241.2L-6.9 240.4L-6.9 256.75Q-6.95 256.05 -7.5 255.6L-8.7 255.4L-10.3 255.8L-10.7 256.6L-11.1 260L-9.5 262.2L-8.5 262.2L-8.4 262.2L-7.5 262L-6.9 261L-6.9 278.35Q-6.95 277.65 -7.5 277.2L-8.65 277.1L-8.7 277L-9.3 277L-10.5 277.6L-10.9 278.8L-10.9 281.6L-9.7 283.6L-8.5 283.8L-8.4 283.8L-7.5 283.6L-6.9 282.6L-6.9 301L-7.7 299.6L-8.7 299.4L-10.1 299.6L-10.7 300.4L-11.1 302.6L-10.1 305.6L-8.3 306.2L-7.7 305.8L-6.9 305.2L-6.9 321.8L-7.7 320.2L-8.9 320Q-13.5 322.8 -8.7 327L-8.1 326.8L-6.9 325.8L-6.9 344.2L-8.3 342.4L-9.5 342.6Q-13.3 347.4 -8.3 349.4L-6.9 348.4L-6.9 366.2L-8.3 364.2L-9.3 364.4L-10.9 365.8L-10.7 369.6L-9.3 371.2L-8.3 371.2L-6.9 370.2L-6.9 386.8L-8.1 385L-9.1 385Q-13.3 387.4 -8.7 392"/><path style="fill:url(#:notepad-22-1)" d="M-6.7 405.2L-6.9 391L-6.5 389.4L-6.9 386.8L-6.9 370.2L-6.5 367.8L-6.9 366.2L-6.9 348.4L-6.5 346.8L-6.9 344.2L-6.9 325.8L-6.5 323.4L-6.9 321.8L-6.9 305.2L-6.5 303.4L-6.9 301L-6.9 282.6L-6.5 280.2L-6.9 278.6L-6.9 278.35L-6.9 261L-6.5 258.6L-6.9 257L-6.9 256.75L-6.9 240.4L-6.5 238.6L-6.9 236L-6.9 218.8L-6.5 217L-6.9 214.4L-6.9 196.4L-6.5 194.6L-6.9 192L-6.9 175.6L-6.5 173.8L-6.9 171.4L-6.9 154L-6.5 152.2L-6.9 149.8L-6.9 131.6L-6.5 129L-6.9 127.4L-6.9 110.8L-6.5 109L-6.9 106.6L-6.9 89.4L-6.5 87.6L-6.9 85.2L-6.7 70L-6.9 67.8L-6.5 66L-6.9 63.6L-6.9 45.4L-6.5 43.6L-6.9 41.2L-6.9 24L-6.5 22.2L-6.9 19.8L-6.7 7Q-6.9 3.2 -8.9 2.2Q-7.3 1.6 -5.9 5.6L-6.1 17.8L-5.9 86.8L-6.1 88.6L-6.1 150.4L-5.9 152.6L-6.1 301.6L-5.9 302.2L-5.9 387.2L-5.9 406.6Q-5.7 408.5 -8.45 409.7Q-6.9 408.9 -6.7 405.2"/></g><g class="sc-pa-animated 23" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-23-0)" d="M-3.7 384.6L-4.9 384.6Q-7.1 391.2 -4.1 391.6L-2.9 390.8L-2.9 404.2Q-3.1 408 -4.3 409.4Q-7.9 408 -9.9 403.8L-9.9 8.6Q-9.9 3.2 -4.5 2.4L-4.45 2.4Q-3.3 2.65 -2.9 7.2L-3.1 19.6L-4.3 19Q-7.3 21.6 -4.7 25.8L-3.7 25.8L-3.1 24.8L-3.1 41.2L-3.5 40.4L-4.3 40.4Q-7.3 43 -4.7 47.2L-3.7 47.2L-3.1 46.2L-3.1 63.4L-4.3 62.6Q-7.9 67.6 -4.5 69.4L-3.9 69.6L-3.1 68.6L-3.1 84.8L-4.3 84.2Q-7.3 86.6 -4.7 90.8L-3.7 91L-3.1 90L-3.1 106.2L-4.3 105.6L-5.1 105.6L-5.7 107L-5.9 110.2L-5.3 112L-4.5 112.4L-3.7 112.4L-3.1 111.4L-3.1 126.8L-4.5 126Q-7.3 131.8 -4.7 132.8L-3.7 133L-3.1 132L-3.1 149.4L-3.5 148.6L-4.3 148.6L-5.5 149L-5.9 153L-5.1 155.2L-4.5 155.4L-3.1 154.6L-3.1 171L-3.7 170L-4.5 170Q-7.3 175.4 -4.5 176.8L-3.5 176.8L-3.1 176L-3.1 191.6L-3.5 190.8L-4.3 190.8L-5.3 191L-5.7 192L-5.9 195L-5.3 197.2L-4.3 197.6L-3.1 196.8L-3.1 214L-3.7 213L-4.5 213Q-6.3 213.2 -5.9 217.4L-4.7 219.8L-4.1 219.8L-3.1 219.2L-3.1 235.4L-3.5 234.6L-4.3 234.6L-5.3 234.8L-5.7 235.8L-5.9 238.8L-5.3 241L-4.3 241.4L-3.1 240.8L-3.1 256.2L-3.7 255.2L-4.7 255.2L-5.7 256.4L-6.1 258.4L-5.3 261.6L-4.1 262L-3.1 261.4L-3.1 277.8L-3.5 276.8L-4.3 276.8L-5.5 277.2L-5.9 280.8L-5.1 283.4L-4.3 283.6L-3.1 283L-3.1 300.2L-3.5 299.2L-4.7 299.2L-5.5 299.8L-5.9 301.4L-5.7 304.4L-4.9 306L-4.1 306L-3.1 305.4L-3.1 321L-3.7 319.8L-4.7 319.8Q-7.3 324.2 -4.3 326.6L-3.1 326L-3.1 343.2L-3.7 342.2L-4.5 342.2Q-7.7 344.4 -4.5 349L-3.1 348.6L-3.1 365.4Q-3.8 364.85 -3.7 364L-4.5 364L-5.7 364.8L-5.9 367.8L-5.1 370.6L-4.5 370.8L-3.1 370.4L-3.1 385.8L-3.7 384.6"/><path style="fill:url(#:notepad-23-1)" d="M-2.9 404.2L-2.9 390.8L-3.1 385.8L-3.1 370.4L-3.1 365.4L-3.1 348.6L-3.1 343.2L-3.1 326L-3.1 321L-3.1 305.4L-3.1 300.2L-3.1 283L-3.1 277.8L-3.1 261.4L-3.1 256.2L-3.1 240.8L-3.1 235.4L-3.1 219.2L-3.1 214L-3.1 196.8L-3.1 191.6L-3.1 176L-3.1 171L-3.1 154.6L-3.1 149.4L-3.1 132L-3.1 126.8L-3.1 111.4L-3.1 106.2L-3.1 90L-3.1 84.8L-3.1 68.6L-3.1 63.4L-3.1 46.2L-3.1 41.2L-3.1 24.8L-3.1 19.6L-2.9 7.2Q-3.3 2.65 -4.45 2.4L-3.3 2.6L-2.3 4.2L-1.9 13.4L-2.1 42.4L-1.9 43.8L-1.9 108.4L-2.1 110L-2.1 128.2L-1.9 129.8L-1.9 195L-2.1 195.4L-1.9 301.8L-2.1 304L-1.9 368.4L-2.1 369L-1.9 393.8L-2.1 406.6Q-3.3 409.6 -4.3 409.4Q-3.1 408 -2.9 404.2"/> </g><g class="sc-pa-animated 24" transform="matrix(1.5 0 0 1.2 150 30)"><path style="fill:url(#:notepad-24-0)" d="M-0.3 384.5L-1.3 384.5Q-2.05 385.25 -1.8 389L-1.05 391.35L0.05 391.35L0.2 404.85Q0.05 408.85 -0.95 409.1L-2.8 406.25L-2.55 394.35L-2.95 354.75L-2.8 14.4Q-4.2 3.25 -0.95 2.65Q-0.05 2.9 0.2 7.25L0.05 19.65L-0.2 19L-0.95 19Q-2.55 21.9 -1.3 25.75L-0.3 25.9L0.05 25.25L0.05 40.65L-0.95 40.4Q-2.8 42.25 -1.3 47.15L-0.3 47.25L-0.3 46.75L0.05 46.65L0.05 63.15L-0.3 62.65L-1.05 62.75Q-2.2 64.25 -1.95 68.25L-1.2 69.5L-0.45 69.5L0.05 69L0.3 71.4L0.05 84.4L-1.05 84.15Q-2.55 90.15 -1.2 90.9L-0.45 91L0.05 90.4L0.3 100.5L0.05 106.3L-0.2 105.55L-1.05 105.7Q-2.55 106.3 -1.2 112.3L-0.3 112.45L0.05 111.95L0.05 126.55L-0.45 126.05L-1.2 126.2Q-2.05 126.55 -1.8 131.45L-1.2 132.95L-0.45 132.95L0.05 132.45L0.05 148.95L-0.2 148.55L-1.05 148.55Q-2.2 148.95 -1.8 153.8L-1.2 155.3L-0.7 155.45L-0.2 155.3L0.05 154.7L0.05 170.55L-0.2 170.05L-1.05 170.05Q-2.55 170.7 -1.2 176.8L-0.45 176.95L0.05 176.45L0.3 176.55L0.05 191.7L-0.45 190.7L-1.2 190.7Q-2.7 196.7 -1.2 197.45L-0.3 197.55L0.05 197.2L0.05 214.05L-0.2 213.05L-1.05 213.05Q-2.2 213.3 -1.8 218.05L-1.05 219.8L-0.2 219.8L0.05 219.45L0.3 220.55L0.05 235.55L-0.3 234.55L-1.2 234.55Q-2.05 234.95 -1.8 239.55L-1.05 241.3L0.05 241.05L0.05 255.55L-0.45 255.05L-1.2 255.2Q-2.8 255.8 -1.05 261.95L0.05 261.7L0.05 277.3L-0.55 276.55L-1.2 276.7Q-2.95 282.8 -0.8 283.45L0.05 283.2L0.3 294.7L0.05 299.7L-0.3 299.05L-1.2 299.05Q-2.2 300.2 -1.8 303.8L-1.05 305.95L-0.2 305.95L0.05 305.45L0.3 311.6L0.05 320.35L-0.7 319.6L-1.3 319.75Q-2.05 320.6 -1.8 324.35L-1.05 326.6L-0.45 326.6L0.05 326.1L0.3 341.85L0.05 342.75L-0.55 342L-1.2 342.1L-1.55 342.25L-1.95 343.6L-1.8 346.75L-1.3 348.85L-0.95 349L0.05 348.75L0.05 364.5L-0.45 363.85L-1.3 363.85Q-2.7 369.35 -1.05 370.75L0.05 370.5L0.3 380.75L0.05 385.75L-0.3 384.5"/><path style="fill:url(#:notepad-24-1)" d="M0.95 348L0.95 365.6L1.2 367.1L1.2 368L0.95 369.75L0.95 386.35L0.95 390.5L1.05 399.1L0.8 407.6L0.2 409.1L-0.95 409.1Q0.05 408.85 0.2 404.85L0.05 391.35L0.3 387.35L0.05 385.75L0.3 380.75L0.05 370.5L0.05 370.1L0.3 370L0.05 364.5L0.05 348.75L0.3 348L0.05 342.75L0.3 341.85L0.05 326.1L0.3 325.6L0.05 320.35L0.3 311.6L0.05 305.45L0.3 303.55L0.05 299.7L0.3 294.7L0.05 283.2L0.05 277.3L0.05 261.7L0.05 255.55L0.05 241.05L0.05 240.45L0.3 238.95L0.05 235.55L0.3 220.55L0.05 219.45L0.05 218.2L0.3 215.45L0.05 214.05L0.05 197.2L0.05 196.45L0.3 196.3L0.05 191.7L0.3 176.55L0.05 176.45L0.05 170.55L0.05 154.7L0.05 148.95L0.05 132.45L0.05 126.55L0.05 111.95L0.05 111.2L0.3 110.95L0.05 106.3L0.3 100.5L0.05 90.4L0.05 89.65L0.3 88.65L0.05 84.4L0.3 71.4L0.05 69L0.05 68.15L0.3 67L0.05 63.4L0.05 63.15L0.05 46.65L0.05 45.75L0.3 45.65L0.05 45L0.3 44.75L0.05 40.65L0.05 25.25L0.05 19.65L0.2 7.25Q-0.05 2.9 -0.95 2.65L-0.05 2.65L0.55 3.4L1.05 9.65L0.95 20L0.95 24.15L0.95 41.5L1.2 44.25L0.95 63.9L0.95 68L0.95 85.25L0.95 89.4L1.2 107.8L0.95 110.95L1.2 152.7L0.95 171.45L0.95 175.55L1.2 194.45L0.95 196.2L1.2 207.95L0.95 214.45L0.95 218.55L0.95 236.05L0.95 240.2L1.2 259.55L0.95 272.8L1.2 281.2L1.05 281.55L0.95 282.3L1.2 303.2L0.95 304.8L1.2 305.05L0.95 321.35L0.95 325.5L1.2 342.35L0.95 343.85L0.95 348"/></g></svg><table class="sc-pa-page"><tr><td class="sc-pa-img"></td></tr><tr><td class="sc-pa-des">dfsdsd</td></tr><tr><td class="sc-pa-num">1 / 3</td></tr></table><table class="sc-pa-bttn"><tr><td class="sc-pa-prev"><!----></td><td class="sc-pa-next"><!----></td></tr></table><input type="button" class="sc-pa-key-handler"/>'
                    });
                  } else {
                    if (type == "crossword") {
                      obj = new Crosswords($("#" + containerId), {
                        model : params.isXML ? new Crossword(xml2json.parser(xml).crossword, params) : new Crossword(xml, params),
                        template : "CROSSWORD_EJS_SCRIPT"
                      });
                    } else {
                      if (type == "seekaword") {
                        obj = new SeekAWords($("#" + containerId), {
                          model : new SeekAWord(xml, params),
                          template : "SEEK_A_WORD_EJS_SCRIPT"
                        });
                      } else {
                        if (type == "tabbedpane") {
                          obj = new TabbedPane($("#" + containerId), {
                            model : new iPane(xml2json.parser(xml).tabbedpaneactivity, params),
                            template : '<div class="page"><table style="width: 100%; height: 100%"><tr><td style="text-align: center; vertical-align: middle"><img src="sclb_extras/loading.gif"/></td></tr></table></div><input type="button" class="key-handler"/>'
                          });
                        } else {
                          if (type == "didyouknow") {
                            obj = new DidYouKnow($("#" + containerId), {
                              model : new iQuestion(xml2json.parser(xml).didyouknowactivity, params),
                              template : '<table style="border: 0; border-collapse: collapse; width: 100%; height: 100%;"><tr><td class="sc-dyk-image-1" rowspan="3"><div></div></td><td class="sc-dyk-image-2" rowspan="3"><div></div></td><td class="sc-dyk-question"><div class="sc-dyk-content"></div></td></tr><tr><td class="sc-dyk-answer"><div class="sc-dyk-content"></div></td></tr><tr><td class="sc-dyk-show-answer"><div class="sc-dyk-content"><div class="sc-dyk-button"></div></div></td></tr></table><input  type="button" class="sc-dyk-key-handler"/>'
                            });
                          } else {
                            if (type == "sectionedshape") {
                              obj = new SectionedShape($("#" + containerId), {
                                model : new iChart(xml2json.parser(xml).sectionedshapeactivity, params),
                                template : '<div class="sc-chart-description"><div class="sc-chart-holder"><div class="sc-chart-title"></div><div class="sc-chart-descr"><div></div></div></div></div><div class="sc-chart-marker"><div class="sc-chart-top"></div><div class="sc-chart-bottom"></div></div><div class="sc-chart-alttext"></div><input type="button" class="sc-chart-key-handler"/>'
                              });
                            } else {
                              if (type == "timeline") {
                                obj = new Timelines($("#" + containerId), {
                                  model : new Timeline(xml2json.parser(xml).timeline, params),
                                  template : "TIMELINE_EJS_SCRIPT"
                                });
                              } else {
                                if (type == "flashcard") {
                                  obj = softchalkcard.init(xml, params);
                                } else {
                                  if (type == "slideshow") {
                                    obj = softchalkslide.init(xml, params);
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
      return obj;
    }

    function initialize(params) {
      var obj = null;
      $.ajax({
        type : "GET",
        url : params.xmlPath,
        dataType : "text",
        async : false,
        success : function(xml) {
          if (xml[0] == "<") {
            params.isXML = true;
            obj = showTask(StringtoXML(xml), params);
          } else {
            params.isXML = false;
            obj = showTask(xml, params);
          }
        }
      });
      return obj;
    }

  })(jQuery);
  function getRGB(color) {
    var result;
    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])];
    }
    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];
    }
    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)];
    }
    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)];
    }
  }

  function getMixedColor(bgc, hex, alpha) {
    hex = hex.replace(/#/g, ""), bgc = bgc.replace(/#/g, ""), alpha = alpha || 1;
    var b_r = parseInt(bgc.substring(0, 2), 16), b_g = parseInt(bgc.substring(2, 4), 16), b_b = parseInt(bgc.substring(4, 6), 16), c_r = parseInt(hex.substring(0, 2), 16), c_g = parseInt(hex.substring(2, 4), 16), c_b = parseInt(hex.substring(4, 6), 16);
    return "#" + Math.floor(alpha * c_r + (1 - alpha) * b_r).toString(16) + Math.floor(alpha * c_g + (1 - alpha) * b_g).toString(16) + Math.floor(alpha * c_b + (1 - alpha) * b_b).toString(16);
  }

  function StringtoXML(text) {
    if (window.ActiveXObject) {
      var doc = new ActiveXObject("Microsoft.XMLDOM");
      doc.async = "false";
      doc.loadXML(text);
    } else {
      var parser = new DOMParser();
      var doc = parser.parseFromString(text, "text/xml");
    }
    return doc;
  }
  (function($) {
    var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/;
    $.fn.simulate = function(type, options) {
      return this.each(function() {
        new $.simulate(this, type, options);
      });
    };
    $.simulate = function(elem, type, options) {
      var method = $.camelCase("simulate-" + type);
      this.target = elem;
      this.options = options;
      if (this[method]) {
        this[method]();
      } else {
        this.simulateEvent(elem, type, options);
      }
    };
    $.extend($.simulate.prototype, {
      simulateEvent : function(elem, type, options) {
        var event = this.createEvent(type, options);
        this.dispatchEvent(elem, type, event, options);
      },
      createEvent : function(type, options) {
        if (rkeyEvent.test(type)) {
          return this.keyEvent(type, options);
        }
        if (rmouseEvent.test(type)) {
          return this.mouseEvent(type, options);
        }
      },
      mouseEvent : function(type, options) {
        var event, eventDoc, doc, body;
        options = $.extend({
          bubbles : true,
          cancelable : (type !== "mousemove"),
          view : window,
          detail : 0,
          screenX : 0,
          screenY : 0,
          clientX : 1,
          clientY : 1,
          ctrlKey : false,
          altKey : false,
          shiftKey : false,
          metaKey : false,
          button : 0,
          relatedTarget : undefined
        }, options);
        if (document.createEvent) {
          event = document.createEvent("MouseEvents");
          event.initMouseEvent(type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, options.relatedTarget || document.body.parentNode);
          if (event.pageX === 0 && event.pageY === 0 && Object.defineProperty) {
            eventDoc = event.relatedTarget.ownerDocument || document;
            doc = eventDoc.documentElement;
            body = eventDoc.body;
            Object.defineProperty(event, "pageX", {
              get : function() {
                return options.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
              }
            });
            Object.defineProperty(event, "pageY", {
              get : function() {
                return options.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
              }
            });
          }
        } else {
          if (document.createEventObject) {
            event = document.createEventObject();
            $.extend(event, options);
            event.button = {0:1,1:4,2:2}[event.button] || event.button;
          }
        }
        return event;
      },
      keyEvent : function(type, options) {
        var event;
        options = $.extend({
          bubbles : true,
          cancelable : true,
          view : window,
          ctrlKey : false,
          altKey : false,
          shiftKey : false,
          metaKey : false,
          keyCode : 0,
          charCode : undefined
        }, options);
        if (document.createEvent) {
          try {
            event = document.createEvent("KeyEvents");
            event.initKeyEvent(type, options.bubbles, options.cancelable, options.view, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode);
          } catch(err) {
            event = document.createEvent("Events");
            event.initEvent(type, options.bubbles, options.cancelable);
            $.extend(event, {
              view : options.view,
              ctrlKey : options.ctrlKey,
              altKey : options.altKey,
              shiftKey : options.shiftKey,
              metaKey : options.metaKey,
              keyCode : options.keyCode,
              charCode : options.charCode
            });
          }
        } else {
          if (document.createEventObject) {
            event = document.createEventObject();
            $.extend(event, options);
          }
        }
        if ($.browser.msie || $.browser.opera) {
          event.keyCode = (options.charCode > 0) ? options.charCode : options.keyCode;
          event.charCode = undefined;
        }
        return event;
      },
      dispatchEvent : function(elem, type, event) {
        if (elem.dispatchEvent) {
          elem.dispatchEvent(event);
        } else {
          if (elem.fireEvent) {
            elem.fireEvent("on" + type, event);
          }
        }
      },
      simulateFocus : function() {
        var focusinEvent, triggered = false, element = $(this.target);
        function trigger() {
          triggered = true;
        }
        element.bind("focus", trigger);
        element[0].focus();
        if (!triggered) {
          focusinEvent = $.Event("focusin");
          focusinEvent.preventDefault();
          element.trigger(focusinEvent);
          element.triggerHandler("focus");
        }
        element.unbind("focus", trigger);
      },
      simulateBlur : function() {
        var focusoutEvent, triggered = false, element = $(this.target);
        function trigger() {
          triggered = true;
        }
        element.bind("blur", trigger);
        element[0].blur();
        setTimeout(function() {
          if (element[0].ownerDocument.activeElement === element[0]) {
            element[0].ownerDocument.body.focus();
          }
          if (!triggered) {
            focusoutEvent = $.Event("focusout");
            focusoutEvent.preventDefault();
            element.trigger(focusoutEvent);
            element.triggerHandler("blur");
          }
          element.unbind("blur", trigger);
        }, 1);
      }
    });
    function findCenter(elem) {
      var offset, document = $(elem.ownerDocument);
      elem = $(elem);
      offset = elem.offset();
      return {
        x : offset.left + elem.outerWidth() / 2 - document.scrollLeft(),
        y : offset.top + elem.outerHeight() / 2 - document.scrollTop()
      };
    }
    $.extend($.simulate.prototype, {
      simulateDrag : function() {
        var target = this.target, options = this.options, center = findCenter(target), x = Math.floor(center.x), y = Math.floor(center.y), dx = options.dx || 0, dy = options.dy || 0, coord = {
          clientX : x,
          clientY : y
        };
        this.simulateEvent(target, "mousedown", coord);
        coord = {
          clientX : x + 1,
          clientY : y + 1
        };
        this.simulateEvent(document, "mousemove", coord);
        coord = {
          clientX : x + dx,
          clientY : y + dy
        };
        var self = this;
        setTimeout(function() {
          self.simulateEvent(document, "mousemove", coord);
          self.simulateEvent(document, "mousemove", coord);
          self.simulateEvent(target, "mouseup", coord);
          self.simulateEvent(target, "click", coord);
        }, 200);
      }
    });
  })(jQuery);
  (function(j$, w$) {
    w$.softchalkcard = {};
    w$.softchalkcard._a = {};
    w$.softchalkcard.init = function(xml, params) {
      w$.softchalkcard._a[params.containerId] = new flashcard(params.containerId, j$(xml), params.width, params.height, params.backgroundColor);
    };
    var flashcard = function(id, xml, wwidth, hheight, pcolor) {
      var self = this;
      self.id = id;
      this.params = {
        bgcolor : pcolor || xml.find("color").text(),
        showterm : (xml.find("showterm").text() == "true"),
        showdef : (xml.find("showdef").text() == "true"),
        customDeckText : xml.find("customDeckText").text(),
        wholeDeckText : xml.find("wholeDeckText").text(),
        showText : xml.find("showText").text(),
        showCustomText : xml.find("addToText").text(),
        showTermText : xml.find("showTermText").text(),
        showDefText : xml.find("showDefText").text(),
        show_this : false,
        addcustom : false,
        showcustom : false,
        width : wwidth,
        height : hheight,
        bigtext : (xml.find("bigtext").length) ? (xml.find("bigtext").text() == "true") : false
      };
      this.params.bgcolor = "#" + this.params.bgcolor.replace(/#/g, "");
      this.cards = [];
      this.cards.current = 0;
      this.cards.refresh = function() {
        var c = 0;
        for (var i = 0, l = this.length; i < l; i++) {
          if (this[i].custom) {
            this[i].custom = ++c;
          }
        }
        this.customs = c;
      };
      xml.find("orderset").each(function() {
        self.cards.push({
          term : _parse_string.call(j$(this).find("term").text()),
          def : _parse_string.call(j$(this).find("def").text()),
          img : j$(this).find("image").text(),
          width : parseInt(j$(this).find("width").text()),
          height : parseInt(j$(this).find("height").text()),
          custom : false
        });
      });
      j$.shuffle(self.cards);
      _build_view(self);
    };
    var _build_view = function(self) {
      var _prm = self.params;
      var wrapper = j$("#" + self.id).css({
        width : _prm.width + "px",
        height : _prm.height + "px",
        background : _prm.bgcolor
      }).append($('<div class="sc-cards-bgimage"></div>').css({
        width : _prm.width + "px",
        height : _prm.height + "px"
      })).addClass("sc-cards-flashCard").click( function(self) {
        return function() {
          $("#inputf_" + self.id).focus();
        };
      }(self)).children(".sc-cards-bgimage");
      self.wrapper = wrapper;
      var skeleton = j$('<div><div style="height:' + 308 + 'px;"><table border="0" style="height:' + 308 + 'px;overflow:hidden;" cellpadding="0" cellspacing="0" width="' + _prm.width + '"><tr class="sc-cards-expression"><td colspan="2" style="overflow: hidden;"><div class="sc-cards-term"></div></td></tr><tr class="sc-cards-description-mode-bigtext-smallimage"><td colspan="2"><img src/></td></tr><tr class="sc-card-description-mode-all"><td class="sc-card-description-mode-all-img"><img class="sc-cards-img"/></td><td class="sc-card-description-mode-all-def"><div class="sc-cards-def"></div></td></tr></table></div></div><div style="height:30px"><div class="sc-cards-status"></div></div><div><table border="0" cellpadding="0" cellspacing="0" width="' + _prm.width + '"><tr height="60px"><td width="210px" style=""></td><td width="40px" style="cursor:pointer;"></td><td width="60px" style="cursor:pointer"></td><td width="40px" style="cursor:pointer;"></td><td width="200px" style=""></td></tr></table></div>');
      self.mode_bigtext_smallimage = skeleton.find(".sc-cards-description-mode-bigtext-smallimage");
      self.mode_bigtext_smallimage.img = self.mode_bigtext_smallimage.find("img");
      self.img = skeleton.find(".sc-card-description-mode-all-img .sc-cards-img").hide();
      self.def = skeleton.find(".sc-card-description-mode-all-def .sc-cards-def");
      self.term = skeleton.find(".sc-cards-expression .sc-cards-term").css({
        width : (_prm.width - 80) + "px"
      });
      self.status = skeleton.find(".sc-cards-status");
      self.def_holder = skeleton.find(".sc-card-description-mode-all-def");
      if (self.params.bigtext) {
        self.def_holder.addClass("sc-card-mode-big");
		self.term.addClass('sc-bigText');
      }
      self.showterm = j$('<div class="sc-cards-termText">' + _prm.showTermText + "</div>").data("checked", _prm.showterm).hover(_event_choice_hover_1, _event_choice_hover_2).click(function() {
        self._switch_showterm();
      }).addClass("sc-cards-no-select");
      if (_prm.showterm) {
        self.showterm.css({
          "background-position" : "0px -32px"
        });
      }
      self.showdef = j$('<div class="sc-cards-defText">' + _prm.showDefText + "</div>").css({
        "background-position" : "0px 0px"
      }).data("checked", _prm.showdef).hover(_event_choice_hover_1, _event_choice_hover_2).click(function() {
        self._switch_showdef();
      }).addClass("sc-cards-no-select");
      if (_prm.showdef) {
        self.showdef.css({
          "background-position" : "0px -32px"
        });
      } else {
        self._switch_showdef();
        self._switch_showdef();
      }
      self.addcustom = j$('<div class="sc-cards-customText">' + _prm.showCustomText + "</div>").data("checked", false).hover(_event_choice_hover_1, _event_choice_hover_2).click(function() {
        self._switch_addcustom();
      }).addClass("sc-cards-no-select");
      self.showcustom = $('<div class="sc-cards-customDeck">' + _prm.customDeckText + "</div>").css({}).data("checked", false).hover(_event_choice_hover_1, _event_choice_hover_2).click(function() {
        self._switch_showcustom();
      }).addClass("sc-cards-no-select").hide();
      skeleton.last().find("tr").children("td").eq(0).css({
        "vertical-align" : "top"
      }).append(self.showterm, self.showdef);
      skeleton.last().find("tr").children("td").eq(1).click(function() {
        self.prev();
      });
      skeleton.last().find("tr").children("td").eq(2).addClass("sc-cards-showText").append(_prm.showText).click(function() {
        self.show_this();
      }).addClass("sc-cards-no-select");
      skeleton.last().find("tr").children("td").eq(3).click(function() {
        self.next();
      });
      skeleton.last().find("tr").children("td").eq(4).css({
        "vertical-align" : "top"
      }).append(self.addcustom, self.showcustom);
      var inpC = $('<input class="sc-cards-key-handler" type="button" id="inputf_' + self.id + '"/>').focusin( function(self) {
        return function() {
          self.wrapper.addClass("sc-selectedQuestion");
        };
      }(self)).focusout( function(self) {
        return function() {
          self.wrapper.removeClass("sc-selectedQuestion");
        };
      }(self)).bind("keydown", {
        self : self
      }, self.handleKeys);
      wrapper.append(inpC);
      wrapper.append(skeleton);
      var contId = self.id;
      self.mode_bigtext_smallimage.dh = (parseInt(self.mode_bigtext_smallimage.find("td").css("padding-top")) || 0) + (parseInt(self.mode_bigtext_smallimage.find("td").css("padding-bottom")) || 0);
      self.update();
    };
    var _view_choice_switch = function(c) {
      var left = this[c].css("background-position").split(" ")[0];
      var h = (this.params[c]) ? -32 : -16;
      this[c].css({
        "background-position" : left + " " + h + "px"
      });
    };
    var _event_choice_hover_1 = function() {
      if (!j$(this).data("checked")) {
        var left = j$(this).css("background-position").split(" ")[0];
        j$(this).css({
          "background-position" : left + " -16px"
        });
      }
    };
    var _event_choice_hover_2 = function() {
      if (!j$(this).data("checked")) {
        var left = j$(this).css("background-position").split(" ")[0];
        j$(this).css({
          "background-position" : left + " 0px"
        });
      }
    };
    var _parse_string = function() {
      return decodeURIComponent(this.replace(/\+/gi, " "));
    };
    flashcard.prototype._switch_showterm = function() {
      this.params.showterm = !this.params.showterm;
      this.showterm.data("checked", this.params.showterm);
      this.term[this.params.showterm?"show":"hide"]();
      _view_choice_switch.call(this, "showterm");
    };
    flashcard.prototype._switch_showdef = function() {
      this.params.showdef = !this.params.showdef;
      this.showdef.data("checked", this.params.showdef);
      this.def[0].style.visibility = this.params.showdef ? "visible" : "hidden";
      if (this.mode_bigtext_smallimage.img.attr("src")) {
        this.mode_bigtext_smallimage.img[this.params.showdef?"show":"hide"]();
      } else {
        this.img[this.params.showdef?"show":"hide"]();
      }
      _view_choice_switch.call(this, "showdef");
    };
    flashcard.prototype._switch_addcustom = function() {
      var c = this.cards, o = c[c.current];
      o.custom = !o.custom;
      c.refresh();
      this.params.addcustom = o.custom;
      this.addcustom.data("checked", o.custom);
      _view_choice_switch.call(this, "addcustom");
      this.showcustom[c.customs?"show":"hide"]();
    };
    flashcard.prototype._switch_showcustom = function() {
      if (this.showcustom[0].style.display != "none") {
        this.params.showcustom = !this.params.showcustom;
        this.showcustom.data("checked", this.params.showcustom);
        _view_choice_switch.call(this, "showcustom");
        this.addcustom.css({
          visibility : (this.params.showcustom ? "hidden" : "visible")
        });
        this.cards.current = this.cards.length - 1;
        this.next();
        this.update();
      }
    };
    flashcard.prototype.next = function() {
      var c = this.cards;
      c.current++;
      if (c.current == c.length) {
        c.current = 0;
      }
      if (this.params.showcustom) {
        while (!c[c.current].custom) {
          c.current++;
          if (c.current == c.length) {
            c.current = 0;
          }
        }
      }
      this.update();
    };
    flashcard.prototype.prev = function() {
      var c = this.cards;
      c.current--;
      if (c.current < 0) {
        c.current = c.length - 1;
      }
      if (this.params.showcustom) {
        while (!c[c.current].custom) {
          c.current--;
          if (c.current < 0) {
            c.current = c.length - 1;
          }
        }
      }
      this.update();
    };
    flashcard.prototype.update = function() {
      if (this.params.show_this) {
        this.params.show_this = false;
        if (!this.params.showterm) {
          this.term.hide();
        }
        if (!this.params.showdef) {
          this.def[0].style.visibility = "hidden";
          this.img.hide();
          this.mode_bigtext_smallimage.img.hide();
        }
      }
      var c = this.cards, n = c.current, i = n + 1, len = c.length;
      if (this.params.showcustom) {
        i = c[n].custom;
        len = c.customs;
      }
      this.term.html(c[n].term);
      this.def.html(c[n].def || "&nbsp;");
      this.def_holder.removeClass("sc-card-mode-big-center sc-card-mode-big-middle");
      this.mode_bigtext_smallimage.hide();
      if (c[n].img) {
        this.img.parent().hide();
        if (this.params.bigtext && c[n].height < 100) {
          this.mode_bigtext_smallimage.img.attr({
            height : c[n].height + "px",
            width : c[n].width + "px",
            src : c[n].img
          });
          this.mode_bigtext_smallimage.css({
            height : c[n].height + "px"
          });
          this.mode_bigtext_smallimage.show();
          this.def_holder.addClass("sc-card-mode-big-center");
          var h = c[n].height + this.mode_bigtext_smallimage.dh;
          this.def_holder.css({
            height : (this.def_holder.height - h) + "px"
          });
          this.def.css({
            height : (this.def_holder.height - h) + "px"
          });
        } else {
          this.mode_bigtext_smallimage.img.attr("src", "");
          this.img.attr("src", c[n].img);
          this.img.parent().show();
          this.def_holder.css({
            height : this.def_holder.height + "px"
          });
          this.def.css({
            height : (this.def_holder.height - 10) + "px"
          });
        }
      } else {
        this.img.attr("src", "");
        this.mode_bigtext_smallimage.img.attr("src", "");
        this.img.parent().hide();
        this.def_holder.addClass("sc-card-mode-big-middle").css({
          height : this.def_holder.height + "px"
        });
        this.def.css({
          height : this.def_holder.height + "px"
        });
      }
      this.img[this.params.showdef?"show":"hide"]();
      if (this.params.bigtext && c[n].height < 100) {
        this.mode_bigtext_smallimage.img[this.params.showdef?"show":"hide"]();
      }
      if (this.params.showdef) {
        this.def[0].style.visibility = "visible";
      } else {
        this.def[0].style.visibility = "hidden";
      }
      if (!c[n].img) {
        this.img.hide();
      }
      this.status.html(i + " / " + len);
      this.params.addcustom = c[n].custom;
      this.addcustom.data("checked", c[n].custom);
      _view_choice_switch.call(this, "addcustom");
      this.addcustom.mouseout();
    };
    flashcard.prototype.handleKeys = function(e) {
      var self = e.data.self;
      switch(e.keyCode) {
        case 39:
          self.next();
          break;
        case 37:
          self.prev();
          break;
        case 74:
          if (e.altKey) {
            self._switch_showterm();
          }
          break;
        case 76:
          if (e.altKey) {
            self._switch_showdef();
          }
          break;
        case 77:
          if (e.altKey) {
            self._switch_addcustom();
          }
          break;
        case 75:
          if (e.altKey) {
            self._switch_showcustom();
          }
          break;
        case 13:
          self.show_this();
          break;
        default:
          return true;
      }
      e.preventDefault();
    };
    flashcard.prototype.show_this = function() {
      this.params.show_this = true;
      this.term.show();
      this.def[0].style.visibility = "visible";
      if (this.mode_bigtext_smallimage.img.attr("src")) {
        this.mode_bigtext_smallimage.img.show();
      } else {
        this.img.show();
      }
    };
    flashcard.prototype.reset = function() {
      return false;
    };
    flashcard.prototype.save_state = function() {
      var state = "";
      return state;
    };
    flashcard.prototype.load_state = function() {
      var state = arguments[0].split(";").reverse();
    };
    j$.shuffle = function(arr) {
      for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x) {
      }
    };
  })(jQuery, window);
  SCPTModel("DragNDrop", {
    defaults : {
      img : "",
      labels : [],
      startCoords : []
    }
  }, {
    init : function(jsonObj, params) {
      this._super(jsonObj, params, "dragndrop");
      this.matchset = jsonObj.matchset;
      for (var i = 0; i < this.matchset.length; i++) {
        this.matchset[i].left = this.decode(this.matchset[i].left);
        this.matchset[i].right = this.decode(this.matchset[i].right);
      }
      this.reinit();
    },
    reinit : function() {
      this._super();
      this.pointsArr = [];
      for (var i = 0; i < this.matchset.length; i++) {
        this.pointsArr.push(-2);
      }
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.pointsArr = jsonObj.innerState;
    },
    getState : function(jsonObj) {
      var obj = this._super();
      obj.innerState = this.pointsArr;
      return obj;
    }
  });
  SCPTController("DragNDrops", {}, {
    init : function() {
      var self = this;
      self.options.model.attempts++;
      var container = $("#" + this.options.model.containerId);
      this.options.model.randArrs = [];
      container.html(this.options.template, {
        labels : this.options.model.matchset,
        offsetTop : parseInt(container.offset().top, 10),
        id : this.options.model.containerId,
        color : this.options.model.backgroundColor,
        width : this.options.model.width,
        height : this.options.model.height,
        randArr : this.options.model.returnRandomOrder(this.options.model.matchset.length),
        bigText : this.options.model.isBigText == "true" ? "sc-bigText" : ""
      });
      this._super();
    },
    revert : function(dragId) {
      try {
        $("#" + this.options.model.getIdByIndex(dragId)).css({
          top : this.options.model.startCoords[dragId].y,
          left : this.options.model.startCoords[dragId].x
        });
      } catch(e) {
      }
    },
    bindEvents : function(self) {
      $("#"+self.options.model.containerId).find(".sc-dnd").bind("draginit", function(ev, drag) {
        $(this).css("zIndex", 1);
        return function() {
          if (!self.options.model.fromKeyBoard) {
            drag.revert();
          }
        }();
      }).bind("mousedown", function() {
        $(this).css("zIndex", 5);
      }).bind("mouseup", function() {
        $(this).css("zIndex", 1);
      }).bind("dragend", function(ev, drag) {
        $(drag).css("zIndex", 1);
        var dragId = drag.delegate.getAttribute("data-id");
        if (self.options.model.pointsArr[dragId] < 0) {
          self.revert(dragId);
        }
      });
      $("#"+self.options.model.containerId).find(".sc-dnd-dndTarget").each(function(index) {
        $(this).bind("dropon", function(ev, drop, drag) {
          var isTrue = 0;
          var dragId = drag.delegate.getAttribute("data-id");
          var dropId = drop.element[0].getAttribute("data-id");
          if (dragId == dropId) {
            isTrue = 1;
            drag.revert(false);
            drag.position(new jQuery.Vector($(drop.element[0]).offset().left, $(drop.element[0]).offset().top));
            $(drag.delegate).bind("draginit", function(ev, drag) {
              drag.cancel();
            });
          }
          if (isTrue) {
            if (self.options.model.pointsArr[dragId] == -2) {
              self.options.model.currentScore += isTrue;
            }
            self.options.model.pointsArr[dragId] = dropId;
          } else {
            self.options.model.pointsArr[dragId] = -1;
          }
          if (!isTrue) {
            self.revert(dragId);
            $(drag.delegate).css("zIndex", 1);
          }
          self.playIsCorrect(isTrue);
          self.updateStatus();
          var isCompleted = true;
          for (var i = 0, l = self.options.model.pointsArr.length; i < l; i++) {
            if (self.options.model.pointsArr[i] < 0) {
              isCompleted = false;
              break;
            }
          }
          if (isCompleted) {
            self.completed();
          }
        });
      });
      $("#restart_" + this.options.model.containerId).bind("click", function() {
        self.reset();
      });
    },
    updateStatus : function() {
      var pts = this.options.model.currentScore * (this.options.model.maxScore / this.options.model.pointsArr.length);
      pts = Math.round(10 * pts) / 10;
      $("#statusText_" + this.options.model.containerId).html( this.options.model.scoreText+" " + pts + "/" + this.options.model.maxScore);
    },
    showAnswer : function() {
      for (var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
        var target = $("#dndTarget_" + this.options.model.containerId + "_" + (i));
        $("#" + this.options.model.getIdByIndex(i)).css({
          left : target.css("left"),
          top : target.css("top")
        });
      }
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.updateStatus();
      for (var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
        if (this.options.model.pointsArr[i] > -1) {
          var target = $("#dndTarget_" + this.options.model.containerId + "_" + (i));
          $("#" + this.options.model.getIdByIndex(i)).css({
            left : target.css("left"),
            top : target.css("top")
          });
        }
      }
    }
  });
  SCPTModel("Hotspot", {}, {
    init : function(jsonObj, params) {
      var self = this;
      this._super(jsonObj, params, "hotspot");
      this.image = jsonObj.image;
      this.mask = jsonObj.mask;
      this.completedText = jsonObj.completedtext;
      this.correctText = jsonObj.correcttext;
      this.incorrectText = jsonObj.incorrecttext;
      this.skipText = jsonObj.skiptext || "Skip";
      this.mode = jsonObj.mode;
      this.hint = false;
      this.clue = jsonObj.useclue;
      this.image_clue = (jsonObj.clue) ? jsonObj.clue : "";
      this.image_data = ["ffffff", "ff0000", "ff00", "ff", "ff00ff", "ffff00", "ffff", "c0c0c0", "9d0de9", "be1326", "6b00", "69", "770000", "ff6800", "4f9acf", "ec00ff", "9900", "ffcc00", "666600", "6666", "804000"];
      this.canvas = null;
	  this.randArrs = {};
      this._wrapper_height = (this.mode == "quiz") ? 30 : 0;
      this.wwidth = jsonObj.width;
      this.wheight = jsonObj.height;
      this.task = [];
      this.task.find = function(color) {
        for (var i = this.length; i--; ) {
          if (this[i].color == color) {
            this.current = i;
            break;
          }
        }
      };
      this.reset_text = (jsonObj.resettext instanceof Array) ? jsonObj.resettext[0] : jsonObj.resettext;
      this._ready = false;
      this._overall = 1;
      if (this.clue == "true") {
        this._overall++;
      }

      
      this.pointsArr = [];
      for (var i = 21; i--; ) {
        var text = jsonObj["hs" + i];
        if(text + "" == text && text + "" != "[object Object]") {
          this.task.push({
            text : this.decode(text+""),
            color : self.image_data[i]
          });
        }
      }
	  this.reinit();
      this.task.currentIndex = 0;
      this.task.current = self.returnRandomOrder(self.task.length)[(self.task.currentIndex)];
      this.tooltip = this._bubble(parseInt(jsonObj.bubblestyle));
      this.workspace_p_h = params.height || 0;
      this.workspace_p_w = params.width || 0;
      this.workspace_i_h = 0;
      this.workspace_i_w = 0;
      this.image_paper = {};
      this.image_mask = new Image();
      this.image_mask.onload = function() {
        var canvas = document.createElement("canvas");
        canvas.width = self.image_mask.width;
        canvas.height = self.image_mask.height;
        self.workspace_i_h = this.height;
        self.workspace_i_w = this.width;
        var context = canvas.getContext("2d");
        context.drawImage(self.image_mask, 0, 0);
        self.image_paper.imageData = context.getImageData(0, 0, canvas.width, canvas.height);
        self.image_paper.task = self.task;
        self.image_paper.tooltip = self.tooltip;
        self._overall--;
        if (!self._overall) {
          self._ready = true;
        }
      };
      this.image_mask.src = this.mask;
      this.image_mask.qstn = self;
      if (this.clue == "true") {
        var _image_clue = new Image();
        _image_clue.onload = function() {
          self._overall--;
          if (!self._overall) {
            self._ready = true;
          }
        };
        _image_clue.src = this.image_clue;
      }

    },
    reinit : function() {
      this._super();
      this.pointsArr = [];
      for (var i = 0; i < this.task.length; i++) {
        this.pointsArr.push(-1);
      }
      this.randArrs = [];
      this.task.currentIndex = 0;
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.pointsArr = jsonObj.innerState;
    },
    getState : function(jsonObj) {
      var obj = this._super();
      obj.innerState = this.pointsArr;
      return obj;
    },
    rgb_to_hex : function(r, g, b) {
      if (r > 255 || g > 255 || b > 255) {
        return "ffffff";
      }
      return ((r << 16) | (g << 8) | b).toString(16);
    },
    _unbind : {
      quiz : function(image) {
        image.unbind("click");
      },
      explore : function(image) {
        image.unbind("mousemove");
      }
    },
    _get_image_data : function(crds, self) {
      var i = parseInt((crds.y * this.imageData.width + crds.x) * 4);
      var data = this.imageData.data;
      return self.rgb_to_hex(data[i], data[i + 1], data[i + 2]);
    },
    _get_coords : function(evt) {
      var posx = 0, posy = 0;
      evt = evt || w$.evt;
      if (evt.pageX || evt.pageY) {
        posx = evt.pageX;
        posy = evt.pageY;
      } else {
        if (evt.clientX || evt.clientY) {
          posx = evt.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
          posy = evt.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
      }
      if (evt.changedTouches) {
        posx = evt.changedTouches[0].pageX;
        posy = evt.changedTouches[0].pageY;
      }
      var offset = $(evt.target).offset();
      return {
        x : parseInt(posx - offset.left),
        y : parseInt(posy - offset.top)
      };
    },
    _bubble : function(num) {
      var model = this["_bubble_"+num]();
      var bubble = $(model.html);
      delete model.html;
      for (var i in model) {
        bubble[i] = model[i];
      }
      bubble.content = bubble.find("div.sc-hp-content");
      if (num != 9) {
        bubble.content.css("position", "absolute");
      }
      bubble._type = num;
      bubble.update = function(dh, dv) {
        var sx = (dh) ? "" : "-", sy = (dv) ? "-" : "", dx = (dh) ? 0 : this.w, dy = (dv) ? 0 : this.h, tx = (dh) ? this.tx_l : this.tx_r, ty = (dv) ? this.ty_t : this.ty_b;
        this.find("g").attr("transform", "matrix( " + sx + this.scale_x + ", 0, 0, " + sy + this.scale_y + ", " + dx + ", " + dy + ")");
        this.content.css({
          left : tx + "px",
          top : ty + "px"
        });
        return this;
      };
      return bubble;
    },
    _bubble_1 : function() {
      return {
        html : '<div class="sc-hp-tooltip" style="width:160px;height:80px"><style type="text/css"> .sc-hp-inner {width:100%;height:100%;border:1px solid #000000;background:#ffffff}</style><div class="sc-hp-inner"><div class="sc-hp-content" style="width:' + (160 - 10) + "px;height:" + (80 - 10) + 'px;border:0;paddin:0;margin:5px;"></div></div></div>',
        w : 160,
        h : 80,
        tx_l : 0,
        tx_r : 0,
        ty_b : 0,
        ty_t : 0,
        scale_x : 1,
        scale_y : 1
      };
    },
    _bubble_2 : function() {
      return {
        html : '<div class="sc-hp-tooltip" style="width:153px;height:58px"><?xml version="1.0" encoding="utf-8"?><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" style="width: 100%; height: 100%" xml:space="preserve"><style type="text/css"> .sc-hp-outer {fill:none;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:3;stroke:#333333;stroke-opacity:1} .sc-hp-inner {fill:#FFFFCC;fill-opacity:1}</style><g transform="matrix( 1, 0, 0, 1, 0, 0)"><path class="sc-hp-inner" d="M2 -2L7.3 -13.2L7.3 -49.5Q7.25 -57 14.6 -57L145.5 -57Q152.8 -57 152.85 -49.5L152.85 -13.2Q152.8 -5.7 145.5 -5.7L14.6 -5.7L2 -2" /><path class="sc-hp-outer" d="M14.6 -5.7L145.5 -5.7Q152.8 -5.7 152.85 -13.2L152.85 -49.5Q152.8 -57 145.5 -57L14.6 -57Q7.25 -57 7.3 -49.5L7.3 -13.2 M7.3 -13.2L2 -2L14.6 -5.7" /></g></svg><div class="sc-hp-content" style="top: 0px; left: 0px; width: 135px; height: 50px;"></div></div>',
        w : 153,
        h : 58,
        tx_l : 13,
        tx_r : 6,
        ty_b : 2,
        ty_t : 6,
        scale_x : 1,
        scale_y : 1
      };
    },
    _bubble_3 : function() {
      return {
        html : '<div class="sc-hp-tooltip" style="width:202px;height:80px"><?xml version="1.0" encoding="utf-8"?><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" style="width: 100%; height: 100%" xml:space="preserve"><style type="text/css"> .sc-hp-outer {fill:none;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:3;stroke:#000000;stroke-opacity:1} .sc-hp-inner {fill:#FFFFFF;fill-opacity:1}</style><g transform="matrix( 1, 0, 0, 1, 0, 0)"><path class="sc-hp-inner" d="M162.4 -65.75L167.55 -66Q181.15 -66 190.8 -60.5Q200.4 -55 200.4 -47.25Q200.4 -39.5 190.8 -34L187.8 -32.45L188.15 -29.35Q188.15 -20.1 176.7 -13.55Q165.2 -7 149.05 -7Q136.8 -7 127.25 -10.75Q117.15 -7.85 105.05 -7.85Q85.75 -7.85 71.8 -15.1Q67.1 -14 61.6 -14Q50.15 -14 42.15 -18.65Q33.95 -23.25 34 -29.75Q34 -33.45 36.65 -36.55L34.95 -37.5Q27.1 -41.95 27.1 -48.25Q27.1 -54.55 34.95 -59.05Q42.75 -63.5 53.8 -63.5L61.15 -62.95Q62.55 -67.35 68.5 -70.75Q76.2 -75.15 87.15 -75.15Q97.4 -75.15 104.9 -71.25Q106.4 -72.5 108.4 -73.6Q117.85 -79 131.25 -79Q144.65 -79 154.2 -73.6Q160.2 -70.15 162.4 -65.75" /><path class="sc-hp-outer" d="M154.2 -73.6Q144.65 -79 131.25 -79Q117.85 -79 108.4 -73.6Q106.4 -72.5 104.9 -71.25Q97.4 -75.15 87.15 -75.15Q76.2 -75.15 68.5 -70.75Q62.55 -67.35 61.15 -62.95L53.8 -63.5Q42.75 -63.5 34.95 -59.05Q27.1 -54.55 27.1 -48.25Q27.1 -41.95 34.95 -37.5L36.65 -36.55Q34 -33.45 34 -29.75Q33.95 -23.25 42.15 -18.65Q50.15 -14 61.6 -14Q67.1 -14 71.8 -15.1Q85.75 -7.85 105.05 -7.85Q117.15 -7.85 127.25 -10.75Q136.8 -7 149.05 -7Q165.2 -7 176.7 -13.55Q188.15 -20.1 188.15 -29.35L187.8 -32.45L190.8 -34Q200.4 -39.5 200.4 -47.25Q200.4 -55 190.8 -60.5Q181.15 -66 167.55 -66L162.4 -65.75Q160.2 -70.15 154.2 -73.6z" /><path class="sc-hp-inner" d="M9.65 -5.5Q9.65 -4.6 8.8 -4Q8 -3.35 6.85 -3.35Q5.65 -3.35 4.75 -4Q4 -4.6 4 -5.5Q4 -6.4 4.75 -7.05Q5.65 -7.65 6.85 -7.65Q8 -7.65 8.8 -7.05Q9.65 -6.4 9.65 -5.5" /><path class="sc-hp-outer" d="M9.65 -5.5Q9.65 -4.6 8.8 -4Q8 -3.35 6.85 -3.35Q5.65 -3.35 4.75 -4Q4 -4.6 4 -5.5Q4 -6.4 4.75 -7.05Q5.65 -7.65 6.85 -7.65Q8 -7.65 8.8 -7.05Q9.65 -6.4 9.65 -5.5z" /><path class="sc-hp-inner" d="M12.4 -13.7Q13.65 -14.65 15.45 -14.65Q17.2 -14.65 18.45 -13.7Q19.75 -12.75 19.75 -11.4Q19.75 -10.05 18.45 -9.1Q17.2 -8.15 15.45 -8.15Q13.65 -8.15 12.4 -9.1Q11.15 -10.05 11.15 -11.4Q11.15 -12.75 12.4 -13.7" /><path class="sc-hp-outer" d="M12.4 -13.7Q13.65 -14.65 15.45 -14.65Q17.2 -14.65 18.45 -13.7Q19.75 -12.75 19.75 -11.4Q19.75 -10.05 18.45 -9.1Q17.2 -8.15 15.45 -8.15Q13.65 -8.15 12.4 -9.1Q11.15 -10.05 11.15 -11.4Q11.15 -12.75 12.4 -13.7z" /><path class="sc-hp-inner" d="M36.4 -15.75Q36.2 -13.05 33.7 -11.95Q31.2 -10.85 27.95 -12.05Q26.5 -12.6 25.3 -13.45Q23.75 -14.55 22.6 -16.1Q21.3 -17.7 20.85 -19.25Q20.45 -20.5 20.6 -21.7Q20.85 -24.45 23.35 -25.5Q25.8 -26.6 29.05 -25.4Q32.35 -24.2 34.55 -21.35Q36.65 -18.5 36.4 -15.75" /><path class="sc-hp-outer" d="M36.4 -15.75Q36.2 -13.05 33.7 -11.95Q31.2 -10.85 27.95 -12.05Q26.5 -12.6 25.3 -13.45Q23.75 -14.55 22.6 -16.1Q21.3 -17.7 20.85 -19.25Q20.45 -20.5 20.6 -21.7Q20.85 -24.45 23.35 -25.5Q25.8 -26.6 29.05 -25.4Q32.35 -24.2 34.55 -21.35Q36.65 -18.5 36.4 -15.75z" /></g></svg><div class="sc-hp-content" style="top: 0px; left: 0px; width: 135px; height: 50px;"></div></div>',
        w : 202,
        h : 80,
        tx_l : 44,
        tx_r : 22,
        ty_b : 16,
        ty_t : 15,
        scale_x : 1,
        scale_y : 1
      };
    },
    _bubble_4 : function() {
      return {
        html : '<div class="sc-hp-tooltip" style="width:212px;height:71px"><?xml version="1.0" encoding="utf-8"?><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" style="width: 100%; height: 100%" xml:space="preserve"><style type="text/css"> .sc-hp-outer {fill:none;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:3;stroke:#000000;stroke-opacity:1} .sc-hp-inner {fill:#FFFFFF;fill-opacity:1}</style><g transform="matrix( 1, 0, 0, 1, 0, 0)"><path class="sc-hp-inner" d="M40 -13.55L0 -0.3L27.9 -18.1L28.4 -18.05L13.9 -18.8L19.25 -23.15L5.5 -24.85L13.4 -28.75L0.9 -31.25L11.1 -34.65L0.35 -37.85L12.45 -40.55L3.9 -44.35L17.3 -46.2L11.25 -50.5L25.55 -51.5L22.25 -56.1L36.9 -56.15L36.4 -60.9L50.85 -60.05L53.2 -64.65L66.8 -63L72 -67.4L84.3 -64.85L92.05 -68.85L102.6 -65.6L112.65 -69L121 -65.2L132.9 -67.9L138.8 -63.6L152.1 -65.5L155.3 -60.95L169.55 -62L169.85 -57.35L184.55 -57.5L181.9 -52.85L196.4 -52.1L191.05 -47.75L204.8 -46.05L196.9 -42.15L209.4 -39.65L199.2 -36.25L209.95 -33.05L197.85 -30.4L206.5 -26.55L193 -24.7L199.05 -20.4L184.75 -19.4L188.1 -14.8L173.45 -14.75L173.9 -10L159.5 -10.85L157.1 -6.25L143.5 -7.9L138.3 -3.5L126.05 -6.05L118.25 -2.05L107.7 -5.35L97.7 -1.9L89.3 -5.8L77.4 -3L71.55 -7.3L58.2 -5.4L55 -9.95L40.75 -8.9L40.5 -13.55L40 -13.55M28.4 -18.05L27.9 -18.1" /><path class="sc-hp-outer" d="M40 -13.55L0 -0.3L27.9 -18.1L13.9 -18.8L19.25 -23.15L5.5 -24.85L13.4 -28.75L0.9 -31.25L11.1 -34.65L0.35 -37.85L12.45 -40.55L3.9 -44.35L17.3 -46.2L11.25 -50.5L25.55 -51.5L22.25 -56.1L36.9 -56.15L36.4 -60.9L50.85 -60.05L53.2 -64.65L66.8 -63L72 -67.4L84.3 -64.85L92.05 -68.85L102.6 -65.6L112.65 -69L121 -65.2L132.9 -67.9L138.8 -63.6L152.1 -65.5L155.3 -60.95L169.55 -62L169.85 -57.35L184.55 -57.5L181.9 -52.85L196.4 -52.1L191.05 -47.75L204.8 -46.05L196.9 -42.15L209.4 -39.65L199.2 -36.25L209.95 -33.05L197.85 -30.4L206.5 -26.55L193 -24.7L199.05 -20.4L184.75 -19.4L188.1 -14.8L173.45 -14.75L173.9 -10L159.5 -10.85L157.1 -6.25L143.5 -7.9L138.3 -3.5L126.05 -6.05L118.25 -2.05L107.7 -5.35L97.7 -1.9L89.3 -5.8L77.4 -3L71.55 -7.3L58.2 -5.4L55 -9.95L40.75 -8.9L40.5 -13.55 M28.4 -18.05L27.9 -18.1" /></g></svg><div class="sc-hp-content" style="top: 0px; left: 0px; width: 120px; height: 50px;"></div></div>',
        w : 212,
        h : 71,
        tx_l : 44,
        tx_r : 48,
        ty_b : 10,
        ty_t : 10,
        scale_x : 1,
        scale_y : 1
      };
    },
    _bubble_5 : function() {
      return {
        html : '<div class="sc-hp-tooltip" style="width:155px;height:81px"><?xml version="1.0" encoding="utf-8"?><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" style="width: 100%; height: 100%" xml:space="preserve"><style type="text/css"> .sc-hp-outer {fill:#000000;fill-opacity:1} .sc-hp-inner {fill:#ffffff;fill-opacity:1}</style><g transform="matrix( 0.7, 0, 0, 0.7, 0, 0)"><path class="sc-hp-outer" d="M29.65 -107.35Q118.3 -122 206.95 -107.35L207.25 -107.2L207.45 -106.95Q229.55 -61.9 207.45 -16.8L207.25 -16.6L206.95 -16.45Q112.9 -0.75 29.9 -16.4L3.05 -1.55L2.55 -1.5L2.15 -1.75L2.05 -2.3L2.25 -2.8L25.4 -29.05Q15.25 -67.95 29.1 -106.85L29.35 -107.2L29.65 -107.35M25.85 -27.3L6.15 -5.05L29.45 -17.9L29.55 -17.95L29.85 -18Q112.65 -2.4 206.45 -17.95Q227.85 -61.9 206.45 -105.8Q118.35 -120.35 30.25 -105.85Q16.75 -67.45 26.85 -29.05L26.8 -28.45L26.4 -28.05L25.85 -28.1L25.5 -28.6L25.85 -27.3" /><path class="sc-hp-inner" d="M25.5 -28.6L25.85 -28.1L26.4 -28.05L26.8 -28.45L26.85 -29.05Q16.75 -67.45 30.25 -105.85Q118.35 -120.35 206.45 -105.8Q227.85 -61.9 206.45 -17.95Q112.65 -2.4 29.85 -18L29.55 -17.95L29.45 -17.9L6.15 -5.05L25.85 -27.3L25.5 -28.6" /></g></svg><div class="sc-hp-content" style="top: 0px; left: 0px; width: 120px; height: 60px;"></div></div>',
        w : 155,
        h : 81,
        tx_l : 23,
        tx_r : 13,
        ty_b : 8,
        ty_t : 13,
        scale_x : 0.7,
        scale_y : 0.7
      };
    },
    _bubble_6 : function() {
      return {
        html : '<div class="sc-hp-tooltip" style="width:189px;height:76px"><?xml version="1.0" encoding="utf-8"?><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" style="width: 100%; height: 100%" xml:space="preserve"><style type="text/css"> .sc-hp-outer {fill:none;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:3;stroke:#000000;stroke-opacity:1} .sc-hp-inner {fill:#ffffff;fill-opacity:1}</style><g transform="matrix( 1, 0, 0, 1, 0, 0)"><path class="sc-hp-inner" d="M 187.9 -75.5 Q 165.65 -42.4 171.95 -1.6 Q 92.15 -17.45 1 -8.05 Q 20.9 -36.95 12.4 -60.5 Q 102.15 -62.4 187.9 -75.5" /><path class="sc-hp-outer" d="M 187.9 -75.5 Q 165.65 -42.4 171.95 -1.6 Q 92.15 -17.45 1 -8.05 Q 20.9 -36.95 12.4 -60.5 Q 102.15 -62.4 187.9 -75.5" /></g></svg><div class="sc-hp-content" style="top: 0px; left: 0px; width: 150px; height: 50px;"></div></div>',
        w : 189,
        h : 76,
        tx_l : 16,
        tx_r : 20,
        ty_b : 15,
        ty_t : 10,
        scale_x : 1,
        scale_y : 1
      };
    },
    _bubble_7 : function() {
      return {
        html : '<div class="sc-hp-tooltip" style="width:197px;height:75px"><?xml version="1.0" encoding="utf-8"?><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" style="width: 100%; height: 100%" xml:space="preserve"><style type="text/css"> .sc-hp-outer {fill:#000000;fill-opacity:1} .sc-hp-inner {fill:#ffffff;fill-opacity:1}</style><g transform="matrix( 1, 0, 0, 1, 0, 0)"><path class="sc-hp-inner" d="M74.2 -71.15L80.4 -72Q80.45 -71.75 80.65 -71.6Q80.8 -71.4 81.05 -71.45L88.5 -72.2L88.95 -72.4L89.05 -72.9L95.2 -73.25Q95.2 -73 95.45 -72.85Q95.55 -72.7 95.85 -72.7L103.25 -72.95Q103.5 -72.95 103.65 -73.15L103.85 -73.6L108.65 -73.65L110.35 -73.65L110.55 -73.2Q110.75 -73 111 -73L118.6 -72.85L119.05 -72.95L119.2 -73.4L125.45 -73.1L125.45 -73L125.65 -72.6Q125.8 -72.4 126.1 -72.4L133.5 -71.75L134 -71.9L134.2 -72.35L140.45 -71.5Q140.4 -71.25 140.6 -71.1Q140.7 -70.9 141 -70.85L148.3 -69.6L148.8 -69.7L149.05 -70.1L155.25 -68.75Q155.15 -68.55 155.3 -68.3Q155.45 -68.05 155.7 -68L162.85 -66.05L163.35 -66.15L163.7 -66.5L169.7 -64.55L169.7 -64.5Q169.55 -64.25 169.7 -64L170.05 -63.7L171.2 -63.3L177.35 -60.8L177.85 -60.75L178.15 -61.1L184 -58.1Q183.8 -57.9 183.9 -57.65L184.15 -57.3Q187.65 -55.2 190.25 -52.95L190.65 -52.85Q190.85 -52.85 191.05 -53.05Q193.6 -50.7 195.1 -48.15L194.85 -47.75Q194.7 -47.6 194.9 -47.35Q196.7 -44 196.7 -40.45L196.9 -40Q197.1 -39.8 197.35 -39.8Q197.3 -37.75 196.6 -35.8L196.1 -35.8L195.8 -35.4Q194.55 -32.35 191.85 -29.55L191.65 -29.1L191.85 -28.65L191.9 -28.6Q189.85 -26.65 187.15 -24.7L186.75 -25L186.3 -24.9L180 -21.3L179.65 -20.95L179.65 -20.45L174.2 -18L174.1 -18.05L173.8 -18.35L173.3 -18.35L171.2 -17.5L167.1 -16.05L166.75 -15.75Q166.6 -15.55 166.75 -15.3L160.75 -13.5L160.45 -13.8L160 -13.85L152.75 -12.15Q152.5 -12.1 152.4 -11.85L152.25 -11.4L146.15 -10.25L145.9 -10.6L145.45 -10.75L138 -9.6L137.6 -9.35L137.45 -8.9L131.2 -8.2L131 -8.55L130.5 -8.7L123.1 -8.2Q122.8 -8.2 122.65 -7.95L122.45 -7.6L116.2 -7.3L116.05 -7.7L115.6 -7.9L108.65 -7.85L108.15 -7.85L107.75 -7.65L107.55 -7.2L101.15 -7.3L101.05 -7.8L100.6 -7.95L93.05 -8.3Q92.75 -8.3 92.6 -8.1L92.35 -7.7L86.05 -8.2L85.95 -8.65L85.5 -8.9L78 -9.8L77.5 -9.65L77.25 -9.2L71.05 -10.25L70.95 -10.65L70.55 -11L63.15 -12.5L62.7 -12.35L62.4 -12L56.35 -13.55L56.25 -14.05L55.9 -14.3L51.95 -15.5L51.85 -15.5L51.6 -15.6L50.25 -15.25L49.4 -15L49.55 -14.95L45.7 -13.8L45.35 -13.5L45.35 -13.4L39.15 -11.5L38.95 -11.65L38.45 -11.65L31.25 -9.55L30.85 -9.3L30.8 -8.9L24.75 -7.1L24.5 -7.4L24 -7.4L16.75 -5.25L16.35 -5L16.35 -4.5L10.3 -2.7L10.3 -2.75L10 -3.15L9.5 -3.15L7.5 -2.6L11.35 -4.75L11.7 -5.15L11.7 -5.4L17.2 -8.55L17.5 -8.35L17.95 -8.4L24.4 -12.15L24.75 -12.55L24.65 -12.9L30.05 -16.1L30.1 -16.05L30.5 -15.75L30.9 -15.8L37.4 -19.45L37.65 -19.75L37.7 -19.7L37.95 -20.5L38.1 -20.95L34.35 -22.9L33.85 -22.9L33.55 -22.65L29.3 -25.4L28.25 -26.15L28.35 -26.65L28.15 -27.1Q24.9 -29.7 23.1 -32.45L22.65 -32.8L22.25 -32.65Q20.5 -35.6 20.1 -38.7Q20.35 -38.75 20.55 -38.95L20.65 -39.35L20.6 -40.45Q20.6 -43.45 21.9 -46.25L22 -46.7L21.6 -47.1Q22.9 -49.65 25.3 -52.05Q25.5 -51.85 25.75 -51.85Q26 -51.85 26.15 -52.05Q28.5 -54.3 31.85 -56.4L32.1 -56.85L32.05 -57.3Q34.4 -58.8 37.3 -60.25L37.3 -60.2L37.65 -59.85L38.15 -59.9Q41.2 -61.45 44.85 -62.8L45.15 -63.2L45.2 -63.6L45.95 -63.95L51.45 -65.8Q51.5 -65.55 51.75 -65.45L52.2 -65.4L59.25 -67.4L59.65 -67.7L59.7 -68.15L59.7 -68.2L65.65 -69.6L65.95 -69.15L66.4 -69.05L73.7 -70.45L74.05 -70.7L74.2 -71.15" /><path class="sc-hp-outer" d="M103.65 -73.15Q103.5 -72.95 103.25 -72.95L95.85 -72.7Q95.55 -72.7 95.45 -72.85Q95.2 -73 95.2 -73.25Q95.2 -73.6 95.35 -73.7L95.8 -73.95L103.25 -74.2L103.65 -74.05L103.85 -73.6L103.65 -73.15M119.05 -72.95L118.6 -72.85L111 -73Q110.75 -73 110.55 -73.2L110.35 -73.65L110.55 -74.1Q110.75 -74.3 111 -74.3L118.65 -74.1L119.1 -73.9L119.2 -73.4L119.05 -72.95M134 -71.9L133.5 -71.75L126.1 -72.4Q125.8 -72.4 125.65 -72.6L125.45 -73L125.45 -73.1L125.7 -73.45L126.15 -73.65L133.65 -73L134.1 -72.75L134.2 -72.35L134 -71.9M148.8 -69.7L148.3 -69.6L141 -70.85Q140.7 -70.9 140.6 -71.1Q140.4 -71.25 140.45 -71.5L140.7 -71.95L141.2 -72.1L148.55 -70.85L148.95 -70.5L149.05 -70.1L148.8 -69.7M163.35 -66.15L162.85 -66.05L155.7 -68Q155.45 -68.05 155.3 -68.3Q155.15 -68.55 155.25 -68.75L155.5 -69.15L156 -69.2Q159.7 -68.4 163.25 -67.25L163.6 -66.95L163.7 -66.5L163.35 -66.15M177.85 -60.75L177.35 -60.8L171.2 -63.3L170.05 -63.7L169.7 -64Q169.55 -64.25 169.7 -64.5L169.7 -64.55L170 -64.9L170.45 -64.9L171.55 -64.5L171.6 -64.5L177.85 -61.95L178.25 -61.55L178.15 -61.1L177.85 -60.75M190.65 -52.85L190.25 -52.95Q187.65 -55.2 184.15 -57.3L183.9 -57.65Q183.8 -57.9 184 -58.1L184 -58.15L184.35 -58.4L184.8 -58.35Q188.4 -56.25 191.05 -53.9L191.25 -53.45L191.1 -53.05L191.05 -53.05Q190.85 -52.85 190.65 -52.85M196.9 -40L196.7 -40.45Q196.7 -44 194.9 -47.35Q194.7 -47.6 194.85 -47.75L195.1 -48.15L195.6 -48.2L195.95 -47.95Q197.95 -44.4 197.95 -40.45L197.8 -40L197.35 -39.8Q197.1 -39.8 196.9 -40M191.85 -28.65L191.65 -29.1L191.85 -29.55Q194.55 -32.35 195.8 -35.4L196.1 -35.8L196.6 -35.8L196.9 -35.5L196.95 -35Q195.65 -31.7 192.7 -28.65L192.3 -28.45Q192.05 -28.45 191.9 -28.6L191.85 -28.65M179.65 -20.95L180 -21.3L186.3 -24.9L186.75 -25L187.15 -24.7L187.25 -24.25L187 -23.85Q184.1 -21.95 180.55 -20.2L180.05 -20.15L179.65 -20.45L179.65 -20.95M166.75 -15.75L167.1 -16.05L171.2 -17.5L173.3 -18.35L173.8 -18.35L174.1 -18.05L174.2 -18L174.1 -17.55L173.8 -17.25L171.6 -16.3L167.5 -14.85L167.05 -14.95L166.75 -15.3Q166.6 -15.55 166.75 -15.75M152.4 -11.85Q152.5 -12.1 152.75 -12.15L160 -13.85L160.45 -13.8L160.75 -13.5L160.75 -13.4L160.7 -13Q160.5 -12.75 160.3 -12.65L153 -10.9L152.55 -11L152.25 -11.4L152.4 -11.85M137.6 -9.35L138 -9.6L145.45 -10.75L145.9 -10.6L146.15 -10.25L146.15 -10.15L146 -9.7L145.65 -9.45L138.2 -8.35L137.7 -8.45L137.45 -8.85L137.45 -8.9L137.6 -9.35M122.65 -7.95Q122.8 -8.2 123.1 -8.2L130.5 -8.7L131 -8.55L131.2 -8.2L131.2 -8.15L131.1 -7.65Q130.9 -7.45 130.65 -7.45L123.15 -6.95Q122.85 -6.95 122.7 -7.1L122.45 -7.55L122.45 -7.6L122.65 -7.95M107.75 -7.65L108.15 -7.85L108.65 -7.85L115.6 -7.9L116.05 -7.7L116.2 -7.3L116.05 -6.85L115.6 -6.65L108.65 -6.6L108.15 -6.6Q107.9 -6.6 107.75 -6.8L107.55 -7.2L107.75 -7.65M92.6 -8.1Q92.75 -8.3 93.05 -8.3L100.6 -7.95L101.05 -7.8L101.15 -7.3L101 -6.85L100.55 -6.7L93 -7.05Q92.7 -7.05 92.55 -7.2L92.35 -7.65L92.35 -7.7L92.6 -8.1M77.5 -9.65L78 -9.8L85.5 -8.9L85.95 -8.65L86.05 -8.2L85.85 -7.8L85.35 -7.65L77.8 -8.55L77.4 -8.8Q77.2 -8.95 77.25 -9.2L77.5 -9.65M62.7 -12.35L63.15 -12.5L70.55 -11L70.95 -10.65L71.05 -10.25L70.8 -9.85L70.3 -9.7L62.9 -11.25L62.5 -11.5L62.4 -12L62.7 -12.35M45.35 -13.5L45.7 -13.8L49.55 -14.95L49.4 -15L50.25 -15.25L51.6 -15.6L51.85 -15.5L51.95 -15.5L55.9 -14.3L56.25 -14.05L56.35 -13.55L56 -13.15L55.6 -13.1Q53.45 -13.65 51.45 -14.3L51.15 -14.4L51.1 -14.3L50.7 -14L46.1 -12.6L45.65 -12.65L45.35 -13.05Q45.2 -13.25 45.35 -13.4L45.35 -13.5M30.85 -9.3L31.25 -9.55L38.45 -11.65L38.95 -11.65L39.15 -11.5L39.3 -11.3L39.2 -10.8L38.85 -10.5L31.6 -8.35L31.1 -8.4L30.85 -8.8L30.8 -8.9L30.85 -9.3M16.35 -5L16.75 -5.25L24 -7.4L24.5 -7.4L24.75 -7.1L24.8 -7.05L24.75 -6.55L24.35 -6.2L17.1 -4.1L16.6 -4.15L16.35 -4.5L16.35 -5M11.7 -5.15L11.35 -4.75L7.5 -2.6L9.5 -3.15L10 -3.15L10.3 -2.75L10.3 -2.7L10.25 -2.25L9.85 -1.95L2.7 0.2L2.25 0.1L1.95 -0.25Q1.8 -0.5 1.95 -0.7L2.3 -1L4.35 -1.65L4.35 -1.95L4.6 -2.35L10.75 -5.85L11.25 -5.9L11.6 -5.65L11.7 -5.4L11.7 -5.15M24.75 -12.55L24.4 -12.15L17.95 -8.4L17.5 -8.35L17.2 -8.55L17.1 -8.65Q16.95 -8.9 17.05 -9.1L17.3 -9.45L23.8 -13.25L24.3 -13.3L24.65 -13.05L24.65 -12.9L24.75 -12.55M33.85 -22.9L34.35 -22.9L38.1 -20.95L37.95 -20.5L37.7 -19.7L37.65 -19.75L37.4 -19.45L30.9 -15.8L30.5 -15.75L30.1 -16.05L30.05 -16.1L30.05 -16.5L30.3 -16.85L36.45 -20.3L33.75 -21.75L33.5 -22.15Q33.35 -22.4 33.55 -22.65L33.85 -22.9M22.65 -32.8L23.1 -32.45Q24.9 -29.7 28.15 -27.1L28.35 -26.65L28.25 -26.15L27.8 -25.95L27.35 -26.1Q23.9 -28.85 22.05 -31.8L21.9 -32.3L22.25 -32.65L22.65 -32.8M22 -46.7L21.9 -46.25Q20.6 -43.45 20.6 -40.45L20.65 -39.35L20.55 -38.95Q20.35 -38.75 20.1 -38.7L19.65 -38.8L19.4 -39.25L19.35 -40.45Q19.35 -43.7 20.8 -46.75L21.15 -47.1L21.6 -47.1L22 -46.7M32.1 -56.85L31.85 -56.4Q28.5 -54.3 26.15 -52.05Q26 -51.85 25.75 -51.85Q25.5 -51.85 25.3 -52.05L25.1 -52.45L25.3 -52.9Q27.75 -55.3 31.15 -57.5L31.6 -57.6L32.05 -57.3L32.1 -56.85M45.15 -63.2L44.85 -62.8Q41.2 -61.45 38.15 -59.9L37.65 -59.85L37.3 -60.2L37.3 -60.25Q37.15 -60.5 37.3 -60.7L37.6 -61.05L44.4 -64L44.85 -64L45.2 -63.6L45.15 -63.2M59.7 -68.15L59.65 -67.7L59.25 -67.4L52.2 -65.4L51.75 -65.45Q51.5 -65.55 51.45 -65.8L51.45 -66.25L51.85 -66.55L58.95 -68.55L59.4 -68.5L59.7 -68.2L59.7 -68.15M74.05 -70.7L73.7 -70.45L66.4 -69.05L65.95 -69.15L65.65 -69.6Q65.55 -69.85 65.75 -70L66.15 -70.35L73.5 -71.7L73.95 -71.6L74.2 -71.15L74.05 -70.7M88.95 -72.4L88.5 -72.2L81.05 -71.45Q80.8 -71.4 80.65 -71.6Q80.45 -71.75 80.4 -72Q80.3 -72.25 80.5 -72.45L80.95 -72.7L88.35 -73.45L88.85 -73.25L89.05 -72.9L88.95 -72.4" /></g></svg><div class="sc-hp-content" style="top: 0px; left: 0px; width: 120px; height: 50px;"></div></div>',
        w : 197,
        h : 75,
        tx_l : 45,
        tx_r : 30,
        ty_b : 10,
        ty_t : 15,
        scale_x : 1,
        scale_y : 1
      };
    },
    _bubble_8 : function() {
      return {
        html : '<div class="sc-hp-tooltip" style="width:221px;height:117px"><?xml version="1.0" encoding="utf-8"?><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" style="width: 100%; height: 100%" xml:space="preserve"><style type="text/css"> .sc-hp-outer {fill:#000000;fill-opacity:1} .sc-hp-inner {fill:#ffffff;fill-opacity:1}</style><g transform="matrix( 1, 0, 0, 1, 0, 0)"><path class="sc-hp-outer" d="M29.65 -107.35Q118.3 -122 206.95 -107.35L207.25 -107.2L207.45 -106.95Q229.55 -61.9 207.45 -16.8L207.25 -16.6L206.95 -16.45Q112.9 -0.75 29.9 -16.4L3.05 -1.55L2.55 -1.5L2.15 -1.75L2.05 -2.3L2.25 -2.8L25.4 -29.05Q15.25 -67.95 29.1 -106.85L29.35 -107.2L29.65 -107.35M25.85 -27.3L6.15 -5.05L29.45 -17.9L29.55 -17.95L29.85 -18Q112.65 -2.4 206.45 -17.95Q227.85 -61.9 206.45 -105.8Q118.35 -120.35 30.25 -105.85Q16.75 -67.45 26.85 -29.05L26.8 -28.45L26.4 -28.05L25.85 -28.1L25.5 -28.6L25.85 -27.3" /><path class="sc-hp-inner" d="M25.5 -28.6L25.85 -28.1L26.4 -28.05L26.8 -28.45L26.85 -29.05Q16.75 -67.45 30.25 -105.85Q118.35 -120.35 206.45 -105.8Q227.85 -61.9 206.45 -17.95Q112.65 -2.4 29.85 -18L29.55 -17.95L29.45 -17.9L6.15 -5.05L25.85 -27.3L25.5 -28.6" /></g></svg><div class="sc-hp-content" style="top: 0px; left: 0px; width: 180px; height: 85px;"></div></div>',
        w : 221,
        h : 117,
        tx_l : 28,
        tx_r : 13,
        ty_b : 13,
        ty_t : 20,
        scale_x : 1,
        scale_y : 1
      };
    },
    _bubble_9 : function() {
      return {
        html : '<div class="sc-hp-tooltip" style="width:100%;bottom:-50px;"><table style="width:100%"><tr><td align="center"><div class="sc-hp-content" style="border:1px solid #000000;background:#ffffff;padding:5px;margin:0;"></div></td></tr></table></div>',
        w : 0,
        h : 0,
        tx_l : 0,
        tx_r : 0,
        ty_b : 0,
        ty_t : 0,
        scale_x : 0,
        scale_y : 0
      };
    }
  });
  SCPTController("Hotspots", {}, {
    init : function() {
      var self = this, _super = self._super;
      if (this.options.model._ready) {
        self._start.call(self);
      } else {
        setTimeout(function() {
          self.init.call(self);
        }, 50);
      }
    },
    _start : function() {
      var self = this, model = self.options.model;
      self.options.model.attempts++;
      var container = $("#" + model.containerId).removeClass("hotspots").addClass("sc-hp-hotspots");
      if (model.attempts == 1) {
        container.html(this.options.template, {
          offsetTop : parseInt(container.offset().top, 10),
          id : model.containerId,
          color : model.backgroundColor,
          width : model.width,
          height : model.height,
          mode : model.mode
        });
        container.find(".sc-hp-mainDiv").css({
          border : "1px solid " + getMixedColor("#3c3c3c", model.backgroundColor, 0.5),
        });


//language
        container.find(".sc-hp-skip").html(self.options.model.skipText);
        $("#restart_" + self.options.model.containerId ).html(self.options.model.restartText);
        $("#finish_" + self.options.model.containerId ).html(self.options.model.finishText);
        var img_wrapper = container.find(".sc-hp-workspace .sc-hp-wrapper");
        var p_top = parseInt(img_wrapper.css("padding-top")) || 0;
        var p_left = parseInt(img_wrapper.css("padding-left")) || 0;
        var p_right = parseInt(img_wrapper.css("padding-right")) || 0;
        var p_bottom = parseInt(img_wrapper.css("padding-bottom")) || 0;
        var max_h = Math.max((model.workspace_p_h), (p_top + model.workspace_i_h + p_bottom));
        var max_w = Math.max((model.workspace_p_w), (p_left + model.workspace_i_w + p_right)) - p_left - p_right;
        img_wrapper.css({
          width : max_w + "px",
          height : model.workspace_i_h + "px"
        });
        this.image_paper = container.find(".sc-hp-workspace .sc-hp-wrapper .sc-hp-image").css({
          "background-image" : "url(" + model.image + ")",
          width : model.workspace_i_w + "px",
          height : model.workspace_i_h + "px"
        });
        if (max_w > model.workspace_i_w) {
          this.image_paper.css({
            left : ((max_w - model.workspace_i_w) / 2) + "px"
          });
        }
        var rgb = getRGB("#" + model.backgroundColor);
        rgb = [(rgb[0] + 256) / 2, (rgb[1] + 256) / 2, (rgb[2] + 256) / 2];
        var question = container.find(".sc-hp-question").css({
          "background-color" : "RGB(" + parseInt(rgb[0]) + ", " + parseInt(rgb[1]) + ", " + parseInt(rgb[2]) + ")"
        });
        if (model.clue == "true") {
          question.find(".sc-hp-hint").show();
          question.show();
        }
        if (model.mode == "quiz") {
          this.qstn_text = container.find(".sc-hp-questionText div").html(model.task[model.task.current].text);
		  container.find('.sc-hp-add' ).css('height',Math.max(0,model.height-90-model.workspace_i_h-47-5)+"px");
        }
        this.next = this.qstn_skip = container.find(".sc-hp-button.sc-hp-skip").bind("complete", function() {
          $(this).addClass("sc-hp-complete");
          self.responce.html("");
        });
        this.qstn_hint = container.find(".sc-hp-button.sc-hp-hint").bind("complete", function() {
          $(this).addClass("sc-hp-complete");
        }).bind("click", function() {
          self.hint = !self.hint;
          var img = (self.hint) ? model.image_clue : model.image;
          self.image_paper.css({
            "background-image" : "url(" + img + ")",
          });
        });
        if (model.mode == "explore") {
          this.image_paper.append(model.tooltip);
        }
        this.responce = container.find(".sc-hp-response").bind("correct", function() {
          $(this).css({
            color : "green"
          }).html(model.correctText);
        }).bind("incorrect", function() {
          $(this).css({
            color : "red"
          }).html(model.incorrectText);
        }).bind("reset", function() {
          $(this).css({
            color : "black"
          }).html("");
        });
        this._bind[model.mode](model.image_paper, self);
        this._super(self);
      }
      this.qstn_hint.removeClass("sc-hp-complete");
      this.qstn_skip.removeClass("sc-hp-complete");
      this.qstn_skip.unbind("click").click(function() {
        if (model.task.currentIndex != model.task.length - 1) {
          model.task.current = model.returnRandomOrder.call(model, model.task.length )[(++model.task.currentIndex)];
          self.qstn_text.html(model.task[model.task.current].text);
        } else {
          self.qstn_text.html(model.completedText);
          self.qstn_skip.trigger("complete");
          self.qstn_hint.trigger("complete");
          self.completed();
        }
      });
    },
    bindEvents : function(self) {
      $("#restart_" + this.options.model.containerId).bind("click", function() {
        self.reset();
        self.options.model.task.currentIndex = -1;
        self.qstn_skip.click();
        self.responce.trigger("reset");
      });
    },
    updateStatus : function() {
      var pts = this.options.model.currentScore * (this.options.model.maxScore / this.options.model.pointsArr.length);
      pts = Math.round(10 * pts) / 10 || 0;
      $("#statusText_" + this.options.model.containerId).html( this.options.model.scoreText+" " + pts + "/" + this.options.model.maxScore);
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.updateStatus();
      this.options.model.task.currentIndex = 0;
	  for(var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
	    if(this.options.model.pointsArr[this.options.model.returnRandomOrder(this.options.model.task.length)[i]] > -1) {
		  this.options.model.qstn_skip.click();
		} else {
		  this.options.model.task.currentIndex = i;
		  this.options.model.task.current = this.options.model.returnRandomOrder(this.options.model.task.length)[i];
		  break;
		}
      }
    },
    handleKeys : function(e) {
    },
    _bind : {
      quiz : function(image, self) {
        self.image_paper.click(function(evt) {
          var crds = self.options.model._get_coords(evt);
          var color = self.options.model._get_image_data.call(image, crds, self.options.model);
          self.options.model.pointsArr[image.task.current]++;
          if (color == image.task[image.task.current].color) {
            if (self.options.model.pointsArr[image.task.current] == 0) {
              self.options.model.currentScore++;
            }
            self.responce.trigger("correct");
            self.next.trigger("click");
            self.playIsCorrect(true);
            self.updateStatus();
          } else {
            self.responce.trigger("incorrect");
            self.playIsCorrect(false);
          }
        });
      },
      explore : function(image, self) {
        var height = self.image_paper.height() / 2;
        var width = self.image_paper.width() / 2;
        self.image_paper.bind("click mousemove", function(evt) {
          var crds = self.options.model._get_coords(evt);
          var color = self.options.model._get_image_data.call(image, crds, self.options.model);
          var bubble = image.tooltip;          
          if (color != "0") {            
            if (color != image.task[image.task.current].color) {
              image.task.find(color);
            }
            var padding, dx, dy, dh, dv;
            if (crds.x < width) {
              dx = +3;
              dh = true;
            } else {
              dx = -bubble.w - 3;
              dh = false;
            }
            if (crds.y < height) {
              dy = +3;
              dv = true;
            } else {
              dy = -bubble.h - 3;
              dv = false;
            }
            bubble.content.html(image.task[image.task.current].text);
            if (bubble._type != 9) {
              bubble.css({
                left : crds.x + dx + "px",
                top : crds.y + dy + "px"
              });
            }
            bubble.update(dh, dv).show();
          } else {
            bubble.hide();
            $(this).css("cursor", "default");
          }
        });
      }
    }
  });
  SCPTModel("Labeling", {
    defaults : {
      img : "",
      labels : [],
      startCoords : []
    }
  }, {
    init : function(jsonObj, params) {
      this._super(jsonObj, params, "labeling");
      this.img = jsonObj.image;
      this.labels = jsonObj.labelset.length ? jsonObj.labelset : [jsonObj.labelset];
      for (var i = 0; i < this.labels.length; i++) {
        this.labels[i].name[1] = this.decode(this.labels[i].name[1]);
      }
      if (jsonObj.linecolor == 0) {
        this.lineColor = "#000000";
      } else {
        this.lineColor = jsonObj.linecolor || "#ff0000";
      }
      this.imgPosition = [jsonObj.imagex || 0, jsonObj.imagey || 0];
      this.reinit();
    },
    reinit : function() {
      this._super();
      this.pointsArr = [];
      for (var i = 0; i < this.labels.length; i++) {
        this.pointsArr.push(-2);
      }
      this.randArrs={};
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.pointsArr = jsonObj.innerState;
    },
    getState : function(jsonObj) {
      var obj = this._super();
      obj.innerState = this.pointsArr;
      return obj;
    }
  });
  SCPTController("Labelings", {}, {
    init : function() {
      var self = this;
      self.options.model.attempts++;
      var container = $("#" + this.options.model.containerId);
      var returnOrder = this.options.model.returnRandomOrder(this.options.model.labels.length);
      container.html(this.options.template, {
        img : this.options.model.img,
        imgPos : this.options.model.imgPosition,
        labels : this.options.model.labels,
        id : this.options.model.containerId,
        color : this.options.model.backgroundColor,
        width : this.options.model.width,
        height : this.options.model.height,
        randArr : returnOrder,
        bigText : this.options.model.isBigText == "true" ? "sc-bigText" : ""
      });
     
      var labels = this.options.model.labels;    
	  self.options.model.rlcounter = 0;
      this.resizeLabels(labels,returnOrder);
      setTimeout(function(){self.resizeLabels(labels,returnOrder)},200)
      container.find(".sc-labelContainerDiv")[0].style.visibility = 'visible'
      this._super();          
  },
  resizeLabels : function(labels,returnOrder) {
	var self = this;
    var maxW = 10;
    var maxH = 20;
    
    //resize labels
    for (var i = 0; i < labels.length; i++) {
      var obj = $("#" + this.options.model.getIdByIndex(i));
      maxW = Math.max(maxW, obj.width());
    }
    maxW += 2;
    maxW = Math.min(264, maxW);


    for (var i = 0; i < labels.length; i++) {
      var obj = $("#" + this.options.model.getIdByIndex(returnOrder[i]));
      obj.css({
        width : maxW + "px",
      });
    }
    for (var i = 0; i < labels.length; i++) {
      var obj = $("#" + this.options.model.getIdByIndex(i));
      maxH = Math.max(maxH, obj.height());      
      if(obj.height()<obj.find('div').height() && Math.abs(obj.height()-obj.find('div').height())!=1) {        
        obj.css('width','auto');        
		if(self.options.model.rlcounter++<100) {
		console.log(obj.height(),obj.find('div').height())
        this.resizeLabels(labels,returnOrder);
        return;                             
		}
      }
    }

    maxH = Math.min(42, maxH);    
    var dx = (this.options.model.width - maxW - 10) / this.options.model.labels.length;
    var dy = Math.min(4,(80-maxH)/this.options.model.labels.length);    
    for (var i = 0; i < labels.length; i++) {
      var obj = $("#" + this.options.model.getIdByIndex(returnOrder[i]));
      obj.css({
        left: (10+i*dx)+"px",
        top : (dy*i+380)+"px"
      });
    }


    for (var i = 0; i < labels.length; i++) {
      var obj = $("#" + this.options.model.getIdByIndex(i));
      var target = $("#labelTarget_" + this.options.model.containerId + "_" + (i));
      target.css({
        width : maxW+2 + "px",
        height : maxH + "px"
      });
      obj.css({
        height : maxH + "px",
      });
      if(maxH == 20) {        
        obj.css({
        height : maxH-4 + "px",
        "padding-top":"4px"
        });        
      }            
      this.drawLine(obj, target, labels[i], maxW, maxH);
    }
    return;    
  },
  drawLine : function(obj, target, label, maxW, maxH) {
      var xy1 = [label.dotx + $("#" + this.options.model.containerId).offset().left, label.doty + $("#" + this.options.model.containerId).offset().top];
      var xy2 = [target.offset().left, target.offset().top];
      if (xy1[0] <= xy2[0] + maxW * 0.33) {
      } else {
        if (xy1[0] >= xy2[0] + maxW * 0.66) {
          xy2[0] += maxW;
        } else {
          xy2[0] += maxW / 2;
        }
      }
      if (xy1[1] <= xy2[1] + maxH * 0.33) {
      } else {
        if (xy1[1] >= xy2[1] + maxH * 0.66) {
          xy2[1] += maxH;
        } else {
          xy2[1] += maxH / 2;
        }
      }
      var height = Math.abs((parseInt((-xy1[1] + xy2[1])))) || 1;
      var width = Math.abs(parseInt((-xy1[0] + xy2[0])));
      var lw = this.options.model.lineweight;
      var c = $("<canvas width=" + (width + 2 * lw) + " height=" + (Math.abs(height) + 2 * lw) + "></canvas").css({
        position : "absolute",
        left : Math.min(xy1[0], xy2[0]) - $("#" + this.options.model.containerId).offset().left - lw,
        top : Math.min(xy1[1], xy2[1]) - $("#" + this.options.model.containerId).offset().top - lw
      }).appendTo($("#"+this.options.model.containerId).children()[0]);
      var ctx = c[0].getContext("2d");
      ctx.strokeStyle = ("#"+this.options.model.lineColor).replace("##","#");
      ctx.lineWidth = lw;
      ctx.lineCap = "round";
      ctx.beginPath();
      if ((xy1[1] > xy2[1] && xy1[0] < xy2[0]) || (xy1[1] < xy2[1] && xy1[0] > xy2[0])) {
        ctx.moveTo(lw, height + lw);
        ctx.lineTo(width + lw, lw);
      } else {
        ctx.moveTo(lw, lw);
        ctx.lineTo(width + lw, height + lw);
      }
      ctx.stroke();
    },
    revert : function(dragId) {
      try {
        $("#" + this.options.model.getIdByIndex(dragId)).css({
          top : this.options.model.startCoords[dragId].y,
          left : this.options.model.startCoords[dragId].x
        });
      } catch(e) {
      }
    },
    bindEvents : function(self) {
      $("#"+self.options.model.containerId).find(".sc-labels").bind("draginit", function(ev, drag) {
        return function() {
          if (!self.options.model.fromKeyBoard) {
            drag.revert();
          }
        }();
      });
      $("#"+self.options.model.containerId).find(".sc-labelsTargets").each(function(index) {
        $(this).bind("dropon", function(ev, drop, drag) {
          var isTrue = 0;
          var dragId = drag.delegate.getAttribute("data-id");
          var dropId = drop.element[0].getAttribute("data-id");
          if (dragId == dropId) {
            isTrue = 1;
            drag.revert(false);
            drag.position(new jQuery.Vector($(drop.element[0]).offset().left, $(drop.element[0]).offset().top));
            $(drag.delegate).unbind().data("dropped", "true");
          }
          if (isTrue) {
            if (self.options.model.pointsArr[dragId] == -2) {
              self.options.model.currentScore += isTrue;
            }
            self.options.model.pointsArr[dragId] = dropId;
          } else {
            self.options.model.pointsArr[dragId] = -1;
          }
          if (!isTrue) {
            self.revert(dragId);
          }
          self.playIsCorrect(isTrue);
          self.updateStatus();
          var isCompleted = true;
          for (var i = 0, l = self.options.model.pointsArr.length; i < l; i++) {
            if (self.options.model.pointsArr[i] < 0) {
              isCompleted = false;
              break;
            }
          }
          if (isCompleted) {
            self.completed();
          }
        });
      });
      $("#restart_" + this.options.model.containerId).bind("click", function() {
        self.reset();
      });
    },
    updateStatus : function() {
      var pts = this.options.model.currentScore * (this.options.model.maxScore / this.options.model.pointsArr.length);
      pts = Math.round(10 * pts) / 10;
      $("#statusText_" + this.options.model.containerId).html( this.options.model.scoreText+" " + pts + "/" + this.options.model.maxScore);
    },
    showAnswer : function() {
      for (var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
        var target = $("#labelTarget_" + this.options.model.containerId + "_" + (i));
        $("#" + this.options.model.getIdByIndex(i)).css({
          left : target.css("left"),
          top : target.css("top")
        });
      }
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.updateStatus();
      for (var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
        if (this.options.model.pointsArr[i] > -1) {
          var target = $("#labelTarget_" + this.options.model.containerId + "_" + (i));
          $("#" + this.options.model.getIdByIndex(i)).css({
            left : target.css("left"),
            top : target.css("top")
          });
        }
      }
    }
  });
  SCPTModel("Ordering", {
    defaults : {
      img : "",
      labels : [],
      startCoords : []
    }
  }, {
    init : function(jsonObj, params) {
      this._super(jsonObj, params, "ordering");
      this.orderset = jsonObj.orderset;
      for (var i = 0; i < this.orderset.length; i++) {
        this.orderset[i].item = this.decode(this.orderset[i].item);
      }
      this.reinit();
    },
    reinit : function() {
      this._super();
      this.pointsArr = [];
      for (var i = 0; i < this.orderset.length; i++) {
        this.pointsArr.push(-2);
      }
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.pointsArr = jsonObj.innerState;
    },
    getState : function(jsonObj) {
      var obj = this._super();
      obj.innerState = this.pointsArr;
      return obj;
    }
  });
  SCPTController("Orderings", {}, {
    init : function() {
      var self = this;
      self.options.model.attempts++;
      this.options.model.randArrs = [];
      var container = $("#" + this.options.model.containerId);
      container.html(this.options.template, {
        labels : this.options.model.orderset,
        offsetTop : parseInt(container.offset().top, 10),
        id : this.options.model.containerId,
        color : this.options.model.backgroundColor,
        width : this.options.model.width,
        height : this.options.model.height,
        randArr : this.options.model.returnRandomOrder(this.options.model.orderset.length),
        bigText : this.options.model.isBigText == "true" ? "sc-bigText" : ""
      });
      this._super();
    },
    revert : function(dragId) {
      try {
        $("#" + this.options.model.getIdByIndex(dragId)).css({
          top : this.options.model.startCoords[dragId].y,
          left : this.options.model.startCoords[dragId].x
        });
      } catch(e) {
      }
    },
    bindEvents : function(self) {
      $("#"+self.options.model.containerId).find(".sc-order").bind("draginit", function(ev, drag) {
        return function() {
          if (!self.options.model.fromKeyBoard) {
            drag.revert();
          }
        }();
      });
      $("#"+self.options.model.containerId).find(".sc-orderTarget").each(function(index) {
        $(this).bind("dropon", function(ev, drop, drag) {
          var isTrue = 0;
          var dragId = drag.delegate.getAttribute("data-id");
          var dropId = drop.element[0].getAttribute("data-id");
          if (dragId == dropId) {
            isTrue = 1;
            drag.revert(false);
            drag.position(new jQuery.Vector($(drop.element[0]).offset().left, $(drop.element[0]).offset().top));
            $(drag.delegate).bind("draginit", function(ev, drag) {
              drag.cancel();
            });
          }
          if (isTrue) {
            if (self.options.model.pointsArr[dragId] == -2) {
              self.options.model.currentScore += isTrue;
            }
            self.options.model.pointsArr[dragId] = dropId;
          } else {
            self.options.model.pointsArr[dragId] = -1;
          }
          if (!isTrue) {
            self.revert(dragId);
          }
          self.playIsCorrect(isTrue);
          self.updateStatus();
          var isCompleted = true;
          for (var i = 0, l = self.options.model.pointsArr.length; i < l; i++) {
            if (self.options.model.pointsArr[i] < 0) {
              isCompleted = false;
              break;
            }
          }
          if (isCompleted) {
            self.completed();
          }
        });
      });
      $("#restart_" + this.options.model.containerId).bind("click", function() {
        self.reset();
      });
    },
    updateStatus : function() {
      var pts = this.options.model.currentScore * (this.options.model.maxScore / this.options.model.pointsArr.length);
      pts = Math.round(10 * pts) / 10;
      $("#statusText_" + this.options.model.containerId).html( this.options.model.scoreText+" " + pts + "/" + this.options.model.maxScore);
    },
    showAnswer : function() {
      for (var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
        var target = $("#orderTarget_" + this.options.model.containerId + "_" + (i));
        $("#" + this.options.model.getIdByIndex(i)).css({
          left : target.css("left"),
          top : target.css("top")
        });
      }
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.updateStatus();

      for (var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
        if (this.options.model.pointsArr[i] > -1) {
          var target = $("#orderTarget_" + this.options.model.containerId + "_" + (i));
          $("#" + this.options.model.getIdByIndex(i)).css({
            left : target.css("left"),
            top : target.css("top")
          });
        }
      }
    }
  });
  SCPTModel("Puzzle", {}, {
    init : function(jsonObj, params) {
      var self = this;
      var k$ = Kinetic;
      this._super(jsonObj, params, "jigsawpuzzle");
      this.maxScore = parseInt(jsonObj.score) || 0;
      this.reinit();
      this.cols = parseInt(Math.min(Math.max(jsonObj.columns, 2), 20));
      this.rows = parseInt(Math.min(Math.max(jsonObj.rows, 2), 20));
      var paramStr = jsonObj.puzzleimage.image.replace(/%3D/gi, "=").replace(/%2F/gi, "/").replace(/%22/gi, '"');
      this.image = paramStr.match(/src="[^\"]*"/gi)[0].replace(/src=/gi, "").replace(/"/gi, "");
      this.wwidth = paramStr.match(/width="[^\"]*"/gi)[0].replace(/width=/gi, "").replace(/"/gi, "");
      this.hheight = paramStr.match(/height="[^\"]*"/gi)[0].replace(/height=/gi, "").replace(/"/gi, "");
      this.resizeSizes();
      this.toph = 360 / 2 - this.hheight / 2;

      this.scoreText = jsonObj.scorelabel || this.scoreText || "Score";
      this.restartText = this.decode(jsonObj.restartbuttonlabel) || this.restartText || "Restart";
      this.finishText = jsonObj.finishbuttonlabel || this.finishText || "Finish";


      this.paper = null;
      this.board = null;
      this.pieces = [];
      this.pieces.s = this.maxScore / (this.cols * this.rows);
      this.pieces.w = this.wwidth / this.cols;
      this.pieces.h = this.hheight / this.rows;
      this.pieces.current = -1;
      this.cnv_id = this.containerId + "-cnv";
      this.holder = $('<div class="sc-pz-puzzleHolder" style="background-color:' + this.backgroundColor + '"></div>');
      this.canbox = $('<div class="sc-pz-puzzleCanBox" id="' + this.cnv_id + '"></div>').css({
        "background-color" : this.backgroundColor
      });
      this.w_load = $('<img src="res/puzzle/loading.gif"/>').css({
        position : "relative",
        opasity : "0.3",
        top : "-300px",
        left : "300px"
      });
    },
    reinit : function() {
      this.currentScore = 0;
      this.tcurrentScore = 0;
      this._super();
    },
    next : function() {
      this.pieces[this.arr[this.pieces.current]].highlight = false;
      if (++this.pieces.current == this.pieces.length) {
        this.pieces.current = 0;
      }
      this.pieces[this.arr[this.pieces.current]].highlight = true;
      this.pieces[this.arr[this.pieces.current]].shape.moveToTop();
      this.pieces.layer.draw();
    },
    score : function() {
      var result = 0;
      for (var i = this.pieces.length; i--; ) {
        if (this.pieces[i].shape._right) {
          result += this.pieces.s;
        }
      }
      return Math.min(result, this.params.score);
    },
    reset : function() {
      this.attempts++;
      var _pcs = this.pieces;
      var minx = 400, gatex = 270 - _pcs.w, miny = _pcs.l, gatey = this.hheight - _pcs.h - _pcs.l * 2;
      for (var i = this.pieces.length; i--; ) {
        var x = Math.round(Math.random() * gatex + minx) - _pcs[i].ox, y = Math.round(Math.random() * gatey + miny) - _pcs[i].oy;
        _pcs[i].shape.setPosition(x, y);
        _pcs[i].shape.draggable(true);
      }
      this.pieces.layer.draw();
    },
    load_state : function(obj) {
      var state = obj.split(";").reverse();
      for (var i = this.pieces.length, p; i--; ) {
        var p = state[i].split(",");
        this.pieces[i].shape.setPosition(parseInt(p[0]), parseInt(p[1]));
        if (p[0] == "0" && p[1] == "0") {
          this.pieces[i].shape._right = true;
        } else {
          this.pieces[i].shape._right = false;
          this.pieces[i].shape.draggable(true);
        }
      }
      this.pieces.layer.draw();
    },
    unhighlight : function() {
      for (var i = this.pieces.length; i--; ) {
        this.pieces[i].highlight = false;
      }
      this.pieces.layer.draw();
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.load_state(jsonObj.innerState);
    },
    getState : function(jsonObj) {
      var obj = this._super();
      var state = "";
      for (var i = this.pieces.length, p; i--; ) {
        var p = this.pieces[i].shape.getPosition();
        state += state ? ";" : "";
        state += p.x + "," + p.y;
      }
      obj.innerState = state;
      return obj;
    },
    resizeSizes : function() {
      var w = this.wwidth, h = this.hheight;
      var max = 350;
      if (w > max || h > max) {
        if (w > h) {
          h = h * max / w;
          w = max;
        } else {
          w = w * max / h;
          h = max;
        }
      }
      this.wwidth = w, this.hheight = h;
    }
  });
  SCPTController("Puzzles", {}, {
    init : function() {
      var self = this;
      var k$ = Kinetic;
      var container = $("#" + this.options.model.containerId);
      container.html(this.options.template, {
        offsetTop : parseInt(container.offset().top, 10),
        id : this.options.model.containerId,
        color : this.options.model.backgroundColor,
        width : this.options.model.width,
        height : this.options.model.height
      });
      $("#restart_" + self.options.model.containerId ).html(self.options.model.restartText);
      $("#finish_" + self.options.model.containerId ).html(self.options.model.finishText);

      $("#puzzle_container_" + this.options.model.containerId).append(this.options.model.holder.append(this.options.model.canbox, this.options.model.w_load));
      this.stage = new k$.Stage(this.options.model.cnv_id, 710, 360);
      this.board = new k$.Layer();
      this.chips = new k$.Layer();
      this.frame = new k$.Shape(function() {
        var ctx = this.getContext();
        ctx.save();
        ctx.rect(5, self.options.model.toph, self.options.model.wwidth, self.options.model.hheight);
        ctx.lineWidth = 4;
        ctx.strokeStyle = "black";
        ctx.shadowColor = "#3c3c3c";
        ctx.shadowBlur = 5;
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
        ctx.fillStyle = "white";
        ctx.stroke();
        ctx.fill();
        ctx.restore();
        this.sx = 5;
        this.sy = self.options.model.toph;
      }, "board");
      this.board.add(this.frame);
      this.stage.add(this.board);
      this.stage.add(this.chips);
      this.board.draw();
      this.options.model.pieces.layer = this.chips;
      this.options.model.pieces.current = 0;
      this.drawPuzzle();
      this._super();
    },
    drawPuzzle : function() {
      var self = this;
      var k$ = Kinetic;
      var n = Math.max(this.options.model.cols, this.options.model.rows) / 2, a = Math.round(100 / n) / 4, b = Math.round(50 / n) / 4, b2 = Math.round(b * 2), p_prm = [], p_path = [], bound = [];
      this.options.model.pieces.l = a;
      for (var c = 0; c < this.options.model.cols; c++) {
        p_prm[c] = [];
        for (var r = 0; r < this.options.model.rows; r++) {
          var o_O = p_prm[c][r] = {};
          if (c != this.options.model.cols - 1) {
            var s = Math.round(Math.random()) * 2 - 1;
            var d = Math.round(Math.random() * this.options.model.pieces.h / 4 + this.options.model.pieces.h / 4);
            var w = Math.round(a * s);
            bound.push(["m", c * this.options.model.pieces.w + this.options.model.pieces.w, r * this.options.model.pieces.h], ["l", 0, d], ["q", w, -b, w, b], ["q", 0, b2, -w, b], ["l", 0, this.options.model.pieces.h - b2 - d]);
            o_O.v = {
              d : d,
              w : w
            };
          }
          if (r != this.options.model.rows - 1) {
            var s = Math.round(Math.random()) * 2 - 1;
            var d = Math.round(Math.random() * this.options.model.pieces.w / 4 + this.options.model.pieces.w / 4);
            var w = Math.round(a * s);
            bound.push(["m", c * this.options.model.pieces.w + this.options.model.pieces.w, r * this.options.model.pieces.h + this.options.model.pieces.h], ["l", -d, 0], ["q", b, w, -b, w], ["q", -b2, 0, -b, -w], ["l", -this.options.model.pieces.w + b2 + d, 0]);
            o_O.h = {
              d : d,
              w : w
            };
          }
        }
      }
      this.board.add(new k$.Shape(this._make_shape(bound, self)));
      this.target = new k$.Shape(this._make_target(self));
      this.target_xmax = this.options.model.cols - 1;
      this.target_ymax = this.options.model.rows - 1;
      this.target_x = 0;
      this.target_y = 0;
      this.board.add(this.target);
      for (var c = 0; c < this.options.model.cols; c++) {
        for (var r = 0; r < this.options.model.rows; r++) {
          var p_path = [], w, d, dx = 0, dy = 0;
          p_path.push(["m", c * this.options.model.pieces.w, r * this.options.model.pieces.h]);
          if (r == 0) {
            p_path.push(["l", this.options.model.pieces.w, 0]);
          } else {
            d = p_prm[c][r - 1].h.d;
            w = p_prm[c][r - 1].h.w;
            dy = Math.min(dy, w);
            p_path.push(["l", this.options.model.pieces.w - b2 - d, 0], ["q", -b, w, b, w], ["q", b2, 0, b, -w], ["l", d, 0]);
          }
          if (c == this.options.model.cols - 1) {
            p_path.push(["l", 0, this.options.model.pieces.h]);
          } else {
            d = p_prm[c][r].v.d;
            w = p_prm[c][r].v.w;
            p_path.push(["l", 0, d], ["q", w, -b, w, b], ["q", 0, b2, -w, b], ["l", 0, this.options.model.pieces.h - b2 - d]);
          }
          if (r == this.options.model.rows - 1) {
            p_path.push(["l", -this.options.model.pieces.w, 0]);
          } else {
            d = p_prm[c][r].h.d;
            w = p_prm[c][r].h.w;
            p_path.push(["l", -d, 0], ["q", b, w, -b, w], ["q", -b2, 0, -b, -w], ["l", -this.options.model.pieces.w + b2 + d, 0]);
          }
          if (c == 0) {
            p_path.push(["l", 0, -this.options.model.pieces.h]);
          } else {
            d = p_prm[c-1][r].v.d;
            w = p_prm[c-1][r].v.w;
            dx = Math.min(dx, w);
            p_path.push(["l", 0, -this.options.model.pieces.h + b2 + d], ["q", w, b, w, -b], ["q", 0, -b2, -w, -b], ["l", 0, -d]);
          }
          this.options.model.pieces.push({
            path : p_path,
            shape : null,
            ox : c * this.options.model.pieces.w,
            oy : r * this.options.model.pieces.h
          });
        }
      }
      this.img = new Image();
      this.img.onload = function() {
        var arr = [];
        for (var i = self.options.model.pieces.length; i--; ) {
          arr.push(i);
        }
        self.shuffle(arr);
        self.options.model.arr = arr;
        for (var i = self.options.model.pieces.length; i--; ) {
          var pci = self.options.model.pieces[arr[i]];
          var obj = pci.shape = new k$.Shape(self._make_piece(pci, self.img, self));
          pci.highlight = false;
          obj.draggable(true);
          obj.model = self.options.model.pieces;
          obj.on("mouseover", function() {
            self.options.model.canbox.css("cursor", "pointer");
          });
          obj.on("mouseout", function() {
            self.options.model.canbox.css("cursor", "default");
          });
          obj.on("mousedown touchstart", function(i) {
            return function() {
              var c = self.options.model.pieces.current;
              i = self.options.model.arr[i];
              self.options.model.pieces[c].highlight = false;
              self.options.model.pieces[i].highlight = true;
              self.options.model.pieces.current = i;
              this.moveToTop();
              this.parent.draw();
            };
          }(i));
          obj.on("mouseup touchend", function() {
            this._check(self);
          });
          self.chips.add(obj);
          self.chips.draw();
        }
        self.options.model.reset();
        self.options.model.w_load.remove();
        self.imageFinish = $(self.img).appendTo($("#" + self.options.model.containerId).find(".sc-pz-puzzleCanBox")).css({
          width : self.options.model.wwidth + "px",
          height : self.options.model.hheight + "px",
          top : self.options.model.toph + 0 + "px",
          left : 5 + "px",
          position : "absolute"
        }).hide();
      };
      k$.Shape.prototype._check = function(self) {
        if (this._right) {
          return;
        }
        var crds = this.getPosition();
        if (Math.abs(crds.x) < this.model.w / 8 && Math.abs(crds.y) < this.model.h / 8) {
          this._right = true;
          this.setPosition(0, 0);
          this.draggable(false);
          this.parent.draw();
          self.options.model.tcurrentScore++;
          self.updateStatus();
        } else {
          this._right = false;
        }
      };
      this.img.src = this.options.model.image;
      this.board.draw();
    },
    _make_target : function(self) {
      var sx = 5, sy = self.options.model.toph, ox = sx, oy = sy, cx = 0, cy = 0;
      var pieces = self.options.model.pieces, arr, ind;
      return function() {
        if (self.target_x > -1 && self.target_y > -1) {
          var ctx = this.getContext();
          ind = self.target_x * (self.target_ymax + 1) + self.target_y;
          arr = pieces[ind].path;
          ctx.save();
          ctx.beginPath();
          ctx.lineWidth = 0;
          ctx.fillStyle = "#ffda6b";
          for (var i = 0, l = arr.length; i < l; i++) {
            if (arr[i][0] == "m") {
              ox = sx;
              oy = sy;
            }
            cx = ox + arr[i][3];
            cy = oy + arr[i][4];
            ox += arr[i][1];
            oy += arr[i][2];
            ctx[self._canvas_map[arr[i][0]]](ox, oy, cx, cy);
            ox = isNaN(cx) ? ox : cx;
            oy = isNaN(cy) ? oy : cy;
          }
          ctx.closePath();
          ctx.fill();
          ctx.restore();
        }
      };
    },
    _make_piece : function(pci, img, self) {
      var sx = 5, sy = self.options.model.toph, arr = pci.path;
      return function() {
        var brd = this.parent.getChild("board"), ox = sx, oy = sy, cx = 0, cy = 0;
        var ctx = this.getContext();
        ctx.restore();
        ctx.save();
        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.fillStyle = "green";
        ctx.strokeStyle = (pci.highlight) ? "orange" : "black";
        ctx.shadowColor = "#3c3c3c";
        ctx.shadowBlur = 0;
        for (var i = 0, l = arr.length; i < l; i++) {
          if (arr[i][0] == "m") {
            ox = sx;
            oy = sy;
          }
          cx = ox + arr[i][3];
          cy = oy + arr[i][4];
          ox += arr[i][1];
          oy += arr[i][2];
          ctx[self._canvas_map[arr[i][0]]](ox, oy, cx, cy);
          ox = isNaN(cx) ? ox : cx;
          oy = isNaN(cy) ? oy : cy;
        }
        ctx.closePath();
        ctx.clip();
        ctx.drawImage(img, sx, sy, self.options.model.wwidth, self.options.model.hheight);
        ctx.stroke();
        ctx.restore();
        ctx.save();
        ctx.strokeStyle = (pci.highlight) ? "orange" : "black";
        ctx.stroke();
        ctx.restore();
      };
    },
    _make_shape : function(arr, self) {
      var self = this;
      return function() {
        var brd = this.parent.getChild("board"), ox = brd.sx, oy = brd.sy, cx = 0, cy = 0;
        var ctx = this.getContext();
        ctx.save();
        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.lineCap = "butt";
        ctx.lineJoin = "round";
        ctx.strokeStyle = "black";
        for (var i = 0, l = arr.length; i < l; i++) {
          if (arr[i][0] == "m") {
            ox = brd.sx;
            oy = brd.sy;
          }
          cx = ox + arr[i][3];
          cy = oy + arr[i][4];
          ox += arr[i][1];
          oy += arr[i][2];
          ctx[self._canvas_map[arr[i][0]]](ox, oy, cx, cy);
          ox = isNaN(cx) ? ox : cx;
          oy = isNaN(cy) ? oy : cy;
        }
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
      };
    },
    _canvas_map : {
      m : "moveTo",
      l : "lineTo",
      q : "quadraticCurveTo"
    },
    move : function() {
      var m = this.options.model;
      if (m.pieces.current == -1 || m.pieces[m.arr[m.pieces.current]].shape._right) {
        return;
      }
      var pieces = m.pieces;
      var tind = this.target_x * (this.target_ymax + 1) + this.target_y;
      var cind = m.arr[m.pieces.current];
      var crds = {
        x : pieces[tind].path[0][1] - pieces[cind].path[0][1],
        y : pieces[tind].path[0][2] - pieces[cind].path[0][2]
      };
      pieces[cind].shape.setPosition(crds.x, crds.y);
      pieces[cind].shape._check(this);
      pieces.layer.draw();
    },
    target_move : function(x, y) {
      this.target_x += x;
      this.target_y += y;
      if (this.target_x > this.target_xmax) {
        this.target_x = 0;
      }
      if (this.target_y > this.target_ymax) {
        this.target_y = 0;
      }
      if (this.target_x < 0) {
        this.target_x = this.target_xmax;
      }
      if (this.target_y < 0) {
        this.target_y = this.target_ymax;
      }
      this.board.draw();
    },
    bindEvents : function(self) {
      $("#restart_" + this.options.model.containerId).bind("click", function() {
        self.reset();
      });
      $("#finish_" + this.options.model.containerId).bind("click", function(self) {
        return function() {
          for (var i = 0; i < self.options.model.pieces.length; i++) {
            var pcs = self.options.model.pieces[i].shape;
            self.imageFinish.show();
            pcs._right = true;
            pcs.setPosition(0, 0);
            pcs.draggable(false);
            pcs.parent.draw();
            self.playIsCorrect(true);
          }
          self.completed();
        };
      }(this));
    },
    updateStatus : function() {
      var pts = this.options.model.tcurrentScore * (this.options.model.maxScore / this.options.model.pieces.length);
      pts = Math.round(10 * pts) / 10;
      this.options.model.currentScore = pts;
      if (this.options.model.tcurrentScore == this.options.model.pieces.length) {
        this.imageFinish.show();
        this.playIsCorrect(true);
        this.completed();
        this.options.model.unhighlight();
      }
      $("#statusText_" + this.options.model.containerId).html( this.options.model.scoreText+" " + pts + "/" + this.options.model.maxScore);
    },
    setState : function(jsonObj) {
      this.options.model.setState(jsonObj);
      this.updateStatus();
    },
    handleKeys : function(e) {
      var self = e.data.self;
      var dt = 10;
      if (e.altKey) {
        switch(e.keyCode) {
          case 85:
            e.data.self.reset(false);
            return false;
            break;
          case 81:
            $("#finish_" + self.options.model.containerId).click();
            break;
          default:
            return true;
        }
      } else {
        switch(e.keyCode) {
          case 32:
            if (e.ctrlKey) {
            } else {
              self.options.model.next();
            }
            break;
          case 13:
            self.move();
            break;
          case 37:
            self.target_move(-1, 0);
            break;
          case 38:
            self.target_move(0, -1);
            break;
          case 39:
            self.target_move(1, 0);
            break;
          case 40:
            self.target_move(0, 1);
            break;
          default:
            return true;
        }
      }
      e.preventDefault();
    },
    reset : function() {
      this.imageFinish && this.imageFinish.hide();
      this.options.model.reinit();
      this.options.model.reset();
      for (var i = this.options.model.pieces.length; i--; ) {
        this.options.model.pieces[i].shape._right = false;
      }
      this._super(true);
      this.updateStatus();
    },
    disableActivity : function() {
      this._super();
      var self = this;
      for (var i = 0; i < self.options.model.pieces.length; i++) {
        var pcs = self.options.model.pieces[i].shape;
        pcs.draggable(false);
      }
    },
    shuffle : function(o) {
      for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x) {
      }
      return o;
    }
  });
  (function(j$, w$) {
    w$.softchalkslide = {};
    w$.softchalkslide.init = function(xml, params) {
      return new slideshow(params.containerId, j$(xml), params.width, params.height, params.backgroundColor);
    };
    var slideshow = function(id, xml, width, height, pcolor) {
      var self = this;
      self.id = id;
      this.params = {
        bgcolor : pcolor || xml.find("color").text(),
        viewText : xml.find("viewText").text(),
        slideText : xml.find("slideText").text(),
        duration : parseInt(xml.find("minimumDuration").text()) * 1000,
        slideshow : false
      };
      this.cards = [];
      this.cards.current = 0;
      xml.find("slidedata").each(function() {
        self.cards.push({
          title : _parse_string.call(j$(this).find("title").text()),
          slide : _parse_string.call(j$(this).find("content").text()),
          image : j$(this).find("slide").text(),
          audio : j$(this).find("audio").text(),
          width : parseInt(j$(this).find("width").text()),
          height : parseInt(j$(this).find("height").text())
        });
      });
      this.wrapper = j$("#" + self.id).css({
        width : "600px",
        height : "540px",
        "background-color" : "#" + self.params.bgcolor,
        margin : "0",
        padding : "20px",
        border : "1px solid #7094b7",
        "line-height" : "110%"
      });
      this._ready = false;
      this._total = 0;
      for (var i = this.cards.length; i--; ) {
        if (this.cards[i].image) {
          this._total++;
        }
        if (this.cards[i].audio) {
          this._total++;
        }
      }
      for (var i = this.cards.length; i--; ) {
        if (this.cards[i].audio) {
          _load_media(this.cards[i].audio, self);
        }
        if (this.cards[i].image) {
          _load_mediaImg(this.cards[i].image, self);
        }
      }
    };
    var _load_mediaImg = function(link, self) {
      var img = new Image();
      img.onload = function() {
        self._total--;
        if (!self._total) {
          _build_view(self);
        }
      };
      img.src = link;
    };
    var _load_media = function(link, self) {
      j$.ajax({
        url : link,
        cache : false,
        success : function() {
          self._total--;
          if (!self._total) {
            _build_view(self);
          }
        },
        error : function(e1, e2, e3) {
          self.wrapper.append('<p style="margin:0;padding:0;color: red;font-family:Verdana;font-size:12px">Not found next file: ' + link + "</p>");
        }
      });
    };
    var _build_view = function(self) {
      var _prm = self.params;
      var wrapper = self.wrapper.click( function(self) {
        return function(event) {
          if (event.target.tagName != "SELECT") {
            $("#inputf_" + self.id).focus();
          }
        };
      }(self));
      var skeleton = j$('<table border="0" cellpadding="0" cellspacing="0"><tr height="450px"><td></td></tr></table><table border="0" cellpadding="0" cellspacing="0"><tr height="26px"><td width="30px" style="cursor:pointer;"></td><td width="400px" style=""></td><td width="30px" style="cursor:pointer"></td><td width="140px" style="cursor:pointer;"></td></tr></table><table border="0" cellpadding="0" cellspacing="0"  class="slideShowJp"><tr height="38px"><td></td></tr></table><table border="0" cellpadding="0" cellspacing="0" class="slideShowJp"><tr height="30px"><td width="150px" style="cursor:pointer;"></td><td width="300px" style=""></td><td width="150px" style="cursor:pointer"></td></tr></table>').css({
        width : "600px",
        "border-spacing" : "0px"
      });
      self.image = j$('<img src="sclb_extras/loading.gif"/>');
      self.slide = j$("<div></div>").css({
        "text-align" : "left",
        "font-family" : "Verdana",
        "font-size" : "12px",
        "background-color" : "#fff",
        margin : "0",
        padding : "5px",
        border : "2px groove #c3c3c3",
        overflow : "hidden",
        width : "596px",
        height : "436px"
      }).hide();
      self.slide_select = j$('<select size="1"></select>').css({
        width : "380px",
        border : "1px solid #c3c3c3",
        "-webkit-border-radius" : "5px",
        "-moz-border-radius" : "5px",
        "border-radius" : "5px"
      }).bind("enable", function() {
        j$(this).removeAttr("disabled");
      }).bind("disable", function() {
        j$(this).attr("disabled", "true");
      }).trigger("disable");
      var slide_options = "";
      for (var i = self.cards.length; i--; ) {
        slide_options = "<option value='" + i + "'>" + self.cards[i].title + "</option>" + slide_options;
      }
      self.slide_select.change(function() {
        self.select();
      }).html(slide_options);
      self.slide_show = j$("<div>Start Slideshow</div>").css({
        cursor : "pointer",
        width : "120px",
        height : "14px",
        "font-size" : "12px",
        "text-align" : "center",
        "font-family" : "Verdana",
        padding : "2px 0",
        margin : "auto",
        border : "3px double #919191",
        "-webkit-border-radius" : "5px",
        "-moz-border-radius" : "5px",
        "border-radius" : "5px",
        "line-height":"100%"
      }).hover(function() {
        if (!j$(this).hasClass("bttn-disabled")) {
          j$(this).css({
            border : "3px double #89cc73"
          });
        }
      }, function() {
        if (!j$(this).hasClass("bttn-disabled")) {
          j$(this).css({
            border : "3px double #919191"
          });
        }
      }).bind("disable", function() {
        j$(this).addClass("bttn-disabled").css({
          cursor : "default"
        });
      }).bind("enable", function() {
        j$(this).removeClass("bttn-disabled").css({
          cursor : "pointer"
        });
      }).click(function() {
        if (!j$(this).hasClass("bttn-disabled")) {
          self.slideshow();
        }
      }).css(_not_selectable).trigger("disable");
      self.slide_view = j$("<div>"+self.params.viewText+"</div>").css({
        cursor : "pointer",
        width : "180px",
        height : "14px",
        "font-size" : "12px",
        "text-align" : "center",
        "font-family" : "Verdana",
        padding : "2px 0",
        margin : "auto",
        border : "3px double #919191",
        "-webkit-border-radius" : "5px",
        "-moz-border-radius" : "5px",
        "border-radius" : "5px",
        "line-height":"100%"
      }).hover(function() {
        if (!j$(this).hasClass("bttn-disabled")) {
          j$(this).css({
            border : "3px double #89cc73"
          });
        }
      }, function() {
        if (!j$(this).hasClass("bttn-disabled")) {
          j$(this).css({
            border : "3px double #919191"
          });
        }
      }).bind("disable", function() {
        j$(this).addClass("bttn-disabled").css({
          cursor : "default"
        });
      }).bind("enable", function() {
        j$(this).removeClass("bttn-disabled").css({
          cursor : "pointer"
        });
      }).click(function() {
        if (!j$(this).hasClass("bttn-disabled")) {
          self.change_view();
        }
      }).css(_not_selectable).trigger("disable");
      self.control = {};
      skeleton.eq(0).find("td").css({
        "vertical-align" : "middle",
        "text-align" : "center"
      }).append(self.image, self.slide);
      self.control.prev = skeleton.eq(1).find("td").eq(0).addClass("slideShowPrev").click(function() {
        if (!j$(this).hasClass("bttn-disabled")) {
          self.prev();
        }
      }).bind("enable", function() {
        j$(this).removeClass("bttn-disabled").css({
          "background-position" : "0px -26px",
          cursor : "pointer"
        });
      }).bind("disable", function() {
        j$(this).addClass("bttn-disabled").css({
          "background-position" : "0px 0px",
          cursor : "default"
        });
      }).trigger("disable");
      skeleton.eq(1).find("td").eq(1).css({
        "vertical-align" : "center",
        "text-align" : "center"
      }).append(self.slide_select);
      self.control.next = skeleton.eq(1).find("td").eq(2).addClass("slideShowNext").click(function() {
        if (!j$(this).hasClass("bttn-disabled")) {
          self.next();
        }
      }).bind("enable", function() {
        j$(this).removeClass("bttn-disabled").css({
          "background-position" : "0px -26px",
          cursor : "pointer"
        });
      }).bind("disable", function() {
        j$(this).addClass("bttn-disabled").css({
          "background-position" : "0px 0px",
          cursor : "default"
        });
      }).trigger("disable");
      skeleton.eq(1).find("td").eq(3).css({
        "vertical-align" : "center",
        "text-align" : "center"
      }).append(self.slide_show);
      skeleton.eq(3).find("td").eq(1).css({
        "vertical-align" : "center",
        "text-align" : "center"
      }).append(self.slide_view);
      self.jpCont = j$('<div style="width:0;height:0"></div>');
      var jpCont = self.jpCont;
      var jpPlayer = j$('<div class="jp-seek-bar"></div>').append(j$('<div class="jp-play-bar"></div>').append(j$("<div></div>").css({
        "background-color" : "#e4f8dc",
        height : "13px"
      }))).append(j$("<div class='jp-current-time'>00.00</div>").css({
        position : "relative",
        "float" : "right",
        height : "13px",
        width : "100%",
        "vertical-align" : "center",
        "text-align" : "right",
        "font-size" : "10px",
        top : "-20px",
        "margin-right" : "3px"
      }));
      var vol_wrapper = $("<div></div>").css({
        position : "relative",
        margin : 0,
        padding : 0,
        width : "150px",
        height : "30px",
        overflow : "auto"
      });
      var vol_jp_volume_max = j$("<div class='jp-volume-max'></div>").css({
        position : "absolute",
        top : "2px",
        right : "0px",
        width : "12px",
        height : "12px",
        margin : "3px 3px 3px 3px"
      }).hover(function() {
        $(this).addClass("jp-volume-max-hover");
      }, function() {
        $(this).removeClass("jp-volume-max-hover");
      });
      var vol_jp_volume_bar = j$("<div class='jp-volume-bar'></div>").css({
        position : "absolute",
        top : "2px",
        right : "26px",
        width : "51px",
        height : "30x",
        margin : "3px"
      }).append(j$("<div class='jp-volume-bar-over'></div>"), j$("<div></div>").css({
        height : "2px",
        "padding-left" : "10px",
        position : "relative",
        border : "1px solid #cdd4d4",
        top : "2px",
        left : "6px"
      }), j$("<div class='jp-volume-bar-value'></div>"));
      var vol_jp_volume_min = j$("<div class='jp-volume-min'></div>").css({
        position : "absolute",
        top : "2px",
        right : "78px",
        width : "9px",
        height : "12px",
        margin : "3px"
      }).hover(function() {
        $(this).addClass("jp-volume-min-hover");
      }, function() {
        $(this).addClass("jp-volume-min-hover");
      }).click( function(jpCont) {
        return function() {
          jpCont.jPlayer("volume", 0);
        };
      }(jpCont));
      vol_wrapper.append(vol_jp_volume_max, vol_jp_volume_bar, vol_jp_volume_min);
      skeleton.eq(3).find("td").eq(2).css({
        "vertical-align" : "top"
      }).append(vol_wrapper);
      self.playStop = j$('<div class="play"></div>').hover(function() {
        j$(this).css({
          border : "3px double #89cc73"
        });
      }, function() {
        j$(this).css({
          border : "3px double #919191"
        });
      }).click( function(jpCont) {
        return function() {
          if (($(this).css("background-image") + "").indexOf("play.png") == -1) {
            $(this).removeClass("playStop");
            jpCont.jPlayer("pause");
          } else {
            if ($(this).parents("table").prev().find(".jp-play-bar").css("width") == "600px") {
              jpCont.jPlayer("playHead", 0).jPlayer("play");
            } else {
              $(this).addClass("playStop");
              jpCont.jPlayer("play");
            }
          }
        };
      }(jpCont));
      skeleton.eq(3).find("td").eq(0).css({
        "vertical-align" : "center",
        "text-align" : "right",
        visibility : "hidden"
      }).append(self.playStop).append(j$('<div class="p_back"></div>').append(j$("<div></div>").css({
        width : "19px",
        height : "24px",
        "float" : "left",
      }).hover(function() {
        j$(this).addClass("left_hover");
      }, function() {
        j$(this).removeClass("left_hover");
      }).click( function(jpCont) {
        return function() {
          jpCont.jPlayer("playHead", 0);
        };
      }(jpCont)).append(j$('<div class="left"></div>'))).append(j$("<div></div>").css({
        width : "19px",
        height : "24px",
        "float" : "left"
      }).hover(function() {
        j$(this).addClass("right_hover");
      }, function() {
        j$(this).removeClass("right_hover");
      }).click( function(jpCont) {
        return function() {
          jpCont.jPlayer("playHead", 100);
        };
      }(jpCont)).append(j$('<div class="right"></div>'))));
      skeleton.eq(2).find("td").append(jpCont).append(jpPlayer);
      self.control.audioPlayer = jpCont;
      self.audioDivs = [];
      self.audioDivs.push(skeleton.eq(3).find("td").eq(0));
      self.audioDivs.push(jpPlayer);
      self.audioDivs.push(skeleton.eq(3).find("td").eq(2));
      var inpC = $('<input type="button" id="inputf_' + self.id + '"/>').css({
        width : "1px",
        height : "1px",
        border : "0",
        position : "absolute",
        "z-index" : "-1"
      }).focusin( function(self) {
        return function() {
          self.wrapper.addClass("sc-selectedQuestion");
        };
      }(self)).focusout( function(self) {
        return function() {
          self.wrapper.removeClass("sc-selectedQuestion");
        };
      }(self)).bind("keydown", {
        self : self
      }, self.handleKeys);
      wrapper.append(inpC);
      wrapper.append(skeleton);
      var contId = self.id;
      jpCont.jPlayer({
        swfPath : "lib/jPlayer",
        wmode : "window",
        supplied : "mp3, oga",
        solution : "html",
        preload : "none",
        volume : 0.66,
        muted : false,
        backgroundColor : "#000000",
        cssSelectorAncestor : "#" + self.id,
        cssSelector : {
          videoPlay : ".jp-video-play",
          play : ".jp-play",
          pause : ".jp-pause",
          stop : ".jp-stop",
          seekBar : ".jp-seek-bar",
          playBar : ".jp-play-bar",
          volumeBar : ".jp-volume-bar",
          volumeBarValue : ".jp-volume-bar-value",
          volumeMax : ".jp-volume-max",
          currentTime : ".jp-current-time",
          duration : ".jp-duration",
          fullScreen : ".jp-full-screen",
          restoreScreen : ".jp-restore-screen",
          gui : ".jp-gui",
          noSolution : ".jp-no-solution"
        },
        errorAlerts : false,
        warningAlerts : false,
        ready : function(event) {
          self.update();
        },
        ended : function() {
          $(this).jPlayer("pause");
          jpCont.jPlayer("playHead", 100);
          if (self.params.slideshow) {
            self.next();
          }
        }
      });
      $(".jp-volume-max, .jp-volume-bar, .jp-volume-min").show().children().show();
    };
    var _parse_string = function() {
      return decodeURIComponent(this.replace(/\+/gi, " "));
    };
    var _not_selectable = {
      "-webkit-user-select" : "none",
      "-khtml-user-select" : "none",
      "-moz-user-select" : "none",
      "-o-user-select" : "none",
      "user-select" : "none"
    };
    slideshow.prototype.handleKeys = function(e) {
      var self = e.data.self;
      switch(e.keyCode) {
        case 39:
          self.next();
          break;
        case 37:
          self.prev();
          break;
        case 76:
          if (e.altKey) {
            self.slideshow();
          }
          break;
        case 77:
          if (e.altKey) {
            self.change_view();
          }
          break;
        case 38:
          var volBarValue = j$(self.wrapper).find(".jp-volume-bar-value");
          var vol = volBarValue.width() / volBarValue.parent().width();
          vol = Math.min(vol + 0.1, 1);
          self.jpCont.jPlayer("volume", vol);
          break;
        case 40:
          var volBarValue = j$(self.wrapper).find(".jp-volume-bar-value");
          var vol = volBarValue.width() / volBarValue.parent().width();
          vol = Math.max(vol - 0.1, 0);
          self.jpCont.jPlayer("volume", vol);
          break;
        case 71:
          if (e.altKey) {
            self.playStop.trigger("click");
          }
          break;
        case 74:
          if (e.altKey) {
            self.jpCont.jPlayer("playHead", 0);
          }
          break;
        case 75:
          if (e.altKey) {
            self.jpCont.jPlayer("playHead", 100);
          }
          break;
        default:
          return true;
      }
      e.preventDefault();
    };
    slideshow.prototype.change_view = function() {
	var self = this;
      if (this.image.is(":visible")) {
        this.image.hide();
        this.slide.show();
        this.slide_view.html(self.params.slideText);
      } else {
        this.image.show();
        this.slide.hide();
        this.slide_view.html(self.params.viewText);
      }
    };
    slideshow.prototype.next = function() {
      var c = this.cards;
      if (c.current != c.length - 1) {
        c.current++;
        this.update();
      } else {
        if (this.params.slideshow) {
          this.slideshow();
        }
      }
    };
    slideshow.prototype.prev = function() {
      var c = this.cards;
      if (c.current !== 0) {
        c.current--;
        this.update();
      }
    };
    slideshow.prototype.select = function() {
      this.cards.current = parseInt(this.slide_select.val());
      this.update();
    };
    slideshow.prototype.slideshow = function() {
      var self = this, c = this.cards;
      if (this.params.slideshow) {
        clearInterval(self.params.slideshowI);
        self.slide_show.html("Start Slideshow");
      } else {
        if (c.current == c.length - 1) {
          c.current = 0;
          self.update();
        }
        self.slide_show.html("Stop Slideshow");
        self.params.slideshowI = setInterval(function() {
          self.next();
        }, self.params.duration);
      }
      this.params.slideshow = !this.params.slideshow;
    };
    slideshow.prototype.update = function() {
      this.slide_select.trigger("enable");
      this.slide_show.trigger("enable");
      this.slide_view.trigger("enable");
      var c = this.cards, n = c.current;
      var self = this;
      this.image.attr({
        src : c[n].image,
        width : c[n].width,
        height : c[n].height
      });
      this.slide.html(c[n].slide);
      this.slide_select.val(n);
      if (c[n].audio) {
        if (this.params.slideshow) {
          clearInterval(this.params.slideshowI);
        }
        this.control.audioPlayer.jPlayer("setMedia", {
          mp3 : c[n].audio,
          oga : c[n].audio.substring(0, c[n].audio.lastIndexOf(".")) + ".ogg"
        });
        setTimeout(function() {
          self.control.audioPlayer.jPlayer("play", 0);
        }, 100);
        for (var i = 0; i < this.audioDivs.length; i++) {
          this.audioDivs[i].css({
            visibility : "visible"
          });
        }
      } else {
        this.control.audioPlayer.jPlayer("stop");
        for (var i = 0; i < this.audioDivs.length; i++) {
          this.audioDivs[i].css({
            visibility : "hidden"
          });
        }
        if (this.params.slideshow) {
          clearInterval(this.params.slideshowI);
          this.params.slideshowI = setInterval(function() {
            self.next();
          }, this.params.duration);
        }
      }
      if (n == c.length - 1) {
        this.control.prev.trigger("enable");
        this.control.next.trigger("disable");
      } else {
        if (n == 0) {
          this.control.prev.trigger("disable");
          this.control.next.trigger("enable");
        } else {
          this.control.prev.trigger("enable");
          this.control.next.trigger("enable");
        }
      }
    };
    slideshow.prototype.reset = function() {
      return false;
    };
    slideshow.prototype.save_state = function() {
      var state = "";
      return state;
    };
    slideshow.prototype.load_state = function() {
      var state = arguments[0].split(";").reverse();
    };
    j$.shuffle = function(arr) {
      for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x) {
      }
    };
  })(jQuery, window);
  SCPTModel("Sorting", {
    defaults : {
      img : "",
      labels : [],
      startCoords : []
    }
  }, {
    init : function(jsonObj, params) {
      this._super(jsonObj, params, "sorting");
      this.cards = jsonObj.card.length ? jsonObj.card : [jsonObj.card];
      for (var i = 0; i < this.cards.length; i++) {
        this.cards[i].text = this.decode(this.cards[i].text);
        this.cards[i].title = this.decode(this.cards[i].title);
        this.cards[i].title2 = this.decode(this.cards[i].title2);
      }
      this.reinit();
      this.sortLabels = [];
      for (var i = 1; i < 6; i++) {
        if (jsonObj["cat" + i]) {
          this.sortLabels.push(this.decode(jsonObj["cat" + i]+""));
        }
      }
    },
    reinit : function() {
      this._super();
      this.pointsArr = [];
      this.selectedObject = -1;
      this.currentZIndex = 1;
      for (var i = 0; i < this.cards.length; i++) {
        this.pointsArr.push(-2);
      }
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.pointsArr = jsonObj.innerState;
    },
    getState : function(jsonObj) {
      var obj = this._super();
      obj.innerState = this.pointsArr;
      return obj;
    }
  });
  SCPTController("Sortings", {}, {
    init : function() {
      var self = this;
      self.options.model.attempts++;
      var container = $("#" + this.options.model.containerId);
      this.options.model.randArrs = [];
      this.randomOrder = this.options.model.returnRandomOrder(this.options.model.cards.length)
      container.html(this.options.template, {
        labels : this.options.model.cards,
        sortLabels : this.options.model.sortLabels,
        offsetTop : parseInt(container.offset().top, 10),
        id : this.options.model.containerId,
        color : this.options.model.backgroundColor,
        width : this.options.model.width,
        height : this.options.model.height,
        randArr : self.randomOrder,
        bigText : this.options.model.isBigText == "true" ? "sc-bigText" : ""
      });
      for (var i = 0; i < this.options.model.cards.length; i++) {
        var obj = $("#" + this.options.model.getIdByIndex(i));
        this.options.model.startCoords[i] = {
          x : obj.css("left"),
          y : obj.css("top")
        };
      }
      var par = 100;
      container.find(".sc-sort-image > img").each(function() {
        var img = new Image();
        var t = $(this).parent().parent().parent().attr("id");
        img.onload = function() {
          var w = this.width;
          var h = this.height;
          var r;
          if (this.width > par) {
            r = par / w;
            w = par;
            h = this.height * r;
          }
          if (h > par) {
            r = par / h;
            h = par;
            w = w * r;
          }
          $("#" + t).find("img").css({
            width : w + "px",
            height : h + "px"
          });
        };
        img.src = this.src;
      });
      this._super();
      this.showDeckTop(self.options.model.cards.length);
    },
    revert : function(dragId) {
      $("#" + this.options.model.getIdByIndex(dragId)).css({
        top : this.options.model.startCoords[dragId].y,
        left : this.options.model.startCoords[dragId].x
      });
    },
    bindEvents : function(self) {
      $("#" + this.options.model.containerId).find(".sc-sort").bind("draginit", function(ev, drag) {
        return function() {
          if (!self.options.model.fromKeyBoard) {
            drag.revert();
          }
        }();
      });
      $("#" + this.options.model.containerId).find(".sc-sort-sortTarget").each(function(index) {
        $(this).bind("dropon", function(ev, drop, drag) {
          var isTrue = 0;
          var dragId = drag.delegate.getAttribute("data-id");
          var dropId = drop.element[0].getAttribute("data-id");
          if (drag.delegate.getAttribute("target-id") == dropId) {
            isTrue = 1;
            drag.revert(false);
            drag.position(new jQuery.Vector($(drop.element[0]).offset().left, $(drop.element[0]).offset().top));
            $(drag.delegate).unbind();
          }
          if (isTrue) {
            if (self.options.model.pointsArr[dragId] == -2) {
              self.options.model.currentScore += isTrue;
            }
            self.options.model.pointsArr[dragId] = dropId;
          } else {
            self.options.model.pointsArr[dragId] = -1;
          }
          if (!isTrue) {
            self.revert(dragId);
          }
          self.playIsCorrect(isTrue);
          self.updateStatus();
          var isCompleted = true;
          for (var i = 0, l = self.options.model.pointsArr.length; i < l; i++) {
            if (self.options.model.pointsArr[i] < 0) {
              isCompleted = false;
              break;
            }
          }
          if (isCompleted) {
            self.completed();
          }
        });
      });
      $("#" + this.options.model.containerId).find(".sc-sort-sortDeck").bind("click", function() {
        self.nextCard();
      });
      $("#" + this.options.model.containerId).find("#sort_0_" + this.options.model.containerId).bind("click", function() {
        self.reDeal();
      });
      $("#restart_" + this.options.model.containerId).bind("click", function() {
        self.reset();
      });
    },
    nextCard : function() {
      this.options.model.selectedObject++;
      var targetCard = this.randomOrder[this.options.model.selectedObject];
      while (this.options.model.pointsArr[targetCard] > -1 && targetCard < this.options.model.pointsArr.length) {
        this.options.model.selectedObject++;
        targetCard = this.randomOrder[this.options.model.selectedObject];
      }
      $("#" + this.options.model.getIdByIndex(targetCard)).show().css({
        "z-index" : this.options.model.currentZIndex++
      });
      var unshowed = 0;
      for (var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
        if (!$("#" + this.options.model.getIdByIndex(i)).is(":visible")) {
          unshowed++;
        }
      }
      this.showDeckTop(unshowed);
    },
    reDeal : function() {
      this.options.model.selectedObject = -1;
      var unshowed = 0;
      for (var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
        if (this.options.model.pointsArr[i] < 0) {
          unshowed++;
          $("#" + this.options.model.getIdByIndex(i)).hide();
        }
      }
      for (var i = 1; i <= 3; i++) {
        $("#sort_" + i + "_" + this.options.model.containerId).show();
      }
      this.showDeckTop(unshowed);
    },
    showDeckTop : function(unshowed) {
      if (unshowed < 3) {
        $("#sort_3_" + this.options.model.containerId).hide();
        if (unshowed < 2) {
          $("#sort_2_" + this.options.model.containerId).hide();
        }
        if (unshowed < 1) {
          $("#sort_1_" + this.options.model.containerId).hide();
        }
      }
    },
    updateStatus : function() {
      var pts = this.options.model.currentScore * (this.options.model.maxScore / this.options.model.pointsArr.length);
      pts = Math.round(10 * pts) / 10;
      $("#statusText_" + this.options.model.containerId).html( this.options.model.scoreText+" " + pts + "/" + this.options.model.maxScore);
      var notPlaced = 0;
      for (var i = 0; i < this.options.model.pointsArr.length; i++) {
        if (this.options.model.pointsArr[i] < 0) {
          notPlaced++;
        }
      }
      $("#sort_sub_" + this.options.model.containerId).html(notPlaced + "/" + this.options.model.pointsArr.length);
    },
    switchToNext : function() {
      if ($("#sort_1_" + this.options.model.containerId).is(":visible")) {
        this.nextCard();
      } else {
        this.reDeal();
      }
    },
    showAnswer : function() {
      for (var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
        var obj = $("#" + this.options.model.getIdByIndex(i));
        var target = $("#sortTarget_" + (obj.attr("target-id")) + "_" + this.options.model.containerId);
        var container = $("#" + this.options.model.containerId);
        obj.css({
          left : target.offset().left - container.offset().left - 4,
          top : target.offset().top - container.offset().top - 4
        }).show();
      }
      this.nextCard();
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.updateStatus();
      for (var i = 0, l = this.options.model.pointsArr.length; i < l; i++) {
        if (this.options.model.pointsArr[i] > -1) {
          var target = $("#sortTarget_" + (this.options.model.pointsArr[i]) + "_" + this.options.model.containerId);
          $("#" + this.options.model.getIdByIndex(i)).css({
            left : target.offset().left - 4,
            top : target.offset().top - 4
          }).show();
        }
      }
    }
  });
  SCPTModel("Crossword", {}, {
    init : function(jsonObj, params) {
      if (!params.isXML) {
        jsonObj = this.parseStringToXML(jsonObj);
      }
      this._super(jsonObj, params, "crossword");
      this.dimensions = [jsonObj.rows || 15, jsonObj.columns || 15];
      this.acrosstext = jsonObj.acrosstext;
      this.downtext = jsonObj.downtext;
      this.words = jsonObj.words;
      this.isXML = params.isXML;
      this.acrossSource = jsonObj.across;
      this.downSource = jsonObj.down;
      if (!this.isXML) {
        var wordSize = 0;
        for (var i = this.words.length; i--; ) {
          wordSize = Math.max(wordSize, this.words[i].word.length);
        }
        var maxDim = 25;
        if (jsonObj.words.length < 20 && wordSize < 15) {
          maxDim = 15;
        } else {
          if (jsonObj.words.length >= 20 && jsonObj.words.length < 30 && wordSize < 20) {
            maxDim = 20;
          }
        }
        this.dimensions = [maxDim, maxDim];
        var newCrossWord = generateCrossword(this.dimensions[0], this.dimensions[1], this.words);
        this.acrossSource = newCrossWord.across;
        this.downSource = newCrossWord.down;
      }
      this.state = new Array(this.dimensions[0]);
      for (var i = 0; i < this.state.length; i++) {
        this.state[i] = new Array(this.dimensions[1]);
      }
      this.dictionary = {
        indexes : []
      };
      if (this.acrossSource.word.length == undefined) {
        this.acrossSource = {
          clue : [this.acrossSource.clue],
          index : [this.acrossSource.index],
          word : [{
            word : this.acrossSource.word.word
          }],
          x_pos : [this.acrossSource.x_pos],
          y_pos : [this.acrossSource.y_pos]
        };
      }
      if(!this.downSource.word) {
        this.downSource.word = [];      
      }      
      if (this.downSource.word.length == undefined) {
        this.downSource = {
          clue : [this.downSource.clue],
          index : [this.downSource.index],
          word : [{
            word : this.downSource.word.word
          }],
          x_pos : [this.downSource.x_pos],
          y_pos : [this.downSource.y_pos]
        };
      }
      for (var i = 0; i < this.acrossSource.word.length; i++) {
        this.acrossSource.clue[i] = this.decode(this.acrossSource.clue[i]);
        this.acrossSource.word[i].word = this.decode(this.acrossSource.word[i].word);
      }
      for (var i = 0; i < this.downSource.word.length; i++) {
        this.downSource.clue[i] = this.decode(this.downSource.clue[i]);
        this.downSource.word[i].word = this.decode(this.downSource.word[i].word);
      }
      this.across = this.orderWords(this.acrossSource, this.dictionary, "across");
      this.down = this.orderWords(this.downSource, this.dictionary, "down");
      this.direction = "down";
      this.selectedWord = [];
      this.reinit();
    },
    reinit : function() {
      this._super();
      this.keyPressed = [];
      this.outerDirection = false;
      if (!this.isXML) {
        this.dictionary = {
          indexes : []
        };
        var newCrossWord = generateCrossword(this.dimensions[0], this.dimensions[1], this.words);
        this.acrossSource = newCrossWord.across;
        this.downSource = newCrossWord.down;
        for (var i = 0; i < this.acrossSource.word.length; i++) {
          this.acrossSource.clue[i] = this.decode(this.acrossSource.clue[i]);
          this.acrossSource.word[i].word = this.decode(this.acrossSource.word[i].word);
        }
        for (var i = 0; i < this.downSource.word.length; i++) {
          this.downSource.clue[i] = this.decode(this.downSource.clue[i]);
          this.downSource.word[i].word = this.decode(this.downSource.word[i].word);
        }
        this.across = this.orderWords(this.acrossSource, this.dictionary, "across");
        this.down = this.orderWords(this.downSource, this.dictionary, "down");
      }
      this.isFinished = false;
      this.pointsArr = new Array(this.dictionary.indexes.length);
      for (var i = 0; i < this.state.length; i++) {
        for (var j = 0; j < this.state[i].length; j++) {
          this.state[i][j] = -1;
        }
      }
      for (var i = 0; i < this.down.length; i++) {
        for (var t = 0; t < this.down[i].word.length; t++) {
          this.state[this.down[i].x_pos][this.down[i].y_pos + t] = this.down[i].index + "d";
        }
      }
      for (var i = 0; i < this.across.length; i++) {
        for (var t = 0; t < this.across[i].word.length; t++) {
          this.state[this.across[i].x_pos+t][this.across[i].y_pos] = this.across[i].index + "a";
        }
      }
      for (var i = 0; i < this.pointsArr.length; i++) {
        this.pointsArr[i] = 0;
      }
      this.activeCell = [this.dictionary[this.dictionary.indexes[0]].x_pos, this.dictionary[this.dictionary.indexes[0]].y_pos];
      this.selectedWord.index = 1;
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.pointsArr = jsonObj.pointsArr;
      this.state = jsonObj.state;
    },
    getState : function(jsonObj) {
      var obj = this._super();
      obj.pointsArr = this.pointsArr;
      obj.state = this.state;
      return obj;
    },
    orderWords : function(jsonObj, dict, direction) {
      var h = {}, obj = [], indArr = [];
      for (var i = 0; i < jsonObj.word.length; i++) {
        indArr.push(jsonObj.index[i]);
      }
      indArr.sort(function(a, b) {
        return a - b;
      });
      for (var i = 0; i < jsonObj.word.length; i++) {
        indArr["s" + jsonObj.index[i]] = i;
      }
      for (var i = 0; i < indArr.length; i++) {
        h[indArr[i]] = indArr["s" + indArr[i]];
      }
      for (var s in h) {
        obj.push({
          index : s,
          x_pos : jsonObj.x_pos[h[s]],
          y_pos : jsonObj.y_pos[h[s]],
          word : jsonObj.word[h[s]].word,
          clue : jsonObj.clue[h[s]]
        });
        var s1 = s + direction[0];
        dict.indexes.push(s1);
        dict[s1] = {
          index : s1,
          x_pos : jsonObj.x_pos[h[s]],
          y_pos : jsonObj.y_pos[h[s]],
          word : jsonObj.word[h[s]].word,
          clue : jsonObj.clue[h[s]],
          direction : direction
        };
      }
      return obj;
    },
    parseStringToXML : function(str) {
      var retObj = {
        words : []
      };
      var params = str.split("&");
      for (var i = 1; i < params.length - 1; i++) {
        var pair = params[i].split("=");
        if (pair[1]) {
          pair[1] = this.decode(pair[1]);
        }
        var prefix = pair[0].substring(0, 4);
        if (prefix == "word" || prefix == "clue") {
          var ind = pair[0].substring(4);
          if (!retObj.words[ind]) {
            retObj.words[ind] = {};
          }
          retObj.words[ind][prefix] = pair[1];
        } else {
          retObj[pair[0]] = pair[1];
        }
      }
      return retObj;
    }
  });
  SCPTController("Crosswords", {}, {
    init : function() {
      var self = this;
      self.options.model.attempts++;
      var container = $("#" + this.options.model.containerId);
      container.html(this.options.template, {
        id : this.options.model.containerId,
        color : this.options.model.backgroundColor,
        width : this.options.model.width,
        height : this.options.model.height,
        dimensions : this.options.model.dimensions,
        acrossText : this.options.model.acrosstext,
        downText : this.options.model.downtext,
        maxScore : this.options.model.maxScore,
        across : this.options.model.across,
        down : this.options.model.down,
        state : this.options.model.state
      });
      this._super();
      if (self.options.model.isIpad) {
        this.bindKeyEvents();
      }
      this.refreshView();
      var scroll_w = ('ontouchstart' in document.documentElement) ? 4 : 10;
      if('ontouchstart' in document.documentElement) {
        container.find('.crosswordDefs').niceScroll({
          'cursorwidth' : scroll_w
        });
      } else {
        container.find('.crosswordDefs').niceScroll({
          'cursorwidth' : scroll_w,
          cursoropacitymin : 1,
          cursoropacitymax : 1
        });
      }
    },
    bindKeyEvents : function() {
      var self = this;
      var contId = self.options.model.containerId;
      if (!this.options.model.isAndroid) {
        $("#" + contId).click( function(self) {
          return function() {
            $("#inputf_" + contId).focus();
          };
        }(self));
      }
      $("#inputf_" + contId).focusin( function(self) {
        return function() {
          $("#" + contId).children().first().addClass("sc-selectedQuestion");
        };
      }(self)).focusout( function(self) {
        return function() {
          $("#" + contId).children().first().removeClass("sc-selectedQuestion");
        };
      }(self)).bind("keyup", {
        self : self
      }, self.handleKeys).bind("keypress", {
        self : self
      }, function(evt) {
        self.options.model.keyPressed.push(evt.keyCode);
      }).bind("keydown", function(evt) {
        if (evt.keyCode == 32 || (evt.keyCode >= 37 && evt.keyCode <= 40)) {
          evt.preventDefault();
        }
      });
    },
    bindEvents : function(self) {
      var self = this;
      $("#restart_" + this.options.model.containerId).bind("click", function() {
        self.reset();
      });
      $(".crosswordCellInput").bind("click", function(contId, self) {
        return function(e) {
          var tarr = $(this).attr("id").split("_");
          self.options.model.prevCell = [self.options.model.activeCell[0], self.options.model.activeCell[1]];
          self.options.model.activeCell = [parseInt(tarr[2]), parseInt(tarr[3])];
          if (self.options.model.firstCell) {
            self.restoreCellPosition(self.options.model.firstCell, self);
          }
          this.coords = $(this).position();
          this.pos = [parseInt(tarr[2]), parseInt(tarr[3])];
          self.options.model.firstCell = this;
          self.refreshView();
          if (!self.options.model.isAndroid) {
            $("#inputf_" + contId).focus();
          }
        };
      }(this.options.model.containerId, self)).bind("keyup", {
        self : self
      }, function(e) {
        $(this)[0].value = "";
        var m = e.data.self.options.model;
        var targetInput = $("#inputf_" + e.data.self.options.model.containerId);
        e.currentTarget = targetInput[0];
        targetInput.trigger(e);
      }).bind("keypress", {
        self : self
      }, function(evt) {
        self.options.model.keyPressed.push(evt.keyCode);
      });
      $("#" + this.options.model.containerId).find(".crosswordDefs").eq(0).find(".crosswordDef").bind("click", function() {
        var coord = ($(this).attr("data-cell") + "").split("#");
        self.options.model.direction = "across";
        self.options.model.outerDirection = true;
        var id = $(this).attr("id") + "";
        self.options.model.outerWord = self.options.model.dictionary[id.substr(id.lastIndexOf("_") + 1)];
        $("#cellinput_" + self.options.model.containerId + "_" + coord[0] + "_" + coord[1]).click();
      });
      $("#" + this.options.model.containerId).find(".crosswordDefs").eq(1).find(".crosswordDef").bind("click", function() {
        var coord = ($(this).attr("data-cell") + "").split("#");
        self.options.model.direction = "down";
        self.options.model.outerDirection = true;
        var id = $(this).attr("id") + "";
        self.options.model.outerWord = self.options.model.dictionary[id.substr(id.lastIndexOf("_") + 1)];
        $("#cellinput_" + self.options.model.containerId + "_" + coord[0] + "_" + coord[1]).click();
      });
      $("#finish_" + self.options.model.containerId).bind("click", function() {
        self.showAnswer();
        self.completed();
      });
      $("#inputf_" + self.options.model.containerId).bind("keydown", function(evt) {
        if (evt.keyCode == 32 || (evt.keyCode >= 37 && evt.keyCode <= 40) || evt.keyCode == 8) {
          evt.preventDefault();
        }
      });
    },
    restoreCellPosition : function(cell, self) {
      $(cell).css({
        left : self.options.model.firstCell.coords.left + "px",
        top : self.options.model.firstCell.coords.top + "px"
      });
    },
    switchWord : function(ind) {
      var list = $("#" + this.options.model.containerId).find(".crosswordDef"), p = "";
      for (var i = 0; i < list.length; i++) {
        if (list.eq(i).hasClass("sc-selected")) {
          p = list.eq((i + ind) % list.length);
        }
      }
      if (p) {
        p.click();
      }
    },
    showAnswer : function() {
      var m = this.options.model;
      m.isFinished = true;
      for (var i = 0; i < m.down.length; i++) {
        for (var t = 0; t < m.down[i].word.length; t++) {
          $("#cell_" + m.containerId + "_" + m.down[i].x_pos + "_" + (m.down[i].y_pos + t)).html(m.down[i].word[t]);
        }
      }
      for (var i = 0; i < m.across.length; i++) {
        for (var t = 0; t < m.across[i].word.length; t++) {
          $("#cell_" + m.containerId + "_" + (m.across[i].x_pos + t) + "_" + m.across[i].y_pos).html(m.across[i].word[t]);
        }
      }
      this.refreshView();
    },
    handleKeys : function(e) {
      var m = e.data.self.options.model;
      m.prevCell = [m.activeCell[0], m.activeCell[1]];
      if (e.altKey) {
        switch(e.keyCode) {
          case 85:
            e.data.self.reset(false);
            return false;
            break;
          case 81:
            e.data.self.showAnswer();
            e.data.self.completed();
            break;
          case 77:
            e.data.self.switchWord(1);
            break;
          case 80:
            e.data.self.switchWord(-1);
            break;
          default:
            return false;
        }
      } else {
        switch(e.keyCode) {
          case 37:
            m.keyPressed.shift();
            if (m.activeCell[0] > 0 && m.state[m.activeCell[0]-1][m.activeCell[1]] != -1) {
              m.activeCell[0]--;
            }
            break;
          case 38:
            m.keyPressed.shift();
            if (m.activeCell[1] > 0 && m.state[m.activeCell[0]][m.activeCell[1] - 1] != -1) {
              m.activeCell[1]--;
            }
            break;
          case 39:
            m.keyPressed.shift();
            if (m.activeCell[0] < m.state[0].length - 1 && m.state[m.activeCell[0]+1][m.activeCell[1]] != -1) {
              m.activeCell[0]++;
            }
            break;
          case 40:
            m.keyPressed.shift();
            if (m.activeCell[1] < m.state.length - 1 && m.state[m.activeCell[0]][m.activeCell[1] + 1] != -1) {
              m.activeCell[1]++;
            }
            break;
          case 46:
            m.keyPressed.shift();
            $("#cell_" + e.data.self.options.model.containerId + "_" + m.activeCell[0] + "_" + m.activeCell[1]).html("");
            break;
          case 8:
            if (!e.data.self.options.model.isAndroid) {
              $("#cell_" + e.data.self.options.model.containerId + "_" + m.activeCell[0] + "_" + m.activeCell[1]).html("");
              e.data.self.toPrevCell();
            }
            m.keyPressed.shift();
            e.preventDefault();
            break;
          case 20:
          case 17:
          case 46:
          case 40:
          case 35:
          case 13:
          case 27:
          case 36:
          case 45:
          case 37:
          case 34:
          case 33:
          case 39:
          case 16:
          case 9:
          case 38:
          case 116:
          case 18:
            return true;
          default:
            var code = e.keyCode;
            var character = String.fromCharCode(m.keyPressed.shift() || e.which).toUpperCase();
            if (code == 188) {
              character = ",";
            }
            if (code == 190) {
              character = ".";
            }
            $("#cell_" + e.data.self.options.model.containerId + "_" + m.activeCell[0] + "_" + m.activeCell[1]).html(character);
            e.data.self.toNextCell();
            return true;
        }
      }
      e.preventDefault();
      e.data.self.refreshView();
    },
    refreshView : function() {
      var m = this.options.model;
      if (m.prevCell) {
        $("#cell_" + m.containerId + "_" + m.prevCell[0] + "_" + m.prevCell[1]).parent().parent().removeClass("sc-selected");
      }
      var tgt = m.activeCell[0] + "_" + m.activeCell[1];
      $("#cell_" + m.containerId + "_" + tgt).parent().parent().addClass("sc-selected");
      var isSameWord = false;
      for (var i = 0; i < m.selectedWord.length; i++) {
        if (tgt == m.selectedWord[i]) {
          isSameWord = true;
        }
      }
      if (!isSameWord) {
        for (var i = 0; i < m.selectedWord.length; i++) {
          $("#cell_" + m.containerId + "_" + m.selectedWord[i]).parent().parent().removeClass("highlighted");
        }
        if (m.selectedWord.index) {
          $("#def_" + m.containerId + "_" + m.selectedWord.index).removeClass("sc-selected");
        }
        m.selectedWord = [];
        var tobj = m.dictionary[m.state[m.activeCell[0]][m.activeCell[1]]];
        if (m.outerDirection) {
          tobj = m.outerWord;
        }
        m.selectedWord.index = tobj.index;
        $("#def_" + m.containerId + "_" + tobj.index).addClass("sc-selected");
        if ((m.outerDirection && m.direction == "across") || (!m.outerDirection && (m.activeCell[0] > 0 && m.state[m.activeCell[0]-1][m.activeCell[1]] != -1 || m.activeCell[0] < m.state.length - 1 && m.state[m.activeCell[0]+1][m.activeCell[1]] != -1))) {
          m.direction = "across";
          for (var i = 0; i < tobj.word.length; i++) {
            $("#cell_" + m.containerId + "_" + (tobj.x_pos + i) + "_" + (tobj.y_pos)).parent().parent().addClass("highlighted");
            m.selectedWord.push((tobj.x_pos + i) + "_" + (tobj.y_pos));
          }
        } else {
          m.direction = "down";
          for (var i = 0; i < tobj.word.length; i++) {
            $("#cell_" + m.containerId + "_" + tobj.x_pos + "_" + (tobj.y_pos + i)).parent().parent().addClass("highlighted");
            m.selectedWord.push((tobj.x_pos) + "_" + (tobj.y_pos + i));
          }
        }
        m.selectedWord.index = tobj.index;
      }
      if (m.firstCell && m.isIpad) {
        $(m.firstCell).css({
          top : (m.firstCell.coords.top + (m.activeCell[1] - m.firstCell.pos[1]) * 30) + "px",
          left : (m.firstCell.coords.left + (m.activeCell[0] - m.firstCell.pos[0]) * 30) + "px"
        });
      }
      m.outerDirection = false;
      this.checkAnswer();
      this.updateStatus();
    },
    checkAnswer : function() {
      var m = this.options.model;
      var dirs = ["across", "down"];
      for (var ii = 0; ii < dirs.length; ii++) {
        for (var i = 0; i < m[dirs[ii]].length; i++) {
          var isT = true;
          for (var t = 0; t < m[dirs[ii]][i].word.length; t++) {
            var dx = 0, dy = 0;
            if (dirs[ii] == "across") {
              dx = t;
            } else {
              dy = t;
            }
            $("#cell_" + m.containerId + "_" + (m[dirs[ii]][i].x_pos + dx) + "_" + (m[dirs[ii]][i].y_pos + dy) ).parent().parent().removeClass("correct");
            if ($("#cell_" + m.containerId + "_" + (m[dirs[ii]][i].x_pos + dx) + "_" + (m[dirs[ii]][i].y_pos + dy)).html() != m[dirs[ii]][i].word[t]) {
              isT = false;
            }
          }
          var tgtindex = -1;
          for (var jj = 0; jj < m.dictionary.indexes.length; jj++) {
            if (m.dictionary.indexes[jj] == m[dirs[ii]][i].index + dirs[ii][0]) {
              tgtindex = jj;
              break;
            }
          }
          if (isT) {
            m.pointsArr[tgtindex] = 1;
          } else {
            m.pointsArr[tgtindex] = 0;
          }
        }
      }
      var isCompleted = true;
      var currentScore = 0;
      for (var i = 0; i < m.pointsArr.length; i++) {
        if (m.pointsArr[i] == 1) {
          currentScore++;
          var obj = m.dictionary[m.dictionary.indexes[i]];
          for (var t = 0; t < obj.word.length; t++) {
            var dx = 0, dy = 0;
            if (obj.direction == "across") {
              dx = t;
            } else {
              dy = t;
            }
            $("#cell_" + m.containerId + "_" + (obj.x_pos + dx) + "_" + (obj.y_pos + dy)).parent().parent().addClass("correct");
          }
        } else {
          isCompleted = false;
        }
      }
      if (!m.isFinished) {
        m.currentScore = currentScore;
        if (isCompleted) {
          this.completed();
        }
      }
    },
    toNextCell : function() {
      var m = this.options.model;
      if (m.direction == "down") {
        if (m.activeCell[1] < m.state.length - 1 && m.state[m.activeCell[0]][m.activeCell[1] + 1] != -1) {
          m.activeCell[1]++;
        } else {
          if (m.activeCell[0] < m.state[0].length - 1 && m.state[m.activeCell[0]+1][m.activeCell[1]] != -1) {
            m.direction = "across";
            this.toNextCell();
          }
        }
      } else {
        if (m.activeCell[0] < m.state[0].length - 1 && m.state[m.activeCell[0]+1][m.activeCell[1]] != -1) {
          m.activeCell[0]++;
        } else {
          if (m.activeCell[1] < m.state.length - 1 && m.state[m.activeCell[0]][m.activeCell[1] + 1] != -1) {
            m.direction = "down";
            this.toNextCell();
          }
        }
      }
      this.refreshView();
    },
    toPrevCell : function() {
      var m = this.options.model;
      if (m.direction == "down") {
        if (m.activeCell[1] > 0 && m.state[m.activeCell[0]][m.activeCell[1] - 1] != -1) {
          m.activeCell[1]--;
        } else {
          if (m.activeCell[0] > 0 && m.state[m.activeCell[0]-1][m.activeCell[1]] != -1) {
            m.direction = "across";
            this.toPrevCell();
          }
        }
      } else {
        if (m.activeCell[0] > 0 && m.state[m.activeCell[0]-1][m.activeCell[1]] != -1) {
          m.activeCell[0]--;
        } else {
          if (m.activeCell[1] > 0 && m.state[m.activeCell[0]][m.activeCell[1] - 1] != -1) {
            m.direction = "down";
            this.toPrevCell();
          }
        }
      }
      this.refreshView();
    },
    updateStatus : function() {
      var m = this.options.model;
      var pts = m.currentScore * (m.maxScore / (m.pointsArr.length));
      pts = Math.round(10 * pts) / 10;
      $("#statusText_" + m.containerId).html( m.scoreText+" " + pts + "/" + m.maxScore);
    },
    setState : function(jsonObj) {
      var m = this.options.model;
      this._super(jsonObj);
      var viewState = jsonObj.viewState;
      for (var i = 0; i < m.state.length; i++) {
        for (var j = 0; j < m.state[i].length; j++) {
          if (m.state[i][j] != -1) {
            $("#cell_" + m.containerId + "_" + (i) + "_" + (j)).html(viewState[i][j]);
          }
        }
      }
      this.refreshView();
      this.updateStatus();
    },
    getState : function() {
      var m = this.options.model;
      var obj = m.getState();
      var viewState = new Array(m.state.length);
      for (var i = 0; i < m.state.length; i++) {
        viewState[i] = new Array(m.state[i].length);
        for (var j = 0; j < m.state[i].length; j++) {
          if (m.state[i][j] != -1) {
            viewState[i][j] = $("#cell_" + m.containerId + "_" + (i) + "_" + (j)).html();
          }
        }
      }
      obj.viewState = viewState;
      return obj;
    }
  });
  var generateCrossword = function(num_rows, num_columns, words) {
    var counter = 0;
    var _global = this;
    var self = this;
    var target_num_words = 50;
    var crossword_grid = [];
    initialize_crossword_random_main = function() {
      var countWords = 0;
      var retObj = {};
      while (countWords < 2 && counter++ < 35 && words.length!=countWords) {
        retObj = initialize_crossword_random();
        countWords = 0;
        var drs = ["across", "down"];
        for (var i = 0; i < drs.length; i++) {
          var obj = retObj[drs[i]];
          countWords += obj.word.length;
          for (var j = 0; j < obj.word.length; j++) {
            var l = obj.word[j].word.length;
            if (drs[i] == "across") {
              l += obj.x_pos[j];
            } else {
              l += obj.y_pos[j];
            }
            if (l >= crossword_grid.length) {
              countWords = -1000;
            }
          }
        }
        var startletter = [], stack = [];
        for (var i = 0; i < crossword_grid.length; i++) {
          for (var j = 0; j < crossword_grid.length; j++) {
            if (crossword_grid[i][j].letter != "") {
              startletter = [i, j];
              stack.push([i, j]);
              break;
            }
          }
          if (startletter.length > 0) {
            break;
          }
        }
        while (stack.length > 0) {
          arr = stack.pop();
          crossword_grid[arr[0]][arr[1]].letter = "";
          if (arr[0] - 1 > 0 && crossword_grid[arr[0]-1][arr[1]].letter) {
            stack.push([arr[0] - 1, arr[1]]);
          }
          if (arr[0] + 1 < crossword_grid.length && crossword_grid[arr[0]+1][arr[1]].letter) {
            stack.push([arr[0] + 1, arr[1]]);
          }
          if (arr[1] - 1 > 0 && crossword_grid[arr[0]][arr[1] - 1].letter) {
            stack.push([arr[0], arr[1] - 1]);
          }
          if (arr[1] + 1 < crossword_grid.length && crossword_grid[arr[0]][arr[1] + 1].letter) {
            stack.push([arr[0], arr[1] + 1]);
          }
        }
        for (var i = 0; i < crossword_grid.length; i++) {
          for (var j = 0; j < crossword_grid.length; j++) {
            if (crossword_grid[i][j].letter != "") {
              countWords = -1000;
            }
          }
        }
      }
      return retObj;
    };
    initialize_crossword_random = function() {
      getData();
      crossword_grid = get_empty_crossword_grid();
      num_created_words = 0;
      var consecutive_idle = 0;
      embed_initial_words();
      while (true) {
        var old_num_created = num_created_words;
        test_embedding_possibilities();
        if (old_num_created == num_created_words) {
          consecutive_idle++;
        } else {
          consecutive_idle = 0;
        }
        if (consecutive_idle == 5 || num_created_words > target_num_words) {
          break;
        }
      }
      var retObject = {
        across : {
          clue : [],
          index : [],
          word : [],
          x_pos : [],
          y_pos : []
        },
        down : {
          clue : [],
          index : [],
          word : [],
          x_pos : [],
          y_pos : []
        }
      };
      var index = 1;
      for (var i = 0; i < crossword_grid.length; i++) {
        for (var j = 0; j < crossword_grid[i].length; j++) {
          var cell = crossword_grid[i][j];
          if (cell.first_letter) {
            for (var m = 0; m < cell.word_directions.length; m++) {
              retObject[cell.word_directions[m]].index.push(index);
              retObject[cell.word_directions[m]].x_pos.push(cell.k);
              retObject[cell.word_directions[m]].y_pos.push(cell.j);
              var wword = "";
              for (var ii = 0; ii < cell.through_directions.length; ii++) {
                if (cell.through_directions[ii] == cell.word_directions[m]) {
                  wword = cell.words_using_letter[ii];
                }
              }
              retObject[cell.word_directions[m]].word.push({
                word : wword.word
              });
              retObject[cell.word_directions[m]].clue.push(wword.clue);
            }
            index++;
          }
        }
      }
      return retObject;
    };
    getData = function() {
      word_list = new Array();
      maximum_word_length = Number.NEGATIVE_INFINITY;
      for (var j = 0; j < words.length; j++) {
        words[j].used = false;
        words[j].direction = "across";
        word_list.push(words[j]);
        if (words[j].word.length > maximum_word_length) {
          maximum_word_length = words[j].word.length;
        }
      }
    };
    embed_initial_words = function() {
      var list0 = filter_words_exact_length(words, maximum_word_length);
      var across_word = list0.rande();
      var rad = Math.max(0,Math.floor((num_columns - across_word.word.length - 1) / 2));
      var x = _global.randi(rad, 2 * rad);
      var y = _global.randi(Math.floor(num_rows / 3), Math.floor(2 / 3 * num_rows));
      var bool = embed_word_at(across_word, y, x, "across");
    };
    filter_words_exact_length = function(words, length) {
      var list = new Array();
      for (var j = 0; j < words.length; j++) {
        if ((words[j].word.length == length) && !words[j].used) {
          list.push(words[j]);
        }
      }
      return (list);
    };
    embed_word_at = function(word_obj, j, k, direction) {
      if (!word_is_embeddable(word_obj, j, k, direction)) {
        direction = (direction == "across") ? "down" : "across";
        if (!word_is_embeddable(word_obj, j, k, direction)) {
          return (false);
        }
      }
      crossword_grid[j][k].first_letter = true;
      crossword_grid[j][k].word_directions.push(direction);
      for (var n = 0; n < word_obj.word.length; n++) {
        var x = (direction == "across") ? (k + n) : k;
        var y = (direction == "down") ? (j + n) : j;
        var word_letter = word_obj.word.charAt(n);
        var grid_letter = crossword_grid[y][x].letter;
        crossword_grid[y][x].through_directions.push(direction);
        crossword_grid[y][x].words_using_letter.push(word_obj);
        crossword_grid[y][x].first_letter_x.push(k);
        crossword_grid[y][x].first_letter_y.push(j);
        if ((word_letter == grid_letter) || (grid_letter == "")) {
          crossword_grid[y][x].letter = word_letter;
        }
      }
      word_obj.used = true;
      num_created_words++;
      return (true);
    };
    word_is_embeddable = function(word_obj, j, k, direction) {
      try {
      for (var n = 0; n < word_obj.word.length; n++) {
        var x = (direction == "across") ? (k + n) : k;
        var y = (direction == "down") ? (j + n) : j;
        if (x < 0 || y < 0 || x > crossword_grid.length - 1 || y > crossword_grid[x].length - 1) {
          return false;
        }        
        if (direction == "across") {
          var nei0 = crossword_grid[y-1][x];
          var nei1 = crossword_grid[y+1][x];
          var end = crossword_grid[y][Math.min(x+1,crossword_grid.length - 1)];
        } else {
          var nei0 = crossword_grid[y][x - 1];
          var nei1 = crossword_grid[y][x + 1];
          var end = crossword_grid[Math.min(y+1,crossword_grid.length - 1)][x];
        }
        var word_letter = word_obj.word.charAt(n);
        var grid_letter = crossword_grid[y][x].letter;
        if ((word_letter != grid_letter) && (grid_letter != "")) {
          return (false);
        }
        var nei0_empty = (nei0.letter == "");
        var nei1_empty = (nei1.letter == "");
        var nei0_undef = (nei0.letter == undefined);
        var nei1_undef = (nei1.letter == undefined);
        if (((grid_letter == "") && ((!nei0_empty && !nei0_undef) || (!nei1_empty && !nei1_undef))) || ((n == word_obj.word.length - 1) && (end.letter != ""))) {
          return (false);
        }
      }
      return (true);
      } catch(e) {
        return false;
      }
    };
    test_embedding_possibilities = function() {
      var possibilities = get_analyzed_filtered_possibilities();
      possibilities.shuffle();
      for (var j = 0; j < possibilities.length; j++) {
        var poss = possibilities[j];
        var start = (poss.direction == "across") ? poss.possible_start.k : poss.possible_start.j;
        var end = (poss.direction == "across") ? poss.k : poss.j;
        for (var n = start; n <= end; n++) {
          var len = poss.possible_length - (n - start);
          var list0 = filter_words_lesser_greater_length(word_list, (n - start), poss.possible_length);
          var list1 = filter_words_containing_letter_at(list0, poss.letter, end - n);
          list1.shuffle();
          var x = (poss.direction == "across") ? n : poss.k;
          var y = (poss.direction == "down") ? n : poss.j;
          for (var m = 0; m < list1.length; m++) {
            var result = embed_word_at(list1[m], y, x, poss.direction);
            if (result) {
              return (true);
            }
          }
        }
      }
      return (false);
    };
    get_analyzed_filtered_possibilities = function() {
      var possibilities = get_cell_possibilities_list();
      for (var j = 0; j < possibilities.length; j++) {
        var cell = possibilities[j];
        var x = cell.k + (cell.direction == "across" ? -1 : 0);
        var y = cell.j + (cell.direction == "down" ? -1 : 0);
        var len2 = 0;
        while (y > 0 && x > 0 && crossword_grid[y][x].letter.length == 0) {
          len2++;
          if (cell.direction == "across") {
            x--;
          }
          if (cell.direction == "down") {
            y--;
          }
        }
        if (y < crossword_grid[x].length - 1 && x < crossword_grid.length - 1 && crossword_grid[y][x] != undefined) {
          len2 -= 2;
          if (cell.direction == "across") {
            x += 2;
          }
          if (cell.direction == "down") {
            y += 2;
          }
        } else {
          if (cell.direction == "across") {
            x++;
          }
          if (cell.direction == "down") {
            y++;
          }
        }
        cell.possible_start = {
          j : y,
          k : x
        };
        var x = cell.k + (cell.direction == "across" ? 1 : 0);
        var y = cell.j + (cell.direction == "down" ? 1 : 0);
        var len1 = 0;
        while (y < crossword_grid[x].length - 1 && x < crossword_grid.length - 1 && crossword_grid[y][x].letter.length == 0) {
          len1++;
          if (cell.direction == "across") {
            x++;
          }
          if (cell.direction == "down") {
            y++;
          }
        }
        if (y > 1 && x > 1 && crossword_grid[y][x] != undefined) {
          len1 -= 2;
          if (cell.direction == "across") {
            x -= 2;
          }
          if (cell.direction == "down") {
            y -= 2;
          }
        } else {
          if (cell.direction == "across") {
            x--;
          }
          if (cell.direction == "down") {
            y--;
          }
        }
        cell.possible_end = {
          j : y,
          k : x
        };
        cell.start_length = len1;
        cell.end_length = len2;
        cell.possible_length = len1 + len2 + 1;
        if (cell.possible_length < 2) {
          possibilities.splice(j, 1);
          j--;
        }
      }
      return (possibilities);
    };
    get_cell_possibilities_list = function() {
      var list = new Array();
      for (var j = 0; j < num_rows; j++) {
        for (var k = 0; k < num_columns; k++) {
          var cell = crossword_grid[j][k];
          if ((cell.letter != "") && adjacents_valid_configuration(cell)) {
            list.push(cell);
          }
        }
      }
      return (list);
    };
    adjacents_valid_configuration = function(cell) {
      if (cell.j <= 0 || cell.k <= 0 || cell.k >= crossword_grid[cell.j].length - 1 || cell.j >= crossword_grid.length - 1) {
        return false;
      }
      var adjacents = get_list_adjacent_cells(cell.j, cell.k);
      if (adjacents.length >= 3) {
        return (false);
      }
      for (var j = 0; j < adjacents.length; j++) {
        var cell0 = adjacents[j];
        for (var k = j + 1; k < adjacents.length; k++) {
          var cell1 = adjacents[k];
          if (Math.abs(cell0.j - cell1.j) == 2 && (cell0.k == cell1.k)) {
            cell.direction = "across";
          }
          if (Math.abs(cell0.k - cell1.k) == 2 && (cell0.j == cell1.j)) {
            cell.direction = "down";
          }
          if ((Math.abs(cell0.j - cell1.j) <= 1) && (Math.abs(cell0.k - cell1.k) <= 1)) {
            return (false);
          }
        }
      }
      if (adjacents.length == 1) {
        if (Math.abs(cell.j - adjacents[0].j) == 1) {
          cell.direction = "across";
        }
        if (Math.abs(cell.k - adjacents[0].k) == 1) {
          cell.direction = "down";
        }
      }
      return (true);
    };
    get_list_adjacent_cells = function(j, k) {
      var adjacents = new Array();
      if (crossword_grid[j+1][k].letter.length > 0) {
        adjacents.push(crossword_grid[j+1][k]);
      }
      if (crossword_grid[j-1][k].letter.length > 0) {
        adjacents.push(crossword_grid[j-1][k]);
      }
      if (crossword_grid[j][k + 1].letter.length > 0) {
        adjacents.push(crossword_grid[j][k + 1]);
      }
      if (crossword_grid[j+1][k + 1].letter.length > 0) {
        adjacents.push(crossword_grid[j+1][k + 1]);
      }
      if (crossword_grid[j-1][k + 1].letter.length > 0) {
        adjacents.push(crossword_grid[j-1][k + 1]);
      }
      if (crossword_grid[j][k - 1].letter.length > 0) {
        adjacents.push(crossword_grid[j][k - 1]);
      }
      if (crossword_grid[j+1][k - 1].letter.length > 0) {
        adjacents.push(crossword_grid[j+1][k - 1]);
      }
      if (crossword_grid[j-1][k - 1].letter.length > 0) {
        adjacents.push(crossword_grid[j-1][k - 1]);
      }
      return (adjacents);
    };
    filter_words_lesser_greater_length = function(words, low, high) {
      var list = new Array();
      for (var j = 0; j < words.length; j++) {
        if ((words[j].word.length >= low) && (words[j].word.length <= high) && !words[j].used) {
          list.push(words[j]);
        }
      }
      return (list);
    };
    filter_words_containing_letter_at = function(words, letter, pivot) {
      var list = new Array();
      for (var j = 0; j < words.length; j++) {
        if ((words[j].word.indexOf(letter) == pivot) && !words[j].used) {
          list.push(words[j]);
        }
      }
      return (list);
    };
    get_empty_crossword_grid = function() {
      var grid = new Array();
      for (var j = 0; j < num_rows; j++) {
        grid[j] = [];
        for (var k = 0; k < num_columns; k++) {
          grid[j][k] = {
            letter : "",
            display_letter : "",
            index : "",
            first_letter : false,
            first_letter_x : [],
            first_letter_y : [],
            word_directions : [],
            through_directions : [],
            words_using_letter : [],
            j : j,
            k : k
          };
        }
      }
      return (grid);
    };
    _global.randi = function(l, r) {
      return l + Math.floor(Math.random() * r);
    };
    Array.prototype.rande = function() {
      return this[Math.floor(Math.random() * this.length)];
    };
    Array.prototype.shuffle = function() {
      for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x) {
      }
      return this;
    };
    return initialize_crossword_random_main();
  };
  SCPTModel("iQuestion", {}, {
    init : function(jsonObj, params) {
      this.params = params;
      this.current = 0;
      this._super(jsonObj, params, "didyouknow");
      this.answer = this.decode(jsonObj.answer);
      this.button = this.decode(jsonObj.reveallabel);
      this.question = this.decode(jsonObj.question.question);
      this.img_1 = (jsonObj.question.primaryicon.image + "" != "[object Object]") ? this.decode(jsonObj.question.primaryicon.image) : "";
      this.img_2 = (jsonObj.question.secondaryicon.image + "" != "[object Object]") ? this.decode(jsonObj.question.secondaryicon.image) : "";
      this.height = (params.height) ? Math.max(200, params.height) : "100%";
      this.width = Math.max(600, params.width);
    }
  });
  SCPTController("DidYouKnow", {}, {
    init : function() {
      this.scroll_w = ("ontouchstart" in document.documentElement) ? 4 : 10;
      var self = this, holder = $("#" + this.options.model.containerId).html("").addClass("sc-dyk-didyouknow").css({
        border : "1px solid " + getMixedColor("#3c3c3c", this.options.model.backgroundColor, 0.5),
        background : this.options.model.backgroundColor,
        height : this.options.model.height + "px",
        width : this.options.model.width + "px"
      }).append(this.options.template);
      var content_w = holder.width(), question_w, answer_w, answer_h;
      this.button = holder.find(".sc-dyk-show-answer .sc-dyk-button").html(this.options.model.button).click(function() {
        self.show_answer();
      });
      this.button = holder.find(".sc-dyk-show-answer .sc-dyk-content");
      if (this.options.model.img_1) {
        var container = holder.find(".sc-dyk-image-1").children().first().addClass("sc-dyk-nonempty");
        var image = $(this.options.model.img_1).removeAttr("width").removeAttr("height");
        this._adjust_image(container, image);
        container.append(image);
        content_w -= container.outerWidth(true);
      }
      if (this.options.model.img_2) {
        var container = holder.find(".sc-dyk-image-2").children().first().addClass("sc-dyk-nonempty");
        var image = $(this.options.model.img_2).removeAttr("width").removeAttr("height");
        this._adjust_image(container, image);
        container.append(image);
        content_w -= container.outerWidth(true);
      }
      var question = holder.find(".sc-dyk-question > .sc-dyk-content");
      question_w = content_w - (parseInt(question.css("margin-left")) + parseInt(question.css("padding-left")) + parseInt(question.css("padding-right")) + parseInt(question.css("margin-right")));
      question.css({
        "max-height" : (this.options.model.height / 2 - 15) + "px",
        width : question_w + "px"
      }).html(this.options.model.question);
      if ("ontouchstart" in document.documentElement) {
        question.niceScroll({
          cursorwidth : 4
        });
      }
      var question_h = holder.height() - holder.find(".sc-dyk-question").outerHeight(true);
      this.answer = holder.find(".sc-dyk-answer > .sc-dyk-content");
      this.answer_img = holder.find(".sc-dyk-image-2").css({
        opacity : 0
      });
      answer_w = content_w - (parseInt(this.answer.css("margin-left")) + parseInt(this.answer.css("padding-left")) + parseInt(this.answer.css("padding-right")) + parseInt(this.answer.css("margin-right")));
      this.answer.html(this.options.model.answer).css({
        "max-height" : (this.options.model.height / 2 - 45) + "px",
        width : answer_w + "px"
      }).bind("keydown", function(evt) {
        self.key_handler.trigger(evt);
      });
      var common_h = Math.max(50, this.answer.outerHeight(true), this.button.outerHeight(true));
      var answer_h = common_h - (this.answer.outerHeight(true) - this.answer.height());
      var button_h = common_h - (this.button.outerHeight(true) - this.button.height());
      this.answer.css({
        height : answer_h + "px"
      }).hide();
      this.button.css({
        height : button_h + "px"
      });
      this.key_handler = holder.find(".sc-dyk-key-handler").attr("id", "inputf_" + this.options.model.params.containerId);
      this._super();
    },
    _adjust_image : function(container, image) {
      var img = new Image();
      img.src = image.attr("src");
      var max_h = container.height() || 200;
      var max_w = container.width() || 150;
      img.onload = function() {
        var top = "", left = "";
        if (this.height > max_h) {
          top = "-" + ((this.height - max_h) / 2) + "px";
        }
        if (this.width > max_w) {
          left = "-" + ((this.width - max_w) / 2) + "px";
        }
        if (left || top) {
          image.css({
            position : "relative",
            left : left,
            top : top
          });
        }
      };
    },
    show_answer : function() {
      this.button.hide();
      this.answer.show();
      this.answer_img.css({
        opacity : 1
      });
      if ("ontouchstart" in document.documentElement) {
        this.answer.niceScroll({
          cursorwidth : 4
        });
      }
    },
    hide_answer : function() {
      this.answer.hide();
      this.button.show();
      this.answer_img.css({
        opacity : 0
      });
    },
    getState : function(jsonObj) {
      return {
        show : this.answer.is(":visible")
      };
    },
    setState : function(jsonObj) {
      var act = (jsonObj.show) ? "show" : "hide";
      this[act+"_answer"]();
      return true;
    },
    handleKeys : function(e) {
      var self = e.data.self;
      var dt = 10;
      switch(e.keyCode) {
        case 13:
          self.show_answer();
          break;
        default:
          return true;
      }
      e.preventDefault();
    },
    resetQuestion : function() {
      this.hide_answer();
      return;
      void (0);
    },
    disableActivity : function() {
      this._super();
    }
  });
  SCPTModel("iAlbum", {}, {
    init : function( jsonObj, params ) {
      this.params = params;
      this.current = 0;
      this._ready = false;
      this._super(jsonObj, params, "photoalbum");
      
      this.bgcolor = '#' + ( jsonObj.color.replace(/#/g,'') || this.backgroundColor.replace(/#/g,'') );
  
      this.textAlign = params.textAlign || "left";
      this.photo = jsonObj.photo.length ? jsonObj.photo : [jsonObj.photo];      
      var max_height = 430, // for images in their container
          max_width = 600,
          kkk = max_width / max_height,
          len = this.photo.length,
          num = 0, self = this;
      
      for ( var i = this.photo.length; i-- ;) {      
        this.photo[i].caption = this.decode( this.photo[i].caption+"" );
        var img = new Image();
        img.src = this.photo[i].url;
        img.onload = function( obj ) {
          return function() {
            var h = parseInt( this.height ) ,
                w = parseInt( this.width ) ,
                k = w / h;
            if ( h > max_height || w > max_width ) {
              if ( kkk < k ) {
                w = max_width / w * w;
                h = max_width / w * h;
              } else {
                w = max_height / h * w;
                h = max_height / h * h;
              }
            } 
            obj.w = w;
            obj.h = h;
            //console.log( w + ' x ' + h );
            //console.log( '====================' );         
            if ( ++num == len ) self._ready = true;          
        }}( this.photo[i] );
      }
    }
  });
  SCPTController("PhotoAlbum", {}, {
    init : function() {
      var self = this;
      if (!this.options.model._ready) {
        setTimeout(function() {
          self.init();
        }, 50);
      } else {
        this.holder = $("#" + this.options.model.params.containerId).addClass("sc-pa-photoalbum").css({
          background : this.options.model.bgcolor,
          border : "1px solid " + getMixedColor("#3c3c3c", this.options.model.bgcolor, 0.5)
        }).append(this.options.template);
        this.view = {
          page : self.holder.find(".sc-pa-page").fadeOut(0),
          img : self.holder.find(".sc-pa-img"),
          des : self.holder.find(".sc-pa-des"),
          num : self.holder.find(".sc-pa-num"),
          prev : self.holder.find(".sc-pa-prev"),
          next : self.holder.find(".sc-pa-next")
        };
        this.album = self.options.model.photo;
        this.current = self.options.model.current;
        this._set_page();
        this._get_frame(0).show();
        this.animation = null;
        this.frames = 25;
        this.frame = 1;
        this.view.next.click(function() {
          self.next();
        });
        this.view.prev.click(function() {
          self.prev();
        });
        this.holder.find(".sc-pa-key-handler").attr("id", "inputf_" + this.options.model.params.containerId);
        //text-align
        this.holder.find('.sc-pa-des').css("text-align",self.options.model.textAlign);        
        this._super();
      }
    },
    _set_page : function() {
      this.view.img.html('<img src="' + this.album[this.current].url + '" style="width: ' + this.album[this.current].w + "px; height: " + this.album[this.current].h + 'px"/>');
      this.view.des.html(this.album[this.current].caption);
      this.view.num.html((this.current + 1) + " / " + (this.album.length));
      this.view.page.fadeIn("slow");
    },
    prev : function() {
      if (!this.animation) {
        this.view.page.fadeOut(100);
        if (this.current == 0) {
          this.current = this.album.length - 1;
        } else {
          this.current--;
        }
        this._prev_animate();
      }
    },
    next : function() {
      if (!this.animation) {
        this.view.page.fadeOut(100);
        if (this.current == this.album.length - 1) {
          this.current = 0;
        } else {
          this.current++;
        }
        this._next_animate();
      }
    },
    _get_frame : function(n) {
      return this.holder.find((n < 10) ? ".0" + n : "." + n);
    },
    _prev_frame : function() {
      this._get_frame(this.frame).hide();
      if (this.frame == 1) {
        if (this.animation) {
          clearInterval(this.animation);
          this.animation = null;
          this._set_page();
        }
        this.frame = this.frames;
      } else {
        this.frame--;
      }
      this._get_frame(this.frame).show();
    },
    _next_frame : function() {
      this._get_frame(this.frame).hide();
      if (this.frame == this.frames) {
        if (this.animation) {
          clearInterval(this.animation);
          this.animation = null;
          this._set_page();
        }
        this.frame = 1;
      } else {
        this.frame++;
      }
      this._get_frame(this.frame).show();
    },
    _prev_animate : function() {
      if (this.frame == 1) {
        this.frame = this.frames;
      }
      var self = this;
      this.animation = setInterval(function() {
        self._prev_frame();
      }, 50);
    },
    _next_animate : function() {
      if (this.frame == this.frames) {
        this.frame = 1;
      }
      var self = this;
      this.animation = setInterval(function() {
        self._next_frame();
      }, 50);
    },
    getState : function(jsonObj) {
      return {
        page : this.current
      };
    },
    setState : function(jsonObj) {
      this.current = parseInt(jsonObj.page);
      this._set_page();
      return
      void (0);
    },
    handleKeys : function(e) {
      var self = e.data.self;
      var dt = 10;
      switch(e.keyCode) {
        case 37:
          self.prev();
          break;
        case 39:
          self.next();
          break;
        default:
          return true;
      }
      e.preventDefault();
    },
    reset : function() {
      return
      void (0);
    },
    disableActivity : function() {
      this._super();
    }
  });
  SCPTModel("iChart", {}, {
    init : function(jsonObj, params) {
      this.params = params;
      this.radius = 170;
      this.height = 430;
      this._super(jsonObj, params, "sectionedshape");
      this.type = jsonObj.shapetype || "circle";
      this.section = [];
      this.t = {
        circle : [185, 225],
        pyramid : [10, 10]
      };
      this.marker = {
        min : 20,
        max : 400
      };
      this.title = this.decode(jsonObj.directionslabel);
      this.descr = this.decode(jsonObj.directionstext);
      var auto = 0;
      overall = 0, num = 0, sub_overall = 0, sub_num = 0, val = 0, sub = null, s_val = 0;
      if (!jsonObj.shapesection.length) {
        jsonObj.shapesection = [jsonObj.shapesection];
      }
      for (var i = 0, len1 = jsonObj.shapesection.length; i < len1; i++) {
        val = this._round(jsonObj.shapesection[i].shapepercentage);
        if (val == 0) {
          num++;
        }
        overall += val;
        sub = jsonObj.shapesection[i].shapesubsection;
        if (!( sub instanceof Array)) {
          jsonObj.shapesection[i].shapesubsection = [sub];
        }
        sub_overall = 0, sub_num = 0;
        for (var j = 0, len2 = jsonObj.shapesection[i].shapesubsection.length; j < len2; j++) {
          val = this._round(jsonObj.shapesection[i].shapesubsection[j].sectionpercentage);
          if (val == 0) {
            sub_num++;
          }
          sub_overall += val;
        }
        jsonObj.shapesection[i].shapesubsection.auto = (1 - sub_overall) / sub_num;
      }
      auto = this._round((1 - overall) / num);
      overall = 360;
      s_val = 0;
      for (var i = 0, len = jsonObj.shapesection.length; i < len; i++) {
        val = this._round(jsonObj.shapesection[i].shapepercentage) || auto;
        this.section.push({
          val : val,
          sval : this._round(s_val += val),
          angle : Math.round(val * 360),
          subsection : [],
        });
        if (i == len - 1) {
          this.section[i].angle = overall;
        } else {
          overall -= this.section[i].angle;
        }
        sub = jsonObj.shapesection[i].shapesubsection;
        for (var j = 0, len2 = jsonObj.shapesection[i].shapesubsection.length; j < len2; j++) {
          val = parseFloat(jsonObj.shapesection[i].shapesubsection[j].sectionpercentage);
          this.section[i].subsection.push({
            val : (val) ? val : sub.auto,
            color : sub[j].color,
            title : this.decode(sub[j].title),
            descr : this.decode(sub[j].details),
            showTitle : jsonObj.shapesection[i].shapesubsection[j].showtitle != "false"
          });
        }
      }
      this["_build_model_"+this.type]();
    },
    _round : function(str) {
      return parseFloat(parseFloat(str).toFixed(2));
    },
    _build_model_circle : function() {
      var rad = 170, arr = this.section, shape, ang1 = 0, ang2 = 0, x1, y1, x2, y2, p, shape, rm, ang3 = 0, marker = 0, coef, r, self = this, xo1, yo1, xo2, yo2, xr1, yr1, xr2, yr2, rr;
      for (var i = 0, len1 = arr.length; i < len1; i++) {
        ang1 = ang2, ang2 += arr[i].angle;
        ang3 = ang1 + arr[i].angle / 2;
        p = (arr[i].angle > 180) ? 1 : 0;
        x1 = parseInt(rad * Math.cos(Math.PI * ang1 / 180));
        y1 = parseInt(rad * Math.sin(Math.PI * ang1 / 180));
        x2 = parseInt(rad * Math.cos(Math.PI * ang2 / 180));
        y2 = parseInt(rad * Math.sin(Math.PI * ang2 / 180));
        if (i == len1 - 1) {( x2 = rad, y2 = 0);
        }
        for (var j = 0, len2 = arr[i].subsection.length; j < len2; j++) {
          shape = arr[i].subsection[j];
          if (j == 0) {
            coef = shape.val, xo1 = x1 * coef, yo1 = y1 * coef, xo2 = x2 * coef, yo2 = y2 * coef, r = rad * coef;
            shape.path_shape = "M 0 0 L " + xo1 + " " + yo1 + " A " + r + " " + r + " 0 " + p + " 1 ";
            shape.path_text = "M " + (xo1 / 2) + " " + (yo1 / 2) + " A " + (r / 2) + " " + (r / 2) + " 0 " + p + " 1 " + (xo2 / 2) + " " + (yo2 / 2);
            if (xo2 == xo1 && yo2 == yo1) {
              shape.path_shape += -xo2 + " " + yo2 + " A " + r + " " + r + " 0 " + p + " 1 ";
              var xxr1 = r * 4 / 3;
              shape.path_text = "M " + 0 + " " + (xxr1 / 2) + " L " + (0 / 2) + " " + (xxr1 / 2) + " A " + (xxr1 / 2) + " " + (xxr1 / 2) + " 0 " + p + " 1 " + (0 / 2) + " " + (-xxr1 / 2) + "  A " + xxr1 / 2 + " " + xxr1 / 2 + " 0 " + p + " 1 " + (0) / 2 + " " + xxr1 / 2;
            }
            shape.path_shape += xo2 + " " + yo2 + " Z";
            shape.marker = parseInt((r / 2) * Math.sin(Math.PI * ang3 / 180)) + this.t.circle[1];
            shape.path_text_width = Math.round(2 * Math.PI * (r / 2) * arr[i].angle / 360);
          } else {
            coef = arr[i].subsection[j].val, xr1 = xo1 + x1 * coef, yr1 = yo1 + y1 * coef, xr2 = xo2 + x2 * coef, yr2 = yo2 + y2 * coef, rr = r + rad * coef, rm = r + rad * coef / 2;
            shape.path_shape = "M " + xo1 + " " + yo1 + " L " + xr1 + " " + yr1 + " A " + rr + " " + rr + " 0 " + p + " 1 ";
            if (xr2 == xr1 && yr2 == yr1) {
              shape.path_shape += -xr2 + " " + yr2 + " A " + rr + " " + rr + " 0 " + p + " 1 ";
            }
            shape.path_shape += +xr2 + " " + yr2 + " L " + xo2 + " " + yo2 + " A " + r + " " + r + " 0 " + p + " 0 ";
            shape.path_text = "M " + ((xr1 + xo1) / 2) + " " + ((yr1 + yo1) / 2) + " A " + rm + " " + rm + " 0 " + p + " 1 " + ((xr2 + xo2) / 2) + " " + ((yr2 + yo2) / 2);
            if (xo2 == xo1 && yo2 == yo1) {
              shape.path_shape += -xo2 + " " + yo2 + " A " + r + " " + r + " 0 " + p + " 0 ";
              var xxr1 = (rr + rm);
              shape.path_text = "M " + (0 / 2) + " " + (xxr1 / 2) + " L " + (-yo2 / 2) + " " + (xxr1 / 2) + " A " + (xxr1 / 2) + " " + (xxr1 / 2) + " 0 " + p + " 1 " + (0 / 2) + " " + (-xxr1 / 2) + "  A " + xxr1 / 2 + " " + xxr1 / 2 + " 0 " + p + " 1 " + (0) / 2 + " " + xxr1 / 2;
            }
            shape.path_shape += xo1 + " " + yo1 + " z";
            shape.marker = parseInt(rm * Math.sin(Math.PI * ang3 / 180)) + this.t.circle[1];
            shape.path_text_width = Math.round(2 * Math.PI * (rm) * arr[i].angle / 360);
            r = rr, xo1 = xr1, yo1 = yr1, xo2 = xr2, yo2 = yr2;
          }
          shape.dx = parseInt(15 * Math.cos(Math.PI * ang3 / 180));
          shape.dy = parseInt(15 * Math.sin(Math.PI * ang3 / 180));
        }
      }
    },
    _build_model_pyramid : function() {
      var ph = 430, pw = 340, shape, arr = this.section, vx = pw / 2, vy = 0, val_b, val_t, section, xb1 = 0, xb2 = pw, yb1 = yb2 = ph, medial, xt1, yt1, xt2, yt2, sx, sy, nx, ny, dx;
      var triangle = [{
        x : 0,
        y : ph
      }, {
        x : pw,
        y : ph
      }, {
        x : pw / 2,
        y : 0
      }];
      for (var i = arr.length; i--; ) {
        val_h = arr[i].val * ph, val_b = arr[i].sval * pw, val_t = (arr[i].sval - arr[i].val) * pw;
        xt1 = (pw - val_t) / 2, xt2 = xt1 + val_t, yt1 = yt2 = (yb1 - val_h);
        section = [{
          x : xb1,
          y : yb1
        }, {
          x : xb2,
          y : yb2
        }, {
          x : xt2,
          y : yt2
        }];
        if (xt1 != xt2) {
          section.push({
            x : xt1,
            y : yt1
          });
        }
        sx = xb1, sy = yb1;
        for (var j = 0, len2 = arr[i].subsection.length; j < len2; j++) {
          var shape = arr[i].subsection[j], v = shape.val;
          var intersection = $.intersection(section, [{
            x : sx,
            y : sy
          }, {
            x : sx + val_b * v,
            y : sy
          }, {
            x : sx + val_b * v,
            y : sy - val_h
          }, {
            x : sx,
            y : sy - val_h
          }]);
          shape.path_shape = this._buid_path(intersection);
          shape.marker = intersection.mid("y");
          medial = this._build_medial(intersection, shape.marker);
          shape.path_text = medial[0];
          shape.path_text_width = medial[1];
          shape.marker = this._marker(shape.marker);
          if (len2 == 1) {
            shape.dx = 0;
            shape.dy = -10;
          } else {
            if (j == 0) {
              shape.dx = -10;
              shape.dy = 0;
            } else {
              if (j == len2 - 1) {
                shape.dx = 10;
                shape.dy = 0;
              } else {
                shape.dx = 0;
                shape.dy = -10;
              }
            }
          }
          sx += val_b * v;
        }
        xb1 = xt1, xb2 = xt2, yb1 = yb2 = yt1;
      }
    },
    _buid_path : function(arr) {
      var path = "M " + arr[0].x + " " + arr[0].y;
      for (var i = 1, l = arr.length; i < l; i++) {
        path += " L " + arr[i].x + " " + arr[i].y;
      }
      return path += "Z";
    },
    _build_medial : function(arr, mid) {
      var line = [{
        x : 0,
        y : mid
      }, {
        x : 500,
        y : mid
      }];
      mid = $.intersection(arr, line).slice(0, 2).sort(function(a, b) {
        return a.x - b.x;
      });
      return ["M " + mid[0].x + " " + mid[0].y + " L " + mid[1].x + " " + mid[1].y, Math.round(mid[1].x - mid[0].x)];
    },
    _marker : function(num) {
      return Math.min(this.marker.max, Math.max(this.marker.min, num));
    }
  });
  SCPTController("SectionedShape", {}, {
    init : function() {
      this.touch = !!("ontouchstart" in document.documentElement);
      this.scroll_w = (this.touch) ? 4 : 10;
      var self = this, holder = $("#" + this.options.model.containerId).html("").addClass("sc-chart-sectionedshape").css({
        border : "1px solid " + getMixedColor("#3c3c3c", this.options.model.backgroundColor, 0.5),
        background : this.options.model.backgroundColor
      }).append(this.options.template);
      this.marker = holder.find(".sc-chart-marker");
      this.active = null;
      this.title = holder.find(".sc-chart-title").html(this.options.model.title);
      this.descr = holder.find(".sc-chart-descr").html(this.options.model.descr);
      this.alttext = holder.find(".sc-chart-alttext");
      this.alttext.offset = holder.offset();
      this._adjust_labels(holder, this.options.model.section);
      this.section = this._build_sections(holder, this.options.model.section);
      if (!this.touch) {
        holder.bind("mousemove", function(self) {
          return function(evt) {
            self._save_mouse_coords(evt);
          };
        }(this));
        this.alttext.insertAfter(holder.find(".sc-chart-paper"));
      }
      this.descr.parent().niceScroll({
        cursorwidth : this.scroll_w
      });
      var key_handler = holder.find(".sc-chart-key-handler").attr("id", "inputf_" + this.options.model.params.containerId);
      this._super();
    },
    _adjust_labels : function(cnt, arr) {
      var test_box = $('<div class="sc-chart-label">sds</div>').css({
        position : "absolute",
        top : "0px",
        left : "0px",
        border : "0",
        padding : "0",
        margin : "0"
      }).appendTo(cnt).fadeOut(0);
      var str, c_w, r_w;
      for (var s = arr.length; s--; ) {
        for (var c = arr[s].subsection.length; c--; ) {
          str = arr[s].subsection[c].showTitle ? arr[s].subsection[c].title : "";
          c_w = test_box.html(str).width();
          r_w = arr[s].subsection[c].path_text_width;
          while (c_w > r_w) {
            if(str=='') {
            break;
            }
            str = str.slice(0, -1);
            c_w = test_box.html("&nbsp;" + str + "...&nbsp;").width();
          }
          if (arr[s].subsection[c].title != str && str != "") {
            arr[s].subsection[c].label = str + "...";
          } else {
            arr[s].subsection[c].label = str;
          }
        }
      }
      test_box.remove();
    },
    _build_sections : function(cnt, arr) {
      var tr = this.options.model.t[this.options.model.type], defs = "", shapes = "", shape, section = [];
      for (var s = arr.length; s--; ) {
        for (var c = arr[s].subsection.length; c--; ) {
          shape = arr[s].subsection[c];
          shapes += '<g transform="matrix(1 0 0 1 0 0)" opacity="0.5" shape="' + s + "-" + c + '"><path d="' + shape.path_shape + '" stroke="#3c3c3c" fill-opacity="0.5" stroke-width="1" fill="' + shape.color + '"/><text class="sc-chart-label"><textpath xlink:href="#path-' + this.options.model.containerId + "-" + s + "-" + c + '" text-anchor="middle" startOffset="50%" alignment-baseline="middle">' + shape.label + "</textpath></text></g>";
          defs += '<path id="path-' + this.options.model.containerId + "-" + s + "-" + c + '" d="' + shape.path_text + '"/>';
        }
      }
      cnt.append('<svg class="sc-chart-paper" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="370px" height="450px"><defs>' + defs + '</defs><g class="sc-chart-chart" transform="matrix(1 0 0 1 ' + tr.join(" ") + ')">' + shapes + "</g></svg>");
      for (var s = arr.length; s--; ) {
        section[s] = [];
        for (var c = arr[s].subsection.length; c--; ) {
          shape = cnt.find("[shape=" + s + "-" + c + "]").bind("click", function(self, n, s) {
            return function() {
              self.show_section(n, s);
            };
          }(this, s, c));
          if (!this.touch) {
            shape.bind("mouseover", function(self, n, s) {
              return function() {
                self.move_section_frwd(n, s);
              };
            }(this, s, c)).bind("mouseout", function(self, n, s) {
              return function() {
                self.move_section_back(n, s);
              };
            }(this, s, c));
          }
          shape.marker = arr[s].subsection[c].marker;
          shape.title = arr[s].subsection[c].title;
          shape.showTitle = arr[s].subsection[c].showTitle;
          shape.descr = arr[s].subsection[c].descr;
          shape.dx = arr[s].subsection[c].dx;
          shape.dy = arr[s].subsection[c].dy;
          shape.cx = 0;
          shape.cy = 0;
          section[s].unshift(shape);
        }
      }
      return section;
    },
    _move_marker_to : function(top) {
      this.marker.stop().animate({
        top : top + "px"
      });
    },
    _save_mouse_coords : function(evt) {
      this.alttext.x = evt.pageX - this.alttext.offset.left - 10;
      this.alttext.y = evt.pageY - this.alttext.offset.top - 10;
    },
    show_alttext : function(n, s) {
      this.alttext.html(this.section[n][s].title).css({
        left : this.alttext.x + "px",
        top : (this.alttext.y - this.alttext.outerHeight(true)) + "px"
      }).show().fadeIn(100);
    },
    hide_alttext : function() {
      this.alttext.html("").fadeOut(100).hide().css({
        left : "-50px",
        top : "-50px"
      });
    },
    show_section : function(n, s) {
      if (this.active) {
        this.active.attr("opacity", 0.5);
      }
      this.active = this.section[n][s];
      this._move_marker_to(this.active.marker);
      this.active.attr("opacity", 1);
      this.title.html(this.active.title);
      this.descr.parent().getNiceScroll().remove();
      this.descr.html(this.active.descr);
      this.descr.parent().niceScroll({
        cursorwidth : this.scroll_w
      });
      this.move_section_back(n, s);
    },
    move_section_frwd : function(n, s) {
      var o = this.section[n][s], x = (o.dx > 0) ? 1 : -1, y = (o.dy > 0) ? 1 : -1;
      clearTimeout(o.anim);
      var anim = function() {
        if (o.cx != o.dx || o.cy != o.dy) {
          if (o.cx != o.dx) {
            o.cx += x;
          }
          if (o.cy != o.dy) {
            o.cy += y;
          }
          o.attr({
            transform : "matrix(1 0 0 1 " + o.cx + " " + o.cy + ")"
          });
          o.anim = setTimeout(function() {
            anim();
          }, 15);
        }
      };
      anim();
      setTimeout( function(self, n, s) {
        return function() {
          self.show_alttext(n, s);
        };
      }(this, n, s), 500);
    },
    move_section_back : function(n, s) {
      var o = this.section[n][s], x = (o.dx > 0) ? -1 : 1, y = (o.dy > 0) ? -1 : 1;
      clearTimeout(o.anim);
      var anim = function() {
        if (o.cx != 0 || o.cy != 0) {
          if (o.cx != 0) {
            o.cx += x;
          }
          if (o.cy != 0) {
            o.cy += y;
          }
          o.attr({
            transform : "matrix(1 0 0 1 " + o.cx + " " + o.cy + ")"
          });
          o.anim = setTimeout(function() {
            anim();
          }, 15);
        }
      };
      anim();
      setTimeout( function(self) {
        return function() {
          self.hide_alttext(n, s);
        };
      }(this), 100);
    },
    prev_section : function() {
      if (this.active) {
        var state = this.active.attr("shape").split("-"), s = +state[0], c = +state[1];
        s = (s == 0) ? (this.section.length - 1) : (s - 1);
        c = (c <= this.section[s].length - 1) ? c : 0;
      } else {
        s = this.section.length - 1, c = 0;
      }
      this.show_section(s, c);
    },
    next_section : function() {
      if (this.active) {
        var state = this.active.attr("shape").split("-"), s = +state[0], c = +state[1];
        s = (s == this.section.length - 1) ? 0 : (s + 1);
        c = (c <= this.section[s].length - 1) ? c : 0;
      } else {
        s = 0, c = 0;
      }
      this.show_section(s, c);
    },
    prev_chart : function() {
      if (this.active) {
        var state = this.active.attr("shape").split("-"), s = +state[0], c = +state[1];
        c = (c == 0) ? (this.section[s].length - 1) : (c - 1);
      } else {
        s = this.section.length - 1, c = 0;
      }
      this.show_section(s, c);
    },
    next_chart : function() {
      if (this.active) {
        var state = this.active.attr("shape").split("-"), s = +state[0], c = +state[1];
        c = (c == this.section[s].length - 1) ? 0 : (c + 1);
      } else {
        s = this.section.length - 1, c = 0;
      }
      this.show_section(s, c);
    },
    getState : function(jsonObj) {
      if (this.active) {
        return {
          chart : this.active.attr("shape")
        };
      } else {
        return {
          chart : "no"
        };
      }
    },
    setState : function(jsonObj) {
      var state = jsonObj.chart.split("-");
      if (state[0] && state[1]) {
        this.show_section(parseInt(state[0]), parseInt(state[1]));
      }
      return true;
    },
    handleKeys : function(e) {
      var self = e.data.self;
      var dt = 10;
      var n1 = (self.options.model.type == "circle") ? "next_" : "prev_";
      var n2 = (self.options.model.type == "circle") ? "prev_" : "next_";
      var m1 = (self.options.model.type == "circle") ? "chart" : "section";
      var m2 = (self.options.model.type == "circle") ? "section" : "chart";
      switch(e.keyCode) {
        case 38:
          self[n1+m1]();
          break;
        case 37:
          self["prev_"+m2]();
          break;
        case 39:
          self["next_"+m2]();
          break;
        case 40:
          self[n2+m1]();
          break;
        default:
          return true;
      }
      e.preventDefault();
    },
    resetQuestion : function() {
      return;
      void (0);
    },
    disableActivity : function() {
      this._super();
    }
  });
  (function($) {
    $.intersection = function(poly, rect) {
      var result = intersection();
      for (var i = 0, l = rect.length; i < l; i++) {
        result.add(poly_line(poly, rect[i], rect[(i + 1) % l]));
      }
      return result;
    };
    var poly_line = function(poly, p1, p2) {
      var result = intersection();
      for (var i = 0, l = poly.length; i < l; i++) {
        result.add(line_line(p1, p2, poly[i], poly[(i + 1) % l]));
      }
      return result;
    };
    var line_line = function(s1, s2, e1, e2) {
      var result = intersection();
      var us = (e2.x - e1.x) * (s1.y - e1.y) - (e2.y - e1.y) * (s1.x - e1.x);
      var ue = (s2.x - s1.x) * (s1.y - e1.y) - (s2.y - s1.y) * (s1.x - e1.x);
      var up = (e2.y - e1.y) * (s2.x - s1.x) - (e2.x - e1.x) * (s2.y - s1.y);
      if (up != 0) {
        us = us / up, ue = ue / up;
        if (0 <= us && us <= 1 && 0 <= ue && ue <= 1) {
          result.add([{
            x : s1.x + us * (s2.x - s1.x),
            y : s1.y + us * (s2.y - s1.y)
          }]);
        }
      } else {
        if (us == 0) {
          if (s1.x <= s2.x) {
            var a = {
              x : Math.max(s1.x, e1.x),
              y : s1.y
            };
            var b = {
              x : Math.min(s2.x, e2.x),
              y : s2.y
            };
            var m = (a.x + b.x) / 2;
            if (m >= s1.x && m <= s2.x && m >= e1.x && m <= e2.x) {
              result.add([a, b]);
            }
          } else {
            if (s1.x >= s2.x) {
              var a = {
                x : Math.min(s1.x, e1.x),
                y : s1.y
              };
              var b = {
                x : Math.max(s2.x, e2.x),
                y : s2.y
              };
              var m = (a.x + b.x) / 2;
              if (m >= s1.x && m <= s2.x && m >= e1.x && m <= e2.x) {
                result.add([a, b]);
              }
            }
          }
        }
      }
      return result;
    };
    var intersection = function() {
      var result = [];
      result.add = function(p) {
        for (var i = 0, l = p.length; i < l; i++) {
          this.ins(p[i]);
        }
      };
      result.ins = function(p) {
        for (var i = this.length; i--; ) {
          if (this[i].x == p.x && this[i].y == p.y) {
            return;
          }
        }
        void (0);
        this.push(p);
      };
      result.mid = function(c) {
        var min = this[0][c], max = this[0][c];
        for (var i = this.length; i--; ) {
          max = (this[i][c] > max) ? this[i][c] : max;
          min = (this[i][c] < min) ? this[i][c] : min;
        }
        return (min + max) / 2;
      };
      return result;
    };
  })(jQuery);
  SCPTModel("SeekAWord", {}, {
    init : function(jsonObj, params) {
      if (!params.isXML) {
        jsonObj = this.parseStringToXML(jsonObj);
      }
      this._super(jsonObj, params, "seekaword");
      this.pointsArr = new Array(jsonObj.words.length);
      this.words = jsonObj.words;
      this.size = params.sqrsize;
      this.instructions = params.instructions || "";
      this.isHint = (params.hint+"")!='false' || false;
      this.state = [];
      this.paper = null;
      this.sheetSize = 400;
      this.cellSize = 380 / this.size;
      this.keyboard = {
        prevCell : [1, 1],
        activeCell : [1, 1],
        isStarted : false,
        startLine : true
      };
      this.line = {};
      this.reinit();
    },
    reinit : function() {
      this._super();
      for (var i = 0; i < this.pointsArr.length; i++) {
        this.pointsArr[i] = 0;
      }
      this.state = [];
      this.state = (new createSeekAWordSheet(this.size, this.size, this.words)).letter_grid;
      this.line = {
        x : [],
        y : [],
        cells : []
      };
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
      this.state = jsonObj.state;
      this.pointsArr = jsonObj.pointsArr;
    },
    getState : function(jsonObj) {
      var obj = this._super();
      obj.pointsArr = this.pointsArr;
      obj.state = this.state;
      return obj;
    },
    parseStringToXML : function(str) {
      var retObj = {};
      var params = str.split("&");
      for (var i = 1; i < params.length - 1; i++) {
        var pair = params[i].split("=");
        var prefix = pair[0].substring(0, 5);
        if (prefix == "words") {
          var arr = pair[1].split("|");
          for (var j = 0; j < arr.length; j++) {
            arr[j] = this.decode(arr[j]+"").toUpperCase();
          }
          retObj.words = arr;
        } else {
          retObj[pair[0]] = pair[1];
        }
      }
      return retObj;
    }
  });
  SCPTController("SeekAWords", {}, {
    init : function() {
      var self = this, m = self.options.model;
      m.attempts++;
      var container = $("#" + m.containerId);
      container.html(this.options.template, {
        id : m.containerId,
        color : m.backgroundColor,
        width : m.width,
        height : m.height,
        maxScore : m.maxScore,
        state : m.state,
        inst : m.instructions,
        sheetSize : m.sheetSize,
        isHint : m.isHint
      });
      m.draw = $("#seekAWord_Paper_" + m.containerId);
      m.table = $("#seekAWord_Table_" + m.containerId);
      this.initDrawing();
      this._super();
    },
    bindEvents : function(self) {
      var self = this, m = this.options.model;
      if (m.isHint) {
        for (var i = 0; i < m.state.answer_key.length; i++) {
          $("#word_" + i + "_" + m.containerId).bind("click", function(index) {
            return function() {
              self.showHint(index);
            };
          }(i)).css({
            cursor : "pointer"
          });
        }
      }
      $("#restart_" + m.containerId).bind("click", function() {
        self.reset();
      });
      $("#finish_" + m.containerId).bind("click", function() {
        self.showAnswer();
        self.completed();
      });
      $("#inputf_" + m.containerId).bind("keypress", function(evt) {
        var kc = evt.keyCode;
        if (kc == 32 || (kc >= 37 && kc <= 40)) {
          evt.preventDefault();
        }
      });
    },
    initDrawing : function() {
      var self = this, m = this.options.model;
      var tpaper = Raphael("seekAWord_Paper_" + m.containerId, 400, 400);
      m.paper = Raphael("seekAWord_BackPaper_" + m.containerId, 400, 400);
      tpaper.draw = tpaper.rect(0, 0, 400, 400).attr({
        "stroke-width" : 0,
        fill : "white",
        "fill-opacity" : 0,
        opacity : 0,
        cursor : "pointer"
      });
      tpaper.draw.drag(function(dx, dy, x, y) {
        self.moveLine(x, y, self);
      }, function(x, y) {
        self.startLine(x, y, self);
      }, function() {
        self.endLine(self);
      });
    },
    startLine : function(x, y, self) {
      var m = self.options.model;
      m.line.line = m.paper.path("M0,0L0,0").attr({
        "stroke-width" : "10pt",
        stroke : "#9dbdff",
        "stroke-linecap" : "round",
        opacity : 1
      });
      var _obj = self.snapLine(x, y, false);
      m.line.x[0] = _obj.x;
      m.line.y[0] = _obj.y;
      m.line.x[1] = _obj.x;
      m.line.y[1] = _obj.y;
      self.updatePaperState();
    },
    moveLine : function(x, y, self) {
      var m = self.options.model;
      var _obj = self.snapLine(x, y, true);
      m.line.x[1] = _obj.x + 1;
      m.line.y[1] = _obj.y + 2;
      self.updatePaperState();
    },
    endLine : function(self) {
      var m = self.options.model;
      if (!m.line.cells[2]) {
        m.line.cells[2] = m.line.cells[0];
      }
      self.updatePaperState();
      self.checkLine();
    },
    updatePaperState : function() {
      var self = this.options.model;
      var offsetX = self.draw.offset().left;
      var offsetY = self.draw.offset().top;
      var _p = ["M", self.line.x[0] - offsetX, self.line.y[0] - offsetY, "L", self.line.x[1] - offsetX, self.line.y[1] - offsetY];
      self.line.line.attr({
        path : _p
      }).show();
    },
    checkLine : function() {
      var m = this.options.model;
      var isCorrect = false;
      for (var i = 0; i < m.state.answer_key.length; i++) {
        var obj = m.state.answer_key[i];
        var start = obj.start;
        if (obj.start.j + 1 == m.line.cells[2][1] && obj.start.k + 1 == m.line.cells[2][0]) {
          var t = [m.line.cells[2][0], m.line.cells[2][1]];
          m.line.cells[2][0] = m.line.cells[0][0], m.line.cells[2][1] = m.line.cells[0][1], m.line.cells[0][0] = t[0], m.line.cells[0][1] = t[1];
        }
        if (obj.start.j + 1 == m.line.cells[0][1] && obj.start.k + 1 == m.line.cells[0][0]) {
          var end_point = [obj.start.k + 1 + (obj.word.length - 1) * obj.increments.k, obj.start.j + 1 + (obj.word.length - 1) * obj.increments.j];
          if (m.line.cells[2][0] == end_point[0] && m.line.cells[2][1] == end_point[1]) {
            m.pointsArr[i] = 1;
            isCorrect = true;
            $("#word_" + i + "_" + m.containerId).unbind().find("hr").show();
            break;
          }
        }
      }
      if (!isCorrect) {
        m.line.line.remove();
      }
      this.updateStatus();
      this.playIsCorrect(isCorrect);
    },
    snapLine : function(x, y, isFinish) {
      var m = this.options.model;
      var offset = m.table.find("tr:nth-child(" + 1 + ")").find("td:nth-child(" + 1 + ")").offset();
      offset = [offset.left, offset.top];
      var dxy = [x - offset[0], y - offset[1]];
      for (var i = 0; i < dxy.length; i++) {
        if (dxy[i] < m.cellSize / 2) {
          dxy[i] = m.cellSize / 2;
        } else {
          if (dxy[i] > (m.size - 0.5) * m.cellSize) {
            dxy[i] = (m.size - 0.5) * m.cellSize;
          }
        }
      }
      var cell = [(Math.round((dxy[0] / m.cellSize) - 0.5)) + 1, (Math.round((dxy[1] / m.cellSize) - 0.5) + 1)];
      if (isFinish) {
        m.line.cells[1] = cell;
        m.line.cells[2] = this.getClosestLetter();
        cell = m.line.cells[2];
      } else {
        m.line.cells[0] = cell;
      }
      var xy = this.returnXYByCell(cell[1], cell[0]);
      return {
        x : xy[0],
        y : xy[1]
      };
    },
    returnXYByCell : function(i, j) {
      var m = this.options.model;
      var off = m.table.find("tr:nth-child(" + i + ")").find("td:nth-child(" + j + ")").offset();
      return [off.left + m.cellSize / 2 - 2, off.top + m.cellSize / 2 - 3];
    },
    getClosestLetter : function() {
      var m = this.options.model;
      var _loc6 = m.line.cells[0][0];
      var _loc4 = m.line.cells[0][1];
      var _loc5 = m.line.cells[1][0];
      var _loc7 = m.line.cells[1][1];
      var _loc2;
      var _loc3;
      if (Math.abs((_loc6 - _loc5) / (_loc4 - _loc7)) == 1 || Math.abs(_loc6 - _loc5) == 0 || Math.abs(_loc4 - _loc7) == 0) {
        _loc2 = _loc5;
        _loc3 = _loc7;
      } else {
        var _loc8 = Math.abs(Math.atan2(_loc5 - _loc6, _loc7 - _loc4) * 180 / 3.141593);
        if (_loc8 < 22.5 || _loc8 > 157.5) {
          _loc2 = _loc6;
          _loc3 = _loc7;
        } else {
          if (_loc8 > 67.5 && _loc8 < 112.5) {
            _loc2 = _loc5;
            _loc3 = _loc4;
          } else {
            _loc2 = Math.max(Math.abs(_loc5 - _loc6), Math.abs(_loc7 - _loc4)) * this.sign(_loc5 - _loc6) + _loc6;
            _loc3 = Math.max(Math.abs(_loc5 - _loc6), Math.abs(_loc7 - _loc4)) * this.sign(_loc7 - _loc4) + _loc4;
          }
        }
      }
      _loc2 = Math.max(1, _loc2);
      _loc3 = Math.max(1, _loc3);
      _loc2 = Math.min(m.size, _loc2);
      _loc3 = Math.min(m.size, _loc3);
      return [_loc2, _loc3];
    },
    sign : function(val) {
      return (val == 0 ? (0) : (val / Math.abs(val)));
    },
    showHint : function(index) {
      var start = this.options.model.state.answer_key[index].start;
      var xy = this.returnXYByCell(start.j + 1, start.k + 1);
      var offset = this.options.model.draw.offset();
      xy = [xy[0] - offset.left, xy[1] - offset.top];
      this.options.model.paper.path("M" + xy[0] + "," + xy[1] + "L" + xy[0] + "," + (xy[1] + 1)).attr({
        "stroke-width" : "10pt",
        stroke : "#9dbdff",
        "stroke-linecap" : "round",
        opacity : 1
      });
    },
    showAnswer : function() {
      for (var i = 0; i < this.options.model.state.answer_key.length; i++) {
        this.showSingleAnswer(i);
      }
    },
    showSingleAnswer : function(i) {
      var m = this.options.model;
      var offset = this.options.model.draw.offset();
      var obj = m.state.answer_key[i];
      var start = obj.start;
      var xy0 = this.returnXYByCell(start.j + 1, start.k + 1);
      xy0 = [xy0[0] - offset.left, xy0[1] - offset.top];
      var xy1 = this.returnXYByCell(obj.start.j + 1 + (obj.word.length - 1) * obj.increments.j, obj.start.k + 1 + (obj.word.length - 1) * obj.increments.k);
      xy1 = [xy1[0] - offset.left, xy1[1] - offset.top];
      $("#word_" + i + "_" + m.containerId).unbind().find("hr").show();
      this.options.model.paper.path("M" + xy0[0] + "," + xy0[1] + "L" + xy1[0] + "," + xy1[1]).attr({
        "stroke-width" : "10pt",
        stroke : "#9dbdff",
        "stroke-linecap" : "round",
        opacity : 1
      });
    },
    handleKeys : function(e) {
      var self = e.data.self;
      var m = self.options.model;
      if (!e.altKey && e.keyCode != 32 && m.keyboard.isStarted == false) {
        return true;
      }
      m.keyboard.prevCell = [m.keyboard.activeCell[0], m.keyboard.activeCell[1]];
      if (e.altKey) {
        switch(e.keyCode) {
          case 85:
            e.data.self.reset(false);
            return false;
            break;
          case 81:
            e.data.self.showAnswer();
            e.data.self.completed();
            break;
          default:
            return true;
        }
      } else {
        switch(e.keyCode) {
          case 32:
            if (m.keyboard.isStarted == false) {
              m.keyboard.isStarted = true;
            } else {
              if (m.keyboard.startLine) {
                var obj = m.table.find("tr:nth-child(" + m.keyboard.activeCell[1] + ")").find("td:nth-child(" + m.keyboard.activeCell[0] + ")").find("span").removeClass("sc-selected").offset();
                self.startLine(obj.left, obj.top, self);
              } else {
                self.endLine(self);
              }
              m.keyboard.startLine = !m.keyboard.startLine;
              return false;
            }
            break;
          case 37:
            m.keyboard.activeCell = [m.keyboard.activeCell[0] - 1, m.keyboard.activeCell[1]];
            break;
          case 38:
            m.keyboard.activeCell = [m.keyboard.activeCell[0], m.keyboard.activeCell[1] - 1];
            break;
          case 39:
            m.keyboard.activeCell = [m.keyboard.activeCell[0] + 1, m.keyboard.activeCell[1]];
            break;
          case 40:
            m.keyboard.activeCell = [m.keyboard.activeCell[0], m.keyboard.activeCell[1] + 1];
            break;
          default:
            return true;
        }
      }
      if (m.keyboard.activeCell[0] < 0) {
        m.keyboard.activeCell[0] = m.size;
      }
      if (m.keyboard.activeCell[0] > m.size) {
        m.keyboard.activeCell[0] = 0;
      }
      if (m.keyboard.activeCell[1] == 0) {
        m.keyboard.activeCell[1] = m.size;
      }
      if (m.keyboard.activeCell[1] > m.size) {
        m.keyboard.activeCell[1] = 1;
      }
      e.preventDefault();
      self.refreshKeysView(self);
    },
    refreshKeysView : function(self) {
      var m = self.options.model;
      var prevCell = m.table.find("tr:nth-child(" + m.keyboard.prevCell[1] + ")").find("td:nth-child(" + m.keyboard.prevCell[0] + ")").find("span").removeClass("sc-selected");
      var actCell = m.table.find("tr:nth-child(" + m.keyboard.activeCell[1] + ")").find("td:nth-child(" + m.keyboard.activeCell[0] + ")").find("span").addClass("sc-selected");
      if (m.keyboard.activeCell[0] == 0) {
      } else {
        if (!m.keyboard.startLine) {
          var offset = actCell.offset();
          self.moveLine(offset.left, offset.top, self);
        }
      }
    },
    updateStatus : function() {
      var m = this.options.model, currentScore = 0;
      for (var i = 0; i < m.pointsArr.length; i++) {
        currentScore += m.pointsArr[i];
      }
      var pts = currentScore * (m.maxScore / (m.pointsArr.length));
      pts = Math.round(10 * pts) / 10;
      m.currentScore = pts;
      if (pts == m.maxScore) {
        this.completed();
      }
      $("#statusText_" + m.containerId).html( m.scoreText+" " + pts + "/" + m.maxScore);
    },
    setState : function(jsonObj) {
      var m = this.options.model;
      this._super(jsonObj);
      for (var i = 0; i < m.pointsArr.length; i++) {
        if (m.pointsArr[i] != 0) {
          this.showSingleAnswer(i);
        }
      }
      this.updateStatus();
    },
    getState : function() {
      var m = this.options.model;
      var obj = m.getState();
      return obj;
    },
    disableActivity : function() {
      this.options.model.draw.remove();
      this._super();
    }
  });
  createSeekAWordSheet = function(rows, cols, words) {
    this.grid_rows = rows;
    this.grid_columns = cols;
    this.words = words;
    this.answer_key = [];
    this.initialize = function() {
      this.word_bank = this.words.random_subset(this.words.length);
      this.word_bank.sortOn("length");
      this.create_letter_grid();
      this.embed_word_bank();
      this.letter_grid.answer_key = this.answer_key;
    };
    this.create_letter_grid = function() {
      var _loc4 = Array.prototype.get_letter_grid(this.grid_rows, this.grid_columns);
      this.letter_grid = new Array();
      for (var _loc3 = 0; _loc3 < this.grid_rows; ++_loc3) {
        this.letter_grid[_loc3] = new Array();
        for (var _loc2 = 0; _loc2 < this.grid_columns; ++_loc2) {
          this.letter_grid[_loc3][_loc2] = new Object();
          this.letter_grid[_loc3][_loc2].letter = _loc4[_loc3][_loc2];
          this.letter_grid[_loc3][_loc2].word_bank_letter = false;
          this.letter_grid[_loc3][_loc2].letter_found = false;
          this.letter_grid[_loc3][_loc2].drag_selected = false;
        }
      }
    };
    this.embed_word_bank = function() {
      var _loc3 = this.word_bank.return_copy();
      for (var _loc2 = 0; _loc2 < _loc3.length; ++_loc2) {
        var _loc5 = randi(0, this.grid_rows);
        var _loc4 = randi(0, this.grid_columns);
        var _loc6 = this.get_possible_word_directions(_loc3[_loc2].length, _loc5, _loc4);
        var _loc7 = this.embed_word(_loc3[_loc2], _loc5, _loc4, _loc6);
        if (!_loc7) {
          _loc3.push(_loc3[_loc2]);
        }
      }
    };
    this.get_possible_word_directions = function(word_length, index_j, index_k) {
      var _loc3 = new Array();
      if (index_j + word_length < this.grid_rows && index_k + word_length < this.grid_columns) {
        _loc3.push("Top Left to Bottom Right");
      }
      if (index_j + word_length < this.grid_rows && index_k - word_length >= 0) {
        _loc3.push("Top Right to Bottom Left");
      }
      if (index_j - word_length >= 0 && index_k + word_length < this.grid_columns) {
        _loc3.push("Bottom Left to Top Right");
      }
      if (index_j - word_length >= 0 && index_k - word_length >= 0) {
        _loc3.push("Bottom Right to Top Left");
      }
      if (index_j + word_length < this.grid_rows) {
        _loc3.push("Top to Bottom");
      }
      if (index_j - word_length >= 0) {
        _loc3.push("Bottom to Top");
      }
      if (index_k + word_length < this.grid_columns) {
        _loc3.push("Left to Right");
      }
      if (index_k - word_length >= 0) {
        _loc3.push("Right to Left");
      }
      return (_loc3);
    };
    this.embed_word = function(word, index_j, index_k, possible_directions) {
      possible_directions.shuffle();
      if (this.answer_key.length < 0.2 * this.word_bank.length) {
        possible_directions.sortOn("length");
      }
      for (var _loc2 = 0; _loc2 < possible_directions.length; ++_loc2) {
        var _loc3 = this.calculate_slope_increments(possible_directions[_loc2]);
        if (!this.word_overlaps(word, index_j, index_k, _loc3)) {
          this.put_letters_in(word, index_j, index_k, _loc3, possible_directions[_loc2]);
          return (true);
        }
      }
      return (false);
    };
    this.put_letters_in = function(word, index_j, index_k, increments, direction) {
      for (var _loc2 = 0; _loc2 < word.length; ++_loc2) {
        var _loc10 = index_j + _loc2 * increments.j;
        var _loc9 = index_k + _loc2 * increments.k;
        var _loc3 = this.letter_grid[_loc10][_loc9];
        _loc3.word_bank_letter = true;
        _loc3.letter = word.charAt(_loc2);
      }
      var _loc6 = new Object();
      _loc6.start = {
        j : index_j,
        k : index_k
      };
      _loc6.length = word.length;
      _loc6.increments = increments;
      _loc6.direction = direction;
      _loc6.word = word;
      this.answer_key.push(_loc6);
    };
    this.word_overlaps = function(word, index_j, index_k, increments) {
      for (var _loc2 = 0; _loc2 < word.length; ++_loc2) {
        var _loc5 = index_j + _loc2 * increments.j;
        var _loc4 = index_k + _loc2 * increments.k;
        var _loc3 = this.letter_grid[_loc5][_loc4];
        if (_loc3.word_bank_letter && _loc3.letter != word.charAt(_loc2)) {
          return (true);
        }
      }
      return (false);
    };
    this.calculate_slope_increments = function(direction) {
      if (direction == "Top Left to Bottom Right") {
        return ( {
          j : 1,
          k : 1
        });
      } else {
        if (direction == "Bottom Left to Top Right") {
          return ( {
            j : -1,
            k : 1
          });
        } else {
          if (direction == "Top Right to Bottom Left") {
            return ( {
              j : 1,
              k : -1
            });
          } else {
            if (direction == "Bottom Right to Top Left") {
              return ( {
                j : -1,
                k : -1
              });
            } else {
              if (direction == "Left to Right") {
                return ( {
                  j : 0,
                  k : 1
                });
              } else {
                if (direction == "Right to Left") {
                  return ( {
                    j : 0,
                    k : -1
                  });
                } else {
                  if (direction == "Top to Bottom") {
                    return ( {
                      j : 1,
                      k : 0
                    });
                  } else {
                    if (direction == "Bottom to Top") {
                      return ( {
                        j : -1,
                        k : 0
                      });
                    }
                  }
                }
              }
            }
          }
        }
      }
    };
    Array.prototype.get_letter_grid = function(m, n) {
      var _loc4 = new Array();
      for (var _loc3 = 0; _loc3 < m; ++_loc3) {
        _loc4.push(new Array());
        for (var _loc1 = 0; _loc1 < n; ++_loc1) {
          var _loc2 = String.fromCharCode(randi(65, 91));
          _loc4[_loc3].push(_loc2);
        }
      }
      return (_loc4);
    };
    Array.prototype.sortOn = function(p) {
      Array.$sortprop = p;
      var _loc3 = function(a, b) {
        var _loc1 = Array.$sortprop;
        return (b[_loc1] > a[_loc1]);
      };
      this.sort(_loc3);
      delete Array.$sortprop;
    };
    Array.prototype.shuffle = function() {
      for (var _loc2 = 0; _loc2 < this.length; ++_loc2) {
        this.swap(_loc2, randi(0, this.length));
      }
    };
    Array.prototype.swap = function(a, b) {
      var _loc2 = this[a];
      this[a] = this[b];
      this[b] = _loc2;
    };
    function randi(a, b) {
      return (Math.floor(Math.random() * (b - a)) + Math.floor(a));
    }
    Array.prototype.return_copy = function() {
      var _loc3 = new Array();
      for (var _loc2 = 0; _loc2 < this.length; ++_loc2) {
        _loc3[_loc2] = this[_loc2];
      }
      return (_loc3);
    };
    Array.prototype.random_subset = function(n) {
      var _loc4 = new Array();
      var _loc3 = Array.prototype.getIndices(0, this.length - 1);
      _loc3.shuffle();
      for (var _loc2 = 0; _loc2 < n; ++_loc2) {
        _loc4[_loc2] = this[_loc3[_loc2]];
      }
      return (_loc4);
    };
    Array.prototype.getIndices = function(a, b) {
      var _loc3 = new Array();
      for (var _loc1 = a; _loc1 <= b; ++_loc1) {
        _loc3[_loc1 - a] = _loc1;
      }
      return (_loc3);
    };
    this.initialize();
  };
  SCPTModel("iPane", {}, {
    init : function(jsonObj, params) {
      this.params = params;
      this.current = 0;
      this._ready = false;
      this._super(jsonObj, params, "tabbedpane");
      this.orient = (jsonObj.tablocation.match(/left|right/)) ? "vertical" : "horizontal";
      this.stretch = params.stretch;
      var images = [];
      var max_height = (this.orient == "vertical") ? 260 : 200, max_width = 150, kkk = max_width / max_height, num = 0, self = this;
      if (!(jsonObj.tab instanceof Array)) {
        jsonObj.tab = [jsonObj.tab];
      }
      for (var i = 0, len = jsonObj.tab.length; i < len; i++) {
        jsonObj.tab[i].label = this.decode(jsonObj.tab[i].label);
        jsonObj.tab[i].content = this.decode(jsonObj.tab[i].content);
        if (jsonObj.tab[i].image && jsonObj.tab[i].image.image + "" != "[object Object]") {
          jsonObj.tab[i].image.image = this.decode(jsonObj.tab[i].image.image);
          images.push($(jsonObj.tab[i].image.image).attr("src"));
        } else {
          images.push("");
        }
      }
      for (var i = 0, n = 0, len = jsonObj.tab.length; i < len; i++) {
        if (images[i] == "") {
          jsonObj.tab[i].image = "";          
          if (++n == len) {
            self._ready = true;
          }
          continue;
        }
        var img = new Image();
        img.src = images[i];
        img.onload = function(obj) {
          return function() {
            obj.img_h = parseInt(this.height);
            obj.img_w = parseInt(this.width);
            obj.image = obj.image.image;
            if (++n == len) {
              self._ready = true;
            }
          };
        }(jsonObj.tab[i]);
        img.onerror = function(id, link) {
          return function() {
            $("#" + id).find(".page td").first().append('<p class="error"># error: not found image: ' + link + "</p>");
          };
        }(this.containerId, images[i]);
      }
    }
  });
  SCPTController("TabbedPane", {}, {
    init : function() {
      var self = this;
      this.current = 1;
      this.holder = $("#" + this.options.model.params.containerId).html("").addClass("tabbedpane").css({
        background : this.options.model.backgroundColor,
        border : "1px solid " + getMixedColor("#3c3c3c", this.options.model.backgroundColor, 0.5)
      }).append(this.options.template).children(".page");
      this._wait_for_ready(this._super);
    },
    _wait_for_ready : function(_super) {
      var self = this;
      if (!this.options.model._ready) {
        setTimeout(function() {
          self._wait_for_ready(_super);
        }, 50);
      } else {
        self._start(_super);
      }
    },
    _start : function(_super) {
      this._super = _super;
      this.holder.html("");
      this.stretch = this.options.model.stretch;
      this.view = this["_tabspanel_view_"+this.options.model.tablocation]();
      this.view.tabs[0].css({
        background : this.options.model.backgroundColor
      });
      var loc = this.options.model.tablocation, orient = this.options.model.orient, tab = this.options.model.tab;
      if (!( tab instanceof Array)) {
        tab = [tab];
      }
      if (orient == "vertical") {
        this.tab_param = ["height", (this.view.tabs[0].outerHeight(true) / tab.length)];
      } else {
        this.tab_param = ["width", Math.min(this.view.tabs[0].outerWidth(true) / tab.length, 150)];
      }
      for (var i = 0, l = tab.length; i < l; i++) {
        this._add_tab_bttn(loc, orient, tab[i], i + 1);
        this._add_tab_desc(orient, tab[i]);
      }
      this.show_tab(1);
      if (this.stretch) {
        var stretch = {
          height : "100%"
        };
        this.holder.css(stretch).parent().css(stretch);
        for (var i = 0, l = this.view.desc.length; i < l; i++) {
          this.view.desc[i].css(stretch).children().css(stretch).children().css(stretch);
        }
      }
      this.view.keys = this.holder.parent().find(".key-handler").attr("id", "inputf_" + this.options.model.params.containerId);
      this._super();
      this.holder.show();
    },
    _tabspanel_view_top : function() {
      return {
        tabs : [$('<div class="horizontal-tabs"></div>').appendTo(this.holder)],
        desc : [$('<div class="horizontal-desc"></div>').appendTo(this.holder)]
      };
    },
    _tabspanel_view_bottom : function() {
      return {
        desc : [$('<div class="horizontal-desc"></div>').appendTo(this.holder)],
        tabs : [$('<div class="horizontal-tabs"></div>').appendTo(this.holder)]
      };
    },
    _tabspanel_view_left : function() {
      return {
        tabs : [$('<div class="vertical-tabs"></div>').appendTo(this.holder)],
        desc : [$('<div class="vertical-desc"></div>').appendTo(this.holder)]
      };
    },
    _tabspanel_view_right : function() {
      return {
        desc : [$('<div class="vertical-desc"></div>').appendTo(this.holder)],
        tabs : [$('<div class="vertical-tabs"></div>').appendTo(this.holder)]
      };
    },
    _add_tab_bttn : function(loc, orient, tab, n) {
      var evt_name = ("ontouchstart" in document.documentElement) ? "click" : "mouseenter", l_color = getMixedColor("#ffffff", tab.color, 0.9), r_color = getMixedColor("#ffffff", tab.color, 0.5), self = this;
      var tabColor = parseInt("0x" + tab.color.substr(tab.color.indexOf("#") + 1)) > 8355711 ? "#000000" : "#FFFFFF";
      return this.view.tabs.push($('<div class="' + orient + '-tab-bttn" style="background:' + tab.color + ";" + this.tab_param[0] + ":" + this.tab_param[1] + 'px"><div style="color:' + tabColor + ";" + this.tab_param[0] + ":" + (this.tab_param[1] - 10) + 'px">' + tab.label + "</div></div>").appendTo(this.view.tabs[0])._lineargradient(loc, l_color, r_color).each(function() {
        $(this).bind(evt_name, function() {
          self.show_tab(n);
        });
      }).fadeTo(0, 0.3));
    },
    _add_tab_desc : function(orient, tab) {
      var scroll_w = ("ontouchstart" in document.documentElement) ? 4 : 12;
      tab.image = tab.image.image || tab.image || "";
      tab.img_h = tab.img_h || 20;
      stretch = this.stretch;
      this.view.desc.push($('<div class="' + orient + '-tab-desc" style="background:' + getMixedColor("#ffffff", tab.color, 0.1) + ';px"><div style="outline-width: 0px"><div style="min-height: ' + tab.img_h + 'px">' + tab.image + tab.content + "</div></div></div>").appendTo(this.view.desc[0]).each(function() {
        $(this).children("div").bind("keydown", function(evt) {
          self.view.keys.trigger(evt);
        });
        if (!stretch) {
          $(this).children("div").niceScroll({
            cursorwidth : scroll_w
          });
        }
        $(this).data("color", getMixedColor("#ffffff", tab.color, 0.1));
      }).hide());
      var tab_view = this.view.desc[this.view.desc.length - 1];
      if (!this.stretch) {
        tab_view.scroll = tab_view.children().first().getNiceScroll().hide();
      }
    },
    prev : function() {
      var n;
      if (this.current == 1) {
        n = this.view.tabs.length - 1;
      } else {
        n = this.current - 1;
      }
      this.show_tab(n);
    },
    next : function() {
      var n;
      if (this.current == this.view.tabs.length - 1) {
        n = 1;
      } else {
        n = this.current + 1;
      }
      this.show_tab(n);
    },
    show_tab : function(n) {
      if (!this.stretch) {
        this.view.desc[this.current].scroll.hide();
      }
      this.view.tabs[this.current].fadeTo("fast", 0.3);
      this.view.desc[this.current].hide();
      this.current = n;
      this.view.desc[this.current].show();
      this.view.tabs[this.current].fadeTo("fast", 1);
      if (!this.stretch) {
        this.view.desc[this.current].scroll.show();
      }
      this.holder.css({
        background : this.view.desc[this.current].data("color")
      });
    },
    getState : function(jsonObj) {
      return {
        tab : this.current
      };
    },
    setState : function(jsonObj) {
      this.show_tab(parseInt(jsonObj.tab));
    },
    handleKeys : function(e) {
      var self = e.data.self;
      var dt = 10;
      switch(e.keyCode) {
        case 38:
          self.prev();
          break;
        case 37:
          self.prev();
          break;
        case 39:
          self.next();
          break;
        case 40:
          self.next();
          break;
        default:
          return true;
      }
      e.preventDefault();
    },
    reset : function() {
      return
      void (0);
    },
    disableActivity : function() {
      this._super();
    }
  });
  (function($) {
    $.fn._lineargradient = function(type, from, to) {
      return this.css({
        background : "linear-gradient(" + type + ", " + from + ", " + to + ")",
        background : "-o-linear-gradient(" + type + ", " + from + ", " + to + ")",
        background : "-ms-linear-gradient(" + type + ", " + from + ", " + to + ")",
        background : "-moz-linear-gradient(" + type + ", " + from + ", " + to + ")",
        background : "-webkit-linear-gradient(" + type + ", " + from + ", " + to + ")"
      });
    };
  })(jQuery);
  SCPTModel("Timeline", {
    defaults : {}
  }, {
    init : function(jsonObj, params) {
      this._super(jsonObj, params, "timeline");
      this.title = this.decode(jsonObj.title);
      this.closeTxt = jsonObj.closetxt;
      this.ordermethod = jsonObj.ordermethod;
      this.startTime = this.getMsDate(jsonObj.startmonth + "/" + jsonObj.startday + "/" + jsonObj.startyear);
      this.endTime = this.getMsDate(jsonObj.endmonth + "/" + jsonObj.endday + "/" + jsonObj.endyear);
      this.startYear = jsonObj.startyear;
      this.endYear = jsonObj.endyear;
      this.intervals = jsonObj.intervals;
      this.visualContainers = [];
      this.events = jsonObj.event.length ? jsonObj.event : [jsonObj.event];
      this.createStructure(this.events);
      this.partWidth = this.calculateWidth();
    },
    createStructure : function(events) {
      if (this.ordermethod == "numbered") {
        this.visualContainers[0] = "";
        for (var i = 0; i < events.length; i++) {
          events[i].visPosition = events[i].date;
          events[i].visWidth = 0;
          this.visualContainers.push(events[i].date);
        }
      } else {
        var partMsWidth = this.intervals * 365 * 24 * 3600000;
        for (var i = 0; i < events.length; i++) {
          events[i].visPosition = (this.getMsDate(events[i].date + "") - this.startTime) / partMsWidth;
          events[i].visWidth = 0;
          if (events[i].end + "" != "[object Object]") {
            events[i].visWidth = (this.getMsDate(events[i].end + "") - this.getMsDate(events[i].date + "")) / partMsWidth;
          }
        }
        var startYear = this.startYear;
        var endYear = this.endYear;
        while (startYear < endYear) {
          this.visualContainers.push(startYear);
          startYear += this.intervals;
        }
      }
      for (var i = 0; i < events.length; i++) {
        events[i].title = this.decode(events[i].title || "");
        events[i].content = this.decode(events[i].content || "");
      }
      this.events = events;
      this.calculateWidth();
    },
    setState : function(jsonObj) {
      this._super(jsonObj);
    },
    getState : function(jsonObj) {
      var obj = this._super();
      return obj;
    },
    getMsDate : function(date) {
      var arr = date.split("/");
      return new Date(arr[2], arr[0], arr[1]).getTime();
    },
    calculateWidth : function() {
      minWidth = 260;
      rows = 3;
      timeLineWidth = this.events.length * minWidth;
      strip_mc_imelinestrip_mc_width = timeLineWidth / rows;
      var _loc2 = new Array();
      for ( x = 0; x < this.events.length; x++) {
        setDate = this.events[x].date.toString();
        my_array = setDate.toString().split("/");
        var _loc3 = new Date(my_array[2], my_array[0] - 1, my_array[1]);
        if (this.ordermethod == "date") {
          _loc3.setFullYear(my_array[2]);
        }
        percentage = Math.abs((this.startTime - _loc3.valueOf()) / (this.endTime - this.startTime));
        _loc2[x] = strip_mc_imelinestrip_mc_width * percentage;
      }
      for ( x = 0; x < this.events.length; x++) {
        if (Math.abs(_loc2[x] - _loc2[x + 2]) < minWidth) {
          minWidth = Math.abs(_loc2[x] - _loc2[x + 2]);
        }
      }
      strip_mc_imelinestrip_mc_width = timeLineWidth / rows * (minWidth / minWidth);
      numOfIntervals = (parseInt(this.endYear) - parseInt(this.startYear)) / parseInt(this.intervals);
      return Math.max(strip_mc_imelinestrip_mc_width / numOfIntervals,50);
    }
  });
  SCPTController("Timelines", {}, {
    init : function() {
      var self = this, m = this.options.model;
      self.options.model.attempts++;
      var container = $("#" + m.containerId);
      container.html(this.options.template, {
        id : m.containerId,
        color : m.backgroundColor,
        width : m.width,
        height : m.height,
        title : m.title,
        visualContainers : m.visualContainers,
        ordermethod : m.ordermethod,
        partWidth : m.partWidth,
        events : m.events,
        closeTxt : m.closeTxt
      });
      this._super();
      var scroll_w = ("ontouchstart" in document.documentElement) ? 4 : 10;
      $("#timeline_container_" + m.containerId).scroll().niceScroll({
        touchbehavior : true,
        grabcursorenabled : false,
        cursoropacitymin : 0,
        cursoropacitymax : 0
      });
      this.adjustSizeAndScroller();
      setTimeout(function() {
        self.adjustSizeAndScroller();
        $("#" + m.containerId).children().eq(0).css({
          visibility : "visible"
        });
      }, 200);
    },
    adjustSizeAndScroller : function() {
      var self = this;
      var m = this.options.model;
      var totalW = $("#timeline_container_"+m.containerId)[0].scrollWidth;
      var table = $("#timeline_container_" + m.containerId).find("table:first");
      var tableW = table.width();
      var lastTd = table.find("td:last").children().first();
      lastTd.css({
        width : totalW - tableW + lastTd.width() + "px"
      });
      var pos = [];
      for (var i = 0; i < m.events.length; i++) {
        var obj = $("#timeline_label_" + i + "_" + m.containerId);
        obj.bind("click", function(j, self) {
          return function() {
            self.showPopup(j);
          };
        }(i, self));
        pos[i] = [obj.position().left, obj.position().left + obj.width() + 20];
      }
      var resPos = [];
      for (var j = 0; j < m.events.length; j++) {
        var i = 0;
        while (i < resPos.length && resPos[i] > pos[j][0]) {
          i++;
        }
        resPos[i] = pos[j][1];
        $("#timeline_label_" + j + "_" + m.containerId).css("top", 20 * (i + 1) + "px");
        var obj1 = $("#timeline_label_" + j + "_" + m.containerId);
      }
      var _flag = true;
      var obj = $("#timeline_container_" + m.containerId);
      var tgt1 = $("#timeline_sm_" + m.containerId);
      if (obj.children().eq(0).width() > obj.width()) {
        tgt1.width($("#timeline_sb_" + m.containerId).width() * obj.width() / obj.children().eq(0).width());
        var tw = $("#timeline_sb_" + m.containerId).width() - tgt1.width();
        $("#timeline_sm_" + m.containerId).bind("draginit", function(ev, drag) {
          _flag = false;
          drag.horizontal();
          drag.limit($("#timeline_sb_" + m.containerId));
        }).bind("dragmove", function(ev, drag) {
          obj.scrollLeft((tgt1.position().left - 31) * (obj.children().eq(0).width() - obj.width()) / tw);
        }).bind("dragend", function() {
          _flag = true;
        });
        $("#timeline_container_" + m.containerId).scroll(function(ev) {
          if (_flag) {
            tgt1.css({
              left : tw * obj.scrollLeft() / (obj.children().eq(0).width() - obj.width()) + 31 + "px"
            });
          }
        });
        $("#timeline_la_" + m.containerId).click(function() {
          var sl = obj.scrollLeft() - 0.1 * (obj.children().eq(0).width() - obj.width());
          if (sl < 0) {
            sl = 0;
          }
          obj.scrollLeft(sl);
        });
        $("#timeline_ra_" + m.containerId).click(function() {
          var sl = obj.scrollLeft() + 0.1 * (obj.children().eq(0).width() - obj.width());
          if (sl / (obj.children().eq(0).width() - obj.width()) > 1) {
            sl = obj.children().eq(0).width() - obj.width();
          }
          obj.scrollLeft(sl);
        });
      } else {
        $("#timeline_sc_" + m.containerId).hide();
      }
    },
    bindEvents : function() {
      var self = this, m = this.options.model;
      $("#timeline_closeButton_" + m.containerId).bind("click", function(self) {
        return function() {
          $("#timeline_popup_" + m.containerId).hide().children().first().getNiceScroll().remove();
        };
      }(self)).hover(function() {
        $(this).css({
          "border-color" : "#c1f0ae"
        });
      }, function() {
        $(this).css({
          "border-color" : "#9ca2a2"
        });
      });
      for (var i = 0; i < m.events.length; i++) {
        $("#timeline_label_" + i + "_" + m.containerId).bind("click", function(j, self) {
          return function() {
            self.showPopup(j);
          };
        }(i, self));
      }
    },
    showCorrectDate : function(date) {
      var retDate = "";
      date = date+"";
      date = date.split("/");
      if(date.length<3) {
        date = [0,0,date[0]];
      }
      for(var i=0;i<3;i++) {
        retDate+= date[i]=="0" ? "" : "/"+date[i];
      }
      return retDate.substring(1);
    },	
    showPopup : function(slideNumber) {
      var m = this.options.model;
      var ev = m.events[slideNumber];
      var title = "", text = "";
      if (ev.title + "" != "[object Object]" && ev.title + "" != "undefined") {
        title += "<b>" + ev.title + "</b>";
      }
      if (m.ordermethod == "numbered") {
        title = "<b>" + this.showCorrectDate(ev.date) + ". </b>" + title;
      } else {
        title += " " + this.showCorrectDate(ev.date);
        if (ev.end + "" != "[object Object]") {
          title += " - " + ev.end;
        }
      }
      if (ev.content + "" != "[object Object]" && ev.content + "" != "undefined") {
        text = ev.content;
      }
      $("#timeline_popupTitle_" + m.containerId).html(title);
      $("#timeline_popupText_" + m.containerId).html(text);
      $("#timeline_popupImg_" + m.containerId).hide();
      if (ev.image) {
        var img = new Image();
        img.onload = function() {
          $("#timeline_popupImg_" + m.containerId).attr("src", ev.image).show();
          $("#timeline_popup_" + m.containerId).show();
        };
        img.src = ev.image;
      } else {
        $("#timeline_popup_" + m.containerId).show();
      }
      setTimeout(function() {
        var obj = $("#timeline_popup_" + m.containerId).show();
        if (("ontouchstart" in document.documentElement)) {
          obj.children().first().niceScroll({
            cursorwidth : 4,
            touchbehavior : true,
            grabcursorenabled : false
          });
        } else {
          $(".timelinePopupText").css("overflow", "auto");
        }
      }, 300);
    },
    updateStatus : function() {
    },
    handleKeys : function(e) {
    }
  });
}
